Bart's Blog

Just another WordPress.com weblog

  • Categories

  • Archives

Archive for the ‘.NET’ Category

Modular IoC container initialization using Castle Windsor

Posted by bartmaes on June 22, 2010

You might want to split up the initialization code for your IoC container in several classes. There might be several reasons to do so:

  • You want to be able to easily replace just a subset of the components configured in your IoC container.
  • You are building a class libary or a framework and you want to provide others a default initialization routine for the classes in your library/framework.

 

After some searching on the internet, it seems that Castle Windsor provides a nice way of doing this by using the IWindsorInstaller:

public class MyLibrariesWindsorInstaller: IWindsorInstaller
{
  public void Install(IWindsorContainer container, IConfigurationStore store)
  {
    //container.AddComponent<IMyInterface1, MyImplementation1>();
    //…
  }
}

You can find another example here.

Now you need to call the Windsor Installer from your main WindsorContainerBootstrapper. (A bootstrapper is a component that runs as part of the startup process to activate a more complex system.)

public class WindsorBootstrapper
{
  private static IWindsorContainer _container;

  public static void Initialize()
  {
    //initialize container with some IWinsorInstallers
    container = new WindsorContainer(new XmlInterpreter());
    //delegate initialzation to the configured Windsor Installers
    _container.Install(_container.ResolveAll<IWindsorInstaller>());
  }
}

In your app.config, you can now configure a list of IWindsorInstallers:

<Configuration>
  <configSections>
    <section name=”castle” type=”Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor” />
  </configSections>

  <castle>
    <components>
      <component id=”installer” service=”Castle.Windsor.IWindsorInstaller, Castle.Windsor” type=”MyLibrary.MyLibrariesWindsorInstaller, MyLibrary” />
      <!– Configure more IWindsorInstallers here –>
    </components>
  </castle>

I find this a clean solution, which I found here. The only thing left to do is to call the WindsorBootstrapper.Initialize() method at application startup.

One last advice: be careful for registring components for the same interface in different IWindsorInstallers. Using this solution, there is still only one IoC container in your application…

Posted in .NET, Programming | 1 Comment »

Visual Studio 2010 Pro Power Tools

Posted by bartmaes on June 15, 2010

“Visual Studio 2010 Pro Power Tools” has been released and provides you with a number of extensions to improve productivity. You can download it here.

Posted in .NET, Programming, Tools | Leave a Comment »

Nunit unit tests passing and failing inconsistently

Posted by bartmaes on March 23, 2010

On one of our C# .NET projects, unit tests were passing and failing inconsistently

  • When running the tests one by one in Visual Studio, all the tests passed
  • When running all the tests in the test class, a specific set of tests failed every time
  • When the tests were running on the CruiseControl build server, those same tests were failing over and over again

Several people have lost some time looking at this problem, e.g. looking whether the dll’s and the configuration files used for the tests were correct. In the end, we found out that one of the tests in the batch was initialising a static variable and that it was never reset to null. Apparently NUnit does not do this for you and you have to do this manually in the [TearDown] part. After we made this change, all tests were passing.

Posted in .NET | Leave a Comment »

Error 1053: The service did not respond to the start or control request in a timely fashion

Posted by bartmaes on March 8, 2010

Last week we had an error while starting a Windows Service on a new Windows 2003 R2 server. The error message said: “Error 1053: The service did not respond to the start or control request in a timely fashion”. The strange thing was that the error popped up immediately. (Normally, this error message does not appear until after a 30-second time-out.) Nothing was logged in the event log.

Since we didn’t find any more information about the error, we decided to start debugging using WinDbg, which is part of Debugging Tools for Windows. (Install “Debugging Tools for Windows” to “C:\Program Files\Debugging Tools for Windows\”. First you need to get your debugger attached.

Since you don’t have the time to attach your debugger after starting the service, you need to attach it right away. The way how to do this, is to use gflags.exe which you can find in the “Debugging Tools for Windows” directory. Click on the tab “Image File” and enter the name of your service. To find the name of the service, go to properties and use the name you find in “Path to executable”. The name to use should be something like MyService.exe. In gflags, enable the “Debugger” checkbox and type “C:\Program Files\Debugging Tools for Windows\ntsd.exe -server tcp:port=1234 -noio”. (ntsd.exe can be found in the same directory, so adapt the path if necessary.) The reason not to use WinDbg directly is because Windows Services don’t interact with the desktop. In stead, we will connect via WinDbg using “Connect to Remote Session…” (On Windows Server 2008, Windows Services also run in a different session, known as session 0.) Before we can start debugging, you should increase the default 30-second time-out. To do this, open your registry (using the Start button, Run…, “regedit) and add the DWORD “HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\ServicesPipeTimeout” and set the value to 86400000, which is the amount of milliseconds in 24 hours… You’ll need to restart the machine before the setting is taken into account.

Now we are ready to debug. Start the Windows Service. You can now run “windbg.exe -remote tcp:server=localhost,port=1234” to connect to the remote session and start debugging.

During my debugging experience, I first issued a “go” command. I saw several assemblies being loaded into memory, so I performed a “Break”. Since the mscorwks assembly was loaded in the meanwhile, I could continue with:
.loadby sos mscorwks
!ca ex
go
(There was a new break on the next exception so now I could start debugging it.)

Apparently, an exception was thrown in the constructor of the class inheriting from ServiceBase, so even before the OnStart was executed. Probably this was also the reason why nothing was logged to the event log…

I’m not sure how to break automatically once the mscorwks assembly gets loaded. I might have been lucky that I was fast enough to perform a “break” manually…

I also noticed that since recently “Debugging Tools for Windows” is part of the Windows Driver Kit (WDK). You can download this as an .ISO file and mount with Daemon Tools. Actually the installer files (.msi) for “Debugging Tools for Windows” are in the debugger directory on this disk…

Posted in .NET | Leave a Comment »

Pivot extension method for LINQ

Posted by bartmaes on March 2, 2010

A colleague of mine asked me how to pivot a table using LINQ. I didn’t want to cast the table to an array of arrays, so I came up with the following code:

public static class TableExtensions
{
 public static IEnumerable<IEnumerable> Pivot(this IEnumerable<IEnumerable> table)
 {
  IEnumerable first = table.FirstOrDefault();
  if (first != null)
  {
   List enumerators = new List();
   foreach (IEnumerable row in table)
   {
    enumerators.Add(row.GetEnumerator());
   }
   foreach (object element in first)
   {
    yield return GetColumn(enumerators);
   }
  }
 }

 private static IEnumerable GetColumn(IEnumerable enumerators)
 {
  foreach (IEnumerator enumerable in enumerators)
  {
   if (enumerable.MoveNext())
   {
    yield return enumerable.Current;
   }
  }
 }
}

You can see the result when testing with the following console application:

class Program
{
 private static object[][] _table = new object[][]
 {
  new object[]{11,12,13},
  new object[]{21,22,23},
  new object[]{31,32,33},
  new object[]{41,42,43}
 };

 static void Main(string[] args)
 {
  PrintTable(_table);
  PrintTable(_table.Pivot());
  Console.ReadLine();
 }

 private static void PrintTable(IEnumerable<IEnumerable> table)
 {
  foreach (var row in table)
  {
   foreach (object o in row)
   {
    Console.Write(o.ToString() + ” “);
   }
   Console.WriteLine();
  }
  Console.WriteLine();
 }
}

Now this code works fine as long as you nicely iterate over each of the columns in the correct order. You will notice the bug when doing the following:

PrintTable(_table.Skip(1));
PrintTable(_table.Pivot().Skip(1));
PrintTable(_table.Pivot().Pivot().Skip(1));

The reason for this bug is that the constructed enumerators are shared between all the “column enumerators” and their state is changed along the way. There is no efficient way to work around this problem when only using the IEnumerable interface (efficient in the sense of memory and time consumption), so you’ll have to settle with the next best thing, casting to an object array:

public static IEnumerable<IEnumerable> Pivot(this IEnumerable<object[]> table)
{
 object[] first = table.FirstOrDefault();
 if (first != null)
 {
  for (int i = 0; i < first.Count(); ++i)
  {
   yield return table.Select(row => row[i]);
  }
 }
}

Of course you can work with generics to get a strongly typed result, but sometimes the elements in every column can have another type. The tuple class in .NET 4.0 can help you with this. You just have to create a bunch of overloads like this:

public static Tuple<IEnumerable<T1>, IEnumerable<T2>, …> Pivot<T1, T2, …>(this IEnumerable<Tuple<T1, T2, …>> table)

Posted in .NET | 2 Comments »