Go to content Go to navigation Go to search


Timer.Elapsed event – The Silent Killer
· 2009-02-26 12:54 by Thijs Kroesbergen for Brokenwire.NET

Yesterday we ran into some issue where exceptions would disappear into a black hole. We had some code running within the Elapsed event of a System.Timers.Timer which seemed to crash without us being able to catch the exception in our global “unhandled exception” exception handler. It looked like we had a Ninja in our code somewhere, deadly and accurate.

So we finally figured out what was happening and I’ll explain it to you here.

To start with the code to reproduce this looks like this:
An example project can be downloaded here: SilentKiller.zip

static void Main(string[] args)
    AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
    System.Timers.Timer aTimer;
    aTimer = new Timer(1000);
    aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
    aTimer.Enabled = true;
    Console.WriteLine("Press the Enter key to exit the program.");

private static void OnTimedEvent(object source, ElapsedEventArgs e)
    Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
    Console.WriteLine("Ninja attack!");
    throw new ApplicationException("Ninja!");
    Console.WriteLine("You didn't see this one coming");

private static void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
    Exception ex = (Exception)e.ExceptionObject;
    Console.WriteLine("Caught an exception: " + ex.Message);

The problem here is that you’d expect the OnUnhandledException method to fire, but this doesn’t happen. It seems like the exception is silenced within the timer! It took us quite a while to find that out. But actually the MSDN documentation is accurate about this, and my colleague Paul was the first to catch this line:

In the .NET Framework version 2.0 and earlier, the Timer component catches and suppresses all exceptions thrown by event handlers for the Elapsed event. This behavior is subject to change in future releases of the .NET Framework.

So it’s not a bug, it’s a feature!

And when you peek inside the System.dll assembly from the .Net framework you’ll see the following code for the handling of the Elapsed event

private void MyTimerCallback(object state)
    if (state == this.cookie)
        if (!this.autoReset)
            this.enabled = false;
        FILE_TIME lpSystemTimeAsFileTime = new FILE_TIME();
        GetSystemTimeAsFileTime(ref lpSystemTimeAsFileTime);
        ElapsedEventArgs e = new ElapsedEventArgs(lpSystemTimeAsFileTime.ftTimeLow, lpSystemTimeAsFileTime.ftTimeHigh);
            ElapsedEventHandler onIntervalElapsed = this.onIntervalElapsed;
            if (onIntervalElapsed != null)
                if ((this.SynchronizingObject != null) && this.SynchronizingObject.InvokeRequired)
                    this.SynchronizingObject.BeginInvoke(onIntervalElapsed, new object[] { this, e });
                    onIntervalElapsed(this, e);

Now I wonder who had the guts to break the rule “Never (ever) use an empty catch”! And why did they do this?!

(This would be a nice question for a Microsoft exam ;). How many of you knew about this?)

Permalink -

Super-easy access to the Sysinternals tools
· 2009-02-18 11:54 by Thijs Kroesbergen for Brokenwire.NET

Leon Meijer blogged about the "new" way to access the sysinternals tools back in May 2008.

Today I found out another cool trick. You can not only use the  http://live.sysinternals.com/ "Open Directory" server to download the tools, you can also do the following: (Start, run, type:)


And presto! You now have access to a network share with easy and up-to-date access to the tools!

You can also map a drive letter to this share if you want to, just type:

net use * \\live.sysinternals.com\Tools

If you consider yourself an "IT-Professional" and you haven't seen or heard of any of the Sysinternals tools, shame on you! (But hey, it's never too late to learn, so go check them out!)

(This trick depends on the Windows ability to access a WebDAV share as a regular network share, so this won't work on systems where the client bit (the WebDAV mini-redirector) isn't installed (such as my Windows Server 2003)). On Windows Vista this works straight out of the box.
Another reason for some of you to leave the "antique" versions of windows behind and move on?

Permalink -

TFS BuildStore: Stopping and removing builds
· 2008-04-11 12:17 by Thijs Kroesbergen for Brokenwire.NET

Here is a quick tip on how to remove a build that got stuck in your Team Foundation Server build environment.

The scenario: You've started a build and someone else has decided that it's a good idea to shutdown the buildserver... (Hi Martijn!)
After that you're left with a started build in the TFS buildstore with a BuildStatus of "Compilation Started". The problem here is that this build will never finish (because the server was shutdown while building). As an additional bonus you'll have team explorer sorting this build to the top of the list as well, which is confusing. On top of that: the list of builds doesn't have a button to delete a build.

So we want to remove it. How? PowerShell!

I used my friend get-tfs, and added a line to the script for the BuildController object. The complete get-tfs function now looks like this:

function get-tfs ( [string] $serverName = $(Throw 'serverName is required') ) { # load the required dll [void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client") $propertiesToAdd = ( ('VCS', 'Microsoft.TeamFoundation.VersionControl.Client', 'Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer'), ('WIT', 'Microsoft.TeamFoundation.WorkItemTracking.Client', 'Microsoft.TeamFoundation.WorkItemTracking.Client.WorkItemStore'), ('BS', 'Microsoft.TeamFoundation.Build.Common', 'Microsoft.TeamFoundation.Build.Proxy.BuildStore'), ('BC', 'Microsoft.TeamFoundation.Build.Common', 'Microsoft.TeamFoundation.Build.Proxy.BuildController'), ('CSS', 'Microsoft.TeamFoundation', 'Microsoft.TeamFoundation.Server.ICommonStructureService'), ('GSS', 'Microsoft.TeamFoundation', 'Microsoft.TeamFoundation.Server.IGroupSecurityService') ) # fetch the TFS instance, but add some useful properties to make life easier # Make sure to "promote" it to a psobject now to make later modification easier [psobject] $tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($serverName) foreach ($entry in $propertiesToAdd) { $scriptBlock = ' [System.Reflection.Assembly]::LoadWithPartialName("{0}") > $null $this.GetService([{1}]) ' -f $entry[1],$entry[2] $tfs | add-member scriptproperty $entry[0] $ExecutionContext.InvokeCommand.NewScriptBlock($scriptBlock) } return $tfs }

Next I had to figure out the BuildUri for the broken build. I used the following snippet to get all builds with a status of "Compilation Started" from the BuildStore:

$tfs = get-tfs http://tfs-server:8080 $tfs.BS.GetListOfBuilds("TeamProject", "DailyBuild") | where {$_.Buildstatus -eq "Compilation Started"}

Before running this, I made sure no other builds where running and to make sure you are going to delete the correct build you MUST double check the results here! Next I copied the BuildUri from the build that I wanted to stop & delete.

Then the following three lines of PowerShell made the magic happen:

$message = "" $tfs.BC.StopBuild("vstfs:///Build/Build/04102008_134057_94286", [ref] $message) $tfs.BC.DeleteBuild("vstfs:///Build/Build/04102008_134057_94286", [ref] $message)

If something goes wrong the $message variable will be filled with a helpful error message.

By combining the BuildStore and the BuildController objects it is also possible to write an automated build-cleanup mechanism using PowerShell. (TFS2008 has this functionality built-in, but version 2005 doesn't)
The pseudo code for this script would look like this:

Loop through ListOfBuilds WHERE BuildQuality equals "Rejected" (maybe another Quality?)
And for each build found:

Writing this in PowerShell should be easy now. And as usual: the actual implementation of this script is left as an exercise for my dear readers ;)

Let me know if you succeed (or fail, in that case we'll sort it out together).

Permalink -

Get the OS version in C#
· 2008-04-02 11:42 by Thijs Kroesbergen for Brokenwire.NET

After I wrote about the new wave of operating systems written in C# I noticed an increase in traffic from people who are looking for something completely different.

They did type C#, Operating system and Version into their favorite search engine, and they found this site. But they didn't find an answer to their question.

So for all these people I now show you how to determine the OS version using C# (and the .NET framework).

The very short answer:

System.OperatingSystem osInfo

By looking at osInfo.Version property and the table with version numbers on the Windows Wikipedia page you can determine the OS version.

Or with PowerShell (just because it's possible)


Now on to the more sophisticated version. If you want not only the major versions but also the details about the product types and even information about the edition (suite) the machine is running, then you can use some (more complicated) API's, like GetVersionEx.

First of all you need to understand how the OS version number scheme of Windows works. There is a great article about this subject written by Marius Bancila. In this article he explains how the version scheme is laid out. He also shows how to use C++ and the Platform SDK to get to the information we need.

But you wanted to use C# (or .NET in general), so I've also dug up an article on CodeProject which shows the C# code to get the operating system version. The article on CodeProject is not up-to-date (think Vista, server 2008) but by combining the two articles you can create the complete OS detection code. I leave this as an exercise for those of you who really need this...

Have fun!

Permalink -

Sign in to Windows Live using CardSpace
· 2008-03-19 19:52 by Thijs Kroesbergen for Brokenwire.NET

Did you know that you can use CardSpace to sign into the windows live services? By using CardSpace you don’t need to enter your password to sign into a service. This way you can use a longer, more secure, password and have the leisure to just show your card whenever you want to sign in (from your own pc).

It’s really easy, here is how to set this up:

  1. Install the .Net framework version 3.0 (already present if you use Vista)
  2. Get either IE7 or Firefox with a CardSpace plugin. I used Firefox with the Identity Selector extension.
  3. Assign a Card to your Live / Passport account on the Information Card management page. On this page you can associate a Card with your Windows Live ID.
  4. Sign into your favorite Live site. (for example, SkyDrive but also Hotmail)
  5. Never type your password again, just pick the Card whenever you want to sign in.

The CardSpace support in Windows Live is still Beta, but it is very usable. The .NET 3.0 homepage describes CardSpace in the following way:

Windows CardSpace is client software that enables users to provide their digital identity to online services in a simple, secure and trusted way. It is what is known as an identity selector:  when a user needs to authenticate to a web site or a web service, CardSpace pops up a special security-hardened UI with a set of “information cards”  for the user to choose from. Each card has some identity data associated with it – though this is not actually stored in the card – that has either been given to the user by an identity provider such as their bank, employer or government or created by the user themselves. Having the user as an identity provider sounds a bit strange on first acquaintance – who would trust the user? –  but this is a very common scenario: this is what we do every time we register at a web site. The CardSpace UI enables users to create Personal cards (aka self-issued cards) and associate a limited set of identity data. It also enables the user to import Managed cards from third party identity providers. When the user chooses a card, a signed and encrypted security token containing the required information (e.g. name and address, employer’s name and address, or credit limit) is generated by the identity provider that created the card. The user, in control at all times, then decides whether to release this information to the requesting online service. If the user approves then the token is sent on to this relying party where the token is processed and the identity information is extracted.

If you want to learn more about CardSpace and it’s role in the Identity Metasystem take a look a Kim Cameron’s IdentityBlog, he is one of the gurus in the identity area.

Permalink -

Singularity: open source C# Operating System
· 2008-03-07 11:16 by Thijs Kroesbergen for Brokenwire.NET

The source code for the Microsoft Research project "Singularity" has been published on CodePlex. I’ve written about Cosmos about a month ago and I’ve had many visitors looking for information about a C# operating systems.

I’ve not yet tried to actually run Singularity from the provided sources, but from the "About" page and the supplied documentation it seems that they have a pretty complete implementation.

From the include slide shows you can conclude that Singularity is actually written in SpeC#, a superset of C# (formerly A#). Their runtime is named "Bartok" and translates the MSIL code to x86 binary code.

The mentioned target scenario is "eHome digital-convergence" which means that Singularity could run on devices like Smart Remotes, Set-Top boxes and Media Servers and provide a common platform for these kind of devices.

If the network support is complete enough, Singularity could also be a nice start for embedded (home automation?) projects.

Furthermore they have include a slide deck which says something about the performance of Singularity in comparison with other OS’s (FreeBSD, Linux, Windows). From these slides you can conclude that the performance currently is very similar to these OS’s!

So far I know about three OS implementations in C#:

  1. Cosmos
  2. SharpOS
  3. Singularity

Concluding from my shallow investigations it seems like Singularity is by far the most complete project, with it’s network support and many demo applications. I’m amazed by the size of this project!

One final highlight for pong-addicts: "Pong.cs" is included!

Ps. for the non-native English speakers (just like me): I looked up "Technological singularity" and that actually means something like an intelligence explosion, caused by the self-improving intelligence of machines, which will eventually surpass human intelligence. Think about that for second, does this project prelude the end of mankind?

Permalink -

Previous Next