Improve Wordpress permalinks in IIS7

May 5th, 2009

Using Wordpress on a Windows Server with IIS7 causes the permalinks to have “index.php” in the url. An example would be “http://www.smartasseses.be/index.php/2009/05/05/improve-wordpress-permalinks-in-iis7″, while this url is a valid link which will be spidered by search engines, it isn’t as esthetical as one would like.

Removing the “index.php” is rather straightforward, once you know how to. First you wan’t to add the following Web.Config to you virtual directory running the Wordpress blog. This will enable a rewriting rule in IIS7, which will rewrite every request that does not point to a physical file to “index.php”. Basicly transforming it to the way it previously worked.

<?xml version="1.0"?>
<configuration>
    <system.webServer>
      <rewrite>
        <rules>
          <rule name="Main Rule" stopProcessing="true">
            <match url=".*" />
            <conditions logicalGrouping="MatchAll">
              <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
              <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
            </conditions>
            <action type="Rewrite" url="index.php" />
          </rule>
        </rules>
      </rewrite>
    </system.webServer>
</configuration>

Once we’ve added the config we can change the permalink structure in the admin pages of Wordpress. Choose your structure and remove the “index.php” prefix, be sure to leave a slash at the beginning of the desired structure.

// Change this:
/index.php/%year%/%monthnum%/%day%/%postname%/

// To this for instance:
/%year%/%monthnum%/%day%/%postname%/


Thoughts on BDD

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#

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

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.


Introducing RovingContacts

April 18th, 2009

It’s been in the pipeline for quite some time, but it’s finally here RovingContacts . It’s the first of a series of products that will give your life in the digital era a bit more structure and let you be more productive. RovingContacts allows you to input or import your contacts, see how they are related, add fields that are important to you, see their location on a map, get driving directions, create reports or greeting cards for that matter, and much more.

rovingcontactsdetailsmall

This first version does not mark the end of development on this new platform. RovingContacts and all the other suites are still under active development. We are constantly reworking and refining existing features while adding new and exciting functionality that will help you get your work done. One very attractive feature is being able to synchronize your contacts to pretty much any platform in the world. Yes any platform, that includes your cellphone, Plaxo, MS Outlook, AOL, Windows Live, Google Contacts,… you name it, we sync it.

This is the start of a very interesting journey for us, so jump aboard and go download a copy! 

rovingcontactsoverviewsmall

Moving WPF control to class library

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

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

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.


Breakpoints in Xcode stop firing

February 18th, 2009

Apple's Xcode is a nice IDE and just like every program it has its occasional quirks. Here's a tip: when all of a sudden your breakpoints stop firing, without any apparent reason, try this: Instead of following Googles advice and deselecting the "Load symbols lazily" option in the Preferences screen, (which will solve the breakpoints not hitting, I have to admit) perform a cleanup of your target. (Build – Clean All Targets) This will remove all intermediate files created during the build process and will force Xcode to process every file the next time you build, basicly a full rebuild. Xcode processes only the changed files during subsequent builds, but apparently this incremental strategy fails once in a while, with the aforementioned effect.

In the end both methods solve the problem, but I like to leave the default settings on, instead of changing them to fix some glitch in the system.


Custom username password validator with Geneva

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