Archive for the 'C#' Category

Published by breki on 24 Aug 2010

Windsor Castle: Strange Resolving Behavior

A user reported a bug in Maperitive – it throws

Castle.MicroKernel.Resolvers.DependencyResolverException: Could not resolve non-optional dependency for ‘Karta.DataSources.OsmFileMapDataSource’ (Karta.DataSources.OsmFileMapDataSource). Parameter ‘fileName’ type ‘System.String’

I tried to reproduce this behavior using a simple unit test, but I couldn’t, so I’m posting the actual code. This is where the exception occurs:

return windsorContainer.Resolve<OsmFileMapDataSource>();

And this is how OsmFileMapDataSource constructors look like:

        public OsmFileMapDataSource(
            string fileName,
            IFileSystem fileSystem,
            IMapDataLayerFactory layerFactory)
        {
            ...
        }

        public OsmFileMapDataSource(IMapDataLayerFactory layerFactory)
        {
           ...
        }

Needless to say, both IFileSystem and IMapDataLayerFactory are registered in the container (IMapDataLayerFactory is registered as a typed factory, by the way). OsmFileMapDataSource is also registered as an implementation of itself. And I’m using version 2.1.0.6655 of the library.

What’s strange about this is that if I move the second constructor in front of the first one, the component is resolved without problems. I’m not sure if this is intended behavior, but I doubt the order of constructors should be a determining factor on how components are resolved.

But as I said, I couldn’t reproduce this behavior using a simplified test code, so I guess I should start debugging it instead.

Published by breki on 06 Aug 2010

Maperitive: Enhanced Usability & Scripting Support

Maperitive running scripts

For the last week or so I’ve been busting my fingers with one of the harder things to implement in a desktop GUI: application responsiveness when executing longer-running tasks. By longer-running I mean something that takes more than a couple of seconds.

Simple desktop applications tend to run everything synchronously: when the user presses a button, the action gets run. After the action finishes, the control is given back to the user. Simple, but totally crappy. The problem is that the action gets run on the same thread that services the GUI, so until the action finishes, the application will not be able even to refresh itself or respond in any meaningful way to user clicks or key presses. And since there is no refresh, you cannot show any progress indicators to the user. I know I wouldn’t want to wait half an hour for something to finish without some reassurance that the application is still alive and not waiting for the electricity to run out.

Maperitive already had a lot of responsiveness code implemented, but it was still an “under the construction” design. The additional complication was the fact I want Maperitive to have a good script runner and scripts can take a very long time (downloading OSM data, generating tiles etc.). After a lot of trials and errors I finally managed to implement the whole thing in a consistent package. And believe me when I say it was not easy.

So what is new:

  • When running scripts (or longer tasks), Maperitive draws an indicator on the map (see the screenshot above) and launches a “sort of modal” mode – most of GUI controls are disabled so the script doesn’t get confused by some inadvertent user action. However, the application is still responsive: you can view the progress of the script in the command log.
  • Aborting scripts: as the indicator says, you can press the escape key to abort the script. If you prefer torturing your mouse instead of your keyboard, there’s an “Abort task” button in the bottom right corner which does the same thing.

Not all of running tasks have been switched to the new system. Loading OSM files is one example of a task that will still block the GUI, but I will gradually improve these things.

You can download the latest release at http://maperitive.net/download/

Enjoy!

Published by breki on 12 Jul 2010

Uri Class Cheat Sheet

Another reference post, this time covering usage of .NET Uri class.

Example URL: http://somewhere.else.com:9999/service/packages?page=2#fragment

The table below contains values for various properties of Uri for that example URL:

AbsolutePath /service/packages
AbsoluteUri http://somewhere.else.com:9999/service/packages?page=2#fragment
Authority somewhere.else.com:9999
DnsSafeHost somewhere.else.com
Fragment #fragment
Host somewhere.else.com
HostNameType Dns
IsAbsoluteUri true
IsDefaultPort false
IsFile false
IsLoopback false
IsUnc false
LocalPath /service/packages
OriginalString http://somewhere.else.com:9999/service/packages?page=2#fragment
PathAndQuery /service/packages?page=2
Port 9999
Query ?page=2
Scheme http
Segments array: “/”, “service/”, “packages”
UserEscaped false
UserInfo “” (empty string)

Published by breki on 11 Jul 2010

Windsor Castle: Auto-Wiring Using Parameter Names

NOTE: this is probably only one way of doing things in Windsor Castle. If you know of any other, don’t hesitate to write a comment.

A design problem I was trying to solve yesterday: I have a component which depends on two implementations of the same interface:

public class HelpCommand (    
   ICommandDescriptor oneLinerDescriptor,     
   ICommandDescriptor detailedDescriptor)     
{     
   ...     
}     

HelpCommand prints out human-readable descriptions of various commands in Maperitive. If the user specifies the exact command, HelpCommand prints out a detailed description. On the other hand, if the command parameter is not specified, HelpCommand lists all of the commands and prints a one-liner description for each of them. So there are two implementations of the ICommandDescriptor interface: OneLinerDescriptor and DetailedDescriptor classes.

The problem I was having with this design is that all of my *Command components are registered in one go, using the convention like

container.Register (AllTypes.Of<ICommand>().FromAssembly (typeof(ICommand).Assembly)    
   .Configure (c => c.Named (c.Implementation.Name).LifeStyle.Transient));

so I’m letting Windsor do all the wiring magic without me being able to provide any custom registration logic for individual commands like HelpCommand. So how do I tell Windsor which component to use for oneLinerDescriptor and which for detailedDescriptor?

Bad Solution

Of course, I could simply specify the concrete implementations in HelpCommand’s constructor:

public class HelpCommand (    
   OneLinerDescriptor oneLinerDescriptor,     
   DetailedDescriptor detailedDescriptor)     
{     
   ...     
}     

But this couples the three classes together and goes against the “rely on abstractions, not implementations” mantra. It also makes unit testing of HelpCommand more difficult, since I have to drag the two descriptor classes around (and they could have their own dependencies to satisfy, which further bloats the unit testing code).

Factories?

I could use a factory to get the implementations I need, but that would be wasteful: a simple constructor dependency is much slicker and it doesn’t introduce an additional component (factory) into the picture. Also, factories are more suited for components which are created later, on-demand. In my case I want the descriptors to be available right at the beginning of HelpCommand’s lifecycle.

Resolving By Name

So I got an idea: why not use the name of the constructor parameter as an indicator of what kind of implementation I need?

This requires writing a custom subresolver:

    public class SubDependencyResolverByName : ISubDependencyResolver
    {
        public SubDependencyResolverByName(IKernel kernel, string componentPrefix)
        {
            this.kernel = kernel;
            this.componentPrefix = componentPrefix;
        }

        public bool CanResolve(
            CreationContext context, 
            ISubDependencyResolver contextHandlerResolver, 
            ComponentModel model, 
            DependencyModel dependency)
        {
            if (dependency.IsOptional)
                return false;

            return FindCandidateComponent(dependency.DependencyKey, dependency.TargetType) != null;
        }

        public object Resolve(
            CreationContext context, 
            ISubDependencyResolver contextHandlerResolver, 
            ComponentModel model, 
            DependencyModel dependency)
        {
            ComponentModel dependencyResolvingComponent = FindCandidateComponent (dependency.DependencyKey, dependency.TargetType);
            return kernel.Resolve(dependencyResolvingComponent.Name, dependency.TargetType);
        }

        protected ComponentModel FindCandidateComponent (string dependencyKey, Type targetType)
        {
            foreach (GraphNode node in kernel.GraphNodes)
            {
                ComponentModel visitedComponent = (ComponentModel) node;
                if (visitedComponent.Service != targetType)
                    continue;

                if (componentPrefix == null)
                {
                    if (0 == string.Compare(visitedComponent.Name, dependencyKey, StringComparison.InvariantCultureIgnoreCase))
                        return visitedComponent;
                }
                else
                {
                    if (false == visitedComponent.Name.StartsWith(componentPrefix, StringComparison.InvariantCultureIgnoreCase))
                        continue;

                    string nameWithoutPrefix = visitedComponent.Name.Substring(componentPrefix.Length);
                    if (0 == string.Compare (nameWithoutPrefix, dependencyKey, StringComparison.InvariantCultureIgnoreCase))
                        return visitedComponent;                    
                }
            }

            return null;
        }

        private readonly IKernel kernel;
        private readonly string componentPrefix;
    }

…and attaching it to the container:

container.Kernel.Resolver.AddSubResolver (
   new SubDependencyResolverByName (container.Kernel, "auto_"));

Results

Initially I had problems with this new resolver: it tried to be too smart and it messed with the existing (non-problematic) component wiring. So I decided to limit its scope only on dependency components which have a container ID starting with a certain prefix (in my case “auto_”). So if I want OneLinerDescriptor and DetailedDescriptor to be auto-detected by the resolver, I need to register them as “auto_OneLinerDescriptor” and “auto_DetailedDescriptor” in the Windsor container (casing is ignored). The resolver is currently limited to constructor dependencies only, but I see no reason it shouldn’t work for property injections too.

Is name-matching a good approach to auto-wiring components? I don’t know, time will tell. I certainly feel there’s something missing in how Windsor resolves dependencies by the default: type-matching is fine for simple scenarios, but as soon as you have more than one implementation of the same service interface, you need to specify service overrides or rely on "black magic” to wire things for you.

Published by breki on 07 Jul 2010

System.Web.HttpRequest Paths Cheat Sheet

More a “remember” post for me than a real reference thing, but I think it might be useful to anybody doing more than simple work with HttpRequests.

Example request URL: http://localhost:65107/Services.svc/services?page=30

The table below contains values for various path-related properties of HttpRequest for that example request URL:

ApplicationPath /
AppRelativeCurrentExecutionFilePath ~/Services.svc
CurrentExecutionFilePath /Services.svc
FilePath /Services.svc
Path /Services.svc/services
PathInfo /services
PhysicalApplicationPath D:\svn\eEnvoyer\SEPA\EEnvoyer.Server\
PhysicalPath D:\svn\eEnvoyer\SEPA\EEnvoyer.Server\Services.svc
RawUrl /Services.svc/services?page=30
Url http://localhost:65107/Services.svc/services?page=30

Published by breki on 25 Apr 2010

Windows Services And Working Directories

A reminder for me: when developing Windows services, in the initialization code set the Environment.CurrentDirectory to the directory where your binaries are located:

string applicationFullPath = Assembly.GetExecutingAssembly().Location;
string applicationDirectory = Path.GetDirectoryName(
Path.GetFullPath(applicationFullPath));

log.InfoFormat(
"Setting the current directory to '{0}'...",
applicationDirectory);
Environment.CurrentDirectory = applicationDirectory;

This helps avoiding problems with .NET framework implicitly accessing various file resources stored together with your binaries. I had a situation where I wanted to validate an XML file using XSD schema files stored in my application directory. The code worked OK in the integration tests but failed when run inside a Windows service. It turns out .NET Framework’s XML validation code wanted to import certain dependent XSD schema files from the current directory, which is, in the case of Windows services, C:\Windows\System32 by default. Of course, the needed XSD files weren’t there, but the validation code doesn’t really tell you this, it just reports an unhelpful validation error.

Published by breki on 22 Apr 2010

Kerning Or How To Outfox GDI+

500px-Metal_type_kerning.svg[1] (image taken from Wikipedia)

I’m working on a text-on-path algorithm for Maperitive to be able to render things like street names. GDI+ does not have a built-in function for drawing texts on a path, so I’m stuck with writing my own.

Although there are a lot of implementations of such an algorithm out there, they all miss one important thing: kerning. Kerning is basically telling a character to move a bit closer to its neighbor if there is enough space for them to huddle together:

Kerning[1] (image taken from Wikipedia)

Since the path can consist of several line segments (and even curves), you need to render each character (glyph to be more precise) separately to be able to rotate it using the angle of the line segment it will be drawn on. The problem is determining how far from the previous character to place the next character. GDI+ offers a method called MeasureString, but calling it on a single isolated character returns a character width value without any kerning taken into account, so characters like V and A can appear too spread apart. There is another method, MeasureCharacterRanges, which can measure each individual character width for a given text, but it has a practical limit of 32 characters and is pretty processor- and resource-intensive. I’ve used it for the text-on-path algorithm for Kosmos but the results weren’t very satisfactory.

From my (basic) understanding of how kerning usually works on computer typography, a font which has kerning information stores kerning offsets for character pairs. So, for example, V and A will have a different (usually stronger) kerning than say, character pair V and T. The problem with GDI+ is that you don’t really have access to this information.

One option would be to use old GDI’s font and text functions to fetch the information about the kerning pairs, but these need to be P/invoked and thus will probably not work on Mono, which makes them unusable for Maperitive – I’m really trying to make Maperitive run on multiple platforms.

So after spending a day in brainstorming, I got an idea on how to handle kerning myself. It’s really simple: I will calculate the kerning myself (using the mentioned MeasureString method). The formula is simple:

<character kerned width> = <character non-kerned width> – (<character pair non-kerned width> – <character pair kerned width>)

I can get all of the three values on the right of the equation using the MeasureString: first I’ll measure each character’s individual (non-kerned) width and then I’ll measure the width when they are drawn together. The difference between these is the actual kerning, which is then used to calculate the kerned width of the first character.

The added twist to this tale is that I’ll keep this information in a cache, to keep the expensive calls to the MeasureString method to the minimum. This cache could even be persisted to the disk. Of course, each font family and font style dictates its own kerning, so the cache needs to be extended with this information.

One potential problem is how to handle kerning information for different font heights. Since Maperitive supports continuous zooming levels, the number of different font heights used is (almost) limitless. I’ve decided to cut some corners here: the kerning will be calculated (and stored) for some nominal font height (say 100 em) and then interpolated for any needed height. We’ll see how that goes… next time.

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…

Next »