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 🙂

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.

First of all, let me apologize for the lack of activity in the blog. I’ve been abroad for about a month and that’s why I was slow on responding to comments (which I did for most of them, so go back and check it out) as well as posting here.

OK… Now that the sorry execuse is behind us, let’s get back to business from now on…. 😉

A reader named Kipp left some comments on my “Ambiguous match found” post. He had some problems making WinDbg break on CLR exceptions (like the ones generated by the compiler during the ASP.NET compilation of the page that eventually causes the “Ambiguous match found” error).

Kipp also asked the question on Yedda (disclosure: Yedda is my day time job) and I answered him.

I think this is an important piece of information that should be shared with everyone, so here it goes – How to enable and disable CLR exceptions breaking in WinDbg.

First, a little background about Structured Exception Handling (SEH) in Windows and the CLR.

CLR Exceptions in SEH World
In the regular world of Structured Exception Handling (SEH) each exception has its own specific exception code. All CLR exceptions are seen in the regular Windows world as the same type of exception since they all have the same error code.

The additional information of the exception is stored in the managed world and that is why you need the SOS extension to print it our, read it and see it.

WinDbg has a built in ability to filter in or out various exception codes and sometimes, the CLR exception code is not enabled causing CLR exception not to break in WinDbg.

Enabling/Disabling CLR exceptions in WinDbg

  1. Open WinDbg and make sure you are breaked into a program that you attached or run (if you need to break when attached simply press Ctrl-Break).
  2. Go to the “Debug” menu and select “Event Filters…”.
  3. Select “CLR exception” and click on the “Enabled” radio button in the “Exception” area.

UPDATE: Dan McKinley was kind enough to remind me that there are shortcuts that you can type in the WinDbg prompt to do what I’ve written above. To enable CLR exceptions type “sxe clr” and to disable type “sxd clr“. To view the list of exception types and their current status type “sx“. Thanks Dan!

That’s all, you are now good to go and any .NET exception that will be thrown (even ones that are caught eventually in the code) will break in WinDbg.
To disable, simply selected “Disabled” instead of “Enabled”.

I hope it will help you all!

While I don’t normally repost links and try to avoid it as much as possible, I’ve stumbled upon this post by Jeff Atwood (he works on CPU-based parallelism in the .NET CLR team sorry I mixed things up a bit. Jeff Atwood doesn’t work on the CLR team and not for Microsoft. David, thanks for pointing that out to me. I guess I just mixed things up a bit, since I also wanted to place a link to Joe Duffy’s post about thread priorities) about Thread Priorities.

Read it carefully and think twice before writing:

thread.Priority = ThreadPriority.BelowNormal

While the sample Jeff gives is for CPU starvation and the problem he is illustrating will likely be caused on machines with a single CPU, it IS important to understand that thread priorities WILL affect your application, sometimes in the worst possible way.

While I’m at it (“it” being doing a links post 🙂 ), Maoni (which got a GREAT blog about .NET and its internals) has a philosophical post about performance work. This post really highlights the fact that general fundemental knowledge is always useful when trying to understand a problem.

If pre-optimization is the root of all evil, fixing things that are not there or are not the problem is the fertizlier that makes the root of all evil grow and grow and grow, consuming your code!

While I know its been quite here due to my “other job” (which I highly recommend you check 😉 ), I have a few things down the pipe that will, hopefully, be of use to all of you.

A friend of mine asked me a question which reminded me a very important issue regarding STA (Single Threaded Apartment) COM objects in ASP.NET Web applications. STA COM objects were created so that most people won’t have to deal with threading issues. The COM framework itself will make sure that each call to any method in an STA COM object will be blocked so that other requests from other threads won’t be able to get into that certain method until a previous call exited it (they will be queued).

My friend tried to create an STA COM object within the web application. The COM object was suppose to access a network share on some other machine in the network.

The ASP.NET process was configured to use the default IUSR_XXX (where XXX is your machine name) user, which has little access to anything.

In order to access the network share we had to change the context of the calling thread, so my friend used the <identity> tag in the web.config to make sure each request to the page running this code will impersonate to the user specified in the <identity> tag.

The problem starts with the threading model of ASP.NET. ASP.NET threads which executes the various request it receives are MTA (Multi Threaded Apartment). When an STA COM object is created on an MTA thread, to actually being able to perform the synchronization that STA COM objects give, we will have to context switch to the default STA thread of the process (which is a dedicated thread for that purpose) and the COM object will be created there.

Here our problem starts. The <identity> tag makes sure that the thread executing the request (the MTA thread) will impersonate its security context to the user specified in the <identity> tag but our STA COM object eventually was created on the default STA thread which was not impersonate, causing it to get the security context of the process (which was IUSR_XXX – the least powerful user of all). This meant that when the STA COM object tried to access the network share it failed since it didn’t get the right credentials.

So, how can we solve this issue? There are a number of ways.

The easiest way of all is to change the user running the ASP.NET application. To do that in Windows XP or Windows 2000 you need to go to the machine.config file and change the username and password in the processModel section. It is not recommended to put your password in clear text in the machine.config. That is why Microsoft released this utility which will encrypt your username and password in the registry.

In Windows 2003, you’ll need to create a new Application Pool and make sure the identity of that pool is the needed user that can do all the necessary things, security wise, that your application needs to do.

Another option, is to use the identity flag as specified in MSDN but to add the ASPCompat attribute to the your page class (or enable it in the ASPX page as described here). This will make sure that each of your requests to that page will actually run in an STA thread instead of an MTA thread, so when creating an STA object from within this page, the object will be created on the calling thread (since we are already in an STA thread) which will have the correct identity (we are using the <identity> configuration in the web.config).

And the last option, which works in .NET Framework 1.1 SP1 and above and in .NET Framework 2.0 (though I haven’t tested it in .NET 2.0), is to add a special flag called “apartmentThreading” which essentially changes all of your page to work the same way as adding the ASPCompat attribute.

In any case, in order not to hurt performance and scalability too much, use as little STA COM objects as you can and specifically mark the pages calling these STA objects using the ASPCompat attribute. When you have to use an STA COM object, create it, use it and released it as soon as you can, preferably using Marshal.ReleaseCOMObject (which will force it to die as soon as you call this method instead of waiting for the next garbage collection. To get more information about what Marshal.ReleaseCOMObject does see my previous post).

Update 13/6/2006: Updated a few typos.

At my day job (which is part of the reason I’m posting less frequently) I’ve had to P/Invoke a bit and gathered some P/Invoke tips that I’ve decided to share.
Today’s tip is about P/Invoking and C style unions.

Let’s take the following union:

union MYUNION {
int number;
double d;
}

This is quite a standard union, which means its memory is contiguous. Its translation in C# would look like this:

[StructLayout(LayoutKind.Explicit)]
public struct MYUNION {
[FieldOffset(0)]
public int number;
[FieldOffset(0)]
public double d;
}

Notice two important things. First, the StructLayout attribute is set to LayoutKind.Explicit, this means that using the FieldOffset attributes we are building the memory layout of the struct and it will look exactly like this. When usually handling C structs in .NET and P/Invoking we usually use LayoutKind.Sequential so that the memory layout will be as described using the layout of the fields as we have put them.

The second important thing is the FieldOffset attribute. Notice that both fields have the same offset. This will tell the P/Invoke layer that these two fields are actually part of the same memory (remember, these two fields were declared inside a union!).

This is how unions will work for you in your P/Invoke code. Enjoy!

Technorati : , , , , , , ,
Del.icio.us : , , , , , , ,
Ice Rocket : , , , , , , ,

One of the big changes in P/Invoke in .NET Framework 2.0 vs. .NET Framework 1.0/1.1 is that you can now pass function pointers from a C API back to .NET.

In previous versions (1.0/1.1) you could pass a delegate as a function pointer to a C API, but could not receive a function pointer from the C API back to .NET.

This technique of passing a pointer from within the API is relatively common in more than a few APIs in Windows, where you have one function that initializes a special struct that simply contains pointers to various functions. This is like an interface for an unobject oriented language like C. It gives the designers of the API the ability to plugin and replace an implementation of a certain function dynamically depending on either the environment or parameters passed to the function that initializes the struct.

Quite cool!

This also means that various other Windows APIs (SSPI, for example) can now be called directly from C# and does not require a bridging C dll or writing a mixed (managed and unmanaged) code in C++ to glue things together.

I’ve previously covered a few of the common problems in P/Invoke code, so be sure to read that if you are facing problems when P/Invoking code!

I know I haven’t been posting much lately, but I’m a bit caught up in a startup I’m involved in called Yedda. It has taken most of my time, but I do find, once in a while, something to post like the “Ambiguous match found” problem, so bear with me 🙂

Today, I’ll give a small tip for !clrstack.

If you use !clrstack to show a managed call stack and you want to see the addresses of parameters that were passed to the functions without doing a lot of fancy shmancy WinDbg tricks simply run:

!clrstack -p

That’s all you need to do. This will list each function in the call stack and below it the name of the parameter and its address. From there on, you can use !do ( !do == !dumpobject – which shows a managed object) and see the content of the object.

Quite simple and very effective.

As a general rule of thumb, most SOS command have a very descriptive help. To use it, simply run:

!help <command>

i.e.

!help !clrstack

I’ve found this interesting post on Mike Stall’s blog.

Felice Pollano is working on merging MDbg (I’ve talked about it before here) with Reflector (the .NET disassembler) so one can debug application without having debug symbols and still be able to get a bit more information than just IL code (you’ll be able to choose the language that will be displayed while debugging)

This is definitely something that I will keep on tracking since it can provide a bridge between hard core WinDbg debugging, soft core MDbg debugging and Visual Studio debugging.