Bart's Blog

Just another WordPress.com weblog

  • Categories

  • Archives

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 »

TeamViewer – easier than setting up a VPN

Posted by bartmaes on May 12, 2010

I have read an article (sorry, but the article is in Dutch…) about a tool called TeamViewer. It allows you to create a “Remote Desktop Connection” to another computer with TeamViewer installed (or at least the client module). Both computers need to be connected to the internet, but the great thing is that all communication is sent using http, which means that firewalls probably won’t stop you! (Of course all communication is well encrypted using RSA Public-/Private Key Exchange and AES (256 Bit) Session Encoding.) Moreover this tool is compatible with Windows 7 and free for non-commercial use!! Last but not least, you can up- or down-load files to/from your remote computer. Just download the “TeamViewer Full Version – Windows” from the TeamViewer website.

TeamViewer can be used for “Remote Support”. In this scenario, someone at the remote computer should manually accept when you create a connection.

If you want to use TeamViewer as a “Remote Desktop Connection” tool, you don’t want manual interventions like this. Therefore you should configure TeamViewer on your client computer like this (I’m translating the settings to English, so hopefully you can recognize them…):

  • Go to the menu “Extras -> Options” and go to the tab “Security”
  • Type in a strong password (I’d recommence at least 10 characters, including combinations of minor case/major case, numbers and special characters…)
  • If you want to be able to connect when the Windows logon screen is displayed on the remote computer, you also have to set “Windows logon” to “Allowed for all users”
  • Also set the password strength for spontaneous connections to “Very safe (10 characters)” or “Off (no session password)”
  • Make sure that “Access management” is set to “Full access”
  • You could still add a black- or white list, but I think these settings are quiet secure yet…

I also found a nice demo of this tool on youtube. Easy isn’t it?

Posted in Tools | Leave a Comment »

CruiseControl integration problems when upgrading to Visual Studio 2010, .NET 4.0 and MVC 2.0

Posted by bartmaes on April 23, 2010

Yesterday, I upgraded a website solution from Visual Studio 2008 to Visual Studio 2010. I also upgrade all projects to target the .NET 4.0 framework and MVC 2.0. (Some small changes needed to be applied in the code to be compatible with the new IValueProvider.) When I committed the code in our source control system, there were a few things to be solved on our CruiseControl integration server:

  • I already installed the .NET 4.0 framework on the CruiseControl server using the Microsoft .NET Framework 4 standalone installer (which doesn’t require an internet connection during installation).
  • The build on the build server fails with the error message: “The type or namespace name ‘Mvc’ does not exist in the namespace ‘System.Web’ (are you missing an assembly reference?)”. Apparantely the MVC 2.0 libraries are not part of the .NET framework 4.0 installation, so I installed these seperately. Since I have no internet connection on the build server, I couldn’t use the Web Platform Installer 2.0, so I installed the ASP.NET MVC 2 RTM seperately.
  • I force a new build and this one fails again with 2 new error messages: “The type or namespace name ‘Routing’ does not exist in the namespace ‘System.Web’ (are you missing an assembly reference?)” and “The type or namespace name ‘RouteValueDictionary’ could not be found (are you missing a using directive or an assembly reference?)”. After a little bit of thought and opening the System.Web assembly in reflector, I found out that RouteValueDictionary is defined in the System.Web assembly in the .NET 4.0 framework. The problem was that I was still using the old version of MsBuild for building the solution. Our CruiseControl uses a configuration file located at “C:\Program Files\CruiseControl.NET\server\CruiseControlConfig” and was indeed configured to use MsBuild.exe from the .NET 3.5 framework. So I changed the setting:

    <msbuild>
            <executable>C:\windows\Microsoft.NET\Framework\v3.5\MSBuild.exe</executable>

    to

    <msbuild>
            <executable>C:\windows\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe</executable>
  • My next build still fails, this time with the error message: “The type or namespace name ‘VisualStudio’ does not exist in the namespace ‘Microsoft’ (are you missing an assembly reference?)”. When searching in the solution, I see that the test projects (containing unit tests written using NUnit) in the solution reference “Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll”. This dll is installed together with Visual Studio 2010, but is not part of the standalone installer. I did not find an installer on the internet to install the quality tools seperately. From this moment on, I asked a colleague, who had already done some upgrades to the release candidates of Visual Studio 2010, for help. According to him, Microsoft advices to install Visual Studio 2010 on your build server, but does this mean that you have to install any component from any vendor on your build server just because one or another product makes use of it. And what happens if those vendors release updates of those products. So we copied the “Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll” into the references folder of our project and added it in our source control system. Now we just had to make sure that the dll was found on our build server. Since the dll is added as a .NET reference, the <HintPath> is not automatically set. So we changed the .csproj files of our test projects manually (by first unloading the projects in Visual Studio and then right-clicking them to edit the xml). We changed
    <Reference Include=Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL />
    into
    <Reference Include=Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL“>
     
    <
    HintPath>..\..\references\Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll</HintPath>
    </
    Reference>
    Notice that the HintPath is relative to the .csproj file. This makes sure that the dll can be found on the build server where the absolute path is different.
    In fact since the test projects were using NUnit and not MsTest, we also could have replaced the Test projects with regular class library projects and get rid of the reference to the dll…
  • My next build on the build server still fails, but the “MsBuilding” of the project already works. When I look at the end of the Build Log, I get a clue of what’s wrong:

    <![CDATA[ProcessModel: Default    DomainUsage: Single
    Execution Runtime: net-2.0.50727.3603
    Unhandled Exception:
    System.BadImageFormatException: Could not load file or assembly ‘C:\src\MyProject.UnitTest\bin\release\MyProject.UnitTest.dll’ or one of its dependencies. This assembly is built by a runtime newer than the currently loaded runtime and cannot be loaded.
    File name: ”C:\src\MyProject.UnitTest\bin\release\MyProject.UnitTest.dll’Server stack trace:
       at System.Reflection.AssemblyName.nGetFileInformation(String s)
       at System.Reflection.AssemblyName.GetAssemblyName(String assemblyFile)
       at NUnit.Core.Builders.TestAssemblyBuilder.Load(String path)
       at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, Boolean autoSuites)
       at NUnit.Core.Builders.TestAssemblyBuilder.Build(String assemblyName, String testName, Boolean autoSuites)
       at NUnit.Core.TestSuiteBuilder.BuildSingleAssembly(TestPackage package)
       at NUnit.Core.TestSuiteBuilder.Build(TestPackage package)
       at NUnit.Core.SimpleTestRunner.Load(TestPackage package)
       at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
       at NUnit.Core.ProxyTestRunner.Load(TestPackage package)
       at NUnit.Core.RemoteTestRunner.Load(TestPackage package)
       at System.Runtime.Remoting.Messaging.StackBuilderSink._PrivateProcessMessage(IntPtr md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
       at System.Runtime.Remoting.Messaging.StackBuilderSink.PrivateProcessMessage(RuntimeMethodHandle md, Object[] args, Object server, Int32 methodPtr, Boolean fExecuteInContext, Object[]& outArgs)
       at System.Runtime.Remoting.Messaging.StackBuilderSink.SyncProcessMessage(IMessage msg, Int32 methodPtr, Boolean fExecuteInContext)Exception rethrown at [0]:
       at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
       at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
       at NUnit.Core.TestRunner.Load(TestPackage package)
       at NUnit.Util.TestDomain.Load(TestPackage package)
       at NUnit.ConsoleRunner.ConsoleUi.Execute(ConsoleOptions options)
       at NUnit.ConsoleRunner.Runner.Main(String[] args)Assembly manager loaded from:  C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\mscorwks.dll
    Running under executable  C:\Program Files\NUnit 2.5\bin\net-2.0\nunit-console.exe

    I also have a lot of warnings, but I’ll get back to that in the next paragraph… The problem is that NUnit uses the wrong version of the .NET framework for loading the UnitTest dll. Since our build server is using nunit-console.exe, we open the “C:\Program Files\NUnit 2.5\bin\net-2.0\nunit-console.exe.config” file in a text editor and we add:
       <startup>
          <supportedRuntime version=”v4.0″/>
       </startup>
    under <configuration>. (We might have added extra supported runtimes, but apparently this was not necessary on our build server…). After reforcing a new build, the build succeeds!

  • However there a still a lot of warnings with the message:
    C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\Microsoft.Common.targets (847,9): warning MSB3644: The reference assemblies for framework “.NETFramework,Version=v4.0” were not found. To resolve this, install the SDK or Targeting Pack for this framework version or retarget your application to a version of the framework for which you have the SDK or Targeting Pack installed. Note that assemblies will be resolved from the Global Assembly Cache (GAC) and will be used in place of reference assemblies. Therefore your assembly may not be correctly targeted for the framework you intend.

    We search in our project where these error messages come from. In every .csproj file, we find the same string “.NETFramework,Version=v4.0”:
    <ItemGroup>
      <BootstrapperPackage Include=.NETFramework,Version=v4.0>
        <
    Visible>False</Visible>
        <
    ProductName>Microsoft .NET Framework 4 %28×86 and x64%29</ProductName>
        <
    Install>true</Install>
      </
    BootstrapperPackage>
      <BootstrapperPackage Include=
    Microsoft.Net.Client.3.5>
        <
    Visible>False</Visible>
        <
    ProductName>.NET Framework 3.5 SP1 Client Profile</ProductName>
        <
    Install>false</Install>
      </
    BootstrapperPackage>
      <BootstrapperPackage Include=Microsoft.Net.Framework.3.5.SP1>
        <
    Visible>False</Visible>
        <
    ProductName>.NET Framework 3.5 SP1</ProductName>
        <
    Install>false</Install>
      </
    BootstrapperPackage>
      <BootstrapperPackage Include=Microsoft.Windows.Installer.3.1>
        <
    Visible>False</Visible>
        <
    ProductName>Windows Installer 3.1</ProductName>
        <
    Install>false</Install>
      </
    BootstrapperPackage>

    </ItemGroup>

    This section was added when upgrading the solution to Visual Studio 2010 and the BootstrapperPackage for .NET 4.0 must have been added when upgrading the project to target .NET 4.0. When adding new projects to the solution, the the BootstrapperPackages are not added to the .csproj files. The only reason we can come up with why the BootstrapperPackages are needed in the .csproj files is if you would want to be able to deploy the project with ClickOnce.
    Because we want to avoid having to change the .csproj files for every project that we upgrade to .NET 4.0 in the future, we start searching for a solution. This morning, I receive a mail from my colleague who solved this final issue. According to him, the reference assemblies are installed together with the .NET 4.0 framework standalone installer, but they are installed in the GAC and not found in the directories where the build server is looking. One way to get rid of the errors is to install the .NET Framework 4.0 SDK or any other application that installs the .NET 4.0 Multi-Targetting Pack (which cannot be installed alone). The solution we choose was to manually copy the reference assemblies from our development server to our build server (C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\).

It has taken us a while, but finally everything seems to work propertly…

Posted in Programming | 1 Comment »

Unmoveable files when shrinking your C: partition on Windows 7

Posted by bartmaes on April 7, 2010

You can shrink partitions in “Computer Management” – “Disk Management” on Windows 7. (You can find this in “Control Panel” – “System and Security” – “Administrative Tools”.) When you right-click your operating system partition and choose “Shrink Volume…”, the available shrink space is being calculated. The available shrink space does not only depend on the amount of available disk space on this partition, but there can also be some unmoveable files that prevent you from shrinking the disk space more than a certain amount.

On my new DELL computer, I could only shrink the disk to half it’s size (150 GB), while only 20 GB was used. Also defragmenting the disk did not help.

After the “Querying Shrink Space” has finished, you can see which unmoveable file is responsible. To do this, you need to go to Event Viewer (which you can find in Computer Management as well). You have to go to “Windows Logs” – “Application”. You will see 2 entries in a row for which the source is “Defrag”. The second one gives the information you are searching for.

On my computer, the message says: “The last unmovable file appears to be: \System Volume Information\{f94d9e25b-4217-11df-9570-005056c00008}{3808876b-c176-4e48-b7ae-04046e6cc752}:$DATA

I found out that this file is part of a System Restore Point. You can remove the file by disabling System Restore. (You can enable it again and create a new restore point after shrinking your disk space.) To disable System Restore, you should go to “Control Panel” – “System and Security” – “System” – “Advanced System Settings” – tab “System Protection”. Click on the drive for which you want to disable system restore (probably your C: drive) and click “Configure…”. Now choose “Turn off system protection” and click Apply. Hopefully there are no other unmoveable files which prevent you from shrinking your disk drive to the prefered size.

Posted in Programming | 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 »