Master, Usus.NET and other projects

It has been a long time since I published my last blog post. A little over two years actually. Back then I was writing about the small Visual Studio extensions that I created in order to improve my productivity. Now, two years later, I just finished the biggest Visual Studio extensibility project I have ever worked on. I worked on this project while writing my masters thesis about static code analysis, code metrics and clean code at andrena objects AG ( Before I come to describing what it is, let me express my satisfaction about being done studying. I obtained my Master Of Science in Computer Science degree last Friday.

When I was done with my bachelor, I wrote that a degree does not really proof anything except that one spent some dedicated time studying complex topics and coding experimental software in daylong labs. I am glad I spent that time. I learned a lot but the most important stuff I learned I learned outside the classroom. Writing my masters thesis at andrena was a great opportunity to learn from great people like Fahd Al-Fatish and Robert C. Martin. Unfortunately andrena is mainly a Java shop, so I did not find many C# projects there where I could use my over 7 years of experience in programming for the .NET framework. When I submitted my thesis I had one month of free time until I started my first full time job on 1st October at STP Informationstechnologie AG (

In that one month I thought I would have time to write this blog post but time was never really there. It is not here now either, but I am forcefully taking these minutes. Scott Hanselman left me with an adjusted view on how to approach things (watch his very interesting talk at There have been a few projects of mine that I really want to introduce here. Since I don’t know whether I will have the time to pursue any further projects during my spare time, I at least want to be done with the others waiting in the back of my mind to be written about.

I also want to show some code snippets. In my previous posts those snippets always looked ugly so I went and looked for a better solution. Due to the fact that I don’t host my own content management system but use the free wordpress hosted thing, I do not find much use in source code formatting plugins. What I found was this Code Highlighter at Unfortunately Windows Live Writer decided it can no longer post to my wordpress blog. So I had to copy this text over into the web interface. All the formatting of the code snippets got lost and I did not want to format it all by hand. So the code in this post looks even uglier than in the previous posts but I just don’t care anymore. You can distinguish the code from the rest based on the line numbers.


My masters thesis was about static code analysis and how this can be utilized to improve clean code. I created a Visual Studio extension which can perform a static code analysis and calculate metrics and quality indicators on every build. It shows problematic sites in the code and calculates code metrics and the andrena software quality index. I also engineered a dedicated clean code metric based on the statistical distribution of the metrics which I call The Naujoks Coefficient (lambda of the geometric distribution). This metric can be applied to any metric histogram and is based on intentions of Robert C. Martins book Clean Code.

The name of the extension is Usus.NET and it is entirely open source. I also take pull requests. You can find the source and everything related (including my masters thesis) at If you don’t want to get the code and compile it yourself, you find the VSIX file for directly installing onto Visual Studio on my website at But this is not the most recent version. I compiled it when I finished my masters thesis. Any later check-ins to the repository at github are not included.

The screenshot below shows how the information is visualized in Visual Studio.

But Usus.NET also comes as a simple library which lets you integrate its functionality into your own applications. Here is the code that analyzes an assembly or the executing assembly itself.

  1. //var metrics = Analyze.PortableExecutables(assemblyToAnalyze);
  2. var metrics = Analyze.Me();
  3. foreach (var method in metrics.Methods)
  4. {
  5.     Console.WriteLine(“Signature: ” + method.Signature);
  6.     Console.WriteLine(“CC: ” + method.CyclomaticComplexity);
  7. }

The quality indicators can be queried like this.

  1. RatedMetrics rated = metrics.Rate();
  2. double acd = rated.AverageComponentDependency;
  3. int cyclicNamespaces = rated.NamespacesWithCyclicDependencies;

The problematic sites in the code, which Usus.NET refers to as Hotspots, can be determined like shown below.

  1. MetricsHotspots hotspots = metrics.Hotspots();
  2. var complicatedMethods = hotspots.OfCyclomaticComplexity();
  3. var bigClasses = hotspots.OfClassSizeOver(10);

Usus.NET has opinionated default thresholds for any calculation. Those could also be adjusted at runtime, but I don’t recommend that. There has been much consideration gone into finding those thresholds. If you would like to know more about this, please read my master thesis at

But with all these metrics and quality indicators, I believe that the community needs to have an adjusted mindset regarding interpretation of code metrics. A method with a high cyclomatic complexity (CC) is not listed because of its high CC but because it is complicated. The developer should not try to get it off the list but to make it more manageable and less complicated. If you are not sure what the difference between complex and complicated is, take a look at the great image at Erwin van der Koogh’s blog.

Usus.NET is far from being done. I am done with my masters thesis and thus with actively developing it. I will be adjusting it when time allows it, but I would like the community to have a look at it, take it on, improve it and make it awesome.


Before I even started working on Usus.NET I actually had some free time. I was actively creating many Windows Phone 7 apps. A list of all those apps can be found on my website at Anyway, wanted my apps to be in both German and English at the same time. I don’t like the approach that .NET is taking with resource files, so I tried to create my own very lightweight solution of internationalization. LangLight is a Visual Studio extension that enables simple translations for WPF, Silverlight and Windows Phone 7-7.5. It uses XML driven code generation and creates bindable properties.

You need to create a simple XML file that contains the translation information like below.

If you click on the “generate code file” button, LangLight will create a C# source code file for you. Then you can bind to any of these translations using XAML like so.

  1. Content=”{Binding merken.Translation, Source={StaticResource translations}}”
  2. Content=”{Binding hierWeiterlesen.Translation, Source={StaticResource translations}}”
  3. Content=”{Binding versenden.Translation, Source={StaticResource translations}}”

Or use it directly in code.

  1. App.Helper.AppBarMenu(this, 2).Text = LangLight.i18n1Translations.Instance.nächstesKapitel.Translation;
  2. App.Helper.AppBarMenu(this, 1).Text = LangLight.i18n1Translations.Instance.vorherigesKapitel.Translation;

It allows for language switches without restarting the application and provides a very easy to understand API. You can change the language with a simple method call.

  1. LangLight.i18n1Translations.Instance.TranslateToEnglish();
  2. LangLight.i18n1Translations.Instance.TranslateToDeutsch();

I also created a screencast where I show off this basic use case Listening to it myself is still very funny. Anyway, you can download the extension on the Visual Studio gallery at Two of my other extensions are there too: MethodLog and StatePatternModeler. But I already introduced them in the previous blog posts. All my productivity tools can be found on my German website as well


After I wrote my bachelors thesis at CAS Software AG (, I worked on the PrimeSense SDK for Kinect. The Kinect for Windows SDK was not released then but the Kinect was pretty much hyping back then. At CAS, I created a library that enables the Kinect to be used very easily with WPF. Because CAS could not see any direct advantage of integrating natural user interfaces in their applications, I open sourced that library and put its code on github at The library is called MKinect and comes with many helper classes, that make it easy to add special gestures to any .NET application, especially when using WPF. I also created a showroom app in order to show off some of its functionality. The video of it can be viewed at

For example, if I wanted to track body parts as they are projected onto a simple Canvas, I need to declare a special Canvas-wrapping TrackingEllipseCanvas with two boxes that represent button-like areas.

  1. <hcanvas:TrackingEllipseCanvas x:Name=”tracker_canvas”>
  2.     <Rectangle Width=”200″ Height=”100″ Canvas.Left=”84″ Canvas.Top=”200″
  3.        hcanvas:HighlightCanvasItemContext.Handler=”{Binding LeftColorBox}”/>
  4.     <Rectangle Width=”200″ Height=”100″ Canvas.Left=”490″ Canvas.Top=”200″
  5.        hcanvas:HighlightCanvasItemContext.Handler=”{Binding RightColorBox}”/>
  6. </hcanvas:TrackingEllipseCanvas>

Then I need to specify what body parts the Kinect should keep track of.

  1. head = GenericActionFactory.Create<MoveableBodyPart>(this.kinect, s => s.Head);
  2. lHand = GenericActionFactory.Create<MoveableBodyPart>(this.kinect, s => s.LeftHand);
  3. rHand = GenericActionFactory.Create<MoveableBodyPart>(this.kinect, s => s.RightHand);
  4. lShoulder = GenericActionFactory.Create<MoveableBodyPart>(this.kinect, s => s.LeftShoulder);
  5. rShoulder = GenericActionFactory.Create<MoveableBodyPart>(this.kinect, s => s.RightShoulder);
  6. this.tracker_canvas.StartTracking(head, lHand, rHand, lShoulder, rShoulder);

That is all I need to do if I just want to have beach balls floating around which represent the associated body parts. Any additional action can be set up using a very fluent interface.

  1. When.The(leftHand).Enters(LeftColorBox).Do(() =>
                                               RectColor1 = new SolidColorBrush(Colors.Red));
  2. When.The(leftHand).Leaves(LeftColorBox).Do(() =>
                                               RectColor1 = new SolidColorBrush(Colors.Gray));
  3. When.The(rightHand).Enters(LeftColorBox).Do(() =>
                                                RectColor1 = new SolidColorBrush(Colors.Green));
  4. When.The(rightHand).Leaves(LeftColorBox).Do(() =>
                                               RectColor1 = new SolidColorBrush(Colors.Gray));
  5. When.The(rightHand).Enters(RightColorBox).Do(() =>
                                               RectColor2 = new SolidColorBrush(Colors.Blue));
  6. When.The(rightHand).Leaves(RightColorBox).Do(() =>
                                                RectColor2 = new SolidColorBrush(Colors.Gray));

Can it get any easier than that? All this code is freely available but so far requires the PrimeSense NITE SDK.


Quite recently I came across a great CodeProject article by Ziad Elmalki He was experiencing with the method table and JITing. I turned what he found out into a simple isolation framework. Using a very lightweight API, MReplace allows to replace any non-framework method and property at runtime, without any profiler. Full fledged Frameworks like Typemock Isolator, Telerik JustMock and Microsoft Fakes use a profiler to intercept method calls at runtime. MReplace does not. It goes for the method table and substitutes the pointer to any method with a different pointer. Before I show you how to use it, let me tell you that it is open source and can be found on my github at But lets take a look at a simple test method now.

  1. [TestMethod]
  2. public void Replace_StaticMethod()
  3. {
  4.     Assert.AreEqual(2, ClassUnderTest2.StaticMethod2());
  5.    using (Replace.Method(() => ClassUnderTest2.StaticMethod2())
                                     .With(() => ClassUnderTest1.StaticMethod1()))
  6.    {
  7.       Assert.AreEqual(1, ClassUnderTest2.StaticMethod2());
  8.    }
  9.    Assert.AreEqual(2, ClassUnderTest2.StaticMethod2());
  10. }

In the using block, ClassUnderTest2.StaticMethod2() returns something else than outside. MReplace lets you break dependencies by changing method implementations at runtime, without needing anything to be attached to the CLR process. There is one small draw back though: MReplacedoes not work if the application is started in debug mode. But debugging tests is bad practice anyway since TDD should lead to non-debugging development activity.


The last library I want to introduce in this blog post is about screen scraping. It is part of my “getting started faster with any Windows Phone 7 app”-framework called SilverlightRun, which is on github at But since I already needed it in other environments as well, I moved it into its own reusable package. MStrings is also on github at and supports easy string manipulation. I use it very heavily for parsing webpages in The Mentalist Episodes app ( Since there is not much to it. It lets you extract substrings from bigger strings, like shown in the code below.

  1. string result = ContentScraper.For(s)
  2.     .StartingAt(“<“).UntilLast(“>”)
  3.    .Replace(“<“, “”).Replace(“>”, “”)
  4.    .Replace(“\r”, “”).Replace(“\n”, “”)
  5.    .Replace(“&quot;”, “\””)
  6.    .Replace(“&nbsp;”, “”);

I find it very useful for extracting HTML tags. Maybe I will even turn this into a NuGet package.

Ok, the psychic weight of this stuff is now off my mind. I cannot believe it took me over a month to finish writing this blog post. But hopefully you will find something of it useful and consider using it in any of your projects. Most of my stuff is on, so please don’t hesitate to send me pull requests. In case you do not already, please follow me on twitter at and visit my website

Take care

Manuel Naujoks

Model Driven Development with StatePatternModeler

I am proud to announce two Visual Studio 2010 Extensions that are supposed to make development easier and more efficient. Yesterday I also managed to get my German website up to date, so check it out at This is also my first blog entry since Windows Live Spaces, which I liked very much, got closed down.

Logging changes with MethodLog

In my current position there is not much time in my life that I can spend on programming and related stuff, so this is all happening a little bit delayed. I published my first ever Visual Studio Extension in early September but could not write about it until now. I named it MethodLog and what it does is quite shortly to describe. Every change that the user makes to a method, is logged as a comment on that method, containing a running number and a current date and time.


The image above shows how this looks in Visual Studio. You can download this extension on my German website at or directly at the Visual Studio Gallery at

Modeling states and generating code with StatePatternModeler

The other extension that I am announcing is called StatePatternModeler. The caption of this blog post is referring to this one, since it makes Model Driven Development (MDD) easy in Visual Studio. It does not provide for an entire solution to MDD but does solve the development of stateful applications with models. In my previous blog post I was already describing how this could be accomplished with a custom UML Profile and a T4 template file that I created. If you have not read that article, go ahead and do so now, if you are interested in the raw mechanics.

The StatePatternModeler extension just wraps the UML Profile and the T4 template into a Visual Studio 2010 Extension. It provides a Project Template for the UML State Model and an Item Template for the T4 template that generates the code and a derived behavior class to apply custom logic to the state machine.


These templates make it easy to work with the UML Profile and the code generation and therefore allow an easy way to work with state machines in C#.


The images above show how this looks in Visual Studio. You can download this extension on my German website at or directly at the Visual Studio Gallery at StatePatternModeler only works with Visual Studio 2010 Ultimate, since it is relying on the UML Modeling Tools for the State Model Project Template.

A type-safe ViewModel base class

The last thing that mattered to me today and that I want to write about is how you can create a type-safe base class for your ViewModel in WPF or Sivlerlight. For the projects that I was doing so far, I did not need to use the MVVMlight framework. Though, I needed a base class for my ViewModels that does not use strings in order to notify property changes. Having strings can be the source of much frustration since they don’t survive refactoring. The approach that I am using allows you to have a ViewModel like below.

   1: using System.Windows.Input;


   3: namespace SilverlightRun

   4: {

   5:     public class CounterViewModel : ViewModelBase

   6:     {

   7:         private int _Counter;

   8:         public int Counter

   9:         {

  10:             get

  11:             {

  12:                 return _Counter;

  13:             }

  14:             private set

  15:             {

  16:                 _Counter = value;

  17:                 NotifyChange(() => Counter);

  18:             }

  19:         }


  21:         public ICommand CountCommand { get; private set; }


  23:         public CounterViewModel()

  24:         {

  25:             this.CountCommand = new ActionCommand(() => this.Counter++);

  26:         }

  27:     }

  28: }

Ignore everything but line 17. There I notify about a change of the Counter property in a type-safe manner. Pretty cool, if you would ask me! The code of the ViewModelBase class is very simple as well, like you can see below.

   1: using System;

   2: using System.ComponentModel;

   3: using System.Linq.Expressions;


   5: namespace SilverlightRun

   6: {

   7:     public abstract class ViewModelBase : INotifyPropertyChanged

   8:     {

   9:         public event PropertyChangedEventHandler PropertyChanged;


  11:         protected void NotifyChange(Expression<Func<object>> locator)

  12:         {

  13:             if (this.PropertyChanged != null)

  14:             {

  15:                 string property = this.GetNameByLocator(locator);

  16:                 this.PropertyChanged(this, new PropertyChangedEventArgs(property));

  17:             }

  18:         }


  20:         private string GetNameByLocator(Expression<Func<object>> locator)

  21:         {

  22:             LambdaExpression lambdaExp = (LambdaExpression)locator;

  23:             UnaryExpression unExp = (UnaryExpression)lambdaExp.Body;

  24:             MemberExpression memExp = (MemberExpression)unExp.Operand;

  25:             return memExp.Member.Name;

  26:         }

  27:     }

  28: }

The trick is to use a Linq expression that you can parse and get the name of the property, like I do in lines 22 to 25. Now you can refactor all you like and still get a compiling output. Actually, refactoring can be done including strings as well with some tools already. Type-safety as well is also not quite true, since the types don’t matter at all. Everything that is inheriting from object can be used to notify a change of it. It is just more type-safe than strings, so meta-type-safe would be a better term to describe it.

That’s it for this time. Please check out my German website and follow me on twitter (@halllo) if you have not done so already.

Take care!

Manuel Naujoks

Automatically generating states with VS2010 UML tools and T4

Just for the social aspect of this post, I want to let you know that I am done with my studies :) I am still awaiting my degree but I did finish all the exams, thesis and colloquium. Now I am a Bachelor of Science in Computer Science. Anyway, that is just a degree and does not say anything about my actual qualifications and capabilities. It only says that over the last 3,5 years I dedicated very much of my time to sitting in labs and lectures doing and learning stuff that others think are important. I believe that the really important stuff has to be learned outside of university. Maybe even outside of a job. Follow me on twitter (@halllo).

It really starts here

Since Visual Studio 2010 Beta 2 hit the internet, I found it really sad that they do not have a state diagram as part of their UML tools. Well, I really needed some kind of state modeling so I came up with an solution that really fascinated me. It all started when I was reading Oleg Sych’s amazing blog posts about T4. Especially when I read “UML Modeling and Code Generation in Visual Studio 2010” ( So this is where I kind of learned about the opportunities VS2010 enables.

My solution allows you to model states in Visual Studio and automatically generate code. You can use that code to wire up the generated states with your own logic and get all the states and transitioning for free. In this blog post I will demonstrate what I did with T4 and VS2010 Ultimate RC1. In that matter I will show you how you can use my results and am even going to show how I did it. All the source I release as well.

How to use it

I created the possibility to model states with Visual Studio 2010 Ultimate. When you create a new Modeling Project, you cant just create a state diagram. This is very sad, because it would not be too hard to implement for Microsoft, I guess. My approach uses a different perspective on states. In the state pattern you work with states as classes that inherit form a unified state abstraction. Thanks to polymorphic dispatch you can transit between states by setting a current state property in some state context. I kind of used the same idea. First, we will need a class diagram.


In the UML Model Explorer we need to specify the “UML State Profile 1”, like in the picture below. This profile is what I created and I will elaborate on it later in this post. Then we create some UML classes. For each class we set the stereotype to “State”.

 image image

After that, it should look something like in the picture below. What we did so far is specifying each class with an UML meta model directive called stereotype. For more information on that, please glean in the UML 2.2 specs, which you can download here:


Our classes now represent states in a state machine. For the transitions we need to add associations between the classes. Like the classes, we can specify stereotypes on associations as well. Like you can see in the properties of the stereotype “Transition”, it can either be triggered by an “Event” or by a “Literal”. If you choose “Event”, the name that you give that transition is going to become an event on your state machine. If you choose “Literal”, the state machine becomes capable of handling string input. The name you give the transition in the latter case gets interpreted as a regular expression and if it matches the input, the transition is performed.

image image

After creating all the transitions between the states and naming them, our state diagram should look something like below.


State “Class1” transits to state “Class2” if the event “Start” is fired. Then, state “Class2” stays active, as long as the input are digits between “a” and “z”. It the input is a number, state “Class3” gets active and never goes back to “Class2”. When the event “Finish” is fired, the state machine terminates. “Start” and “Finshed” are “Event” transitions, while “[a-z]” and “[0-9]” are “Literal” transitions. It is important to notice, that the states “Class2” and “Class3” have the method Do() defined. These operations have the stereotype “State Behaviour” assigned.

With that, the model of our state machine is complete now. So in order to do something useful with it, we need to create a executable project in VS2010. I just created a Console Application, which I set to be the start project. Then, we need to copy the states template ( into this new project. I also created this template on which I am going to elaborate later in this post. In the template we need to specify the name of our modeling project so that the template can find it. I just changed this line:

string projectPath = Host.ResolvePath(@”..ModelingProject3ModelingProject3.modelproj”);

In order to generate the code from the modeled states, we need to save this *.tt file or run the custom tool, like in the image below.


This generates all the code for the states. Then we can compile the solution and should get no errors. Notice that it is not required to have a project reference to the UML project in the Console Application. Now we can start using the states in code and wire up our own logic. To do this best, I recommend inheriting form the generated class States in namespace StateUser. I did that in the code snippet below. I only wired up calls to WriteLines so that we can see what is going on inside the state machine.

class CustomStates : StateUser.States
    public CustomStates()
        base.Class1.OnExit = () => Console.WriteLine(“Start…”);
        base.Class2.OnDo = () => Console.WriteLine(“Class2.Do()”);
        base.Class3.OnDo = () => Console.WriteLine(“Class3.Do()”);
        base.Class4.OnEntry = () => Console.WriteLine(“Done!”);

If you want the machine to do more comprehensive stuff, you need to specify your behaviour by setting up Action expressions. Notice that the OnDo property represents the “Do” operation on the states “Class2” and “Class3”. Now we have our state machine all connected with the logic that we want it to handle. I put the interactions with the state machine directly in the Main method, like in the snippet below.

static void Main(string[] args)
    var statecontext = new CustomStates();
    statecontext.Input(“b”); statecontext.Do();
    statecontext.Input(“g”); statecontext.Do();
    statecontext.Input(“2”); statecontext.Do();
    statecontext.Input(“u”); statecontext.Do();

I call start on it, give it two digits and then a number. When it gets the number it transits into “Class3” and stays there, even when I give it a number again, because this is the behaviour that we modeled with our UML classes. After each input, I call the Do operation. Dependent on the state that the machine is currently in, the corresponding Action is invoked. When I run the application, I get the following output:


We see that the machine does not leave state “Class3”, once we are in there. Our state machine works! To do all that on your own, you need to download these two files:

    1. The “UML State Profile 1”:
    2. The “States” template:

Feel free to use it and give me feedback about what you think. If you want to change the profile or the template code to redistribute them, go ahead. I would be happy to be mentioned though :)

How it works

To enable the scenario above, I needed to create a custom UML profile. Visual Studio 2010 Ultimate allows that. It is just an XML file with the ending .Profile that needs to be copied to the location below.

C:Program Files (x86)Microsoft Visual Studio 10.0Common7IDEExtensionsMicrosoftArchitecture ToolsUmlProfiles

It also needs to be registered in the “extension.vsixmanifest” file, like below.

…<CustomExtension Type=”Microsoft.VisualStudio.UmlProfile”>umlstateprofile1.Profile</CustomExtension>…

The umlstateprofile1.Profile file itself consists of three parts. The first is the stereotypes tag. Here I defined the stereotypes for IClass, IAssociation and IOperation. The second part contains the names of the meta classes that you provide stereotypes for. The third part is a collection of properties, that you can assign to your stereotypes.


The stereotype for the UML Class is really simple. All you need to specify is the name, the display name and the target, which is the IClass in this case.

<stereotype name=”umlstate” displayName=”State”>
    <metaclassMoniker name=”/umlstateprofile1/Microsoft.VisualStudio.Uml.Classes.IClass” />

The stereotype for the UML Association is a little more. Here you additionally have to provide the parameter indicating whether it is an “Event” or a “Literal” transition.

<stereotype name=”umltransition” displayName=”Transition”>
    <metaclassMoniker name=”/umlstateprofile1/Microsoft.VisualStudio.Uml.Classes.IAssociation” />
    <property name=”transitionaction” displayName=”Transistion Type” defaultValue=”Event”>
        <enumerationTypeMoniker name=”/umlstateprofile1/TransitionRuleType”/>

The enumeration type is referred to as TransitionRuleType. You have to have this one defined in the propertyTypes tag of the profile file. The definition looks like below.

<enumerationType name=”TransitionRuleType”>
    <enumerationLiteral name=”Literal” displayName=”Literal”/>
    <enumerationLiteral name=”Event” displayName=”Event”/>

The stereotype for the operations is equally much as for the association. It is just using a different enumeration type.

<stereotype name=”umlstatebehaviour” displayName=”State Behaviour”>
    <metaclassMoniker name=”/umlstateprofile1/Microsoft.VisualStudio.Uml.Classes.IOperation” />
    <property name=”behaviourtype” displayName=”Behaviour Type” defaultValue=”StateOperation”>
        <enumerationTypeMoniker name=”/umlstateprofile1/StateBehaviourType”/>

That is it for the UML profile. When there exists a project with things that have these stereotypes assigned, you can access them with code. I wrote that code in a T4 template, but you could also write it in a real application. The important thing is to have the correct namespaces referenced in the template. Since the compilation of the template is handled by Visual Studio, you do not need to provide project references. It is sufficient to just include their T4 using like below.

<#@ assembly name=”Microsoft.VisualStudio.Uml.Interfaces.dll” #>
<#@ assembly name=”Microsoft.VisualStudio.ArchitectureTools.Extensibility.dll” #>
<#@ import namespace=”Microsoft.VisualStudio.Uml.Classes” #>
<#@ import namespace=”Microsoft.VisualStudio.ArchitectureTools.Extensibility” #>

You can then get an instance of an IModelingProjectReader object.

string projectPath = Host.ResolvePath(@”..UmlStateClassUmlStateClass.modelproj”);
IModelingProjectReader project = ModelingProject.LoadReadOnly(projectPath);

Once you have that object, you can ask it for the everything that is in the corresponding project. It makes it easier if they have stereotypes assigned, but its not necessary. Below I iterate over all classes in the project and try to get their umlstate stereotype since this is the one that I defined in the UML profile.

foreach (IType t in types)
    IClass c = t as IClass;
    IStereotypeInstance sti = Extensions.GetStereotype(c, “umlstate”);
    if (sti != null) states.Add(new StateRepresentation(c));

Visual Studio allows stereotypes to be added to everything that implements IElement. This is pretty much everything so I could write a generic method that retrieves the instance of a stereotype form something that I give it. The kind of stereotype that is retrieved is specified by the stereotype name, which is a string.

public static IStereotypeInstance GetStereotype(IElement element, string stereotype)
    if (element == null) return null;
    return element.AppliedStereotypes.FirstOrDefault((sti) => sti.Name == stereotype);

When I have an instance of a stereotype, I can ask for its parameters, which i also specify as strings. These strings must be the same as in the UML profile file.

public static string GetStereotypeValue(IStereotypeInstance sti, string typename)
    if (sti == null) return null;
    IList<IStereotypePropertyInstance> stParams = sti.PropertyInstances;
    return stParams.FirstOrDefault((p) => p.Name == typename).Value;

With these constructs, I am able to get all the information that is required to create the state pattern automatically. The creation is done by the T4 engine. For editing the template I highly recommend the T4 editor form, which is available as a free edition. This version does not support IntelliSense on the classes of “Microsoft.VisualStudio.Uml.Interfaces.dll” and “Microsoft.VisualStudio.ArchitectureTools.Extensibility.dll”, which is unfortunate but worked for me.


I am not generating the exact state pattern ( since I am not generating a class for each state. I rather create an object for each state. The abstract state is that class of these objects. Also the transitions are not hard wired in the methods of the classes. Since I am generating an object for each state I use delegates to provide transitioning behaviour. To enable usage of own logic in combination with the generated state machine, I provide protected members for manipulation through any class inheriting. I even allow rewiring of transitions at runtime.

This makes the generated code a powerful framework that supports all kinds of scenarios and makes the anti-if campaign useable with an UML modeling approach. It is important to know, that changes on the UML model does not effect the generated code directly. The custom tool has to be run in order to let the T4 engine create the code with the latest changes. It is also not a good idea to change the generated code. Every change is going to be overwritten on the next run of the custom tool. It is a better idea to inherit from the generated class. Inheritance is an even better and cleaner way than having partial classes.

I really hope you guys like what I did. I am using this state framework to get rid of ifs and have a generic state pattern creator that allows me to model my states in UML. Visual Studio 2010 Ultimate is an amazing tool. Unfortunately the UML tools are only part of the ultimate version which costs very much. This is why I really enjoy the betas and RCs. Anyway, I if anyone read all the way down here, let me know on twitter at (@halllo). Please also checkout my website at

Take care!

Manuel Naujoks (Bachelor of Science)

Partition-Function in C#

Today I was reading some blogs and I came across this one:

Mark Needham was writing a partition-function, that he came across in F#, in C#. He introduced a tuple class to contain two elements in one objects with easy access. He then created an extension method that takes an IEnumerable<T> and a Func<T, bool> and returns a tuple with the first value containing all elements in the original collection, that result in the predicate being true, and in the second value the other ones. Like he mentioned, he is creating two iterators to fill the tuple. I was thinking about a way to have the same tuple available, by using only one iterator.

I could only think about an approach using a caching infrastructure. So I quickly created one.


This is just the class. The important thing is that I manually pull the IEnumerator<T> in the GetNextValue-Method. This method is then invoked in the First and Second getters. These getters pull the elements and apply them to the predicate. Regarding to the predicates return value, the result is either yielded directly and cached in the own list or cached in the list of the other getter. So when the other getter is requested, it is returning the cashed values.


If GetEnumerator is called on the same getter again, the cached values will still be in the list and therefore not been pulled out manually of the enumerator. This will lead to enumerators side effects happening only once. The use of this cached IEnumerable<T> tuple need a change in the Partition-method, like shown below.


The enumerable is not been iterated. Instead, it is passed into the TupleOfTwoCachedCollections, which is left two handle pulling. The pull handles, which are parts.First and parts.Second can then be passed into the regular tuple. This tuple can then be iterated where it is created, like in the Main-method.


When this program is run, it will output the following.


Like expected, the first foreach pulls until it does not get anymore numbers, yields predicate matches and stores the other ones. So when the other foreach runs, it yields the cached ints, then checks for more numbers. Since there are no, no side effects happen anymore. The side effect is shown in the output as happening after the value is returned. This is caused by having placed the Console.Writeline after the yield return in the GetNumbers-method.

A cashing approach is also used in System.Interactive (Interactive Extensions) like Bart De Smet covers in this amazing article:!

I know that my “solution” is highly un-functional since it relies on object state (caches), but it does get the job done! At the end of the day, that is what matters. I also do not claim that this is a good way of doing it. It is just one way. You can get my code here:!


If you do not already, please follow me on twitter: Regards, Manuel Naujoks

“Do I Poken?” Sounds silly somehow….

Yesterday I received a Poken, thanks to the sponsors of xpdays09. When I first read about these little gadgets, I found them stupid and with a silly slogan. A couple of minutes ago, I set up my profile and just wanted to share it on my blog. So here you go, my “business card”:


(For some reason Live Spaces does not let me post the script tag, so this is just a static image!)

I am really curious if using them is a nice experience and am totally looking forward to make many new contacts at xpdays09 in Karlsruhe at the 27.11.09. See you all there.


Creating a ContentControl in Silverlight

Recently I happed to work a lot in Silverlight and also needed to create new Controls. While a UserControl is useful to separate the pieces of an application, I needed that separation with the capability to inject other controls as well. Therefore Silverlight has a class called ContentControl. I derived from it and am now able to use this control as a decorator for the stuff that I can pass in. Because I did all this experimental work at home today on this Friday (actually it already is Saturday), I want me to remember all this when I go back to work on Monday. Coincidently, I did not write a blog post for quite some time, so I decided to to both at the same time: here is me writing shortly about how to create custom ContentControls in Silverlight.

I created a normal Silverlight 3 Application in VS2010 Beta2 and added a new item, a user control. Then I changed the UserControl to a ContentControl by editing the xaml file like below.

<ContentControl x:Class="SilverlightApplication2.CCC1"
        <Style TargetType="local:CCC1">
            <Setter Property="Template">
                    <ControlTemplate TargetType="local:CCC1">
                        <StackPanel Background="{TemplateBinding Background}">
                            <TextBlock x:Name="text1" Text="Hallo…."></TextBlock>
                            <ContentPresenter x:Name="conEl"/>

Notice that I declared the structure of the control in a ControlTemplate directly inside the content control. You could totally have this style in a resource dictionary, but i really like having everything where it is needed. Like this I can only have one of these content controls on a page. I named the TextBlock and the ContentPresenter because I want to access them in the code behind. There I have fields for them which I assign values when a template is applied to the control. I do this by overriding the OnApplyTemplate method.

using System;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace SilverlightApplication2
    public partial class CCC1 : ContentControl
        private TextBlock textBlock;
        private UIElement ContentElement
            get { return this.Content as UIElement; }

        public CCC1()
            this.Loaded += new RoutedEventHandler(CCC1_Loaded);

        private void CCC1_Loaded(object sender, RoutedEventArgs e)

        public override void OnApplyTemplate()

            this.textBlock = base.GetTemplateChild("text1") as TextBlock;

I put a breakpoint at the writeline to get notified when the control is loaded in order to be able to see what the content actually is. That pretty much is the custom ContentControl. I use it in the MainPage.xaml like below.

<UserControl x:Class="SilverlightApplication2.MainPage"

    <Grid x:Name="LayoutRoot" Background="Violet">
        <local:CCC1 Width="200" Height="150">
            <Canvas Width="350" Height="200" Background="Yellow">
                <Button Content="Hallo"></Button>

Notice that I made the custom content control (CCC1) 200 pixels wide and 150 pixels high. Its content I deliberately set to a bigger size to demonstrate that the custom content control is not streched. It would have streched if it was just a UserControl with the canvas placed in it.

Looks nice, doesn’t it?


That’s it for this blog post. If you do not already, please follow me on twitter at


Embracing TDD

Important information at the beginning :)

Roy Osherove is giving an hands-on TDD Masterclass in the UK, September 21-25. Roy is author of "The Art of Unit Testing" (, a leading tdd & unit testing book; he maintains a blog at (which amoung other things has critiqued tests written by Microsoft for MVC – check out the testreviews category) and has recently been on the Scott Hanselman podcast ( where he educated Scott on best practices in Unit Testing techniques. For a further insight into Roy’s style, be sure to also check out Roy’s talk at the recent Norwegian Developer’s Conference ( 

Full Details here:

My new Silverlight 3 Application

I recently launched my Silverlight 3 GraphRelaxing Sample that is capable of layouting graphs with random layout almost perfectly and automatically. All the user needs to do is enter a graph and wait for it to be layouted. The more nodes are on that graph the more time is required. I did this application in Java first but I wanted it to run on Silverlight, so that I would have the motivation to learn more about SL3. I figured there is no Java2D so I ended up writing a lightweight vector math framework that does the required calculations that the algorithm I use, which is Simulated Annealing by the way, needs to perform. Doing math stuff is kind of tricky because the algorithms you come up with could have some weird singularities that you did not think of. Kind of at the same time I was reading and listening into unit testing, so I decided to enforce myself doing “TDD”. I wanted to be able to “proof” that my math is working as expected and without strange behaviors. I am not sure I did it all correctly but I really tried to write tests first, fix only as much as the tests require to pass and design with many interfaces that I could stub out to break everything down into testable units. It was hard to not just go into production code and nail it but to write the test as a specification instead. It was fun though because at all time I knew that what I was working on at that moment worked! The tests proofed it and I liked this feeling. I also felt encouraged by Roy Osherove’s and Uncle Bob’s Sessions at NDC2009 that I watched online. I was feeling that I was becoming a better and more professional developer and this made me not to abandon this practice, which was new for me to do strictly. Now the application is done, I have 244 test cases and 100% code coverage. But this not what counts. The most valuable part is that I got used to testing. I got used to Silverlight 3 as well but the most advantages come out of doing the design the way that i can test it by writing its specification as a unit test. Now every code I write I am writing tests to it. I am not considering myself doing all this stuff right, but life is a learning process, right?

So if you have not already done so, check out the GraphRelaxing Silverlight Application on my website The App also support out of browser, which I like particularly. Here is the direct link:

Please follow me on twitter as well:

Assembling the dice

The last weekend I went with my family to visit our relatives in another area of Germany. While we were staying at my cousins house, I found these six pieces with strange edges that can be build up to a dice. I could not figure it out, so I decided to come a with a simple algorithm to solve the problem. When we came back to our home, I implemented it. It took me a little to get the interactions right but I finally did it and had an application that tells me how to put these pieces together. In this post I want to share some of the functions I coded for my approach. I do know that my solution might not be the best, fastest or shortest. Anyway!

So I took a picture of the pieces to build an assembler. I took it with my cell so the quality is not the best.


Now about the code. I wanted to place the snippets here and have them formatted automatically C# style but I could not find a working solution that did not take me too long to setup, figure out how it is working or why it is not working at all! So I ended up using screenshots.


What is on the picture above is the Main method of my console application. I initialize a dice object by linking its six sides together so that I can easily get references to all surrounding sides of every side by an edge classifier enumeration. This object works like a stub and accepts one of the six pieces to be applied to each side. Once the dice is in memory, I create a DiceMagician (I thought the name is fun) and hand him over all the pieces to build the dice. I give him an action object as well, so he can notify me on every solution he finds.

The solution finding implements a simple recursive back tracking approach. I iterate over all empty sides of the dice and for each side over all unused pieces. Each piece is going to be tried to put it on the current side in one of its mutation. As a mutation the pieces turn and flip so that they are tried eight times each to put it on. If it can be put on, the recursion starts over with all the left sides and pieces. If it can not be put, the recursion ends and tries the next mutation, piece or side.


When all the pieces could be placed on a side of the dice, a solution has been found. Then the caller is notified about it by executing the foundAction function. The interesting part here is where the decision is made whether a piece can be applied. The corresponding side needs to check if the neighbor sides pieces do allow it. Therefore it invokes the IsFree method on all these surrounding sides.


So the sides receive the invocation and check if the edge (form where the request is coming) of the applied piece has an edge that dove-tails with the corresponding edge of the piece that is tried to put on. I am checking on each position of that edge. It can happen that the x or y coordinates of the two pieces are aligned counterclockwise. To deal with this, I let an iteration mapping per edge decide how the coordinates flow.


When the dice is assembled and the sides are linked together, I need to declare which edges are going to face a reversed alignment of coordinates when checking of availability. So the sides that are registered by one another can be linked by normal or reversed edge. Depending on that, there are different iteration actions used. While a normal edge iterates on both connected sides in the same direction, a reversed edge iterates in different directions. This is why my iteration loop has two arguments, i and j. The first is counting down, the second up. When the side is checking with the other side, they can do that by using i and j without the need to know what values they are going to be. The values are determined by the kind of edge that is in between the two sides.


So this is it. When I run the application I get the solutions of how to assemble the dice directly written onto the console. Unfortunately I do not have the pieces so I can not actually build the dice. I also have no idea how many solutions the program will find but there must be a lot of solutions that are ultimately the same and just describe the dice from different perspectives. Feel free to download the application.



Ok, this was a different blog post and I do not believe anybody actually read it all. Anyway, follow me on Twitter: @halllo and check out my website:!

Manuel Naujoks

Summer yet to come

It has been a few days since I last blogged. I wrote about not being listed on So this time there have been a couple of very good things happening in my life that I would like to blog about.

The best thing is that I wrote my last exam of this semester today. That means no more school until first October :) Man, this is my personal start of summer. When I got back home today, I received the long awaited Windows 7 Shirt that I won on So this is me wearing it.


I wanted to do that with the DevExpress Shirt as well, unfortunately I did have it around. So thanks again, guys of I was mentioning and how I got upset about it in my last post. Somehow things changed and how I am successfully listed on bing, like you can see on the screenshot below. I could be ranked first, like I am on another big search engine, but I am really happy that I got ranked at all.


Now I can not say anything bad about bing anymore and continued using it mainly and with satisfaction. But this is not the only thing that was happening an my site in the web. While I was writing exams, I did not want to manually check my marks every time, so I updated my NotenChecker application. I wrote that three or four semesters ago but it stopped working. The reason was an update of the web service of the Hochschule Karlsruhe. So I released a new version of that app and also included a few features like automatic checking every two minutes. I changed the UI a little to make it look new and started using it.


So every time I get a new mark, the tool notifies me. It does so by sitting in the system tray and showing balloon-tooltips.


If you are a student on the HSKA, you can download the tool from

My plans for the summer include working on a few private projects. I want to finish CrossWordMatcher and start a Silverlight 3 project of locating “things” that are connected perfectly on an area. I intend to provide this commercially. I also plan on using these two applications as reference projects when I am applying for a bachelor thesis, which I am starting in two or three weeks. I still have not read “Gödel Escher Bach”, so I need to do that as well.

Alright, this is it for this post. If you do not already, please follow me on If you know me and the other way round, please provide your Skype name. Yes, I installed it again.

Why am I not listed at

I am having English exams next week so I am trying to post this in English to maybe improve my writing. I also figured that this way I get correct spellchecking. Although I found the settings, Windows Live Writer did not let me choose German here.


Anyway, another advantage of getting this text out in English is hopefully resulting in more people reading it. When Microsoft linked to I tried to use Bing as my major search engine. Before that I already knew about it, but I kept using live and another well-known se. So Bing “came out” for me that day and I ended up wondering, why I am not listed. My primary website is and I could not find a single reference to it.


When I was searching for “” I found at least some entries of this blog. Searching for my name resulted in finding my twitter profile at and my Windows Live Profile. So I am listed. What is not listed is my website and this a big deal for me.


So I signed in at the Webmaster Center of Bing. This looked all promising so in spite of minor doubts I went through the website authentication process. I do not even know why I made authentication code blur, since you can see that on my websites meta information. Anyway, I had my website authenticated. At least it looked like it.


After that I was wondering why there was no data appearing in Bings crawling summary. So I went forth to see whether any crawling issue happened. What I am seeing in the issue list is a file not found HTTP result. This is very weird because my website is totally accessible by any browser or other search engines.


I was opening the HTTP verifier, which is, to figure out what the problem is and why Bing is claiming to not be able to find my site. The HTTP status code that I get is “200 OK”, as expected. The thing that is confusing me since, is the result of HTTP conditional GET. I says that it is not enabled. I do not really know what that means so I am going to find out.


I am hosting at If anybody can help on this matter, please feel free to contact me, preferably on twitter at If I get any information about if it is really that, that keeps Bing from indexing me, I am going to post again.

Have a nice day.