“Unable to load one or more of the requested types.” when using EntityDataSource with Entity Framework in ASP.NET

I always love pushing something out that fails miserably and randomly. Especially when using straight Microsoft technologies. It seems these folks don’t eat their own dog food, or we wouldn’t encounter this crap.

Anyway, it took quite a while to figure out the resolution to this issue, but it all lies in the fact that their control is “trying” to be intelligent, and really only needed a little direction.

Let me explain, when the EntityDataSource loads, it looks for the Context. Where may you ask? Well, it actually uses reflection and attempts to load all types from the assembly to resolve the entities. If there is any error in this at all, it blows up. There are a number of reasons this can fail. Dependency mismatches, bad references, and other things that may not break your application but break this feature.

How can I fix this? I am sure you are asking this right now. “Damn it Brian, Get to the freaking point and the fix!” Fine.

It’s pretty simple.

Set this property on the EntityDataSource in your .aspx file. ContextTypeName .

The value? Well, the full namespace and class of your context. Example. Seekford.Data.MyEntityContext

More detailed example:

<asp:EntityDataSource … ContextTypeName="Seekford.Data.MyEntityContext" />

Happy coding!

A new guard page for the stack cannot be created


You get a nice error that says, “A new guard page for the stack cannot be created”, well easy fix. I could be long winded, but the issue is simply this, you caused a stack overflow.

How you say? Well, check to see if you are using a Server.Transfer that transfers you to a page that then Transfers you back and forth, or even to yourself.

Have login code that checks to see if you are logged in? If not, then it bounces you to a login page. Maybe you put it in a master page. Well, if the login page uses the master page, it will just keep transferring itself to itself and you blow the stack.

Response.Redirect will give you a different error as the browser only jumps a low number of redirects before giving up. Server.Transfer uses the internal stack, so it blows up on the server itself.

Happy coding!

How to optimize download performance for files stream from your database via asp.net

I had a requirement to create a download page that streamed office documents to the client from our website. The way Office (Word and Excel at least) open documents from URL’s are the browser downloads it first, then Word and Excel call back to the server to make sure nothing changed.

Normally, these results in you streaming the file twice, unknowingly. That is bad for performance and your bandwidth. No one wants a laggy and latent operation.

So, what is there you can do? Well, if you intercept the headers to a normally hosted document, you will see a header called ETag. This is basically a document hash reference that can be used when the follow request occurs.

Ok, English right.

So, the solution I implemented is pretty easy. I created a unique hash tag (it can be a true hash, or simply a rowid and the recordtimestamp combined) and set the ETag header.

You ask, “Well, how does setting an ETag header prevent duplicate efforts?”. It doesn’t. Here comes the work you do first.

When a request comes in. Look for a header called: IF-None-Match. If you see it, you need to jump into a little simple logic.

First, calculate your Etag value and compare it to the value of the If-None-Match and if it, well, matches, you get to do something special. If it doesn’t match, act like nothing happened and continue on with the normal data return.

So, what is the something special you ask? Simple, Clear your response contents, set your StatusCode to 304, and end the response .

Now I hear, geez. You made this sound very complicated. Is there an easier way to explain this?

Sure…I’ll try.


Here are the steps for simplicity:

  1. Check for If-None-Match header
    1. If Exists, compare value of header to your hash(id combo, CRC, whatever you want to use)
      1. If Matches,
        1. Set StatusCode =304,
        2. Clear Response Contents
        3. End Response
      2. Else.
        1. Continue as normal
  2. Normal Winking smile
    1. Generate ETag hash (again, however you want to identify this file as unique, something that changes if the file changes)
    2. Response with ETag in header

What does that mean in code? I don’t speak flow.

Here is a code example.

  private const string _wordMimeType = "application/msword";// (for Microsoft Word files)
    private const string _excelMimeType = "application/vnd.ms-excel"//(for Microsoft Excel files)
    private void StreamDocumentfromDatabase(Guid documentID)
        string etagFilter = Request.Headers["If-None-Match"];
        string etag;
        //load the bits into memory
        using (var context = new EvidenceReviewContext())
            if (!string.IsNullOrEmpty(etagFilter))
                //check db to see if to respond with ignore (cached copy already found)
                var blobCheck = (from ev in context.Documents
                                 where ev.documentID == documentID &&
                                 select ev.BlobDataId.Value
                if (blobCheck != null)
                    if (etagFilter == (documentID.ToString() + blobCheck.ToString()))
                        Response.StatusCode = 304;                       

            var theBlob = (from ev in context.Documents
                           where ev.documentID == documentID &&
                           select new
                               Data = ev.BlobData.Data,
                               FileExtension = ev.FileExtension,
                               BlobID = ev.BlobDataId.Value

            if (theBlob == null)

            if (theBlob.FileExtension.ToLower().StartsWith(".doc"))
                Response.ContentType = _wordMimeType;
            else if (theBlob.FileExtension.ToLower().StartsWith(".xls"))
                Response.ContentType = _excelMimeType;
            Response.AddHeader("Content-Disposition", "attachment; filename=" + documentID.ToString().Replace("-", "") + theBlob.FileExtension);
            etag = documentID.ToString() + theBlob.BlobID.ToString();
            Response.AddHeader("ETag", etag);

            //Write the file directly to the HTTP content output stream.

            //NOTE: THIS IS NOT MEMORY EFFICIENT AT ALL. TODO: change compression technique for documents
            byte[] dataToSend = null;
            using (MemoryStream dataStream = new MemoryStream(theBlob.Data))
                using (MemoryStream stream = UnzippedData(dataStream))
                    dataToSend = stream.ToArray();
            //relieve some pressure by pushing write of data outside of the blocks above to allow for memory free.

I hope this article helped you out a little and saved you some serious download times. (When Office revisits the file, it remembers the ETag. So you get efficiencies all over the place).

Happy Coding!

How to fix Handler “PageHandlerFactory-Integrated” has a bad module “ManagedPipelineHandler” in its module list

If you did what I did, and just picked the default IIS installation options for your Windows 7 box, then you probably get a bunch of fun errors.

This one is if you didn’t install IIS support for asp.net. (WHICH SURPRISE, IS NOT DEFAULT SELECTED)

This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny"), or set explicitly by a location tag with overrideMode="Deny" or the legacy allowOverride="false".

The fix is to install ASP.NET support. Easy.



Now, why the error from the title? Why no PageHandlerFactory blah blah blah? Well, .NET didn’t register itself with IIS the way it wants, so you need to rectify that.

That is also easy. Never hard if you have the right tool, it’s finding the right tool that is hard.

Open a Command prompt with Administrative Privileges. (Key, otherwise it doesn’t work).

go to your Framework folder. %WINDIRMicrosoft.NET

Pick the one you are working with, and the right bit type. i.e. 64 if your on 64 bit. Then the right version. I use 4.0

Call aspnet_regiis.exe -i




Voila, your done. Restart IIS and try your page again.

VS 2010: An error occurred loading a configuration file: Failed to map the path ‘/’.

I was using the System.Web.Configuration.WebConfiguration class to open the configuration for the site from one of my logic dll’s and I got the wonderful error An error occurred loading a configuration file: Failed to map the path ‘/’.

I freaked out for a second, until I put more thought into it. This is running fine in production! What is the difference with my machine and the server?

Oh! My Visual Studio is running under UAC with limited privileges since I am in Windows 7. DUH!

So, I restarted Visual Studio 2010 under “Run as Administrator” and problem solved. So if you are on Vista or Windows 7, that’s the issue.

NOTE: If you develop with administrative rights, be careful you don’t make development mistakes that assume everyone will run your program as an admin. i.e. writing to program files directory, root directory, etc.

Happy Coding!

HttpRequestValidationException after upgrading to .NET 4.0

The new .NET 4.0 changes the way that the page validation occurs. It puts in validation in more places now which can cause some issues.

<httpRuntime  requestValidationMode="2.0" />

If you want to revert back to the old validation, just make the following change to your web.config.

Make sure you set the validateRequest = false on the page or in the Pages element.

You can check out what Microsoft has to say here.

Happy Coding!

EntityDataSource WHERE filter not filtering the Data set in your grid…

I spent the last hour beating my deciding on which way to destroy my computer, as I battled why my Telerik RadGrid was failing to show the filter data set from my EntityDataSource. (Yes, lazy using these visual controls, but for reports they work well and easy)

Turns out, I had Filtering ON on the data grid. Apparently that disregards the WHERE filter on the data source. Well, that’s a pile of crap.

Anyway, turn off grid filtering or provide your data some other way to the data grid.

Hopefully this saves you time.

Happy coding!

Obvious Tip: How to turn on Tracing in Asp.net

I was wanting to look at my session state variables and a few other tracing bits in my ASP.NET application. It’s fairly easy to turn on and it makes for a nice and nasty look page.

Either way, it proves quite helpful to get those really ugly issues solved fast.

Just add this to your configuration file:

<trace enabled="true" requestLimit="40" localOnly="false"/>


<trace enabled="true" requestLimit="40" localOnly="false"/>

Notice, localOnly needs to be false if you are not actually on the physical server. Duh!

You can read much more about this over @ Microsoft.

Happy Coding!

Validation ($SCHEMA$): Element ‘html’ is not supported in Visual Studio 2010 asp.net

I upgraded to Visual Studio 2010 Beta and so far it has been a pretty good experience. One thing that bit me was building my project to find I had over 4,000 warnings. Geee. I didn’t think I coded that badly.

Well, it turns out each one was a warning about almost every single one of my aspx pages html tags. So, WTF?

This manifests itself not only as the

Validation ($SCHEMA$): Element ‘html’ is not supported

but all your other tags.

Validation ($SCHEMA$): Element ‘div’ is not supported ,etc.

It turns  out the default settings for the validator was, wait for it……NOTHING. Freaking blank.

The resolution was that the validator had no idea what to validate against, so everything was wrong. Simple solution though, just set the validation type in your options box.

Visual Studio 2010 Options Box

Enjoy! and Happy Coding!