Progresscursor

Sample

Class diagram

progresscursor/classdiagram.png

Using the code

Using the code is pretty simple, as you can see.

var progressCursor = Van.Parys.Windows.Forms.CursorHelper.StartProgressCursor(100);

for (int i = 0; i < 100; i++)
{
 progressCursor.IncrementTo(i);

 //do some work
}

progressCursor.End();

The library also has some points of extensibility, by handling the ‘EventHandler<CursorPaintEventArgs> CustomDrawCursor‘ event. By handling this event, the developer can choose to extend the default behaviour by running the DrawDefault method on the CursorPaintEventArgs instance.

...
progressCursor.CustomDrawCursor += progressCursor_CustomDrawCursor;
...

void progressCursor_CustomDrawCursor(object sender,
                    ProgressCursor.CursorPaintEventArgs e)
{
	e.DrawDefault();

	//add text to the default drawn cursor
	e.Graphics.DrawString("Test",
	           SystemFonts.DefaultFont, Brushes.Black, 0,0);

	//set Handled to true, or else nothing will happen,
	//and default painting is done
	e.Handled = true;
}

IProgressCursor also implements IDisposable, which makes the ‘using‘ statement valid on this interface. The advantage is that no custom exception handling has to be done to ensure the End()method is called on the ProgressCursor. An example of the usage is found in 1-3.

using (var progressCursor = CursorHelper.StartProgressCursor(100))
{
    for (int i = 0; i < 100; i++)
    {
        progressCursor.IncrementTo(i);

        //simulate some work
    }
}

Why implement IDisposable

A classic usage of the default cursor classes would be like this:

private void DoStuff()
{
    Cursor.Current = Cursors.WaitCursor;

    try
    {
        //do heavy duty stuff here...
    }
    finally
    {
        Cursor.Current = Cursors.Default;
    }
}

If one wouldn’t implement the cursor change like this, the cursor could ‘hang’ and stay ‘WaitCursor’. To avoid this Try Finally coding style, I implemented IDisposable on the IProgressCursor like this (2-2):

public ProgressCursor(Cursor originalCursor)
{
    OriginalCursor = originalCursor;
}

~ProgressCursor()
{
    Dispose();
}

public void Dispose()
{
    End();
}

public void End()
{
    Cursor.Current = OriginalCursor;
}

How it works

Creating a custom cursor

Basically, all the ‘heavy lifting’ is done by two imported user32.dll methods (1-3). These can be found in the class UnManagedMethodWrapper (what would be the right name for this class?).

public sealed class UnManagedMethodWrapper
{
	[DllImport("user32.dll")]
	public static extern IntPtr CreateIconIndirect(ref IconInfo iconInfo);

	[DllImport("user32.dll")]
	[return: MarshalAs(UnmanagedType.Bool)]
	public static extern bool GetIconInfo(IntPtr iconHandle, ref IconInfo iconInfo);
}

These methods are called in CreateCursor:

private Cursor CreateCursor(Bitmap bmp, Point hotSpot)
{
	//gets the 'icon-handle' of the bitmap
	//(~.net equivalent of bmp as Icon)
	IntPtr iconHandle = bmp.GetHicon();
	IconInfo iconInfo = new IconInfo();

	//fill the IconInfo structure with data from the iconHandle
	UnManagedMethodWrapper.GetIconInfo(iconHandle, ref iconInfo);

	//set hotspot coordinates
	iconInfo.xHotspot = hotSpot.X;
	iconInfo.yHotspot = hotSpot.Y;

	//indicate that this is a cursor, not an icon
	iconInfo.fIcon = false;

	//actually create the cursor
	iconHandle =
	  UnManagedMethodWrapper.CreateIconIndirect(ref iconInfo);

	//return managed Cursor object
	return new Cursor(iconHandle);
}

MSDN documentation:

Circular progress cursor drawing

int fontEmSize = 7;

var totalWidth = (int) Graphics.VisibleClipBounds.Width;
var totalHeight = (int) Graphics.VisibleClipBounds.Height;
int margin_all = 2;
var band_width = (int) (totalWidth*0.1887);

int workspaceWidth = totalWidth - (margin_all*2);
int workspaceHeight = totalHeight - (margin_all*2);
var workspaceSize = new Size(workspaceWidth, workspaceHeight);

var upperLeftWorkspacePoint = new Point(margin_all, margin_all);
var upperLeftInnerEllipsePoint = new Point(upperLeftWorkspacePoint.X + band_width,
                                 upperLeftWorkspacePoint.Y + band_width);

var innerEllipseSize = new Size(((totalWidth/2) - upperLeftInnerEllipsePoint.X)*2,
            ((totalWidth/2) - upperLeftInnerEllipsePoint.Y)*2);

var outerEllipseRectangle =
    new Rectangle(upperLeftWorkspacePoint, workspaceSize);
var innerEllipseRectangle =
    new Rectangle(upperLeftInnerEllipsePoint, innerEllipseSize);

double valueMaxRatio = (Value/Max);
var sweepAngle = (int) (valueMaxRatio*360);

var defaultFont = new Font(SystemFonts.DefaultFont.FontFamily,
                           fontEmSize, FontStyle.Regular);
string format = string.Format("{0:00}", (int) (valueMaxRatio*100));
SizeF measureString = Graphics.MeasureString(format, defaultFont);
var textPoint = new PointF(upperLeftInnerEllipsePoint.X +
  ((innerEllipseSize.Width - measureString.Width)/2),
    upperLeftInnerEllipsePoint.Y +
    ((innerEllipseSize.Height - measureString.Height)/2));

Graphics.Clear(Color.Transparent);

Graphics.DrawEllipse(BorderPen, outerEllipseRectangle);
Graphics.FillPie(FillPen, outerEllipseRectangle, 0, sweepAngle);

Graphics.FillEllipse(new SolidBrush(Color.White), innerEllipseRectangle);
Graphics.DrawEllipse(BorderPen, innerEllipseRectangle);

Graphics.DrawString(format, defaultFont, FillPen, textPoint);

What does it (try to) solve

End users tend to have the impression to be waiting longer on a process with no progress visualization, then a process with progress indication.

Source code

Is available on github.

Share On

DIY Ado.Net Profiler

In a professional project, we are using Entity Framework as an ORM provider for our application. On several occasions we wanted to know what SQL query some LINQ query produced. This mostly is the case when a particular query is very slow, returns unexpected results, etc. To ‘debug’ a LINQ query, we could just use the cool new feature of VS 2010 (Ultimate), IntelliTrace. With this toolwindow, we can inspect which query is run at a given point in time. This is great when we would have an Ultimate license for VS2010, which we unfortunately do not have.

The second negative point about IntelliTrace is that is doesn’t tell us much about the executed query’s performance. Did it take 500ms to run, or 5ms? We just don’t know.

Wait a sec! Why don’t you just use the SQL Profiler software then? Well, I suggest you all try to debug a EF Query using the SQL-Profiler. It’s just a pain in the ****.

Now, that’s why I decided to look for a solution myself. I tried to keep it as basic, and simple as I could, so don’t look for over-engineering here!

This will be a series of articles, I will try to keep an index here so you can find the different parts easily.

Using the Code

Using the code is as simple as this:

/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
    //First and only entry point of the profiler
    ProxyGenerator.Init();

    Application.Run(new Form1());
}

As you can see, this has a minimal impact on how your application should be designed, etc. This makes the profiler ideal for plugging into existing projects. In this first article, we will only use one event to catch all the profiling info, this will eventually change by implementing a WCF service to do the communication between the server (ProxyDbxxx, etc.) and clients (VS2010 add-in). But for now, we can catch all the debugging info using these commands:

public void SomeMethod()
{
    ProxyGenerator.DbProviderInfo +=
      new EventHandler<DbProviderInfoEventArgs>(ProxyGenerator_DbProviderInfo);
}

void ProxyGenerator_DbProviderInfo(object sender, DbProviderInfoEventArgs e)
{
    MessageBox.Show(e.Message);
}

For now, we only show informative messages using the DbProviderInfo event. Later on, when we will discuss the approach to creating a profiling system, we will add real statistics to the game. So for now, only debug messages. There is a sample program included in the download, of which the output will be the following:

ConsoleOutput.png

In the image below, you can see the Class Diagram of the ProxyGenerator:

Next up, I will discuss the technique of creating proxy DbProviders, and how we can use them to intercept all method calls to DbCommandDbConnection, etc. classes.

DbProviderFactory

Fist off, a quick intro to DbProviderFactory (Concept on MSDN). This ‘Factory-pattern’ implementation is designed to abstract all database access away from the code. Each ‘big’ database provider (MSSQL, Oracle, etc.) has an implementation of the DbProviderFactory. The DbProviderFactory itself is an abstract class which contains everything we need to connect to, and query any database. All implementations of the DbProviderFactory are stored by the .NET Framework in the DbProviderFactories class. By using this class, we can execute the following code:

DbProviderFactory factory = DbProviderFactories.GetFactory(providerName);

This will get you an instance of the DbProviderFactory matching the providerName specified. By using this DbProviderFactory pattern, no dependencies are needed to MSSQL, Oracle specific implementations.

How are these implementations stored

The DbProviderFactories class contains three public members, of which one is particularly interesting to us: ‘GetFactoryClasses‘. This method returns a DataTable which contains all the implementations of DbProviderFactory in the loaded assemblies. The first thing that skipped my mind was, can we edit this DataTable so we can provide a custom implementation class for the providers? By using the public method GetFactoryClasses, we can only access a copy of the original DataTable stored in-memory in the DbProviderFactories class. To access the original DataTable, I used a disassembler to inspect the .NET Framework class. I noticed that there is a private static method which returns a reference to the original DataTable created by the DbProviderFactories class.

Finding a way to access the original DataTable containing the combinations of ProviderNames and AQN [^] was key to the success of this approach. It may not seem right to this, but as a friend of mine says, ‘there’s nothing wrong with being stupid’.

//DbProviderFactories has a private static method
//(thanks jetBrains decompiler!) which gives us
//a non copy of the available DbProviderFactories
var dbProvidersFactoriesDataTable = typeof(DbProviderFactories).GetMethod(
  "GetProviderTable",
  BindingFlags.NonPublic | BindingFlags.Static).Invoke(null, null)
  as DataTable;

Here is a diagram of how the default DataTable could look like:

Overriding default DbProviderFactory implementations

There are essentially two approaches to do this. The IOC [^] (CasteLin.Fu) way of creating proxy classes and replacing the original TypeName with the generated Proxy’s type name. I would have loved to do things this way, but I just couldn’t find a (decent) way to proxy a sealed class. If someone out there knows a way of doing this, please let me know!

 

The second way of doing it is by creating the proxy class ourselves. In .NET 1.0 times, this would mean that for every possible DbProvider, we would have to write a proxied version (ProxyOracleDbProviderFactory, etc). Luckily for us, we’ve got generics since .NET 2.0! So we could go and write a class like this:

ProxyDbProviderFactory<T> where T : DbProviderFactory

Simple, yet very powerful! Why is this powerful? Well, we can use this for literally every DbProviderFactory (damn that’s a long word to write all the time) that will ever be made. The following snippet demonstrates how we can create a new type using this generic type.

var DbProviderFactoryTypes =
  dbProvidersFactoriesDataTable.Rows.OfType<datarow>().Select(
  x => x["InvariantName"].ToString()).ToList();

foreach (string providerInvariantName in DbProviderFactoryTypes)
{
    //get an instance of the DbProviderFactory in this loop.
    var factory = DbProviderFactories.GetFactory(providerInvariantName);

    //create new generic type ProxyDbProviderFactory<{TypeOfFactoryToProxy}>
    var factoryType = typeof(ProxyDbProviderFactory<>).MakeGenericType(
                      new Type[] { oringalFactoryType });

    //call static method Initialize to construct the instance
    factoryType.GetMethod("Initialize", BindingFlags.FlattenHierarchy |
                BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

    ... (see below)
}

Before we continue, you should notice that all DbProviderFactory implementations must use the Singleton pattern. In this case, that means all Factories have a static field ‘Instance‘ which contains the only instance used for the type. This is very useful to know, because we have to follow this pattern. As we can see in the last line of code in the previous snippet:

//call static method Initialize to construct the instance
factoryType.GetMethod("Initialize", BindingFlags.FlattenHierarchy |
            BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

We call the static (that’s why the Invoke method is called with the double null parameter) method Initialize to setup the newly created type. This is the Initialize method:

...
//static field containing the singleton instance
public static ProxyDbProviderFactory<tfac> Instance;
...
public static void Initialize()
{
    Instance = new ProxyDbProviderFactory<tfac>();
}
...
public ProxyDbProviderFactory()
{
    //access the singleton instance of the type that is proxied
    FieldInfo field = typeof(TFac).GetField("Instance",
                      BindingFlags.Public | BindingFlags.Static);
    this.ProxiedDbProviderFactory = (TFac)field.GetValue(null);
}

In this Initialize method, we instantiate the singleton instance of our proxied DbProviderFactory. In the above code snippet, we also see the constructor, which extracts the Instance field of the proxied type. We store a reference to this instance named ProxiedDbProviderFactory. So when is the proxied DbProviderFactory (e.g., OracleDbProviderFactory) intialized (= creation of a singleton instance)? This happens in this line of code:

//get an instance of the DbProviderFactory in this loop.
var factory = DbProviderFactories.GetFactory(providerInvariantName);

By getting a factory, we make sure it will be properly initialized. We do not actually need this variable ‘factory‘ in the rest of our program.

Next up is actually overriding the type in the DataTable discussed earlier. The following code snippet demonstrates how we can override the default implementations of DbProviderFactories. Note that theDataTable‘s columns are read-only, so I had to manually override this to replace the field. See it for yourself below:

foreach (string providerInvariantName in DbProviderFactoryTypes)
{
    ... (see above)

    //retrieve the datarow in which we will alter
    //the Type to the newly contructed ProxyType
    var dataRowToEdit =
        dbProvidersFactoriesDataTable.Rows.OfType<datarow>().FirstOrDefault(
        dt => ((string) dt["InvariantName"]) == providerInvariantName);

    if (dataRowToEdit == null)
        return;

    //set readOnly false to edit table
    dbProvidersFactoriesDataTable.Columns["AssemblyQualifiedName"].ReadOnly = false;

    //map the DbProvider to the new proxy
    dataRowToEdit["AssemblyQualifiedName"] = factoryType.AssemblyQualifiedName;

    //set readOnly back to original
    dbProvidersFactoriesDataTable.Columns["AssemblyQualifiedName"].ReadOnly = true;
}

After executing this code, the DataTable now looks like this:

All that is left now to conclude this first part is implementing all the necessary overrides of the abstract class DbProviderFactory in the ProxyDbProviderFactory<TFac> class. For reference, I will include some samples of this implementation here:

...
public override DbCommandBuilder CreateCommandBuilder()
{
    return ProxiedDbProvider.CreateCommandBuilder();
}

public override DbConnection CreateConnection()
{
    return ProxiedDbProvider.CreateConnection();
}

public override DbConnectionStringBuilder CreateConnectionStringBuilder()
{
    return ProxiedDbProvider.CreateConnectionStringBuilder();
}
...

Obviously, what happens is, we just call the proxied instance’s members, so all default functionality is preserved. Later on, we will also create Proxy classes for DbConnectionDbCommand, etc., to enable real profiling.

IServiceProvider interface

One last thing we should briefly discuss is the implementation of the IServiceProvider interface. All DbProviderFactory implementations also implement IServiceProvider. According to MSDN, this interface ‘Defines a mechanism for retrieving a service object; that is, an object that provides custom support to other objects’. While debugging and doing some research on the web, I discovered that the only service that is requested, is of type DbProviderServices. To support this IServiceProvider interface, we implement the service method as follows:

public object GetService(Type serviceType)
{
    ProxyGenerator.OnQueryExecuted(string.Format(
         "GetService requested {0}", serviceType.Name));

    if (serviceType == GetType())
    {
        return ProxiedDbProvider;
    }

    DbProviderServices service;

    if (serviceType == typeof(DbProviderServices))
    {
        if (ProxiedDbProvider is IServiceProvider)
        {
            service = (ProxiedDbProvider as IServiceProvider).GetService(serviceType)
                       as DbProviderServices;
        }
        else
        {
            service = null;
        }
    }

    if (service != null)
    {
        return new ProxyDbProviderServices(service);
    }

    return null;
}

As you can see, we already encapsulate this default return value of the proxied DbProviderFactory GetService() method in a new class called ProxyDbProviderServices. This enables us to do some more initial logging of what’s going on in the base classes.

Disadvantages of this approach

  • Using undocumented features of the .NET Framework (private DataTable)

Advantages of this approach

  • No need for custom ObjectContextDbContext (Entity Framework).
  • No need for custom DbProvider per SQL technology.
  • ‘Single point of intrusion’ => One line of code gives the lib access to the runtime.
  • All implementors of DbProviderFactory covered, even exotic custom made ones.

Round up

So what have we done after this first part? To round it up, this summation:

  • Get a reference to the internally used DataTable containing all DbProviderFactory implementors
  • Create a generic proxy-type to encapsulate the default DbProviderFactory – types
  • Implement abstract methods of DbProviderFactory in ProxyDbProviderFactory<TFac>

Question for the reader

What do you think of this mechanism to alter an internally defined DataTable to change what DbProviders are intialized and used?

Do you see other disadvantages of this approach?

Is there a way to use IOC frameworks such as Castle, Unity, Lin.Fu to create a proxy for a sealed class?

Source code

The source code can be found on my github repo

Share On

MData – Using interfaces as domain model

In a conventional domain model, most domain logic resides in then entities themselves, or in a domain layer called services/repository. This brings some advantages (scalability, POCO). But it also has some liabilities. This is certai ly the case when the domain relies on services to execute business logic. In those scenarios business logic is seperated from the domain model in an almost untestable way. Imagine an example where after an item is sold. Stock should be updated, and deminished by the quantity sold. In a pure POCO world, this could look like this.

I am not saying this approach is absolutely wrong. In the .net community, I saw once too many that people have a very black/white vision on how a domain model should look. I personally think you can/have to adapt the technical implementation to the requirement of the project. Some small projects may justify to use a very simple ‘home-grown’ application framework, while bigger projects usually benefit more from the bigger, wide spread frameworks. This is ofcourse only true if you know there are alternatives. That said, let’s look how I composed the domain model in this experimental framework.

MData Domain Model Entities

In MData, all entities in the domain are defined as interfaces. This means MData uses the ‘POCO principle’ by default. The advantage here is that the implementation of the actual properties/logic can be different in different layers of the domain. This may sound pretty dramatic, but it doesn’t have to be. Imagine a WCF service layer that needs extra validation on entities that are created/modified, etc. This is an example of how a typical domain entity could look like.

1 2 3 4 5 6 7 8 9 10 11 12 13
[MData("Customer")]
public interface ICustomer
{
int Id { get; set; }
string Name { get; set; }
string Notes { get; set; }
bool IsActive { get; set; }
DateTime CreatedOn { get; set; }
DateTime ModifiedOn { get; set; }
 
void Active();
void DeActivate();
}
view raw ICustomer.cs hosted with ❤ by GitHub

Now I have some issues with this model. First of all it contains some properties/methods I would like to be abstracted away from the Customer entity. We could imagine that other entities in the domain would also want to implement IsActive, in combination with Activate() and DeActivate() methods. The most obvious solution would be to add this to a specialized base class, possibly derived from a generic entity base class. Something like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14
public class ActivatableEntity : EntityBase
{
public bool IsActive { get; set; }
public void Active()
{
//...
}
 
public void DeActivate()
{
//...
}
}
view raw ActivatableEntity.cs hosted with ❤ by GitHub

All fine and dandy, but as we are working with interfaces only, this is not an option. Of course it’s to simple to say we just can’t use such a typical OO way of doing things. In this simple scenario the disadvantage of using OO might not be clear right away. But imagine we want to abstract the auditing part of the entity (CreatedOn, ModifiedOn) away too. It could be done in a similar way as for IsActive abstraction, but then we cannot easily combine different ‘patterns’ in one entity. It wouldn’t be easy to use the IsActive in one entity, and both IsActive and Audit in another entity.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
public class ConcreteEntityA : ActivatableEntity
{
//...
}
 
public class ConcreteEntityB : ActivatableEntity, AuditEntity //not possible!!!
{
//...
}
 
public class AuditEntity : EntityBase
{
DateTime CreatedOn { get; set; }
DateTime ModifiedOn { get; set; }
}
 
public class ActivatableEntity : EntityBase
{
public bool IsActive { get; set; }
public void Active()
{
//...
}
 
public void DeActivate()
{
//...
}
}
view raw SampleDomain.cs hosted with ❤ by GitHub

Using interface to enable multi-inheritance

As you can see, it’s not easy to create a plug and play kind of domain model. This is were MData tries to solve something. As you can see in the previous code sample, one way to solve this problem would be multi inheritance. Normal classes are not an option for multi-inheritance in C#, but interfaces are! By using interfaces for the domain model we get multi inheritance for free. We can solve our requirement like this.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
public interface IConcreteEntityA : IActivatableEntity
{
//...
}
 
public interface IConcreteEntityB : IActivatableEntity, IAuditEntity //not possible!!!
{
//...
}
 
public interface IAuditEntity
{
DateTime CreatedOn { get; set; }
DateTime ModifiedOn { get; set; }
}
 
public interface IActivatableEntity
{
bool IsActive { get; set; }
void Active();
void DeActivate();
}
view raw MdataDomainModel.cs hosted with ❤ by GitHub

Yay, all fine and dandy those interfaces, but how will we implement our logic in the logic methods (De)Activate, or how can we define calculated properties? Well, that’s were the concept of DomainLogic comes in. DomainLogic is the actual implementation of an MData entity. It will hold the implementation of the methods defined in the interfaces, and the ability to override method getters to enable readonly properties. This is the implementation of the IActivatable domain interface.

1 2 3 4 5 6 7 8 9 10 11 12
public class ActivatableLogic : LogicBase<IActivatableEntity>
{
public void Active()
{
CurrentInstance.IsActive = true;
}
 
public void DeActivate()
{
CurrentInstance.IsActive = false;
}
}
view raw ActivatableLogic.cs hosted with ❤ by GitHub

To mapping of interface methods to the logicbase methods is done by convention. This convention is really simple: use exactly the same method definition. Because this is not ‘refactor-safe’ (a change in the interface would not cause our logic class to break the build), I usually define the MData model like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
public class ActivatableLogic : LogicBase<IActivatableEntity>, IActivatableEntityLogic
{
public void Active()
{
CurrentInstance.IsActive = true;
}
 
public void DeActivate()
{
CurrentInstance.IsActive = false;
}
}
 
[MData]
public interface IActivatableEntity : IActivatableEntityLogic
{
bool IsActive { get; set; }
}
 
public interface IActivatableEntityLogic
{
void Active();
void DeActivate();
}

This is a compromis between ‘type-safety’ and fragmentation of the domain model.

In the next article we will dive deeper on how the link between the interface and the LogicBase class is done.

Share On

MData – The idea

A while ago, I was playing around with the XAF framework from Devexpress, in particular with the Domain Components technology (see here and here). I was really convinced about this technology which keeps it simple to test/mock domain objects/classes. Now here is the basic idea:

Instead of having a Domain object Customer implemented in a concrete class Customer, we define a Customer with an interface ICustomer. In many traditional DDD implementations, where a sort of anemic domain model is used, all logic on certain entities is placed is so called services. This brings a few problems with it, especially in terms of maintenance. This is explained very well in this talk from Jimmy Bogard

 

The solution to this problem is containing business logic in the domain models itselve. This is a very good theory, but in practice we see that this is very hard to align with the modern ORM’s. When it comes to hosting a WCF, NSericeStack service, we want to reuse this Domain model, but not necessarily transfer all the business logic to the client/server side. This is were my idea comes in. I wanted to create an extensible platform in which a domain model is merely a contract defining which data an entity should hold, and which functionality it exposes. The concrete implementation of these interfaces is something the developer doesnt have to deal with. Those are generated at runtime by MData internals. Now one of the main problems with this approach is that interfaces typically do not contain ‘real’ code. What I mean by this is that an interface never supplies an implementation for let’s say a method (nor any other member). So to make it possible for the developper to actually write his ‘domain logic’, I created the notion of a LogicBase<T>, where T is the interface it supplies the logic for. This is a zero/one to one relationship, meaning that for one given interface (domain model) there can at most be one LogicBase implementation. If no implementation was provided, the system uses the default generic LogicBase class.

Now this blog-series will cover how I implemented the MData framework step by step, I’ll try to list the benefits and liabilities, and show some interesting use cases for this framework.

By the end of the series we will be able to write this code:


private static void Main(string[] args)
{
    //create EF CF context
    using (DomainContext t = new DomainContext())
    {
        //all CRUD operations work
        ICustomer customer = t.Customers.Create();
        t.Customers.Add(customer);

        ICustomer firstCustomerEver = t.Customers.FirstOrDefault(x => x.Id == 1);

        t.SaveChanges();
    }
}

public class DomainContext : MDbContext
{
    public MDbSet<ICustomer> Customers { get; set; }
}

 

In the meanwhile all code for MData is publicly accessible on github

Share On

Generating Assemblies at runtime using IL emit

Let’s start with a bold statement: IL rocks! Fair enough, but can it do Jazz or Mozart too? Turns out, yes it can :)

While thinking of a way to magically create an instance out of an interface for my little MData project, I figured i’d have to go with IL generating such a class. It seemed like a daunting task at first. Really, look at this code:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
Offset OpCode
0 ldnull
1 ldarg.0
2 ldc.i4.2
3 newarr System.Object
8 stloc.0
9 ldloc.0
10 ldc.i4.0
11 ldarg.1
12 stelem.ref
13 ldloc.0
14 ldc.i4.1
15 ldarg.2
16 stelem.ref
17 ldloc.0
18 call System.String System.String::Format(System.IFormatProvider,System.String,System.Object[])
23 ret
view raw gistfile1.txt hosted with ❤ by GitHub

Can you guess which method this is? probably not, well here it is:

1 2 3 4 5 6 7 8
public static string Format(string format, object arg0, object arg1)
{
return Format(null, format, new object[] { arg0, arg1 });
}
 
 
view raw gistfile1.cs hosted with ❤ by GitHub

If you’ve never really looked into IL (or MSIL) this code may seem very hard to understand. Very handy tools to look at the IL code of a given .Net method, are ILSpy (free), Reflector (in combination with Reflexil) or Graywolf (free). These tools let you compare the classic C#/Vb.net code to the compiled IL code. This is the best way to ‘learn’ IL.

Generating a dynamic assembly at runtime

This goes just one step further then just looking at IL code, this is actually writing IL code. While it is not possible to alter existing Assemblies (not in my knowledge), it is certainly possible to create a new one. This is used in several popular frameworks which support creating proxy classes, ducktyping etc. The key here is to *not* use the default System.Reflection.Emit namespace :) . I personally don’t like the structure and approach in the standard BCL, instead I love to use BLToolkit from Igor Tkachev. It allows me to create a ‘Hello world’ example using a very natural flow:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
EmitHelper emit = new AssemblyBuilderHelper("HelloWorld.dll")
.DefineType ("Hello", typeof(object), typeof(IHello))
.DefineMethod(typeof(IHello).GetMethod("SayHello"))
.Emitter;
 
emit
// string.Format("Hello, {0}!", toWhom)
//
.ldstr ("Hello, {0}!")
.ldarg_1
.call (typeof(string), "Format", typeof(string), typeof(object))
 
// Console.WriteLine("Hello, World!");
//
.call (typeof(Console), "WriteLine", typeof(string))
.ret()
;
view raw gistfile1.cs hosted with ❤ by GitHub

And that’s it, we created a new assembly with one type containing one method. As you can see we can define a baseclass for the type, we could also add which interfaces to implement etc.

TIP: To put a certain class in a namespace, define the name as follows: Path.Of.Your.Namespace.[GeneratedTypeName], this will trigger the emit system to extract the namespace from the class name.

Now let’s try to make a working example of a ducktyping system. the purpose of our little library will be to cast any given class to a interface it doesn’t explicitly implement. Something like this:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
class Program
{
static void Main(string[] args)
{
A a = new A();
ITest aAsITest = a.Duck<ITest>();
}
}
 
public class A
{
string Data { get; set; }
 
public void Method()
{
}
}
public interface ITest
{
string Data { get; set; }
void Method();
}
view raw gistfile1.txt hosted with ❤ by GitHub

The notice how class A does not implement ITest, after ‘ducking’ however, I can have an instance of ITest working on the A instance.
The first step would be creating some kind of workflow and scope for this project:

  • The targetType should have all members of the interface defined as public
  • We will not take into account that only a subset of members is implemented by the targetType, so only one on one matches
  • We will map methods, properties and events.

First step is actually creating an ‘AssemblyBuilder’ from the BLToolkit:

1 2 3 4 5 6 7 8 9
static ClassFactory()
{
_assemblyBuilder = new AssemblyBuilderHelper(GetGeneratedAssemblyPath());
}
 
private static string GetGeneratedAssemblyPath()
{
return @".\Duck.Tape.Generated.dll";
}
view raw gistfile1.txt hosted with ❤ by GitHub

That was easy! Now here is the flow of creating all methods, properties and event on the newly generated type:

1 2 3 4 5 6 7 8 9 10 11 12
var typeBuilder = _assemblyBuilder.DefineType(GetGeneratedTypeName(), typeof(object), InterfaceToImplement);
 
//create private field
var classToWrapField = typeBuilder.DefineField(GetGeneratedToWrapFieldName(), ClassToWrap, FieldAttributes.Private);
 
//map interface members
MapInterfaceProperties(classToWrapField, typeBuilder);
MapInterfaceEvents(classToWrapField, typeBuilder);
MapInterfaceMethods(classToWrapField, typeBuilder);
 
//define constructor
DefineConstructor(classToWrapField, typeBuilder);
view raw gistfile1.txt hosted with ❤ by GitHub

As you can see, we have a clear overview of what is happening during the creation of our new Type. This is very important when dealing with the whole Emit thing. Keep things as simple as possible, and please don’t create methods larger then 20-25 lines. It can get real messy, real fast.

Now for some IL magic, let’s look at how the constructor is defined:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
private void DefineConstructor(FieldInfo classToWrapField, TypeBuilderHelper typeBuilder)
{
typeBuilder
//take an instance of 'ClassToWrap' as constructor parameter
.DefinePublicConstructor(ClassToWrap)
.Emitter
//: base()
.ldarg_0
.call(typeof(object).GetConstructors()[0])
//this.[fieldName] = [constructorParameter]
.ldarg_0
.ldarg_1
.stfld(classToWrapField)
//return
.ret();
}
view raw gistfile1.txt hosted with ❤ by GitHub

Most important thing here is that ldarg_0 will always be the equivalent of ‘this’ in a non static environment. For an instance method, parameter loading starts with ldarg_1.

Last example is mapping methods of the interface to methods of the targetType:

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
private void MapInterfaceMethods(FieldInfo classToWrapField, TypeBuilderHelper typeBuilder)
{
//loop al interface methods
foreach (var methodInfo in InterfaceToImplement.GetMethods())
{
//define the method in the generated type
var emitter = typeBuilder.DefineMethod(methodInfo)
.Emitter
//this.[fieldName]
.ldarg_0
.ldfld(classToWrapField);
 
for (var index = 0; index < methodInfo.GetParameters().Length; index++)
//pushs all method arguments on the stack, so we can use them to
//call the targetMethod
emitter.ldarg(index + 1);
 
emitter
//this.[fieldName].[MethodToImplement]([parameters])
.callvirt(GetMappedMethod(methodInfo))
//return
.ret();
}
}
view raw gistfile1.txt hosted with ❤ by GitHub

If you are interested in this library, please download/fork it here!

Please don’t send me e-mails that is doesn’t work for you, just open an issue on github, or create a pull request and solve it yourself ;)

Share On