Archive for the 'ASP.NET' Category

If you are using the AJAX Control Toolkit you’ve probably noticed the ToolkitScriptManager server control.

One of the great features of the ToolkitScriptManager that comes with the AJAX Control Toolkit is its ability to combine all client side scripts that needs to be loaded in the browser into one request, thus saving the browser’s need to issue multiple requests to the server and speeding up the process of loading the page.

The URL of that combined request contains a hash code of each script that should be combined, so if you have different combinations of client side scripts due to different combinations of controls you are using from the AJAX Control Toolkit you will have a unique URL for each such request.

“So what’s in it for me?”, you ask.

It’s simple. Since these scripts are only changed when you change the AJAX Control Toolkit version (and that only happens once in a while) and these scripts can be quite large (even when Gziped), they are perfect candidates for being delivered from a Content Delivery Network (CDN).

In short, CDN can make your site faster by delivering static content (i.e. images,scripts,static html files, etc) from a location closer to the user making the request. It does that by performing the request on behalf of the user requesting that resource, caching it for a certain period of time and distributing it to server that are geographically closer to the user.

In most CDN systems you need to change the hostname of the resource you wish to be fetched from a CDN to something that was preconfigured to work with your site. The problem with the AJAX Control Toolkit is that it is the one that renders the link to the combined javascripts and you have no control over it.

Luckily the designers of the ToolkitScriptManager class thought about a hook that allows you to change the handler URL of the combined scripts.

If you’ll set the “CombineScriptsHandlerUrl” property with a URL that refers to a CDN you’ll make these scripts get downloaded through the CDN, thus making your site load faster.

For example, instead of having the combined scripts URL look like this:

MyPage.aspx?_TSM_HiddenField_=ctl00_ScriptManager_HiddenField&_TSM_CombinedScripts_=…

It will look something like this:

http://mycdnsubdomain.mysite.com/MyPage.aspx?_TSM_HiddenField_=ctl00_ScriptManager_HiddenField&_TSM_CombinedScripts_=…

This will actually make a request to the CDN instead of going directly to your site since “mycdnsubdomain.mysite.com” is a domain mapped to the CDN (of course not all CDN networks work exactly like that, but most of them work in this manner where you map a certain subdomain or another domain to the CDN).

It’s a rather quick and easy way to boost your site’s load speed with very little effort. Keep that in mind when you need to optimize the client load side of things.

Debug.Assert lets you check various things during the debugging process or when you are a debug build.

One of the problems with Debug.Assert is that it pops up a MessageBox dialog. UI dialogs are a big no-no in server applications since there are scenarios in which this UI dialog will never be show and your server application will simply get stuck waiting for someone to push the buttons of the dialog.

One of the most common cases in which you will not see the dialog is when your server application runs under different credentials than your currently logged on user. In that case the UI dialog will hide somewhere in a different sessions without any chance of being seen by any other user.

.NET employs various huristics to figure out when to display the assert dialog. In most cases, in a server application it will not show the assert dialog at all (even in debug builds). As far as I could tell (and its currently just an calculated guess), if you have a debugger installed and registered as a debugger, .NET WILL display the dialog and that may pose a problem if your server application runs under different credentials than the currently logged on user.

It seems there is a way to overcome this by using a configuration flag.

Add the following section to your web.config (or app.config for applications other than ASP.NET) and it will disable poping up a UI window in your application which make cause it to deadlock:

<system.diagnostics>
<assert assertuienabled=”false” />
</system.diagnostics>

If you have any trace listeners that might popup a UI window you can also add the following configuration in your web.config that will clear all trace listeners:

<system.diagnostics>
<trace>
<listeners>
<clear/>
</listeners>
</trace>
</system.diagnostics>

If you are not sure this is really your problem, its very easy figuring it out using WinDbg, by attaching to the process, loading the SOS.dll and running the command:

~*e!clrstack

This command will show the managed call stack of each thread in the application (some of these threads are not managed so they might return an error and you can safely disregard them).

If you’ll see in the call stack a call to “Debug.Assert” followed by “MessageBox.Show” you can be certain that this is the problem you are facing.

Typed DataSets are a type safe wrapper around a DataSet which mirrors your database structure. It was created to make sure that the code accessing the database is type safe and any changes in the database structure that changes tables, columns or column types will be caught at compilation time rather than runtime.

If you have a big typed dataset that contains a lot of tables, columns and relations it might be quite expensive to create it in terms of memory and time.

The main reason that creating a big typed dataset is expensive is due to the fact that all of the meta data that is contained within the typed data sets (tables, columns, relations) is created when you create a typed dataset even if eventually all you’ll use it for is to retrieve data from a single table.

I can speculate that the reason all of the typed dataset meta data is created during the instantiation of the typed dataset is due to the fact that it inherits from a generic DataSet and accessing the meta data (tables, columns) can also be done in a non type safe manner (i.e. access the Tables collection and/or Columns collection of a table).

If you are using a typed dataset (or dataset in general) you might be interested in the following tips:

  • If you have a big typed dataset, avoid creating it too many times in the application. This is specifically painful for web applications where each request might create the dataset. You can use a generic DataSet instead, but this might lead to bugs due to database changes and the fact that you’ll only be able to find these bugs during runtime rather than compilation time (which basically misses the whole point of using a typed dataset in the first place).
  • DataSets (typed datasets included) inherits from the MarshalByValueComponent class. That class implements IDisposable which means DataSets will actually be garbage collected after finalization (you can read more about finalization and the finalizer thread here). To make sure datasets are collected more often and are not hagging around waiting for finalization make sure you call the “Dispose” method of the dataset (or typed dataset) or use the “Using” clause which will call “Dispose” for you at the end of the code block.
  • Don’t use DataSets at all 🙂 Consider using a different data access layer with a different approach such as the one used in the SubSonic project.

I guess it would be rather trivial creating a typed dataset that is lazy in nature which creates the meta data objects only when they are accessed for the first time. That would reduce the memory footprint of a large typed dataset but will make the computation used to create these objects a little less predictable. If you are up to it or already did a lazy typed dataset ping me through the contact form 🙂

If you mix and match 32 bit machines/processes with 64 bit machines/processes in an ASP.NET load balanced environment and you are using the AJAXControlToolkit ToolkitScriptManager class you might end up with the following error:

Message: Assembly “AjaxControlToolkit, Version=1.0.10920.32880, Culture=neutral, PublicKeyToken=28f01b0e84b6d53e” does not contain a script with hash code “9ea3f0e2”.
Stack trace: at AjaxControlToolkit.ToolkitScriptManager.DeserializeScriptEntries(String serializedScriptEntries, Boolean loaded)

at AjaxControlToolkit.ToolkitScriptManager.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

The reason is that the request being sent to retrieve the combined javascripts of the control used in the page contains a hash code that is used internally. That hash code is being generated from the script’s name using the default string.GetHashCode function which returns different values for 32 bit and 64 bit processes.

If your 64 bit process creates the javascript include call which contains the 64 bit hash code and the request will eventually reach the 32 bit process/machine you will get this error since the hash value will not be found internally and vice versa.

There is an open issue about this in CodePlex since late January but as of the time of this post, the latest source version in CodePlex doesn’t have a fix for this.

Sometimes in ASP.NET when you are trying to access a certain page you might get the following error:

External component has thrown an exception

In some other situations in .NET you might get this error as well (not directly related to ASP.NET, but sometimes to Interoping code or COM code), but this is beyond the scope of this post.

In the cases that I’ve stumbled upon, the reason is usually related to on-the-fly compilations ASP.NET performs when first accessing a certain page on an application.

The main problem with this exception that it is less than informative 🙂 . The only way of actually figuring out what is wrong (if this is indeed a case related to compilation error like I’m talking about) is to dig deep using WinDbg.

Luckily, every compilation that runs inside ASP.NET uses an API that upon encountering an error will create an object in the heap called CompilerError.

To debug this issue perform the following steps:

  1. Attach WinDbg to the ASP.NET worker process (w3wp.exe in Windows 2003, aspnet_wp.exe in Windows XP/2000)
  2. Make sure you have CLR exceptions enabled (see this previous post about how to enable CLR exceptions in WinDbg).
  3. Try to access the page that is not working, it should throw an exception and WinDbg should break in.
  4. Run the following command:

    !dumpheap -type CompilerError

    This should produce a list of all CompilerError objects which should allow us to inspect them and see the exact compilation error.

  5. Now dump each of the objects using the following command:

    !dumpobject 0xXXXX

    Where 0xXXXX is the address of the objects listed in the list you got from the !dumpheap command.

  6. At that point you should see the CompilerError object itself and you can dump its errorMessageText member (it’s address is near its name) using !dumpobject which should show you the exact compilation error.

In my case, the problem was that in the web.config file under the <compilation> / <assemblies> element there was no reference to one of the AJAX.NET assemblies (System.Web.Extensions) which caused the page to fail during on-the-fly compilation.

Do remember that this exception sometimes has nothing to do with compilation. If you don’t have any object of type CompilerError or there are a few but they make no sense in regards to the page you are accessing it might be something else.

The ASP.NET Repeater control is a very useful patten that minimizes code and allows you to use templates to represent repetitive data.

All of you are probably familiar with it and use it quite often.

Yesterday I had a big fight with the repeater control, and since most of the Internet (actually search engines for that matter) is filled with lots of data about the Repeater control and how to use it, I couldn’t find the answer I was looking for.

Apparently it was staring me right in the face.

The problem was that I needed to display a list of words with a comma separator and they should have looked like this:

word a, word b, word c, word d

but what I got was this:

word a , word b , word c , word d

An additional and unwanted extra space before the comma.

That code that I used in the ASPX file was this:

<asp:Repeater>

<ItemTemplate>

<% #Eval(“Text”) %>

</ItemTemplate>

<SeparatorTemplate>, </SeparatorTemplate>

</asp:Repeater>

All seems well, right? there is no space before the comma in the separator template, but there was when the whole thing was rendered.

The fix was quite stupid (and is quite fragile):

<asp:Repeater>

<ItemTemplate>

<% #Eval(“Text”) %></ItemTemplate>

<SeparatorTemplate>, </SeparatorTemplate>

</asp:Repeater>

The extra enter which placed the </ItemTemplate> element in a new line was the cause of this problem. That new line was translated in this case into a single space which made everything look weird.

It seem that the Repeater control (and possibly other template based ASP.NET controls) are sensitive to the ASPX formatting. They are not trimming the edges of content that resides inside the template ASPX element, thus making them susceptible for formatting weirdness.

The worst problem of all is that when you use Visual Studio’s auto formating (Ctrl-E, Ctrl-D by default, if I’m not mistaken) it will ruin the layout and you might end up with a Repeater that has an extra space even if you didn’t want it.

I can understand why the edges were not trimmed, so that you can and should be able to enter white spaces as part of your template, but Visual Studio itself when formatting a document to be more clearly read will mess things up and that is the true problem.

While this is not a “real” advanced .NET debugging issue and I didn’t use any cool tools to figure it out it annoying nonetheless 🙂

It is often overlooked, but Response.Redirect has an overloaded method which has two parameters.

The first is like the overloaded version which gets only one parameter – the URL to redirect to.
The second is whether to end the request now or let it complete and only then redirect.

By default when calling the first version:

Response.Redirect(“http://somewherenice.com”);

It will actually call the following code:

Response.Redirect(“http://somewherenice.com”, true);

This means that the request will end right after the execution of the Response.Redirect function and no other code that is hooked to events that occur after the place in which you called Response.Redirect will execute.

For example, if you have a certain code at the Page_PreRender event and you are calling Response.Redirect in the Page_Load event (either on the page or in a control on the page), without using the overload version of Response.Redirect that gets two arguments and setting the second argument to “false”, the code in the Page_PreRender event will never get called.

While this seems very trivial, there are a lot of bugs that sometimes occur because people forget the Response.Redirect with one parameter stops the execution of the request.

Every time you call Response.Redirect, stop for a second and think if you really want to end the request at that point or let it continue to process until it finishes.

If you want it to continue processing the page and perform the redirection after the processing is done use the following code:

Response.Redirect(“http://somewherenice.com”, false);

Thinking 2 seconds before writing a Reponse.Redirect code can save a lot of minutes debugging and figuring out that you never reach the other code because the request ended at the Response.Redirect call.

UPDATE: Fixed the last sample, thanks to Eber Irigoyen

Perhaps its just another case of RTFM but I might have a point here. Really.

I was using AJAX.NET and wanted to attach some silly handler to the “onmousedown” event of a link (“<a href”). I used the nice little $addHandler method in the following syntax:

$addHandler(myElement, “onmousedown”, myHandler);

And to my surprise it didn’t hook up anything.

I did what any developer would do, plunged back to the documentation and after a bit of a careful reading I saw the following line:

“The eventName parameter should not include the “on” prefix. For example, specify “click” instead of “onclick”.”

Now why should I care if I’m writing “onclick” or “click”. The convention used in browsers is “onclick”, after all that’s what you put on an element if you want to add an “onclick” handler in HTML.

Why would anyone want to break this convention. And even if you do decide to break it, adding a simple “if” or checking for the characters “on” at the start of the string and removing them would be nice.

Anyhow, I quickly changed the code to:

$addHandler(myElement, “mousedown”, myHandler);

and everything started to work wonderfully.

At least I’ve learned something new, that the eventName passed to the $addHandler function should not contain the “on” prefix. I also re-learned again that I should always RTFM, even the fine prints in the “Remarks” section.

At my day job, we started getting a strange compilation error when accessing one of the pages (the ASPX file).

Upon first access to an ASPX file, ASP.NET parses the ASPX file and combines it with the ASPX.cs/ASPX.vb (code behind) to create one single .cs/.vb file, compile it and loads it into the memroy.

The error was quite strange:

The type or namespace name ‘Compatibility’ does not exists in the namespace ‘System.Web.UI’ (are you missing an assembly reference?)

This was just a simple page. Not fancy AJAX code. You can see how it looked when I set customErrors=”true” in the web.config here.

After digging a bit more, I’ve turned on the debug=”true” in the <compilation> tag in the web.config file and got a more details error (look at the screenshot here).

I was not familiar with any System.Web.UI.Compatibility namespace in ASP.NET so I searched throughout the project. I came across this namespace in the web.config file itself in the <system.web> \ <pages> \ <tagMapping>.

This set of configuration tags is added for use with AJAX.NET and it simply says that if you see System.Web.UI.WebControls.CompareValidator replace it with System.Web.UI.Compatibility.CompareValidator that is found at System.Web.Extensions – System.Web.Extensions is one of the AJAX.NET assemblies.

A light bulb flickered above my head and I figured that the problem was in the ASPX compilation.

When you set debug=true in the <compilation> tag in the web.config, the path at the bottom of the error page will actually include the temp .cs/.vb file ASP.NET has created as well as a few .cmd file which are in fact the command line passed to the C#/VB.NET compiler to compile the code.

I checked it out and it seems System.Web.Extensions was missing from the command line.

I’ve added it to the <compilation> \ <assemblies> and it worked.

I still don’t know what is the exact cause of this problem, but I figured having an extra reference in the compilation shouldn’t cause any harm. At least for now.

In my previous post about problems with wrongful escaping of the query part in the uri in Request.QueryString, I’ve received a comment from a reader named DuncanS saying that he encountered a similar behavior with the Uri class.

It seems Uri.ToString() function will perform unnecessary unescaping of the different parts of the Url that were escaped (like the query part) to be unescaped.

His solution to the problem is to use Uri.AbosluteUri instead which does not exhibit this behavior.

Thanks for the tip Duncan!