Archive for the 'C#' Category

Published by breki on 05 Mar 2010

Disposing Of The Evidence

Garbage?
Creative Commons License photo credit: wok

In the previous post we discussed various relationships between singletons and transients in an inversion of control container. I introduced WindsorContainerInspector, a little utility class for analyzing the container and showed a sample unit test which looks for singletons that rely on transient objects.

Now I’ll show a few other checks that I think are good to perform on the container. They involve disposability of objects.

Disposable Transients

Let’s say we have a transient service IWebClient:

public interface IWebClient : IDisposable
{
void DownloadMeSomething(string somethingUrl);
}

As you can see, the service implements IDisposable. Now let’s say we have a class DownloadData which depends on this service:

public class DownloadData
{
public DownloadData (IWebClient webClient) {...}

...
}

Note the constructor dependency on IWebClient. What’s wrong with this picture?

What happens when the DownloadData is no longer used? The webClient is not disposed. We could hold up some valuable system resource by not disposing of such an object. And since we know IWebClient is defined as transient in our IoC container, we can be pretty sure that DownloadData is the only one using the received IWebClient instance. So we are responsible for this instance!

In other words, our DownloadData should also be disposable. We can say that, in general, components that depend on disposable transients should also be disposable:

[Test, MultipleAsserts]
public void TransientsThatRelyOnDisposableTransientsShouldAlsoBeDisposable ()
{
    Type disposableType = typeof(IDisposable);
 
    IList<KeyValuePair<ComponentModel, ComponentModel>> dependencies = inspector.FindDependencies (
        (a, b) =>
        {
            return a.LifestyleType == LifestyleType.Transient && false == disposableType.IsAssignableFrom (a.Implementation)
                && b.LifestyleType == LifestyleType.Transient && disposableType.IsAssignableFrom(b.Service);
        });
 
    foreach (KeyValuePair<ComponentModel, ComponentModel> dependency in dependencies)
    {
        Assert.Fail (
            "Transient component {0} relies on the disposable transient component {1}, but it itself is not disposable",
            dependency.Key.Implementation.FullName,
            dependency.Value.Implementation.FullName);
    }
}

Some might say that this kind of check can be done by static analysis like FxCop. FxCop will detect this only if DownloadData stores the IWebClient in a class field. But we could have used IWebClient parameter just within the constructor and then forget about it:

public class DownloadData
{
public DownloadData (IWebClient webClient)
{
webClient.CheckConnection();
}
}

In such cases no warning will be issued by FxCop.

Disposable Implementations Of Non-Disposable Services

What if we had another service, called IMailChecker:

public interface IMailChecker
{
bool AnyNewMail();
}

and we implemented a GMailChecker:

public class GMailChecker : IMailChecker, IDisposable
{
public bool AnyNewMail() {...}
public void Dispose() {...}
}

Notice GMailChecker implements IDisposable in addition to IMailChecker interface. But IMailChecker itself is not defined as disposable. How will the user of IMailChecker service know whether the object it holds should be disposed or not?

One way would be to use reflection to determine this. But this is very cumbersome and easy to forget when coding. My way of thinking is that if there’s reasonable possibility the implementations of the service will require disposability, you should declare the service interface as disposable. We can check for this condition with the following unit test:

[Test, MultipleAsserts]
public void TransientsThatRelyOnDisposableTransientsShouldAlsoBeDisposable ()
{
    Type disposableType = typeof(IDisposable);
 
    IList<KeyValuePair<ComponentModel, ComponentModel>> dependencies = inspector.FindDependencies (
        (a, b) =>
        {
            return a.LifestyleType == LifestyleType.Transient && false == disposableType.IsAssignableFrom (a.Implementation)
                && b.LifestyleType == LifestyleType.Transient && disposableType.IsAssignableFrom(b.Service);
        });
 
    foreach (KeyValuePair<ComponentModel, ComponentModel> dependency in dependencies)
    {
        Assert.Fail (
            "Transient component {0} relies on the disposable transient component {1}, but it itself is not disposable",
            dependency.Key.Implementation.FullName,
            dependency.Value.Implementation.FullName);
    }
}

Below is the updated the implementation of WindsorContainerInspector. Next time we will be discussing issues (= mostly problems) around disposing stuff received from the Windsor container.

public class WindsorContainerInspector
{
    public WindsorContainerInspector(IWindsorContainer container)
    {
        this.container = container;
    }
 
    public IList<KeyValuePair<ComponentModel, ComponentModel>> FindDependencies(
        Func<ComponentModel, ComponentModel, bool> dependencyPredicate)
    {
        List<KeyValuePair<ComponentModel, ComponentModel>> dependencies = new List<KeyValuePair<ComponentModel, ComponentModel>>();
 
        foreach (GraphNode node in container.Kernel.GraphNodes)
        {
            ComponentModel dependingNode = (ComponentModel) node;
 
            foreach (GraphNode depender in node.Dependents)
            {
                ComponentModel dependerNode = (ComponentModel)depender;
 
                if (dependencyPredicate(dependingNode, dependerNode))
                    dependencies.Add(new KeyValuePair<ComponentModel, ComponentModel>(dependingNode, dependerNode));
            }
        }
 
        return dependencies;
    }
 
    public IList<ComponentModel> FindComponents (Func<ComponentModel, bool> predicate)
    {
        List<ComponentModel> components = new List<ComponentModel>();
 
        foreach (GraphNode node in container.Kernel.GraphNodes)
        {
            ComponentModel component = (ComponentModel) node;
            if (predicate(component))
                components.Add(component);
        }
 
        return components;
    }
 
    private readonly IWindsorContainer container;
}

Published by breki on 01 Mar 2010

The Delicate Dance Of Transience

H2O
Creative Commons License photo credit: Flowery Luza*

I’m in the final stages of polishing Maperitive before the first release. Well, not really polishing, I have a bunch of tasks yet to do, but I think I can see the light at the end of the tunnel.

As #I stated a while back#, one of the reasons I decided to do a major rewrite of the Kosmos code was to introduce inversion of control (IoC) into the architecture. Maperitive (ex-Kosmos) now heavily relies on Windsor Castle do to the wiring. I can say that investing in IoC (and sticking to SOLIDs) now starts to pay dividends: I can add new features with more ease and they tend to affect a relatively minor part of “old” code.

The problem with using IoC containers like Windsor Castle is when the components registered exceed a certain number that you can handle in your brain (Maperitive currently has about 130 components in IoC container). Then the whole thing gets a life of its own: even if you write extensive unit tests for individual parts, it gets more and more difficult to predict how the “organism” will behave as a whole.

When used in a Windows desktop application like Maperitive, the problem gets compounded by the intricate dependencies between different lifestyles of components. This is what I want to discuss in this post.

I’ll restrict the discussion to singletons and transients, since I only use these two types in Maperitive. I’ll give examples of components in terms of a mapping application (which Maperitive is), but I think it won’t be a problem to translate this to your own areas. I’ll start with the simple case of…

Singletons Depending On Singletons

This is the easy one: singletons are components which typically share the same lifespan as the application. A Map is a good example of a singleton: the user expects the map to be available at all times (after all, what would Google Earth look like without the map?). User typically uses a mouse to move around the map. And we luckily have only one mouse on our machines, so this is an example of another singleton (I’m a bit oversimplifying the stuff here, bear with me). So the Map subscribes to the Mouse events and this can be seen as singleton to singleton dependency.

These kind of dependencies are easy to handle, since the number of created objects is typically small and they all share the same lifespan. Also, singletons are (typically) created automatically by the IoC container at the start of the application so you don’t really need to explicitly create and destroy them yourself.

Transients Depending On Singletons

This is the second common relationship in a desktop application. You have a short-term task to do (usually as a response to user’s actions) and you create a transient object to do this task. One example would be a WebClient which downloads the map data from the server: once the download is done, you can kill the client (hmmm that sounds tempting).

Transients are typically created using factories. Windsor Castle offers a cool feature called TypedFactoryFacility which makes creating factories a lot easier (you don’t need to write the actual creation code, just specify your factory interface according to facility’s conventions).

A WebClient needs to know whether it has to provide credentials for the Web proxy. We can store this information in a Configuration object, which in our case is a singleton.

A transient component states its dependency on a singleton through constructor or property injection. Again, this scenario should be easy to handle, since the transient object has a shorter lifespan than the singleton it depends upon.

Transients Depending On Transients

This is where things can get messy. There are two possible scenarios when a transient object needs another transient object:

  1. They both share the same lifespan. Let’s say our WebClient wants to check if internet connection is up before sending a request to the download server. It can use a Ping service to ping google.com (it’s immoral, I know). Since both WebClient and Ping will be used for a short time, you can inject the Ping dependency in WebClient’s constructor. When WebClient dies, Ping should also die.
  2. The lifespans overlap, but are not the same.  Example: out WebClient has detected a communication problem with the download server and sends a notice to the user. The notice is displayed as a modeless dialog, which can stay on the screen until the user clicks on the Close button. So Notice is a transient object which does not die together with its creator, WebClient: once WebClient notifies the user, it is no longer needed. Notice, however, will live on until the user chooses to close it.

In the second case, having the Notice dependency in WebClient’s constructor or property is not an ideal option, for two reasons:

  1. It is not guaranteed the notice will even be used: if the download went OK, there is no need to notify the user. If your Notice component is expensive to create, this could be an issue.
  2. By using a constructor injection for a transient component, you are effectively claiming the ownership of this component. This conflicts with the fact that the component will live on even after your main component dies.

How do you solve this problem? My suggestion is to use factories – factories are usually singleton objects, so you end up with “transient depending on singleton” case. Even better: Windsor Castle’s TypedFactoryFacility also offers a mechanism to release components created with such factory.

The last (and most problematic) case is…

Singletons Depending On Transients

The problem with this is that your supposedly transient object will live the whole duration of the application lifetime. While in some cases this could be a valid scenario, in lot of cases it’s merely an oversight of the developer (especially when confronted with a huge number of components in a system).

Windsor Castle Inspector

The solution I used in Maperitive is to write a unit test which checks for singleton-to-transient relationships in my container and fails if it finds any:

[Test]
public void SingletonsShouldNotRelyOnTransients()
{
    IWindsorContainer container = Program.CreateWindsorContainer(false);
 
    WindsorContainerInspector inspector = new WindsorContainerInspector(
        container);
    IList<KeyValuePair<ComponentModel, ComponentModel>> dependencies 
         = inspector.FindDependencies(
        (a, b) =>
            {
                return (a.LifestyleType == LifestyleType.Singleton 
                    || a.LifestyleType == LifestyleType.Undefined)
                    && b.LifestyleType == LifestyleType.Transient;
            });
 
    Assert.AreEqual(0, dependencies.Count);
}

Of course, the condition for the test failure could be a bit modified to exclude any “special cases".

The code uses the WindsorContainerInspector, a little utility class I wrote to assist in inspecting the container:

public class WindsorContainerInspector
{
    public WindsorContainerInspector(IWindsorContainer container)
    {
        this.container = container;
    }
 
    public IList<KeyValuePair<ComponentModel, ComponentModel>> FindDependencies(
        Func<ComponentModel, ComponentModel, bool> dependencyPredicate)
    {
        List<KeyValuePair<ComponentModel, ComponentModel>> dependencies 
            = new List<KeyValuePair<ComponentModel, ComponentModel>>();
 
        foreach (GraphNode node in container.Kernel.GraphNodes)
        {
            ComponentModel dependingNode = (ComponentModel) node;
 
            foreach (GraphNode depender in node.Dependents)
            {
                ComponentModel dependerNode = (ComponentModel)depender;
 
                if (dependencyPredicate(dependingNode, dependerNode))
                    dependencies.Add(new KeyValuePair<ComponentModel, ComponentModel>(
                        dependingNode, 
                        dependerNode));
            }
        }
 
        return dependencies;
    }
 
    private readonly IWindsorContainer container;
}

Right now WindsorContainerInspector offers only one method: FindDependencies, which looks for dependencies based on the supplied predicate. I already have some additional ideas on what other possible problems to detect in the container, but I’lll write about this next time.

Published by breki on 03 Nov 2009

DSL For Rendering Rules

Doodle
Creative Commons License photo credit: The Pack

Yesterday I started thinking about a new rendering rules system for Kosmos. The existing system (using Wiki tables) was OK for a while, but it’s starting to show its old age: there is no rule inheritance, the rules are cumbersome to edit (because of wikitext), the selectors are not very powerful, rules are not reusable etc.

I started by investigating how similar software is doing these things. Mapnik has a more elaborate XML-based ruling system. It’s powerful, but it seems too verbose for what I had in mind – I want the rules to be simple to write and even simpler to read. And I want to stay away from XML: XML is easy to parse but not that friendly to humans. And writing expressions using XML character entities (example: “<Filter>[CARTO] &gt;= 2 and [CARTO] &lt; 5</Filter>”) is really unfriendly and error-prone.

The next thing to look at was MapCSS, a CSS-like language for map stylesheets and is a brainchild of Richard Fairhurst, the author of Potlatch, the excellent web-based OSM editor. I like the idea, but I’m worried how it could be implemented in the context of a database-driven map engine. The databases can be huge and you want to minimize (and optimize) the queries run on them, but MapCSS seems to allow too many combinations to make it usable for generating maps in (almost) real-time, and that’s what Kosmos is about. When working efficiently with the database, the rendering engine wants to collect all the related objects in one go, and then decide how to render them. So, for example, if it wants all highways to be rendered red, it’ll fetch all the highways from the database (with a single query) and then go and paint them all red. MapCSS doesn’t really allow this: you need to process each OSM object on its own and go through the list/tree of MapCSS rules in order to know whether (and how) to render it. Maybe I’m wrong and there is a better way to approach this, I’ll have to discuss this further with Richard and see what he thinks.

So now I’m thinking about defining my own domain-specific language (DSL) which would be used to specify rendering rules. I don’t have any specifics yet, but there are some things worth thinking about:

  • The DSL should not be XML-based: angular brackets are not for humans.
  • Separating definition of features from the definition of styles: features tell you what something represents. A forest, for example, is a feature that corresponds to an area tagged with natural=wood or landuse=forest. How it is rendered depends on the type of the map: on topo maps you would render it in green color. On driving maps maybe you wouldn’t render it at all. So the idea is to have a features definitions that could be stored in one place (one wiki page) and then reused all across the styling rules. Right now this is not possible in Kosmos.
  • Expressions: the selector expressions should be more powerful than just simple logical operators. The same goes for expressions for style attributes.

Anyway, this all means I have to implement some kind of a parser for the DSL. So I started looking into possible C# libraries/tools for writing parsers: ANTLR, Coco/R, GOLD, Irony.NET, … There is also a good article called Grammars and parsing with C# 2.0. Time to do some refreshing of knowledge lost way back from my university days…

Published by breki on 27 Oct 2009

C#: Service Caching Proxies With The A Little Help From Some Functional Code

On a current project we’re working on in our company, we are developing a web application which accesses the back-end through some web services. Nothing special really, except that certain web services provide pretty static information like lookup tables, which don’t change very often, so it’s not really necessary to refetch them all the time.

Since we are heavily relying on the dependency injection and all the back-end services are exposed through C# interfaces, it wasn’t really hard to develop a new implementation of such an interface which calls the back-end service and then caches the results in the HTTP cache to be used by any subsequent calls.

Here’s a simple example of a service interface:

public interface IBackendService
{
    List<string> ListSomeStrings(string parameter1, int parameter2);
}

I won’t bore you with an implementation of this, since it’s really a dumb one. What’s interesting is how the cached implementation looks like:

public class BackendServiceCachingProxy : CachingProxyBase<IBackendService>, IBackendService
{
    public BackendServiceCachingProxy(
        IBackendService wrappedService, 
        Cache cache,
        TimeSpan slidingCacheExpiration)
        : base(wrappedService, cache, slidingCacheExpiration)
    {
    }

    public List<string> ListSomeStrings(string parameter1, int parameter2)
    {
        return CallServiceMethod<string>(
            () => ConstructCacheKey("SomeStrings", parameter1, parameter2),
            s => s.ListSomeStrings(parameter1, parameter2));
    }
}

Our caching wrapper inherits from a base class CachingProxyBase. Before showing you the code for CachingProxyBase, let me just quickly explain what the BackendServiceCachingProxy code does.

We’re using HTTP cache, so we have to supply it to the class in the constructor. We also specify how long the cache should be valid (slidingCacheExpiration parameter).

Each service method in the caching wrapper now uses CallServiceMethod method to implement the cached service method calls. You specify two parameters:

  1. A function delegate for constructing the cache key. This key should be unique for each unique combination of method’s input parameters. The CachingProxyBase offers a helper method ConstructCacheKey to help you with this task.
  2. A function delegate for calling the method on the service. This delegate will be used for calling the actual service implementation which will contact the back-end.

 

CachingProxyBase

And now the implementation of the CachingProxyBase:

public abstract class CachingProxyBase<TService>
{
    public void ExpireAllCachedData()
    {
        foreach (System.Collections.DictionaryEntry entry in cache)
            cache.Remove(entry.Key.ToString());
    }

    protected CachingProxyBase(
        TService wrappedService,
        Cache cache,
        TimeSpan slidingCacheExpiration)
    {
        this.wrappedService = wrappedService;
        this.cache = cache;
        this.slidingCacheExpiration = slidingCacheExpiration;
    }

    protected Cache Cache
    {
        get { return cache; }
    }

    protected TimeSpan SlidingCacheExpiration
    {
        get { return slidingCacheExpiration; }
    }

    protected TService WrappedService
    {
        get { return wrappedService; }
    }

    protected TValue CallServiceMethod<TValue>(
        Func<string> constructCacheKeyFunc,
        Func<TService, TValue> serviceMethodFunc)
        where TValue : class
    {
        string cacheKey = constructCacheKeyFunc();

        TValue cachedValue = GetCachedValue<TValue>(cacheKey);

        if (cachedValue == null)
        {
            cachedValue = serviceMethodFunc(WrappedService);
            CacheValue(cacheKey, cachedValue);
        }

        return cachedValue;
    }

    protected string ConstructCacheKey(
        string function, 
        string environmentId, 
        params object[] args)
    {
        StringBuilder cacheKeyBuilder = new StringBuilder();
        cacheKeyBuilder.AppendFormat(
            CultureInfo.InvariantCulture,
            "Proxy-{0}-{1}",
            function,
            environmentId);

        foreach (object arg in args)
            cacheKeyBuilder.AppendFormat(CultureInfo.InvariantCulture, "-{0}", arg);

        return cacheKeyBuilder.ToString();
    }

    private void CacheValue(string cacheKey, object value)
    {
        Cache.Insert(
            cacheKey,
            value,
            null,
            Cache.NoAbsoluteExpiration,
            SlidingCacheExpiration);
    }

    [SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
    private T GetCachedValue<T>(string cacheKey) 
    {
        return (T)cache.Get(cacheKey);
    }

    private readonly TService wrappedService;
    private readonly Cache cache;
    private readonly TimeSpan slidingCacheExpiration;
}

TService is a generic parameter representing the service interface the proxy is enhancing with the caching. I think the code is pretty self-explanatory. The ExpireAllCachedData method is exposed to be used in unit tests to make sure the cache is empty before doing any work.

Using It With Windsor Castle

I’ve made a helper method for configuring in Windsor Castle a specific back-end service with or without caching:

[SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")]
protected void RegisterServiceWithOptionalCache<TService, TImplementation, TCachedImplementation>(
    IWindsorContainer container,
    TimeSpan slidingCacheExpiration)
    where TImplementation : TService
    where TCachedImplementation : TService
{
    string serviceName = typeof(TService).Name;

    if (IsCachingUsed)
    {
        container.Register(
            Component.For<TService>().ImplementedBy<TCachedImplementation>()
                .ServiceOverrides(ServiceOverride.ForKey("wrappedService").Eq(serviceName))
                .Parameters(Parameter.ForKey("slidingCacheExpiration").Eq(slidingCacheExpiration.ToString())));

        if (log.IsDebugEnabled)
            log.DebugFormat("Registered {0}", typeof(TCachedImplementation).Name);
    }

    container.Register(
        Component.For<TService>().ImplementedBy<TImplementation>()
            .Named(serviceName));            
}

 

Conclusion

There are probably more elegant ways of doing this (probably using Windsor’s interceptors and reflection), but I think this code does its job well if you have a small number of service methods to cover.

Published by breki on 05 Jul 2009

Kosmos v2.5 And GroundTruth And Some Developer’s Musings

I finally managed to integrate my new digital elevation model (DEM) processing code into Kosmos. It was a lot more work than I anticipated, mostly because the existing Kosmos’ source code is getting large, difficult to maintain and even more difficult to introduce new functionality. For me it is the best example of why SOLID principles are not just a developers’ buzzword, but that they do have an impact on maintainability of the code as the code base gets larger and larger. Although Kosmos’ code is highly modular, uses all the paradigms of object-oriented programming, even uses inversion of control (IoC) containers quite a lot, this is not enough: certain portions of the code are pretty bloated with multiple responsibilities, which is a first no-no when we talk about SOLID principles: keeping the design clean by separating responsibilities into separate services/components.

When changing the code which serves more than one responsibility, it is difficult to separate these responsibilities and difficult to test the impacts. Unit tests in fact become mini-integration tests and you typically need more setup code in order for a test to be able to run. Which produces unit tests that are fragile and, like the “main” code, difficult to maintain.

I mentioned the usage of IoC containers (Castle Windsor actually). The problem is that you need some mileage to get things right: a common mistake is to drag the container around in your code and use it explicitly to create objects. This defeats the purpose of the IoC container: to wire things together without your intervention. I agree with Joshua Flanagan when he says that the “container” word was unfortunate choice: it should be called a “composer”. Kosmos was one of the first projects where I used an IoC container and it shows: there are a lot of things which I would have done differently now.

All the more reason for me to continue on my effort of rewriting the critical parts from scratch. But that’s a story for some other blog post.

Anyway, I hope the new IBF thing works. The bad news is that I needed to change/hack some code, so I cannot exclude a possibility of a bug or two. The other bad news is that the old “.dat” contours format is no longer supported, so you’ll need to recreate contours for your projects.

The good news, on the other hand, is that we switched to the NASA’s new SRTM server, since the old one has gone to retirement. And even more: the new IBF code is much better that the old Srtm2Osm one, the contours are now placed properly on the map, the contour generator now knows how to correctly ignore data voids and the contour files are much smaller.

I also made changes to GroundTruth to cut the produced IBF tiles exactly around the specified map boundary.

Oh yes, the download links:

Enjoy! And if you find the stuff I’m making useful, please consider a small donation. It will be used for books, software and equipment, all for the benefit of producing even better stuff in the future:

Thanks!

Published by breki on 16 Jun 2009

Gallio: Starting And Stopping Selenium Server Automatically During Testing Using AssemblyFixture

UPDATE (June 17th): I’ve updated the code, see the reasons for it at the end of the post.

In previous projects I worked on we made sure the Selenium Java server was running by manually starting it on our machines (both developers’ and build ones). This was cumbersome: restarting the build server meant we had to log on to the server after the reboot and run the Selenium server again. Of course, a lot of times we forgot to do this, which caused the build to fail.

This got me into thinking: is there a way in Gallio to specify some initialization (and cleanup) actions on the test assembly level? And of course, the answer is yes: using the AssemblyFixture attribute. This is what I like about Gallio/MbUnit: most of the time the feature requests I come up with are actually already implemented.

So anyway, you can specify this attribute on a class and then add FixtureSetUp and FixtureTearDown attributes on its methods. These will be executed on the test assembly-level: setup methods will be executed before any test fixtures have been run and teardown methods will be executed before the test assembly has been unloaded by the test runner.

I then used this nice feature to start the Selenium server and then dispose of it after tests:

[AssemblyFixture]
public class SeleniumTestingSetup : IDisposable
{
    [FixtureSetUp]
    public void Setup()
    {
        seleniumServerProcess = new Process();
        seleniumServerProcess.StartInfo.FileName = "java";
        seleniumServerProcess.StartInfo.Arguments =
            "-jar ../../../lib/Selenium/selenium-server/selenium-server.jar -port 6371";
        seleniumServerProcess.Start();
    }

    /// <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>
    /// <param name="disposing">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)
        {
            if (disposing)
                DisposeOfSeleniumServer();

            disposed = true;
        }
    }

    private void DisposeOfSeleniumServer()
    {
        if (seleniumServerProcess != null)
        {
            try
            {
                seleniumServerProcess.Kill();
                bool result = seleniumServerProcess.WaitForExit(10000);
            }
            finally 
            {
                seleniumServerProcess.Dispose();
                seleniumServerProcess = null;
            }
        }
    }

    private bool disposed;
    private Process seleniumServerProcess;
}

Note that the class is disposable – this ensures the Selenium server is stopped even if you run tests in the debugger and then force the debugger to stop before finishing the work. The Dispose method calls DisposeOfSeleniumServer, which does the actual work of killing the process and disposing of the evidence.

NOTE: This is a second version of the code. I needed to update the old one because I noticed that when running the tests in CruiseControl.NET, the Selenium server java process was not stopped properly. The only way I could stop it is by killing it, which in general isn’t a good practice. The unfortunate side effect of this “killing” is that the CruiseContol.NET service cannot be stopped normally – it also has to be killed when you need to restart it. I’ll try to solve this problem in the future.

Published by breki on 09 Jun 2009

FxCop: How To Use It

Long Beach Harbor Patrol Say No Photography From a Public Sidewalk
Creative Commons License photo credit: Thomas Hawk

This is a second post on my “guidelines” series. Some information here is specific to the projects I’m working on, and some is more general and so applicable to any project.

FxCop is a free static source code analysis tool created by Microsoft. It analyses your built assemblies and reports any issues it encounters. It has a set of rules (which can be turned on/off) which it uses to detect these issues. FxCop comes both in the command-line form (FxCopCmd) and as a Windows GUI.

Building

The general approach in our build scripts is: the script compiles the code and then immediately runs the FxCop analysis. If it detects any issues, it automatically runs the GUI and opens the relevant FxCop project. NOTE: you need to press F5 key (rebuild project) in order for FxCop to show the latest results!

When run “headless” (on the build server), the script of course doesn’t open the GUI – it just simply fails and then kindly informs the offender via email.

Resolving Issues

There are basically three ways how to resolve issues detected by FxCop, described in the following subsections.

Fixing The Code

Fixing the code where the issue has been detected is the preferred approach.

Applying Suppression Attribute On The Code

SuppressMessageAttribute can be used to suppress reporting of a specific defect by FxCop:

[SuppressMessage("Microsoft.Performance", "CA1822:MarkMembersAsStatic")]

You can autogenerate these suppress lines by right-clicking on the issue, selecting Copy As -> Suppress Message. This will copy the suppress attribute into the clipboard and you can then paste it into the offending code. Depending on the type of the issue, the code has to be copied either in front of a class/interface, method, property or a field.

You should only suppress issues which you think

  1. aren’t really issues
  2. aren’t relevant
  3. the offending code has been designed on purpose.

On all other occasions, it is better to fix the code.

Excluding Issues In FxCop GUI

Sometimes (in rare situations) it is difficult to suppress an issue. In that case you can exclude them in the FxCop GUI by right clicking on the issue(s) and selecting Exclude.

NOTE: if you do any excluding in the GUI, don’t forget to save the FxCop project before exiting!

Language Issues

Since FxCop checks the spelling of class, method and other names in the source code, some FxCop issues are related to English dictionary. For example, on the latest project I’m working on, FxCop reported a spelling error for classes containing the MVC string, since MVC “word” isn’t in the standard English dictionary.

This can be resolved by adding such words in the CustomDictionary.xml file which is stored in the root directory of the project’s solution:

<?xml version="1.0" encoding="utf-8" ?>
<Dictionary>
  <Words>
    ...
    <Recognized>
      ...
      <Word>mvc</Word>
      ...
    </Recognized>
    ...
  </Words>
  ...
</Dictionary>

Adding FxCop Analysis On New VS Projects

When creating new projects in the solution, you have to do two things:

  1. Add the CODE_ANALYSIS compilation symbol in the project (using VisualStudio). Don’t forget to add it both for Debug and Release configurations. Without this symbol, FxCop will ignore any of your Suppress attributes in the code.
  2. Add the project to the FxCop project file, example:
<Target Name="$(ProjectDir)/MyTool/bin/MyTool.dll" Analyze="True" AnalyzeAllChildren="True" />

In general, I tend not to add FxCop analysis for unit test projects because unit test classes usually violate certain rules on purpose (or by design). One example is having test methods which don’t reference class instance stuff, for which FxCop reports the “mark member as static” issue.

Finally

There are some other minor “quirks” which can occur, I’ll try to add additional guidance if/when my team members encounter them :) .

Published by breki on 08 Jun 2009

Gallio: Filter Attributes For Test Methods

There are three attributes which function as filters when running tests using any of the Gallio’s test runners:

  • Pending: tests which are in development and currently don’t run should be marked with the Pending attribute. This means the test runner will skip them when running the build script.
  • Ignore: this attribute is used for marking tests which are never to be run (they are kept in the code as a history). In general, it is a good practice to avoid such tests – you can get the history from your source control.
  • Explicit: tests marked with this attribute will only run when selected individually in the VS (Resharper, TestDriven.NET). They will not be run as part of the build script. Explicit tests are usually those which depend on a certain external system which cannot be guaranteed to be available at all times – we don’t want such tests to cause failures in our builds.

It is a good practice to supply these attributes with a string argument describing the reasons for marking the test.

UPDATE: Jeff Brown kindly provided some additional information about these attributes:

Tests marked [Ignored] and [Pending] will show as Warning annotations in the test report in addition to being skipped. In ReSharper they will also be shown with a yellow warning stripe to remind you that they are there and need to be looked at.

You can also add your own annotations to various code elements with the [Annotation] attribute.

This is my first article in the “guidelines” series I plan to write in the future. I want to maintain these guidelines separate from concrete project’s documentation since in the past I always had to copy this kind of stuff from one project’s wiki to another.

Published by breki on 19 Mar 2009

Welcome To Cairo!

Camouflage class in New York University, where men and women are preparing for jobs in the Army or in industry, New York, N.Y. They make models from aerial photographs, re-photograph them, then work out a camouflage scheme and make a final photograph (LOC
Creative Commons License photo credit: The Library of Congress

No, I’m not going to Egypt. Cairo I’m referring to is an open source 2D graphics library, used by GTK+, Mono, Mozilla Firefox and many others.

As part of my source code spring cleaning effort I started modeling Kosmos mapping library from scratch. The idea is to separate pure map-rendering stuff from the Kosmos application and infrastructure logic. Then this map rendering code could be reused in other applications.

The effort already bore some fruit: the new model has a much cleaner separation of the drawing engine from the rest of the code:

public interface IPainter : IDisposable
{
    void BeginPainting ();
    void Clear ();
    void DrawLines (int[] coords);
    void DrawPoint (int x, int y);
    void EndPainting ();
    void PaintCurve (PaintOperation operation, int[] coords);
    void PaintPolygon (PaintOperation operation, int[] coords);
    void PaintRectangle (PaintOperation operation, int x, int y, int width, int height);
    void SetHighQualityLevel (bool highQuality);
    void SetStyle (PaintingStyle style);
}
 

This is all there is to the drawing (well maybe a few methods like drawing text are missing, but you get the idea). So there are no GDI+ primitives (like Points, Colors, Pens etc) in the interface. Which means I can start playing with other drawing libraries, like Cairo:

mapgdimapcairo

The two images represent a collection of GPS traces: the left one was drawing using GDI+ implementation of the IPainter interface, the right one using Cairo. Alpha-transparency is used to get the effect of area most covered by traces (the dark color) against those only visited once (the lightest color).  As you can see, there are some differences in the coloring between GDI+ and Cairo’s renderings – these are probably because of the quality settings I specified for GDI+, which could not be replicated in Cairo. Also, Cairo is on average twice as slow in rendering compared to GDI+. I’m not sure why, but I’ll try to improve this.

All in all, I’m very pleased with the result, especially considering that I only started this redesign few days ago. And the main point why I’m playing with Cairo is the fact that you can produce SVG output using the same code. This means that Kosmos will be able to produce vector maps in the future, which can then be manually post-processed to fix any rendering problems (like label-placing).

The main issue I always have in my mind is to keep the performance of map rendering the same with this new design. This was a big concern for me before starting, but now I think the new design is so much better that it will actually be a performance improvement, at least memory-wise, if not speed-wise.

Published by breki on 05 Mar 2009

Fix: Slow Debugging In Visual Studio

Morty Comes Home
Creative Commons License photo credit: Kevin Eddy

I’ve just found the cure for slow debugging in Visual Studio. By “slow” I mean waiting couple of seconds after each debugger step. The solution was suggested by Jeff Brown on one of Gallio Google Groups threads: turning off the “Enable property evaluation…” setting in Debugger options (Tools -> Options -> Debugger):

Visual Studio Debugger Options

After turning this off, I don’t notice any real delay between debugging steps. The downside is that you won’t get automatic updates of values of object’s properties in Watch and other debugger windows. Instead you get a nice little Refresh button for each of the properties and you’ll need to click on it to get the current value:

Visual Studio Debugger 2

I think this is a minor nuisance compared to the substantial increase of the debugging speed. Not that I’m a big fan of big debugger usage. To quote Scott Belware:

Debugging code is a slow, time consuming process.  Time spent in a debugger is sloth time.  You might be thinking that you’re perfectly effective in a debugger and that you don’t have any objections to doing code validation in a debugger rather than in a well-factored unit test.  This is merely an assumption fed by how habituated you are to using a debugger.  Without having a TDD practice, you have no basis of comparison for how ineffective debugging is compared to writing well-factored unit tests for well-factored code.

Also check out Jeremy D. Miller’s posts about TDD and debugging.

Next »