Archive for the ‘.Net Framework’ Category

Thoughts on BDD

Monday, April 27th, 2009

I had been reading up on BDD a little while ago. Which stands for Behavior Driven Development and is initially an improvement on TDD. Or better said an improvement on the way to think about TDD. It’s not as much a completely new way of writing tests as an eye opener on how to correctly write tests. Instead of writing tests you’re writing behaviors or specifications of behaviors. The idea of behaviors is much more intuitive then tests.

I mean when I first started to write tests, I had a hard time to get into it. I had a lot of questions about where to start writing tests, how much to test, what was the best way to name your tests and so on… If I had known about BDD back then I would have had a much easier time to get into TDD. Because by only just thinking about it as behaviors it answers some of the questions by itself.

But this post is not an introduction into BDD as there are a lot of good resources on the net about it already.

For example

  • Introduction to BDD by the man who dreamed up BDD Mr. Dan North himself.
  •  BDD by Scott Bellware a big promoter of BDD in .NET land.

What I wanted to talk to you about are in my opinion a few misconceptions about the subject. I have seen people say “Wohow what is this? There are multiple ways to do BDD.”. And yes that is partially correct, because Dan North’s views on it have grown to encompass a much larger idea then just testing. A part of it contains analysis as wel and in such the tests have changed to reflect these new views. 

If you have read the introductory by Dan North or sat at a presentation about BDD you would know that BDD takes a bigger part of Agile software developement then just tests. Among other it forms an ubiquitous language where the “tests” form an extention of it.

On the other hand there is Dave Astels who took the former ideas of BDD that only focus on improving TDD. This is the so called Dave Astels version of BDD that is also known as Context/Specification so not to be confused with BDD. 

These aren’t mutually exclusive ideas, one is just a subset of the other.

You can use the full BDD for writing acceptance tests through stories or use the subset for state/interaction testing. As for the difference in testing framework… wel that’s just like every framework it’s a matter of choice and opinion.

On another note, when writing specifications (or tests) for a library you can use common developer language like dictionary or thread in the naming if it is absolutely necesary to understand what the specification is doing. Because the group you’re targeting are developers I think it is allowed to use programming terminology.

On the other hand I think it is best to keep it at a minimum to make the specifications more easily readable. Also when your specifications are going to be read by non-programmers it is best to prohibit such terminology.

Single instance application with C#

Friday, April 24th, 2009

If you’re developing a winforms application with VB.NET you can set a checkbox in the designer to have a single instance application. This option is not available to C# developers but since language does not matter in the .NET space you can just use the same classes the VB.NET designer uses.

By subclassing WindowsFormsApplicationBase you can get the same behaviour. The class can be found in the Microsoft.VisualBasic.ApplicationServices namespace.

public class SingleInstanceManager
      : WindowsFormsApplicationBase
{
 
    public SingleInstanceManager()
    {
        IsSingleInstance = true;
        EnableVisualStyles = true;
        ShutdownStyle = ShutdownMode.AfterMainFormCloses;
    }
 
    protected override bool OnStartup(StartupEventArgs e)
    {
        return true;
    }
 
    protected override void OnCreateMainForm()
    {
        base.OnCreateMainForm();
        MainForm = new MainForm();
        HideSplashScreen();
    }
 
    protected override void OnStartupNextInstance(StartupNextInstanceEventArgs eventArgs)
    {
        base.OnStartupNextInstance(eventArgs);
        MainForm.Focus();
    }
 
    protected override void OnCreateSplashScreen()
    {
        base.OnCreateSplashScreen();
        SplashScreen = new SplashForm();
    }
}

Change your Program.cs to use this new class.

[STAThread]
static void Main()
{
    var manager = new SingleInstanceManager();
    manager.Run(new string[]{});
}

Using attributes with Spring.NET to configure your application

Friday, April 24th, 2009

When using Spring.Net you end up editing xml files to wire everything together. While something like fluent Spring.Net would be very nice to have, some of the xml authoring can be solved by using attributes. As sample I’ll use a real life example where I implemented it.

I had to add reporting to an application which consists of different modules. Depending on the license of the user he’d have a contacts module, a document management module, tasks, etc. The user would select the contents of his report and then fire up the designers to choose fields, order or group them, etc.

The end-user components we use are quite powerful so I only had to find a way to get the content into the report component as a dataset. Normally I keep away from using datasets but in this case it’s allowed. Note that I’m not using data adapters and other stuff, I just transform my rich object model into a flat dataset.

Each module writes an entitymapper for all of the entities that can be used as reporting source.

[EntityMapper(EntityType = typeof(ContactDto))]
public class ContactMapper
    : EntityMapper
{
    public override DataSet MapToDataSet(IEnumerable<ContactDto> entities)
    {
        DataSet dataSet = new DataSet();
        //fill with data
        return dataSet;
    }
}

I only wanted to add the object definition to the configuration specific for this module. I didn’t want to edit the config for reporting module. It should just pick all the mappers up and use them when entities of that type are handed to it.

The solution for this is using an IObjectPostProcessor to inspect everything that is configured in your container and do some additional logic.

public class MapperPostProcessor
    : IObjectPostProcessor
{
    private readonly Type attributeType;
 
    public MapperPostProcessor()
    {
        attributeType = typeof (EntityMapperAttribute);
    }
 
    public DataSetMapper Mapper
    {
        get;
        set;
    }
 
    #region IObjectPostProcessor Members
 
    public object PostProcessAfterInitialization(object instance, string objectName)
    {
        object[] o = instance.GetType().GetCustomAttributes(attributeType, true);
        if(o.Length == 1)
        {
            var attribute = o[0] as EntityMapperAttribute;
            var entityMapper = instance as IEntityReportMapper;
            Mapper.RegisterMapper(entityMapper, attribute.EntityType);
        }
        return instance;
    }
 
    public object PostProcessBeforeInitialization(object instance, string name)
    {
        return instance;
    }
 
    #endregion
}

Any postprocessor in your Spring context is automatically picked up by Spring and the methods will be called on the appropriate time. In this implementation I check every instance that is handed to the PostProcessAfterInitialization method for my own attribute, if it’s present I register it to my mapper manager for the specified type. For more info about this you should check out the documentation.

Out of the box Spring.NET has some of these already for you. For instance you can put the [Required] attribute on the properties that need to have a value after they have been constructed. If at that time they haven’t been initialized you’ll get an exception.

Moving WPF control to class library

Wednesday, April 15th, 2009

I recently made my first WPF control. It’s just a simple control to show media files. After experimenting with it and seeing all was ok I moved the files to the main project where it would reside in a class library project.

It stopped building with the exception: ‘Library project file cannot specify ApplicationDefinition element’.

To anyone with 15 minutes of WPF experience this does not say a lot. Even after searching the web I couldn’t really understand what was going on but this thread did set me on the right track. You need to set the build action of your WPF control to ‘Page’.

wpfusercontrol

Strongly typed databinding

Monday, March 23rd, 2009

Databinding proves to be very useful in some cases, but often turns out to be a maintenance nightmare. Since it requires strings with the property names to be passed as parameters of the Binding object. When the class, where a textbox is binded to, changes over time, so do property names. But since these property names are passed around as a string, they do not raise compile errors, causing unexpected behaviour of the application.

Here’s how you can make these bindings strongly typed, causing compilation errors if the property name of a class would change. Imagine we would like to bind a textbox to the Name property of the Person class, here’s the function that is going to help us. This function has a lambda expression returning a string and receiving a Person as parameter.

public string GetPropertyName(Expression<Func<Person, string>> propertySelector)
{
   MemberExpression memberExpression = propertySelector.Body as MemberExpression;
   MemberInfo propertyInfo = memberExpression.Member;
   return propertyInfo.Name;
}

The original binding code would like this, notice the “Name” string.

m_TextEditPerson.DataBindings.Add(new Binding("Text", m_Person, "Name"));

Here’s the new binding statement.

m_TextEditPerson.DataBindings.Add(new Binding("Text", m_Person, GetPropertyName(x => x.Name)));

Load event not fired when using the WebBrowser control

Monday, March 16th, 2009

Today I had to add a way so that a webpage could be displayed with each form in a WinForms application. Doesn’t sound that hard now does it? We’ve developed our own little MVC/MVP framework, so in order to enable this behaviour I just had to create a usercontrol, throw a webbrowser control on it, some logic and done. Our framework automatically detects the control and the end user can add these controls at run time to any form he wants.

The logic I had added to the control detected if a certain file had been clicked, since these had to be handled by the application and not by the webbrowser, really straightforward stuff. In the load event of the control I registered to the necessary events which would trigger my code. The only problem being that the load event was never fired. I looked at my code again, maybe 20 lines or so including brackets and braces, and didn’t see anything wrong with it. I then looked to some other controls  my colleagues and I had already written in the past to see if I did something wrong but couldn’t see any big difference. Time for some debugging!

With breakpoints all over the place it was clear that the constructor of my form and presenter was being called and the event subscription was being done but the Load event somehow was never triggered. I went over and over the code again and again but really couldn’t get my head around this. Why on earth wasn’t the event being fired. I even went away from the compiler generated properties back to the old fashioned getters and setters with a field just to make the code look more like all the other controls but nothing worked.

Until I removed the webbrowser control from my usercontrol. Now all of a sudden my load event was being fired, the culprit was found!

So somehow when you use the webbrowser control, your load event, and who knows what else, is fubar. I only found one usable search result on the internet, here. And the workaround mentioned works like a charm, make your webbrowser control invisible until after the load event :-) . Well in my case the presenter calls NavigateToUri(uri) on my view and in that method I set the visibility of the webbrowser to true. Smells like a bug to me but at least now it’s working, too bad it took 4-5 hours.

Custom username password validator with Geneva

Thursday, February 5th, 2009

I had been busy for hours to get my custom username password validator working with the Geneva Framework when I turned to the MSDN forum to look for help. Someone was kind enough to point me to this article by Yossi Dahan which solved my problems.

I’ve modified one of the samples that is installed with the Geneva Framework. It relies on having two certificates, one with CN=localhost and one with CN=STS.

Download

WCF Reliable Session and keep-alives

Monday, January 26th, 2009

We recently used WCF services for a monitoring application, which showed the status of business-critical systems like water/fire-detection in the datacenter, generators powering the production lines and so on. 

Instead of using a polling mechanism, we used an event-driven approach. The clients would subscribe for certain events and the server would notify the clients when these events happened. Relieving the network of excessive and possibly unneeded chatter. Because of the "business-critical" aspect of the application, we had to ensure that our communication with the server was not halted or interrupted. If something happened to the connection, the client would have to notify the user, instead of showing green lights and giving the user the impression that everything is a-ok, while all hell broke loose in the datacenter (and also destroying the PLC) for instance. Since our client would wait for events to happen and wouldn't know when the connection would have been dropped for some reason.

While working through the WCF documentation, we stumbled upon the Reliable Session which could be specified in the binding of the connection. According to the documentation a Reliable Session would send a keep-alive message after half of the Inactivity Timeout. Unfortunately the expected behaviour was not the same as the actual behaviour, the connection would go to the faulted state after 10 minutes despite configuring an Inactivity Timeout of 10 minutes. (Which should have forced a keep-alive message to be sent after 5 minutes) Eventually we came accross this blog post by Paulo Reichert, clarifying this glitch. Apparently it was supposed to work that way, but a last minute change to the Receive Timeout behaviour overrode the keep-alive behaviour. *couch* Unit Testing *couch* 

In the end we implemented our own keep-alive system in the form of a watchdog. A registry in a PLC would change every x seconds and the client would be notified of this change through an event. If our client does not detect a change of this registry for y seconds we notify the user. This ensures the connectivity between the client & server (including feedback to the user) and the proper workings of the PLC. The "keep-alive" message resets the Inactivity Timeout, prohibiting it from reaching the specified value and causing the connection to be dropped.

Setting the Receive Timeout to infinite, as suggested by Microsoft, is a work-around which does not solve the problem at a fundamental level. We sincerely hope Microsoft will fix this bug in a future release!

Safe Cross Thread UI Access

Wednesday, May 21st, 2008

When you have multiple threads running in your application and have a user interface you’ll eventually run into the fact that UI elements are only allowed to be called from the same thread they are created in. The fast workaround for this is to set the CheckForIllegalCrossThreadCalls property of your controls to false but since we’re all good developers we want to solve this in a clean way.

There is an interface to track this behaviour called ISynchronizedInvoke which defines all the methods you need, this interface is implemented by the UI controls. You need to see if the property InvokeRequired is true and call Invoke (or BeginInvoke) to make your call thread safe. I used to declare a delegate for each different method signature I encountered since the Invoke methods take a delegate as argument. But there is a much more elegant way by using the MethodInvoker delegate and an anonymous delegate as you can see below. This prevents you from declaring a lot of delegates just for making your calls thread safe. This is illustrated below by a method in a presenter which updates my view.

public void IncomingMessage(ChatMessage msg)
{
    if (m_ChatView != null && m_ChatView.InvokeRequired)
    {
        m_ChatView.BeginInvoke(new MethodInvoker(delegate
        {
            IncomingMessage(msg);
        }), new object[] { msg }); return;
    }
    m_ChatView.DisplayMessage(BuildIncomingDisplayMessage(msg));
}

Minimal Lucene.Net example

Tuesday, April 15th, 2008

About a year ago we had to incorporate a Lucene.Net index in an application because we were unable to achieve acceptable speeds while performing regular SQL queries on a database. The database was a 4GB large – poorly normalised – full of NULLs – monster, which would eat our queries for breakfast and spit out time-outs in return. We had to make a Google-like search on the data spanning a lot of columns, including full-text search. Using Lucene.Net to index the searchable columns of this database enabled us to search the data within seconds and in some cases even work without the actual database. Because all the data which had to be shown as the result of the search could be extracted out of the index.

Lucene.Net has gained rapid exposure and several articles & tutorials can be found on how to implement it. Quite some time ago I made a minimal example on how to create an index and search it, I thought I’d share it, maybe it’ll help someone with his first steps in the Lucene.Net world.

The minimal Lucene.Net example creates an index of all the postal codes of Belgium (data is read from a .csv file), the postal codes can be searched and the results are shown in a list. Nothing more, nothing less.

Some extra information:

Analyzer analyzer = new StandardAnalyzer();

An analyzer is used when indexing raw text to transform it into searchable terms, removing frequently used words like “the”, “in”, “a”, “and”, “of”.

IndexWriter writer = new IndexWriter(indexFolder, analyzer, true);

An IndexWriter is used for creating and adding/removing items to/from the index, an analyzer should be specified which is used when adding data to the index.

Document document = new Document();
 
document.Add(new Field(POSTALCODECOLUMN, parts[0], Field.Store.YES, Field.Index.UN_TOKENIZED));
document.Add(new Field(CITYCOLUMN, parts[1], Field.Store.YES, Field.Index.UN_TOKENIZED));
 
writer.AddDocument(document);

A document is like a virtual record which contains the fields which are searchable. A field can be specified more than once, if a city has for some reason multiple postal codes, these can be added with the same field name and each time with a different postal code.

writer.Optimize();

After adding the documents the writer is optimized, which rewrites the entire index by merging all segment files into one file, greatly reducing the fysical size of the index and the searching speed.

The example is a VS2005 solution and uses Lucene.Net version 2.0.0.4 (included in the zip-file).

Minimal Lucene Example