Tuesday, 28 June 2011

yUML–> A web based tool for generating simple UML diagrams for use in blogs, forums and wikis

I came across yUML viewing someone's answer on Stack Overflow. It allows you to generate quick diagrams using a simple syntax that can then be presented in a blog.

With just a few lines of syntax you can generate a diagram and a url that can be inserted into a blog post or forum.

[Customer{bg:orange}]+1->*[Order{bg:green}]
[Order]++1-items >*[LineItem{bg:red}]
[Order]-0..1>[PaymentMethod{bg:blue}] 
[Order]-[note{bg:pink}:Aggregate root.]

The previous code is used to generate a URL (http://yuml.me/diagram/scruffy/class/[Customer{bg:orange}]+1->*[Order{bg:green}], [Order]++1-items >*[LineItem{bg:red}], [Order]-0..1>[PaymentMethod{bg:blue}] , [Order]-[note{bg:pink}:Aggregate root.]) which generates the following.

There are a few quirks with it but it gets the job done.

Monday, 27 June 2011

Creating the ASP.Net Application Services Database from code without having to use aspnet_regsql.exe

Recently I have been trying to run some user acceptance tests and have been struggling to generate a membership database for use with the asp.net membership provider on the fly and then clean up afterwards. I like to generate test database with unique names as not to clash with other tests that might be running on the test box and this had been proving rather hard.

I started of trying to generate some scripts from an existing database but I also needed to populate the tables with some standing data and it was all starting to look very ugly so I started to look at how I could run the aspnet_regsql.exe from code and opened it up in dotPeek. In doing so I came across some calls to a static class in the System.Web assembly called SqlServices in the System.Web.Management namespace. aspnet_regsql.exe uses this class to generate the build scripts for creating the application database based on the parameters provided but the class also provides methods that allow you to generate a database there and then. The methods you should be interested in are:

public static void Install(string server, string user, string password, string database, SqlFeatures features)
public static void Install(string server, string database, SqlFeatures features)
public static void Install(string database, SqlFeatures features, string connectionString)

The SqlFeatures are flags which can be applied in combination, the  features available are Membership, Profile, RoleManager and Personalization. There are two overloads, None and All. In the end I went with the server name and database name overload.

var membershipDatabaseName = "<TestProject>Membership" + Guid.NewGuid().ToString("N");
 
SqlServices.Install("localhost", membershipDatabaseName, SqlFeatures.All);
Just remember to clean up when your done!

Sunday, 2 January 2011

Making Fluent NHibernate AutoMapper behave with interfaces

I’ve been an avid user of NHibernate for some time now either using the built in class maps or Castles ActiveRecord. It hasn’t been until recently that I have started using Fluent NHibernate and have been wowed by how easy it is to do the class mappings with the ClassMap base class. This is an improvement over ActiveRecord where domain objects are tightly bound to ActiveRecord because of the decorators but you still have strongly typed mappings which will pick up most issues at compile time whereas the NHibernate class maps will only throw up an issue at runtime. One of the things that I really like about Fluent is how easy it is to use interface references between entities, take the following entity structure for example:

public Interface IFoo { }
 
public Interface IBar { IFoo Foo { get; set; } }
 
public Class Foo : IFoo { }
 
public Class Bar : IBar
{
     public IFoo Foo { get; set; }
}
 
public class BarMapping : ClassMap<Bar> { }

This would result in an “Association references unmapped class: IFoo” exception. This can simply be fixed by adding a reference mapping to the class map:

public class BarMapping : ClassMap<Bar>
{
    public BarMapping()
    {
        References<Foo>( x => x.Foo ).Column( "FooId" ).Cascade.None();
    }
}

This fixes the exception and allows the entity to be correctly mapped to the concrete type and everything was right in the world, or it was until a colleague suggested using AutoMapper to remove the need of have ClassMap implementations. This seemed like it was worth a try but I couldn’t help feeling that I was losing a certain amount of control.

public class FooBarPersistenceModel : AutoPersistenceModel
{
    public FooBarPersistenceModel ()
    {
        AddEntityAssembly(typeof(Foo).Assembly)
            .Where(x => x.Namespace == typeof(Foo).Namespace)
            .BuildMappings();
    }
}

The initial implementation with basic entities worked fine but as soon as we tried anything more complicated such as referencing entity interfaces instead of concrete classes we were back to our old friend “Association references unmapped class”, and if we were having trouble doing this what else was going to be a problem. We were at the point of going back to using the ClassMap when I decided to do a bit more digging and realised how much I misunderstood AutoMapper, it isn’t about mapping entities straight to their related tables but about mapping entities to their related tables via a series of conventions. The reason this was lost on me was because AutoMapper is already wired up with some basic conventions so it works out of the box and with very little documentation or examples it wasn’t easy to see how to do something I had previously done another way.

With this knowledge in hand, some basic examples of AutoMapper conventions and the help of Reflector I was able to work out how to map an entity with references to an interface:

public class FooBarPersistenceModel : AutoPersistenceModel
{
    public PlantAutomationPersistenceModel()
    {
        AddEntityAssembly(typeof(Foo).Assembly)
            .Where(x => x.Namespace == typeof(Foo).Namespace)
            .Conventions.Add(new ReferenceConvention())
            .BuildMappings();
    }
}
 
public class ReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        Type instanceType = instance.Class.GetUnderlyingSystemType();
        if (instanceType = typeof(IFoo))
        {
            instance.CustomClass<Foo>();
        }
 
        instance.Cascade.All();
    }
}
 
//Or a more generic approach might be:
 
public class ReferenceConvention : IReferenceConvention
{
    public void Apply(IManyToOneInstance instance)
    {
        Type instanceType = instance.Class.GetUnderlyingSystemType();
 
        if (instanceType.IsInterface)
        {
            // Assuming that the type starts with an I get the name of the concrete class
            string className = instanceType.Name.Substring( 1 );
 
            instance.CustomClass(instanceType.Assembly.GetType(
                instanceType.FullName.Replace( instanceType.Name, className )));
        }
 
        instance.Cascade.All();
    }
}
 

These classes use the IReferenceConvention interface and if you navigate the FluentNHibernate.Conventions namespace you will see that there are a plethora of conventions. You also have the choice of using your own implementation or a convention builder, the builder is quite nice but if you want reuse then I would opt for a custom implementation.

Everything worked fine until we had an entity that referenced a collection and then we were back to the “Association references unmapped class” exception again. I was in a bit of a rush and couldn’t get the IReferenceConvention to work nor the IHasManyConvention that I had just found. I was about to give up when I came across the IAutoMappingOverride<TEntity> interface.

public Interface IWibble { }
 
public Interface IWobble
{
    IList<IWibble> Wibbles { get; }
}
 
public class Wibble : IWibble { }
 
public class Wobble : IWobble
{
    public IList<IWibble> Wibbles { get; set; }
}
 
public class WobbleAutoMappingOverride : IAutoMappingOverride<Wobble>
{
    public void Override(AutoMapping<Wobble> mapping)
    {
        mapping.HasMany<Wibble>( x => x.Wibbles );
    }
}

It wasn’t perfect but it was a quick fix until my colleague finally found the solution for getting the IHasManyConvention interface to work:

public class ReferenceConvention : IHasManyConvention
{
    public void Apply(IOneToManyCollectionInstance instance)
    {
        var instanceType = instance.ChildType;
        if (instanceType.IsInterface)
        {
           var className = instanceType.Name.Substring(1);
           instance.Relationship.CustomClass(instanceType.Assembly.GetType(instanceType.FullName.Replace(instanceType.Name, className)));
           instance.Cascade.All();
        }
        instance.Cascade.All();
    }
}

As you will see there are many conventions that can be applied which makes AutoMapper very flexible and a better alternative to using the ClassMap base class.

Tuesday, 26 October 2010

Host TeamCity in IIS7

Up until recently I have been using the apache isapi redirector to proxy through from IIS to TeamCity (which runs on Tomcat). This was because I had no alternative until today. Whilst searching the interwebs I came across the Application Request Routing extension for IIS7. This amongst other things allows IIS to proxy through to a service running either locally or remotely running on any port.

Installation

Install the extension using the Web Platform Installer, this will install a number of prerequisites as well as the Application Request Routing extension.

Configuration

  • Once the installation is complete open up the IIS7 management tool where you should now see a new node under the websites folder for your server called server farms.
  • Right click and add a new Farm and name it TeamCity.
  • Click on the advanced settings and enter the correct port number for TeamCity, you will not be able to change this so get it right or you will have to delete the server entry and start again.
  • One you have added the server accept the request to automatically create the rules.

That’s it, any request to your server should now proxy through to TeamCity.

Hosting more than one site

You may want to  or you may already be hosting sites on your server via IIS. With what we have done above these sites will no longer be available. To resolve this click on the server node in the IIS management tool. Click on the url rewriting component, this will show you the rule that was created for your Server Farm. Double click the rule and a new condition:

  • Condition input: {HTTP_HOST}
  • Pattern: <Host/Domain name>, example teamcity.mydomain.com
  • Apply the rule.

This should now only push requests to the specified domain name to the proxy. Other sites can now be hosted as normal.

Tuesday, 29 June 2010

Better know a framework: Flushing the System.IO.StreamWriter

I ran into an issue today where content that was being written to a Stream was being truncated when a large amount of text was being written. The code was something similar to:

using (var memoryStream = new MemoryStream())
using (var streamWriter = new StreamWriter(memoryStream , Encoding.UTF8))
{
    streamWriter.Write(someRealyLongStringValue);
    DoSomethingWithTheStream(memoryStream );
}

The consuming method was then using the Stream but the end was truncated but if you take the following code from MSDN which writes to a FileStream using the StreamWriter it works as expected:

DirectoryInfo[] cDirs = new DirectoryInfo(@"c:\").GetDirectories();
 
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
    foreach (DirectoryInfo dir in cDirs)
    {
        sw.WriteLine(dir.Name);
    }
}

After a bit of digging I realised that you need to call Flush() before using the Stream or turn on AutoFlush when using really long strings (or as good practice). The reason that the MSDN example worked is because it was writing to a FileStream in  a using block, when the Dispose method is called I presume it calls the flush method before destroying itself thus writing the rest of the content to the file. Whilst it would have been nice to see a comment to this affect in the StreamWriter remarks it does make sense.

Wednesday, 16 June 2010

Using the IMapper interface with the System.Converter delegate

Recently I wrote a post about using a standard mapping interface for your mappers which gave the added benefit of providing an easy way to write an extension method for mapping enumerable. As it turns out it also has the added benefit in fitting in with the System.Converter delegate signature in that the signature of the Map method of the IMapper interface is the same as the System.Converter delegate.

Whilst the extension method provides a way of mapping enumerations there may be cases where it is more preferable to us the Array.ConvertAll and the List<T>.ConvertAll methods. The Array method is static and the List is instance but each of these take in a System.Converter delegate and map to a typed array and a typed list respectively. All of which means we can do the following:

IMapper<ObjectA, ObjectB> myAToBMapper = new MyAToBMapper();
 
ObjectA[] aArray = { new ObjectA(), new ObjectA() };
ObjectB[] bArray = Array.ConvertAll<ObjectA, ObjectB>(aArray, myAToBMapper.Map);
 
List<ObjectA> aList = new List<ObjectA> { new ObjectA(), new ObjectA() };
List<ObjectB> bList = aList.ConvertAll<ObjectB>(myAToBMapper.Map);
 
// Or
 
var aToBConverter = new Converter<ObjectA, ObjectB>(myAToBMapper.Map);
 
bArray = Array.ConvertAll(aArray, aToBConverter);
bList = aList.ConvertAll(aToBConverter);

Whilst I prefer the synatax of MapAll this does show that the IMapper interface has versatility elsewhere in the core library.

Support SQLCE BinaryBlob and StringClob in NHibernate without depending on System.Data.SqlServerCe

Out of the box NHibernate 2 does not support the BinaryBlob or StringClob sql types for SQL Server compact 3.5. This results in NText and Image fields being truncated. One of the common workarounds you can find on the web is to override the existing SqlServerCeDriver and cast the parameter to an SqlCeParameter and manual set the parameter types to NText and Image.

using System.Data; 
using System.Data.SqlServerCe; 
using NHibernate.Driver; 
using NHibernate.SqlTypes;
 
public class MySqlServerCeDriver : SqlServerCeDriver 
{ 
    protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType) 
    { 
        base.InitializeParameter(dbParam, name, sqlType); 
 
        var parameter = (SqlCeParameter)dbParam;
 
        if (sqlType is StringClobSqlType) parameter.SqlDbType = SqlDbType.NText; 
        if (sqlType is BinaryBlobSqlType) parameter.SqlDbType = SqlDbType.Image; 
    } 
}

The problem with this is that it couples you directly to the System.Data.SqlServerCe library. For some people this won’t be a problem as they will only need to implement it in the project that is using SQLCE and already be coupled to the library. However in my case I wanted to put it in our core library where it could be reused but didn’t want users of the library to have a dependency on SQLCE.

One way of achieving what I wanted would have been to create a separate  sub library to our core library which dragged in the sql server ce data library but didn’t pollute  the core which would have been fine but you have to ask yourself how is it that the NHibernate library is not dependent on the sql server ce data library. The answer is that they use reflection, in fact the drivers themselves inherit from a the ReflectionBasedDriver and use reflection to create the parameters and set the data types. So assuming that the NHibernate library does it correctly we just need to look at one of the other implementations and replicate how they set the data types which gives rise to the following:

using System.Collections.Generic;
using System.Data;
using System.Reflection;
using NHibernate.Driver;
using NHibernate.SqlTypes;
 
public class SqlServerCe35Driver : SqlServerCeDriver
{
    private PropertyInfo dbParamSqlDbTypeProperty;
 
    public override void Configure(IDictionary<string, string> settings)
    {
        base.Configure(settings);
 
        using (IDbCommand cmd = CreateCommand())
        {
            IDbDataParameter dbParam = cmd.CreateParameter();
            dbParamSqlDbTypeProperty = dbParam.GetType().GetProperty("SqlDbType");
        }
    }
 
    protected override void InitializeParameter(IDbDataParameter dbParam, string name, SqlType sqlType)
    {
        base.InitializeParameter(dbParam, name, sqlType);
 
        if (sqlType is BinaryBlobSqlType)
        {
            dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.Image, null);
        }
        else if (sqlType is StringClobSqlType)
        {
            dbParamSqlDbTypeProperty.SetValue(dbParam, SqlDbType.NText, null);
        }
    }
}

As you can see there is slightly more work involved and we need to use reflection up front to get a hold of the sql db type property of the SqlCeParameter but result is that there is no dependency on the System.Data.SqlServerCe library and we have conformed to how the rest of the NHIbernate ReflectionBasedDriver implementations.