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 (andrena.de). 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 (stp-online.de).

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 vimeo.com/39020426). 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 quickhighlighter.com/index.php?lng=csharp. 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.

Usus.NET

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 github.com/usus/Usus.NET. 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 mnsdc.de/programme/vsix_programme.htm. 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 github.com/usus/Usus.NET/tree/master/Documentation.

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.

LangLight

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 mnsdc.de/wp/. 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.

langlight-s1
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 screencast.com/t/I3iejxYnA. Listening to it myself is still very funny. Anyway, you can download the extension on the Visual Studio gallery at visualstudiogallery.msdn.microsoft.com/7b952a77-3207-4180-a350-c9d4fb852846. 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 mnsdc.de/programme/vsix_programme.htm.

MKinect

After I wrote my bachelors thesis at CAS Software AG (cas.de), 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 github.com/halllo/MKinect. 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 screencast.com/t/wy6ndBGvS.

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.

MReplace

Quite recently I came across a great CodeProject article by Ziad Elmalki codeproject.com/Articles/37549/CLR-Injection-Runtime-Method-Replacer. 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 github.com/halllo/MReplace. 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.

MStrings

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 github.com/halllo/SilverlightRun. 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 github.com/halllo/MStrings and supports easy string manipulation. I use it very heavily for parsing webpages in The Mentalist Episodes app (windowsphone.com/en-us/store/app/the-mentalist-episodes/cd58bb75-dea0-4f7d-b7ad-d5e996a9ff08). 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 github.com/halllo, so please don’t hesitate to send me pull requests. In case you do not already, please follow me on twitter at twitter.com/halllo and visit my website njks.de.

Take care

Manuel Naujoks

Advertisements