“The underlying provider failed on Open”

If you get the above exception message from accessing your database via the Entity Framework after you’ve deployed your web application or service to IIS (7.5), it is probably because of the DefaultAppPool Identity. Changing it to LocalSystem solved this problem for me.

Here’s how you do it:

Go to the ‘Advanced Settings’ for DefaultAppPool:




In the Advanced Settings dialog, look for Identity under Process Model:



Change it to LocalSystem:



And you’re done!

Posted in Uncategorized | Leave a comment

Quick & Dirty: Download A File From The Internet

Here’s a quick and dirty way to download a file from the internet:

public bool DownloadFile(string sourceUrl, string targetFilePath)


      byte[] buff = new byte[MASSIVE_NUMBER];




            WebRequest req = WebRequest.Create(sourceUrl);

            WebResponse response = req.GetResponse();

            Stream stream = response.GetResponseStream();

            BinaryReader br = new BinaryReader(stream);


            buff = br.ReadBytes(MASSIVE_NUMBER);




            FileStream fs = new FileStream(



            fs.Write(buff, 0, buff.Length);



      catch (Exception e)


            Debug.WriteLine(“Exception: {0}”, e.Message);


            return false;




      return true;





It looks like practically the entire function is in the try-block. Let me say that I vehemently discourage the indiscriminate wrapping of the entirety of functions in try/catch blocks as a form of ‘protection’. If you practice that, I suggest you stop it yesterday. Anyway, as for the above sample, practically all the code in the function can clap-out due to I/O errors, which is one of the very very few true exceptions. So that is why, they’re all in the try-block.

As you can see, it is a very quick, and dirty way to download a file from the internet. Quick, because the code is short and simple. Dirty, because it is synchronous, and attempts to just read the whole file by asking for some massive number that should be larger than the file in question. Do use a suitably big but not excessively large MASSIVE_NUMBER number as this dirty way allocates a buffer with it.

Posted in Uncategorized | 4 Comments

Win9X? What is that?

While mucking around the .NET framework sometime back, I stumbled across something I thought was kind of funny. Funny only in that I had almost forgotten about it (kind of). Anyway, I was working on a demo, and was checking out what goes on under the hood of a file open as such:

      Stream f = File.Open(@”C:\windows\system32\ntoskrnl.exe”,





And here’s what it eventually ended up calling somewhere down the line:


Here’s the callstack:


Here’s the registers, when the IP (Instruction Pointer) is at the 3rd line of the IsWin9X() function:


And looking at the code of IsWin9x(), it calls a function immediately: System.Environment.OSVersion.get()




Now, let’s take a look at the return value of this function. The 3rd line of IsWin9X() indicates that it is a struct:

00000000  call        FFFF6E80 
00000005  mov         edx,eax 
00000007  cmp         dword ptr [edx+10h],1 
0000000b  sete        al 
0000000e  movzx       eax,al 
00000011  ret 


It is most certainly at least an OSVERSIONINFO struct (if not an OSVERSIONINFOEX) that was returned. I didn’t bother to verify it at the Win32 level, but System.Environment.OSVersion.get() most probably called GetVersionEx(). A good indicator that it is an OSVERSIONINFO struct is the offset referenced in that 3rd line of code: 10h (0x10/hex 10). That would be the 5th DWORD (4-byte value). Let’s see what the memory contents are based on the address in the eax/edx registers (image above):


You can see the 5th DWORD highlighted above, and the value is 00000002. And from that same 3rd line of code, it is comparing it with the value 1. Let’s see what the OSVERSIONINFO struct (Unicode version) looks like in WinNT.h:

typedef struct _OSVERSIONINFOW {

    DWORD dwOSVersionInfoSize;

    DWORD dwMajorVersion;

    DWORD dwMinorVersion;

    DWORD dwBuildNumber;

    DWORD dwPlatformId;

    WCHAR  szCSDVersion[ 128 ];     // Maintenance string for PSS usage



According to that, it is checking the field dwPlatformId. And here are the possible values in WinNT.h (you may refer to the link above for OSVERSIONINFO):


// dwPlatformId defines:



#define VER_PLATFORM_WIN32s             0


#define VER_PLATFORM_WIN32_NT           2


Aha! So it is checking if it is indeed Win9X! And since I’m running WinNT (Windows 7), you can see from the memory window above that the value for that field is 2. So this looks like it is the OSVERSIONINFO struct. However, the first three DWORD’s look like absolute rubbish. I have no idea.

And finally, IsWin9X() basically returns 1 (true) if dwPlatformId is 1, and 0 (false) otherwise. Well, I know the .NET Framework supports Windows 98 and above, and not Windows 95, so I guess it’s checking to see if it is Win98. Since I don’t have any running Win98 anymore, I can’t check to see how System.IO.FileStream.Init() will behave otherwise… I’m not even sure I’d bother if I could. Win9X is dead. Long live WinNT.

Posted in Uncategorized | Leave a comment

Awesome Operators

Some operators are just more awesome than others. Here are some of my faves. Let’s start with the ternary conditional operator (?:). I have loved this one since C, and is one of those that cannot be overloaded (another awesome feature) in C++. Here’s its definition:

condition ? first_expression : second_expression;

If the condition is true, the first_expression is returned, and second_expression if false. You can think of it as a good one liner for an if-else expression. Very useful when you want to stick a conditional evaluation into another expression, such as a function call. Here are some examples of use:

    uint u = hours.TotalMinutes > 0 ? Convert.ToUInt32(hours.TotalMinutes) : 0;


    // For nullable types

    data.Content = row.items.HasValue ? row.items.Value : 0;


    string.Format(“Has Value: {0}”, count > 0 ? “TRUE” : “FALSE”);


    var v = b ? Foo(“Yes”) : Bar(“No”);



As you can see, it’d be not as brief writing the above with if-else expressions.


This brings me to the next awesome operator… The null-coalescing operator (??). From MSDN:


“The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.”


So this operator is like a specialized ternary conditional operator for null’s. Isn’t that neat? Here are some example uses:



      private void Foo(List<string> items)


            DoSomethingWithList(items ?? new List<string>());



      Debug.WriteLine(“Message: {0}”, message ?? “There is no message”);


      // For nullable types

      int? magic = GetMagicNumber();

      int result = magic ?? 0;



I think it’s a great convenience for handling null’s, and works well with Nullable types of course. And for those who are not aware of Nullable types, it’s another neat feature of .NET. It can be defined in two ways (from MSDN):


System.Nullable<T> variable


T? variable

T is the underlying type of the nullable type. T can be any value type including struct; it cannot be a reference type.


You may have happened upon situations where you have parameters that are value types that can be ‘ignored’. But since they are value types and not reference types, you can’t get a value of null to have it indicate that you should ignore it. For example:

      private void Foo(int value1, int value2)


            // I want the caller to be able to let me know

            // if they want they parameters to be processed

            // or not. Maybe only positive values are valid

            if (value1 >= 0)





            if (value2 >= 0)







Well, in a language like C/C++ that has pointers, it could be easily sorted out with passing the two two int params in as pointers and a NULL would indicate that the function should ignore it. Very standard practice in both the managed and unmanaged code (for reference types). So in the case above, if the parameter values are only valid if they are non-negative, then they should be unsigned in the first place. If it were, then how in the world would we indicate an ‘ignore’ for the parameter?

      private void Foo(uint value1, uint value2)


            // This doesn’t make sense anymore…

            // How now brown cow?

            if (value1 >= 0)







This is exactly where a nullable value type is needed. And to declare one, you can just suffix a ‘?’ to the type:

      private void Foo(uint? value1, uint? value2)


            // Now we is rockin’!

            // test it like this

            if (value1 != null)





            // or like this

            if (value2.HasValue)







Now you can do this kind of null testing on non-reference types with this. Awesome!

Posted in Uncategorized | Leave a comment

C# XOR Compiler ‘Error’

I may as well start with my pet peeve… The C# compilers failure to generate correct code for the following expression:

a ^= b ^= a ^= b;

Before C#, I (and many others, I’m sure) used that in C. For those who are not familiar with that expression, it basically swaps the variables a and b. They’re usually a numeric type.

So, way back in 2003 (using Visual Studio 2003), some friends and I were testing out swap functions to see which one was the fastest, and I tried this XOR swap. I took notice when I started getting bizarre results. You can try it out for yourselves.

Now, let’s take a look at the generated code (x86) for that expression:

			mov         eax,dword ptr [ebp-44h] 
			mov         dword ptr [ebp-4Ch],eax 
			mov         eax,dword ptr [ebp-48h] 
			xor         dword ptr [ebp-44h],eax 
			mov         eax,dword ptr [ebp-44h] 
			xor         dword ptr [ebp-48h],eax 
			mov         eax,dword ptr [ebp-4Ch] 
			xor         eax,dword ptr [ebp-48h] 
			mov         dword ptr [ebp-44h],eax

And if you translate that back into C# (or C for that matter), it is:

			temp = a;
			a ^= b;
			b ^= a;
			temp ^= b;
			a = temp;

As you can see, the compiler makes use of a temp variable, and it basically makes a mistake with it. In the assembly above, it makes the mistake at line 7. It used the initial value of a which it saved in the beginning instead of the new value by the earlier XOR operations. By the time it gets to that last XOR, b already has the value of a, and therefore results in a zero instead of a correct swap.

Others have encountered this, and there has been some debate about how C# evaluates such expressions. Regardless, such expressions have to be evaluated from right-to-left. However, it seems the compiler uses the ‘old’ values for the left operand, and just by luck, it got the first b (from the left) XOR right as it wasn’t modified in the first XOR operation (right most). So how did the Microsoft C compiler get it right? Because it uses the latest values for a and b each time one of the XOR’s is processed. This is the correct way to do it, and you would then get the results you expect.

Therefore, if this is a ‘feature’, it’s hard to say it is a good one by any stretch of the imagination. It must be a bug. And not only that, it is still there in Visual Studio 2010. I can understand that this is a low priority issue if it is indeed a bug as it can be easily worked around by breaking up the expression into the more obvious:

			a ^= b;
			b ^= a;
			a ^= b;

Don’t you just love it when it ain’t your fault?

Posted in Uncategorized | Leave a comment