Skip to main content

Pseudo-Template Meta-Programming in C#

Not full details here, but I'm writing this post as part-memo to myself, but also in the hope that one or two of you might make a mental bookmark to keep checking back.

In the course of my most recent project, which involve classes which wrap a common data storage mechanism (a bit like DataRows) I encountered a problem which was best solved with a solution called (coining a phrase) 'self-aware' properties.  Assuming all the storage access code is provided in a common base, and using attributes to define the string name of the 'column' (to continue the DataRow analogy) to which a property is mapped:

class X
{
  [MappedProperty("actualvaluename")]

  public string SomeValue
  {
     get
     {
        return base.GetPropertyValue("SomeValue");
     }

  }

}

So far so rudimentary.  However, I wanted my framework to be able to support inheritance, so that a class inheriting from another one not only could inherit it's properties, but also so it could actually override the mappings for a property defined by a base, just by using the same attribute.

Also, what I didn't want to have to do was:

a) Store mapping information in every instance of such a class (to weighty)
b) Write some behemoth registry which keeps track of all the mappings (initialisation problems, potential threading issues, not to mention a nightmare to extend and maintain)

The solution that I have produced takes a few ideas from the ideas laid out by C++ Template Meta-Programming (read this book if you want to know more: http://www.amazon.co.uk/Template-Metaprogramming-Concepts-Techniques-Beyond/dp/0321227255), but of course it all happens at run time - because Templates in C++ are not the same as C# Generics.  It takes advantage of an immensely powerful feature of Extension Methods - generic extension methods (think public static void Foo<T>(this T instance, ...) ),  as well dynamic Generic class instantiation using reflection to achieve the generic recursion required to build the data for each level in the class hierarchy.

All it took was a common base (with practically no methods), a static generic class plus some extension methods - and the C# type engine does the rest for you.

In a future post I will lay out the design, but for now I've run out of time (it's Fathers' day - which as many fathers will know doesn't necessarily mean that Father gets to choose what he does!)

Comments

Popular posts from this blog

Asp.Net 2 and 4 default application pool generates CS0016 IIS7.5

Before I start – if you’ve found a bunch of other articles about this around the net, tried the fixes that are mentioned and still not getting any joy – then read on – you might find this solves your problem. Earlier today I discovered that when I run any ASP.Net 2 or 4 application through IIS7.5 using the default application pools (which use ApplicationPoolIdentity) on Windows 2008 R2 x64 I get an error message similar to this:   Server Error in '/MvcApplication31' Application. Compilation Error Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS0016: Could not write to output file 'c:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\mvcapplication31\222b4fe6\4e80a86\App_global.asax.clb4bsnc.dll' -- 'The directory name is invalid. ' Source Error: [No relevant source ...

Serializing to attributes in WCF with DataContractSerializer

It’s a common problem – you want to return an object from a WCF service as XML, but you either want, or need, to deliver some or all of the property values as XML Attributes instead of XML Elements; but you can’t because the DataContractSerializer doesn’t support attributes (you’re most likely to have seen this StackOverflow QA if you’ve done a web search).  Most likely you’ve then migrated all your WCF service code to using the XmlSerializer (with all the XmlElement/XmlAttribute/XmlType attributes et al) – and you’ve cursed loudly. Well, I’m here to rescue you, because it is possible – and the answer to the problem is actually inferred from the MSDN article entitled ‘ Types supported by the Data Contract Serializer ’. The example I’m going to give is purely for illustration purposes only.  I don’t have a lot of time, so work with me! Create a new Asp.Net WCF service application, you can use Cassini as your web server (probably easier – otherwise you might have to enable...

Using WPF to Render Bitmaps

There are a few posts around the net about this, but a lot of them focus on taking XAML controls or pages, and turning parts of them into bitmaps. This is fine, but I want to be able to use WPF entirely off-screen in order to create rich graphical content. What I'm going to present here is a way of doing just that, in a console application just to press home the point. This is the image that you're going to produce - it's a little bit, well, crap - but it does the job. So, it's an Ellipse with a RadialGradientFill (off-centre, white-to-blue gradient stops), and a TextBlock in Arial Black/Bold font of around 40px size. The edges around the ellipse are going to be output as transparent (open up this file in Photoshop or Paint.Net and notice the checkerboard patterns around the edge - useful for web images! Step 1: Create the project Open a new Visual Studio, and create a new Console Application Project.  Make sure it targets .Net 3.5. Add references to: Pr...