Recent Comments


re: Smoothing out <div> scrolling in Mobile WebKit Browsers
Yesterday @ 9:43am | by Anthony

This is super awesome!!! Solved an issue i had with my App list that i've been researching on for days
re: Using the HTML5 <input type="file" multiple="multiple"> Tag in ASP.NET
Friday @ 7:00am | by Ali Ahmad

I learned many things from your web site, and it is one of them.

If any one want to resize the image, rename the image or upload multiple selection then you can see

http://www.advancesharp.com/blog/1130/image-gallery-in-asp-net-mvc-with-multiple-file-and-size
re: Using Cordova and Visual Studio to build iOS Mobile Apps
Friday @ 1:38am | by Rick Strahl

@Mohammad - yup, planning at least a couple more in the next months.
re: Using Cordova and Visual Studio to build iOS Mobile Apps
Friday @ 12:17am | by Mohammad

Nice article
Hopefully you will make more articles on how to make applications in Cordova and VS15
re: Rendering ASP.NET MVC Views to String
January 14, 2015 @ 5:47pm | by Vicente Mantrana

Hi:

Is there any way to extend this functionality in a way that it takes a partial view name and a _layout name and dynamically apply that layout to the partial view and render the resulting view as a string?
re: Tip: Create a Visual Studio Menu option to Open a Command Window
January 14, 2015 @ 9:56am | by Christopher

A potential problem with this approach is that Visual Studio spawns external tools in such a way that CTRL^C interrupts do not work properly. This is an issue if you have watch processes as part of your Grunt or Gulp tasks that you want to stop without closing the command window.

For more information, see https://social.msdn.microsoft.com/Forums/vstudio/en-US/c065a5b9-fdae-4a89-bd42-c7494d2b944c/external-tool-not-receiving-ctrlc-interrupts?forum=vsx
re: Using Cordova and Visual Studio to build iOS Mobile Apps
January 13, 2015 @ 2:00pm | by Rick Strahl

@Chris - I don't see a separate download link anywhere. The page says to install Visual Studio 2015 Preview which I have installed, but this emulator is not there. If you find a separate download link please post.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
January 12, 2015 @ 2:12pm | by Tim

Sorry to nit-pick, but you should change FirstOrDefault to First, unless you check after FirstOrDefault that the object is not null...
re: Using Cordova and Visual Studio to build iOS Mobile Apps
January 12, 2015 @ 12:41pm | by Chris

Regarding the Visual Studio Emulator for Android (http://www.visualstudio.com/en-us/explore/msft-android-emulator-vs.aspx) I believe it's an additional install for both VS2013 and the 2015 preview. There are links on that page to install it. The emulator is an early release but currently supports 4.4 and runs on HyperV so it should run fast and work well on your developer machine. Email me if you run into further issues getting it to work.
re: ASP.NET Routing not working on IIS 7.0
January 12, 2015 @ 8:11am | by darius

Hi,

Just want to add that a hotfix http://support.microsoft.com/kb/980368 did solve the problem, plus we removed everything from webserver section

<system.webServer>
</system.webServer>
re: Tip: Create a Visual Studio Menu option to Open a Command Window
January 12, 2015 @ 7:47am | by Eric Falsken

If you want your new command prompt to open and include the "developer tools", like the icon in your start menu, use this in the cmd.exe arguments box:
/k ""C:\Program Files (x86)\Microsoft Visual Studio 12.0\Common7\Tools\VsDevCmd.bat""
re: Tip: Create a Visual Studio Menu option to Open a Command Window
January 09, 2015 @ 5:01am | by Joe Ficara

Nice post! Sure to save folks time!
re: Tip: Create a Visual Studio Menu option to Open a Command Window
January 09, 2015 @ 4:57am | by peSHIr

Quick comment about something I only found out about recently: if you have a Windows Explorer open in the folder you want a command line opened in, simply get focus in the address bar (by clicking in it), and start typing either "cmd", "powershell" or any other CLI you want to start there, which will overwrite the path, and press Enter. This will start the typed CLI with the path being the current path.
re: Simplistic Object Copying in .NET
January 09, 2015 @ 1:48am | by Alfredo Muñiz López

I know this post has been inactive for a while, but wanted to say that your solution came in handy for solving an issue in our project. We had an entity that was referenced in a lot of places and we wanted to substitute it with another modified one without losing those references and without having to reset it everywhere or going property by property.

I modified your code quite a bit, though:

1. Added a check to ignore Fields with FieldInfo.IsLiteral == true, since trying to copy constants throws exception.

2. Made it optionally recursive to go through all the inherited types, making sure that all members, even inherited private ones, got copied.
re: Debugging Application_Start and Module Initialization with IIS and Visual Studio
January 07, 2015 @ 10:06am | by LeeC

Microsoft has fixed this in Visual Studio Ultimate 2015 Preview. Fixed it as in it's totally screwed up no matter what "server" you use. I'm running my Web site in IIS Express, and the Application_Start is never hit. Thanks, Microsoft. I'll go create a Connect issue so they can mark it "Closed. By design." To which, I'll once again reply, "Fire the designer."
re: Dell XPS 15 review
January 06, 2015 @ 12:36pm | by Jeffrey Cumpsty

I recently purchased BOTH the MacBook Pro and the Dell XPS15

MacBook Pro 2.8Ghz, 16GB, 1TB SSD vs Dell XPS15 2.3Ghz, 16GB, 512GB SSD.

The Mac wipes the floor with the Dell in every aspect. The keyboard is ultra solid, never misses a key, the trackpad is smooth, the screen usually ok at scaling icons and text.

Exporting a VM from Virtualbox took 30 minutes on the Mac. I cancelled it after an hour on the Dell.

I WANTED to like the Dell; keeping the Mac means I need to dev in a VM always...but I am keeping the MAC.
re: GZip/Deflate Compression in ASP.NET MVC
January 05, 2015 @ 1:47pm | by Phil0001

The 'Vary' HTTP header is used to indicate the set of *request-header* fields that fully determines, while the response is fresh, whether a cache is permitted to use the response to reply to a subsequent request.

The header you've used is a response header. It should probably be Accept-Encoding
re: A jquery-watch Plug-in for watching CSS styles and Attributes
January 05, 2015 @ 10:00am | by mark tennenhouse

HI Rick,
Its exactly what I need. BUT, when I test in IE9 using emulation mode, I get an error on the interval property, as though its not defined.
I think its just the way you defined your options but I didn't make time to figure it out.
Please let me know if you update it, because its a very useful plug in.
Thanks,
Mark
re: I can’t find my Find Dialog in Visual Studio
January 04, 2015 @ 3:57am | by Shahin

I can't thank you enough. This was such a frustrating one. I would have never figured this one out if not for your post. The worst part is I still do not know the causality for this. Microsoft please please please do something.
re: Set-Cookie Headers getting stripped in ASP.NET HttpHandlers
December 31, 2014 @ 7:31am | by Remoraz

Hey Rick, late to the party, I know.

Excellent write up. Very helpful stuff, even a version later. I appreciate your summary, especially when you said, "just don't clear the headers, but if you HAD to, do it like this...".

One minor thing: you have a Cookies.Clear() in that clean up method. That won't work, I'm afraid - had issues with it myself. You need to loop the cookies and set the expiry to "yesterday" (DateTime.Now minus a day). Just throwing that in to, MAYBE, help someone avoid a bug in the future.

Great article! Thanks for the contribution!
re: Entity Framework and slow bulk INSERTs
December 28, 2014 @ 2:47pm | by ZZZ Projects

The ZZZ Projects Bulk Operations Library is the solution for you.

It allows you to effectuate various operations such as: Delete, Insert, Update and Merge on a substantial amount of data.

var operation = new SqlBulkOperation();

// ... Custom Settings ....
operation.BulkDelete(dt);
operation.BulkInsert(dt);
operation.BulkUpdate(dt);
operation.BulkMerge(dt);

It also offers more advanced features like output value, column formula, auditing, intercepting, logging and more.

Find out more on http://zzzprojects.com/bulk-operations/ about the most advanced and flexible Bulk Operations library.
re: WebAPI: Getting Headers, QueryString and Cookie Values
December 26, 2014 @ 3:44pm | by shuo

Thanks for sharing this, it really take me more than a few cycles to search online for a clean code. The API is not at all intuitive.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 23, 2014 @ 10:52pm | by Steve

I don't think it's EF, really. Same issues with rdo, ado, ado.net -- putting queries into a loop and hitting the DB thousands of times rather than just once, and then iterating / processing from that, normally will not scale.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 23, 2014 @ 1:42pm | by Rick Strahl

@Albin - yes very good point. My business object does .Dispose() the Context but only if you dispose the bus object which I didn't do in the sample. But you are absolutely correct - the BO instantiation should be wrapped in a using{} block.

Note the production code is quite different from the code here anyway - we don't access the Context in this application code; all that's wrapped inside of the BO. It's broken out for simplicity and single level control flow here.

As to connections... it's my understanding that EF opens a connection as it's needed for each SQL operation - I don't think it keeps connections open UNLESS you explicitly pass in a connection of your own.

Here's some info that points at this from MSDN:
http://msdn.microsoft.com/en-us/library/vstudio/bb896325%28v=vs.100%29.aspx

If you look in the SQL profiler you see all the connection resets and they are on a per operation not per context basis.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 23, 2014 @ 3:47am | by Pete

We use 2 separate DbContexts - one for reads (which has tracking off) and one for writes. I find this works pretty well!
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 2:39pm | by Dan H

I had this same exact problem recently. I had a large batch processing job that gets called via a web service (we'll call this the Batch Request) and was using a per request context. I didn't want to get rid of the per request context so grudgingly, I had that batch job call another web service (we'll call this the Singular Request) with the id of the object I wanted processed. I hated this approach BUT, I then realized that it might work in my favor by calling the singular requests async in batches of 20. Two benefits came of of it - I was processing each record on its own context and I was processing 10 - 20 items at the same time. I actually tried to repeat this job using a new context per item and using async calls with normal processing, but it still wasn't nearly as fast as using the web service method.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 2:24pm | by vk

Check NHibernate, it has request batching feature :) otherwise use hint by @wydok.

Also, instead of loading entire order it makes sense to use projection to load only OrderId and CustomerId.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 1:02pm | by Frans Bouma

Not to pimp my own work, but this is a standard mistake: it's a select N+1 within a loop, which could have been caught during development with tools like ORM Profiler (http://www.ormprofiler.com). Use the tools which are there for you to avoid mistakes which are not obvious.

Entity Framework is rather slow with fetching large sets though (see my benchmarking work here and results: https://github.com/FransBouma/RawDataAccessBencher ). I profiled the fetches and wondered what it is that's slow, apparently it's proxy management for related entities when fetching the set with change tracking. NHibernate has the exact same problem (it's even slower).

Interestingly enough, other sessoin/context based ORMs like Linq to Sql don't have this problem. It looks like a serious design flaw within EF and NH. I don't know whether they've fixed this in EF7 (as they rewrote a lot of it), I hope for EF users they have!

I agree with wydok: fetching sets of projected data to process elements in memory is always more efficient. If possible though, perform bulk operations on the DB directly (so update queries with expressions). EF by default doesn't support them (other ORMs do) but there are extensions for EF which add these features.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 1:01pm | by Albin Sunnanbo

I would also like to point out the importance of disposing your EF Contexts since EF keeps the database connection open until the Context is disposed.

In your example where you recreate your context
BusOrder orderBO = new BusOrder();
inside the loop you might end up creating lots of concurrent database connections instead of reusing open connections from the connection pool.
It might of course being present in your code, but it does not show up in your example.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 12:51pm | by Albin Sunnanbo

Thanks for the reminder about turning off change tracking.

However, there are some major improvements left in this example.
First of all, the concept of making 16000 SQL queries in a loop is still rather naive.

Instead of
foreach (OrderIDsToProcess orderID in orderIDsToProcess)
{
    //var order = orderBO.Load(orderID.OrderID); 
    var order = orderBO.Context.Orders.FirstOrDefault(o=> o.OrderID == orderID.OrderID); 
    orderID.CustomerID = order.CustomerID; 
}

you could load all orders in a single query
var orderIDsToProcess_id = orderIDsToProcess.Select(o => i.OrderID).ToList(); // projects only the ID:s
var allOrders = orderBO.Context.Orders.Where(o => orderIDsToProcess_id.Contains(o.OrderID));
// To get efficient lookups we create a dictionary based on the OrderID
var allOrdersDictionary = allOrders.ToDictionary(o => o.OrderID);
foreach (OrderIDsToProcess orderID in orderIDsToProcess)
{
    var order = allOrdersDictionary[orderID.OrderID]; 
    orderID.CustomerID = order.CustomerID; 
}

the Contains looks a bit backward, but is translated in to IN(...) in SQL.
Beware that before EF6 the Contains slowed down on large lists. If you are stuck on EF<=5, page the list into batches of at most 1000 items.
The code above should get your execution time to at most a few seconds.
This is the recommended approach if you want to use more properties from the Order, or update the Order object. However in this code we only use the CustomerID property and can select only that property, greatly reducing the amount of data sent over the wire from the SQL server.
var orderIDsToProcess_id = orderIDsToProcess.Select(o => i.OrderID).ToList(); // projects only the ID:s
var allOrders = orderBO.Context.Orders.Where(o => orderIDsToProcess_id.Contains(o.OrderID));
// To get efficient lookups we create a dictionary based on the OrderID
var customerIdByOrderId = allOrders.ToDictionary(o => o.OrderID, o => o.CustomerID);
foreach (OrderIDsToProcess orderID in orderIDsToProcess)
{
    var customerID = customerIdByOrderId[orderID.OrderID]; 
    orderID.CustomerID = customerID; 
}

This does not return an entity at all and you don't need to bother with change tracking at all.
This should definitely get you into the sub second range.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 12:40pm | by Rick Strahl

@Alex - Nope. If whatever you're using works for you by all means do. EF has gotten lots better over the years to the point where it's stable and provides good performance IMHO. But you do have to be aware of quirks - just like you do if you write manual SQL which is just as hard if not harder to tune right as well.

There are so many choices these days. I use a lot of MongoDb these days for example which works so much better for many of the data scenarios I'm working with.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 12:03pm | by Alex B

I don't know.. I still don't use EF at all for data processing. Data access layer is still good. Everything fast and predictable. Am I nuts?...
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 11:17am | by Rick Strahl

@wydok - yup, definitely, pre-loading certainly sounds better than running those 16,000 queries in a loop. Even more so, they could pre-select just the 2 or 3 fields that are actually needed instead of the whole record.

As I mentioned the code I posted is somewhat simplified to just point at the looping construct and slow iteration speed - there are a few other criteria that make pre-selection more tricky than the query you suggest :-)

But it's a great point - worth mentioning in the post in fact. I'll add something to the fact. Thanks!

While in this case there might actually be a different solution that avoids that heavy EF iteration altogether, there are valid scenarios where iteration is required and this problem will creep up.
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 22, 2014 @ 4:50am | by wydok

You may also want to consider the fact that your loop runs a SQL statement to get the first order by id for each order in the database. You can preload the orders, as long as you don't mind swapping I/O with RAM usage:

// load all the orders being proccessed
var orders = orderBO.Context.Orders.Where(o => orderIDsToProcess.Select(p => p.OrderID).Contains(o.OrderID).ToList();

foreach (OrderIDsToProcess orderID in orderIDsToProcess)
{
var order = orders.FirstOrDefault(o=> o.OrderID == orderID.OrderID);
orderID.CustomerID = order.CustomerID;
}
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 21, 2014 @ 3:59pm | by Rick Strahl

Thanks Matt, for reminding me. Totally forgot about .AsNoTracking() for individual queries (even though I use that all the time - duh!). Added a section to the post. Thanks!
re: Gotcha: Entity Framework gets slow in long Iteration Loops
December 21, 2014 @ 2:52pm | by Matt Brooks

Regarding your comment about per request option for disabling change tracking, have you seen the IQueryable.AsNoTracking method for EF?

http://msdn.microsoft.com/en-us/library/gg679352%28v=vs.103%29.aspx
re: Web Browser Control – Specifying the IE Version
December 20, 2014 @ 11:17am | by Theodoros Flabouras

@Bernard: Thanks for this :<meta http-equiv="X-UA-Compatible" content="IE=9" > suggestion!

I was doing some tests with d3.js in web browser control inside a vfp form, and was getting script errors.

Many many thanks to Rick as well, you're a real gem!
re: Using plUpload to upload Files with ASP.NET
December 19, 2014 @ 1:44am | by Ersin

Hello Rick, you're right it was a client-side problem. Actually it seems Cache problem :) Thank you again.
re: Using plUpload to upload Files with ASP.NET
December 18, 2014 @ 5:29pm | by Rick Strahl

@Ersin - That should work. All files are passed through, and filtered with the extension filter list so I'm not sure why this wouldn't work. The data coming up is just raw data - is it possible that there's some client side restriction? I haven't used this in a while maybe something's changed?
re: Using plUpload to upload Files with ASP.NET
December 18, 2014 @ 6:55am | by Ersin

Hello Rick, thanks for your well-documented sample. I want to upload files except images. (zip,rar). I changed filters but it didn't work. How can i change this extensions ? Or can i :)

Thanks
re: Mixing $http Promises and $q Promises for cached Data
December 16, 2014 @ 8:33am | by Torgeir

Hm..I don't think there will be any performance issues since Angular services are singletons and you will always be interacting with the same cached promise and calling the same then() method over and over again - passing in a regular callback for it to execute. The down side though is that every caller has to interact with it as a promise every time which means more code than just grabbing a resolved data value....

I go back and forth about caching promises vs the returned data value though.
It is definitely easier to grab a data value if you know your app is in a state where the initial promise is guaranteed to be resolved (e.g. after login in etc)
re: Mixing $http Promises and $q Promises for cached Data
December 16, 2014 @ 1:28am | by Rick Strahl

@Torgeir - interesting approach and yes that would work I suppose. Never thought about caching the actual Promise instance... Wonder if that would have performance implications as you would hook up new handlers to the promise for each access.
re: Mixing $http Promises and $q Promises for cached Data
December 15, 2014 @ 4:11am | by Torgeir

Can't you just do something like the following:

var myPromise = null;

function getAlbums() {
if (myPromise == null)
myPromise = $http.get("/someUrl").then(function (res) {
return res.data;
});
return myPromise;
}

Generally I try to avoid resolving promises in the service, but for caching it does make sense.

re: Mixing $http Promises and $q Promises for cached Data
December 14, 2014 @ 11:35pm | by Rick Strahl

@Alexander - totally agree that $http's special interface was a bad idea in that it goes against all other promises produced in Angular or otherwise. At the very least they should have exposed the .then() method with a senisible signature, but unfortunately that's not the case (.then()'s success method returns an internal object rather than the result data).

While I agree I also think that turning everything into proper promises adds extra overhead when you do use $http as you have to wrap the existing promise into another promise (ie. another extra indirection and of course extra code) and it also goes against the standard guidance for use of $http that you have to be sure to document so there are no surprises.
re: Mixing $http Promises and $q Promises for cached Data
December 14, 2014 @ 10:46pm | by Alexander Pavlyuk

As for me I prefer the opposite approach. We usually have a lot of async stuff in our js apps. And for angular there's $q service to make promises. But $http promise is different in that it produces promises with success() ans error() "helper" functions. I strongly disagree in that this exception to common interface is helping. Maybe ng devs added those functions for beginners that often use jQuery and don't like to read docs... I always wrap $http calls in $q promises inside my services and expose the latter ones to other modules. This unification is reasonable: if any other ng developer uses my modules, he will just read that my module has a list of functions that return $q-compatible promises and that's it.
re: AngularJs ng-cloak Problems on large Pages
December 10, 2014 @ 10:46pm | by Torgeir

Sounds like you have your solution, but I how about this approach?

I have found that for large DOMs it often makes sense to use ng-if to toggle content. The ng-if directive appears similar to ng-hide/show, but with the important difference that it physically removes the actual DOM elements rather than hiding them using styles. My experience is that you can trim your DOM a lot this way. Also, another added benefit is that you don't incur watches on the ng-if excluded content like you would with the ng-show approach.

I have some more info in an article I wrote a while back:
http://www.syntaxsuccess.com/#/viewarticle/547a8ba2c26c307c614c715e

You make a good point by saying that it's easier to control permission based content by returning it from the server. However, I would argue that the same could be accomplished by having your angular application talk to a data api with server side permission checks instead. One idea would be to move away from an mvc, view based application, and instead talk to a web api service that returns json based on user permissions in tandem with ng-if.

Anyway, not sure if this is useful, but just a thought.
re: AngularJs and Promises with the $http Service
December 10, 2014 @ 1:36pm | by Rick Strahl

@Thijs - thanks. Fixed in the article.
re: Rendering ASP.NET MVC Razor Views outside of MVC revisited
December 10, 2014 @ 1:29pm | by Rick Strahl

@Vignesh - No, you have to render the top level view. But it sounds to me that you can do what you want if you do the proper segmentation of your views using partial views rather than sections (or else embed the sections into partial views).
re: Use IIS Application Initialization for keeping ASP.NET Apps alive
December 10, 2014 @ 12:35pm | by Rick Strahl

@Mike - I actually do the same. In fact every Web site I run is hooked up to a monitor that checks whether the site is running and notifies me of failures and it doubles as the ping mechanism.

The ping check in the code above is just a last ditch fail safe. With Application Initialization there's only one scenario where that's required and that's for AppDomain shutdowns. All other scenarios Application Initialization handles for restarting the service and keeping it running (ie. crashes, restarts).