Archive for the 'C#' Category

Published by breki on 07 Apr 2008

UTC Time And .NET: A Constant Hassle

I keep finding new ways to loose half a day in debugging and troubleshooting when working with timezones and UTC time in .NET Framework.

A little background into my problem: we’re trying to use UTC exclusively in our application. So, for example, whenever we ask for current time, we use DateTime.UtcNow property instead of DateTime.Now. And also we are strict on a policy of naming all variables that hold UTC time with an Utc suffix, example: currentTimeUtc. This is just in case nobody gets confused of the timezone used in a variable. This is especially useful when our application communicates with the world, since some external services work with local time only, so there needs to be a conversion. And I recommend using this policy on database columns too, for the same reason.

The latest hassle has to do with converting UTC time to and from a string. As we discovered, we naively belived that all that was necessary was to use DateTime.ToString ("u", CultureInfo.InvariantCulture) to convert the UTC timestamp into the string. Later if we wanted to convert it back into an UTC time, we simply called DateTime.Parse (timeString, CultureInfo.InvariantCulture) to get the DateTime value back.

Off course this doesn’t work. The ToString() method converts the time into "2002-12-10 22:13:50Z" format. But the Parse() method (well actually the override we used) first parses it into UTC time and then automatically converts it into the local time. So we end up with a variable marked as UTC but actually holding the local time, which is no good.

The solution (or what I hope to be the solution) is to use
DateTime.Parse (timeString, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal) override. Let me quote the MSDN documentation on the AdjustToUniversal enumeration value:

Indicates that the date and time will be returned as a Coordinated Universal Time (UTC). If the input string denoted a Local time (through a time zone specifier or AssumeLocal) then the date and time is converted from the local time zone to UTC. If the input string denoted a UTC time (through a time zone specifier or AssumeUniversal) then no conversion occurs. If the input string did not denote a Local or UTC time (no time zone specifier, and neither AssumeLocal nor AssumeUniversal was included), then no conversion occurs and the Kind of the resulting DateTime is Unspecified. Cannot be used with RoundTripKind. 

Just another reminder that if you want to use UTC times in your applications, you shouldn’t assume anything. At least when the .NET Framework is concerned ;)

Published by breki on 31 Mar 2008

Tip: How To Speed-Up Sandcastle

Simply remove (or rename) the Data/Reflection directory, so that Sandcastle cannot find the information about .NET Framework libraries. You will loose the ability to have MSDN help on .NET Framework classes links in your documentation, but I think this is not crucial for day-to-day builds, compared to the substantial increase in your build speed. And also, by deleting the contents of the Reflection folder you’ll gain some 200 MB of space on your disk.

Published by breki on 29 Feb 2008

Multiple instance Windows service in C#

The standard way of installing Windows services using the Visual Studio Windows Service project and the InstallUtil.exe tool does not allow the user to specify the service name after the project has been compiled. This is problematic if you want to install two or more instances of a Windows service on the same computer. So in this post I propose a way to achieve this without much effort.

The procedure consists of the steps described below. I’ll assume that you already have a Visual Studio project and you want to extend it with the multiple instance support:

1. Add a new XML file named App.InstallConfig.xml to your project. It should contain the following XML code:

<installconfig>
    <servicename>My Service Name</servicename>
</installconfig>

2. Add a post-build step to the project:

copy $(ProjectDir)App.InstallConfig.xml $(TargetPath).InstallConfig.xml

This will copy the installation configuration file from the project directory to the target and will replace the ‘App’ name with the name of your project’s assembly.

3. Add a new private method to the main (project) installer class:

private void ConfigureInstaller ()
{
    // find the install configuration file
    string assemblyLocation = Assembly.GetExecutingAssembly ().Location;
    string installConfigFile = assemblyLocation + ".InstallConfig.xml";

    // now load the file and parse it
    XmlDocument xmlDoc = new XmlDocument ();
    xmlDoc.Load (installConfigFile);

    XmlNode serviceNameNode = xmlDoc.SelectSingleNode ("InstallConfig/ServiceName");
    if (serviceNameNode != null)
    {
        string serviceName = serviceNameNode.InnerText.Trim ();
        this.ListenerServiceInstaller.ServiceName = serviceName;
    }
}

This method opens the mentioned configuration file and reads the InstallConfig/ServiceName setting which should contain the actual name of the Windows service instance. It uses this name to set the ServiceInstaller.ServiceName before the installation is initiated.

4. And finally, add the call of the ConfigureInstaller() method to the project installer constructor, like this:

public ProjectInstaller()
{
   // This call is required by the Designer.
   InitializeComponent();

   ConfigureInstaller ();
}

NOTE: replace the name of the ProjectInstaller constructor with your own class name.

This should be it. To install the service under the desired name, you just edit the .InstallConfig.xml file before calling the InstallUtil tool.

Extending this further

You can use the same system to include some other Windows service parameters (like the user account under which it will run, for example). The installer class provided by the .NET Framework does not allow setting the Windows service’s description, but there is a way to do this (see the “Adding a description to a .NET Windows Service” article on CodeProject). Then you can add the description tag in the .InstallConfig.xml file and have a different description for each of the service instances.

Also check out the “Windows Services Can Install Themselves” article on how to create self-installing Windows services (be sure to read the article’s comments, they contain some additional tips).

Published by breki on 15 Feb 2008

Friday Goodies - 15. February

.NET Development

Development

GPS

Published by breki on 05 Feb 2008

Rhino.Mocks Do() handler using anonymous delegates

A reminder post for me on how to use the Rhino.Mocks Do() handler together with anonymous delegates. This is useful when you want to set a method call expectation and the method accepts some complex type as the parameter. Using assertions you can set expectations for the parameter’s value with your own custom logic. There are other ways of achieving this, off course, but this way is elegant for simple (few lines of code) cases.

The example code starts with defining an IStringProcessor interface (which will be mocked):

    public interface IStringProcessor
    {
        void ProcessString (string value);
    }

This is an example interface, just to demonstrate the power of Do() handler.

In the test method we want to make sure that all calls to the IStringProcessor.ProcessString() method provide strings which contain the ‘text’ substring. We then do the test by calling this method with three different string parameters:

    [Test]
    public void RhinoDoExample ()
    {
        IStringProcessor mockProcessor = mocks.CreateMock <IStringProcessor> ();

        mockProcessor.ProcessString (null);
        LastCall.IgnoreArguments ().Do ((Action<string>)delegate (string value)
            {
                Assert.IsTrue (value.Contains ("text"));
            }).Repeat.Any();

        mocks.ReplayAll();

        mockProcessor.ProcessString ("This is a dummy text.");
        mockProcessor.ProcessString ("This is a dummy text2.");
        mockProcessor.ProcessString ("This is a dummy.");

        mocks.VerifyAll();
    }

The test method will fail because of the third call: “This is a dummy.” string does not contain the required ‘text’ substring.

Published by breki on 04 Feb 2008

C# snippet for the Disposable pattern

This is the first post in a series of posts in which I will publish some C# code snippets I find useful in everyday C# coding.

This snippets inserts all of the necessary code to implement Disposable pattern in a C# class. The code is basically the example of how to implement IDisposable interface taken from the FxCop help pages, so this snippet resolves that FxCop issue.

Note the two “TODO”-s where you can add your code for disposing of managed and unmanaged resources.

<codesnippets xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
    <codesnippet format="1.0.0">

            <description>Implements a disposable pattern for the class.</description>
            <author>Igor Brejc</author>
            <keywords>
                <keyword>IDisposable</keyword>
                <keyword>Dispose</keyword>
            </keywords>
            <snippettypes>
                <snippettype>Expansion</snippettype>
            </snippettypes>

        <snippet>
            <code language="CSharp" kind="method decl">
                <!–[CDATA[
      #region IDisposable Members

      /// <summary>

      /// Performs application-defined tasks associated with freeing, releasing, or
      /// resetting unmanaged resources.
      /// </summary>
      public void Dispose()
      {
         Dispose(true);
         GC.SuppressFinalize(this);
      }

      /// <summary>
      /// Disposes the object.
      /// </summary>
      ///
<div  name="disposing"></div>
If <code>false</code>, cleans up native resources.
      /// If <code>true</code> cleans up both managed and native resources</param>
      protected virtual void Dispose(bool disposing)
      {
            if (false == disposed)
            {
                // TODO: clean native resources        

             if (disposing)
             {
                    // TODO: clean managed resources
                    $end$
             }

             disposed = true;
            }
      }

      private bool disposed;

      #endregion
                ]]–>
            </code>
        </snippet>
    </codesnippet>
</codesnippets>

Published by breki on 01 Feb 2008

Friday Goodies - 01. February

Development

.NET Development

VisualStudio

GPS

Published by breki on 29 Jan 2008

C# Source Code Search Engines For Internal Use

I work on a lot of different projects, both in the company I work for and in my spare time. A lot of code has been produced during that time and I constantly find myself searching for that “I remember I once wrote something like this” code. Google helps, but its search engine is not specialized for C# code and I sometimes have to do a lot of searching before finding a snippet that is perfect for my needs. Snippets in VisualStudio are helpful too, but I use them mostly for really repetitive code which merits taking time to write the snippet.

So I started to look for a search engine that would be able to go through my C# source code (and possibly source code repositories like SVN) and offer more developer-oriented search capabilities (like, for example, searching for all classes that implement a certain interface).

Desktop Search

The first thing popping up in my mind was using general desktop search engines (like Google Desktop or similar). In fact I used this approach few years ago when I played around with desktop search engines on my laptop. The problem with general search engines is the fact that they are too general: when you search for code using general search, all kinds of unrelated results pop up. And besides, installing Google Desktop just to search for my source code is a bit of an overkill for me.

Specialized Search Engines

My first stop was Koders Pro. This is a professional solution provided by Koders, an Internet source code search engine which indexes open source projects. I tried Koders Pro beta version just before it went to market and I liked it. It offers most of the features I was looking for. I liked the fact that it knows how to connect to various code versioning systems like SVN. What I didn’t like is the fact that you have to sign up online on Koders website in order to access your company’s internal search site. I like to have those things separated: what I do on my (or my company’s) private network is my own business, thank you (looks like someone else agrees with me).

Open Source Solutions

But since I wanted to have the search capability available not only on projects I work on professionally, but also for my own personal stuff, I was looking for a free (or not too expensive) preferably open source solution. So I started investigating (more or less googling).

I found a very interesting article called Using Lucene to Search Java Source Code. As the name says, it describes how to implement a search engine for Java source code using Lucene, an open source search engine library. The article describes the approach in quite a detail, I won’t go into it since this is not the purpose of this post. But anyway, it was a good point from which to start searching in a more focused way. I also found a related article, Source Code Search with Syntax-Based Heuristics, which builds upon the first article’s idea, but is more ambitious.

CS2 Project

Finally, I stumbled upon CS2 Project. This is an open source academic project created by Simone Busoli. It too uses Lucene (Lucene.Net actually) as a search engine. What I like about CS2 is its extreme simplicity. You just download the zipped binaries package, extract it somewhere on your disk, create an IIS web application for it and that’s it! No MSI installations, no extra Windows services.

When you browse to the CS2 application page, you get two text boxes: the first one is used for entering search keywords, the second one for registering paths on your disk which contain source code and should be indexed.

CS2 even offers some basic query parameters, like searching for method names, comments etc. It also supports search wildcards.

Okey, it’s not feature rich as Koders, but on the other hand the basic functionality it offers is a step in the right direction.

OpenGrok

While I was writing this post I ran into OpenGrok, an open source search engine written in Java. It supports multiple languages search, but I couldn’t find any information on whether it supports indexing of C# sources.

I will post about any new findings in the future.

Published by breki on 19 Jan 2008

Selectively removing List elements using anonymous delegates

This is just a reminder post for me because I keep forgetting the syntax of anonymous delegates.

RemoveAll has the added benefit of not having to write code to go through the collection using the for statement - depending on the type of the list, for statement can lower performance in comparison to foreach. And off course, foreach cannot be used in cases when you want to remove elements from the collection you are traversing.

So anyway here’s the code (an actual production code from Kosmos):

public void ClearAllRasters ()
{
    lock (this)
    {
        // remove all raster joblets
        painterJoblets.RemoveAll (
            delegate (GdiMapPainterJoblet element)
        {
            return element.Command is GdiMapPainterRasterCommand;
        });
    }
}