Random thoughts of wisdom - the personal blog of Michael Holm Andersen

InvalidCastException on linq DB submit with non-integer key – aka LinqToSQL bug

Wasted a whole day on a (confirmed) bug in LinqToSQL. The problem is this:

“When database contains two tables, both with automatic integer primary keys, and a relationship between a unique char field in one and a non-unique char field in the other, inserting new rows into the second table fails on submit with InvalidCastException"

The error returned be LinqToSQL is: specified cast is not valid

I have a table which contains a char column which is ForeignKey to a unique char column in another table. In my case the column is “CurrencyISO” (e.g. the value DKK) in one table which has a FK relation to a unique ISO4217_ISO column in my Currency table.

Running on my development machine (Windows 7, x64) the code executes without problem – however running on my development server (Windows Server 2008 Web edition, x64) LinqToSQL at random (more or less!) throws the exception: specified cast is not valid

After having spend hours on the bug (I thought it was related to different OS and/or differences in MS SQL Server or something other “weird”), I found this article on Microsoft Connect which confirms the bug and the message “I can confirm that this bug has been fixed for .NET 4.0, which is why it's still failing with .NET 3.5 SP”

However a hotfix is available (and it will fix this bug!) – You can download yourself from Connect or if you’re running an x64 OS (Vista and/or Windows Server 2008), you can simple download the below .ZIP file which contains the hotfix (I’ve installed this on my Windows Server 2008 Web edition (x64), rebooted (an IIS reset should be enough!) and finally the bug was gone!!

Grab the hotfix (NDP35SP1-KB963657-x64.exe) for x64 platforms here:

Shortcut key to View Source in IE

I was asked if I knew the shortcut key for “View Source” in Internet Explorer .. and strange enough Microsoft have decided not to make a real (direct) shortcut, so we have to go through the menu:

Alt+V, C

.. maybe it’s a wish for the IE 9.0 feature list :-)

Network commandline tools contains some nice network related tools, e.g. “whois.exe” and “httpget.exe” which will (as the names imply) make a WhoIS lookup and GET the requested URL (and save content to disk) – very useful..

Windows 7 shortcut keys

Windows 7 with the new Taskbar has a number of new and nice keyboard shortcut which will make your everyday life much easier. The most useful ones are…

Window handling

Windows + Up Arrow – Maximize window

Windows + Left Arrow – Snap window to left side covering half of desktop space. Continue pressing the keyboard shortcut will rotate the window between snap to left, snap to right and restore to normal position.

Windows + Right Arrow – Snap window to right side covering half of desktop space. Continue pressing the keyboard shortcut will rotate the window between snap to left, snap to right and restore to normal position.

Windows + Down Arrow – Minimize the window. Restore to normal size and position if the window is currently maximized.


Windows + D – Show desktop and restore desktop (minimize or restore all windows).

Windows + M – Minimize all windows.

Windows + T – Show preview thumbnail of running applications in Windows Taskbar one by one without mouse over.

Windows + U – Open Ease of Access Center.

Windows + P – Display options.

Windows + F – Search window.

Windows + G – Bring all gadgets on top and foreground.

Windows + X – Run Windows Mobility Center.

Windows + R – Open ‘Run’ command.

Windows + E – Run Windows Explorer.

Windows + L – Lock the computer.

Windows + Pause [Break] – Open System Properties.

Windows + [number] – Activate and run the program pinned on Windows 7 Taskbar, running program won’t be affected (regular keys, not keypad).

Windows + Tab – Windows Aero Task Switcher

F1 – Help

F3 – Search

Taskbar modifiers

Shift + Click on icon Open a new instance

Middle click on icon Open a new instance

Ctrl + Shift + Click on icon Open a new instance with Admin privileges

Shift + Right-click on icon Show window menu (Restore / Minimize / Move / etc)
Note: Normally you can just right-click on the window thumbnail to get this menu

Shift + Right-click on grouped icon Menu with Restore All / Minimize All / Close All, etc.

Ctrl + Click on grouped icon Cycle between the windows (or tabs) in the group

IE8, cookies and local addresses that are not localhost

Recently installed Windows 7 which is really nice. IE8 is the default OS browser and typical the one I use as my “default development browser”, which means it is not my default browser (Firefox is), but it’s the browser that Visual Studio opens when I do a “View page in browser”.

I have multiple sites which use ASP.NET Membership (and hence use session cookies to keep me logged in). I typical change my ‘hosts’ file to something like this below, and of course set the ‘binding’ (host header) in IIS7 to match:    site1    site2    site3

(names have been changed to protect the clients :-)

However when I fired up VS2008 and tried to log into one of my sites which uses membership, I simply could not log in. After having done some HTTP Cookie debugging I realized that IE8 did not store my cookie. A fact that was proven correct as the same site worked fine i both Firefox and Chrome.

Surfing the net I found a that this is a “security feature” of IE8 – the thing is that if you have e.g.

Site: http://mha
Cookie domain: mha

should work, but if you do

Site: http://mha
Cookie domain:

..then it won't work, because IE sees that as security risk as does
not match the requested hostname.

Microsoft recommend that you should always name internal servers with
hostnames that are FQDNs, such as mha.local - This also helps to mitigate
problems such as DNS failures and use of suffix handling - eg. if the DNS
automatic suffix for a machine on your network is .com, and you name a
server mha, a request to http://mha could end up requesting
because of the automatic suffix handling.

So to get this to work you need to stop using single words for internal site
URLs and start using e.g. localhost.mha

So .. in order to make IE8 accept cookies from internal sites running on localhost / IIS7, and is mapped in your ‘hosts’ file we need to do a couple of thing:

1) Make sure you’re using a full qualified hostname, e.g. localhost.aspnethotelV25

2) In IIS7 make sure you’ve set up your hostname correctly in binding:


3)  In your ‘hosts’ file, make a matching entry:

# --- IIS7 / localhost ---    localhost.aspnethotelV25

4)  In IE8 make sure to add your site to always allow cookies:

  • Go to Tools –> Internet Options
  • Click ‘Privacy’
  • Click ‘Sites’
  • In Address of website, enter your host header name
  • Click ‘Allow’



That’s it!! – Finally your site, running on your own localhost / IIS7 which is using a different name that localhost or is now able to accept cookie (because we all know that cookies server up from localhost is a big security risk!?! :-)

Enjoy the wonders of Internet Explorer v8 (or simply use Firefox, Chrome or any other browser which just work out-of-the-box)

Sko/Torp @ skråen i Nordkraft


Yesterday, Hanne invited me down to skråen to listen to Sko/Torp .. if you ever get the chance to go to one of their “acostic live” sessions, don’t miss out – It’s an absolute pleasure to enjoy so talented musicians and what they can do with just two guitars and a keyboard.

PS: Sorry about the poor image quality – the “Magic” camera is not that great! :)

Setting DataContext Connection String at runtime

I’m working on a portal/e-shop solution where I’ll be using multiple databases and needs to change the Connection used by my DataContext object at runtime.

I use the HttpContext.Current.Items collection to store which connection is currently “active” - this is setup in the Application_AcquireRequestState event in Global.asax which fires for every request – and using the OnCreated method that is called as part of the DataContext’s constructors, I can easily change which connection to use at runtime.

The good thing about putting the “connection switch” in the OnCreated method is that no matter how I use the DataContext this code is always executed (I have a LinqUtil class which implement a request-scoped DataContext pattern for LINQ to SQL), and using the below approach I don’t have to worry about which Connection is used as this is transparent to any helper / DAL classes.

The code for the partial class which implements the OnCreated method for my DataContext looks (something!) like this:

   1: public partial class GWportalDataContext : System.Data.Linq.DataContext
   2:     {
   3:         // In order to use multiple database connections we use the HttpContext.Current.Items collection to store which database we're currently using (per request)
   4:         partial void OnCreated()
   5:         {
   6:             switch (HttpContext.Current.Items[ConfigurationManager.AppSettings["WebsiteHttpContextItemKey"]].ToString())
   7:             {
   8:                 case "GWDK":
   9:                     this.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["GWportalConnectionDK"].ConnectionString;
  10:                     break;
  11:                 case "GWNO":
  12:                     this.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["GWportalConnectionNO"].ConnectionString;
  13:                     break;
  14:                 default:
  15:                     this.Connection.ConnectionString = ConfigurationManager.ConnectionStrings["GWportalConnectionDK"].ConnectionString;
  16:                     break;
  17:             }
  18:         }
  19:     }

Consolas Font

After having used VS 2010 Beta2 for a while (which includes the Consolas font), I simply have to use this font in VS 2008 also – luckily a font pack is availabe for download:

Consolas Font Pack for Microsoft Visual Studio 2005 or 2008

“Dynamic” LINQ queries – using query composition and deferred execution


LINQtoSQL is GREAT, however we often need to perform dynamic queries, which is not directly supported by LINQ – however if we use the capability of LINQ to do query composition and deferred execution we can perform most of the ‘dynamic’ queries we need (without having to use the PredicateBuilder).

Take a look at this article which shows how to do “dynamic” LINQ to SQL queries just be using query composition and deferred execution:

If you like LinqDataSource (and the benefits it provide, e.g. automatic handling of sort etc.), but would like it to behave a bit more “dynamic”, you should take a look at the “Selecting” event. Scott Gu has an excellent article about just that – Enjoy! :-)

LINQtoSQL Samples

If you’re looking for some great LINQtoSQL samples look no further than MSDN.

As part of the 101 LINQ samples project, Microsoft has put together some nice LINQtoSQL samples – take a look at: