Pablo Picasso
"Computers are useless. They can only give you answers."
My Latest Tweets
Tags

This will be shown to users with no Flash or Javascript.
Calendar
<<  September 2010  >>
MoTuWeThFrSaSu
303112345
6789101112
13141516171819
20212223242526
27282930123
45678910
Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

Sign in

Adding an image in WPF is very straight forward. All you need to do is declare an Image element in XAML and specify the path of the image in the Source attribute:

<Image Source="about.png" />

But rather than deploying all your image files with your application, you might want to embed them in the assembly as resources:

Image resource build action. Once you’ve done that, you can start referring to images using either an absolute or relative URI:

<Image Source="pack://application:,,,/
Tbf.Presentation.Common;component/UI/Images/menu/about.png" />

or

<Image Source="Tbf.Presentation.Common;component/UI/Images/menu/about.png" />

Here Tbf.Presentation.Common is the assembly containing the compiled resource and UI/Images/menu is the project folder where the image is located:

Image folder location.

But this is really prone to errors and can quickly become a maintenance headache if you rename or move files around. Instead wouldn’t it be better to have all the pack URIs into one place? The way to do this is to add a new resource dictionary, say ImageResources.xaml, to your project.

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:Images="clr-namespace:Tbf.Presentation.Common.UI.Images">

    <!-- Menu -->
  <ImageSource x:Key="about_menu">
	Tbf.Presentation.Common;component/UI/Images/menu/about.png
  </ImageSource> 

</ResourceDictionary>

Then simply merge it into your App.xaml file or any other application-wide resource file…

<Application x:Class="Tbf.Presentation.Shell.App"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Startup="Application_Startup"
             Activated="Application_Activated"
             Deactivated="Application_Deactivated"
             DispatcherUnhandledException="Application_DispatcherUnhandledException"
             Exit="Application_Exit">
    <Application.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>

                <ResourceDictionary Source="pack://application:,,,/
                       Tbf.Presentation.Common;component/Infrastructure
                       /Resources/ImageResources.xaml" />

            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </Application.Resources>
</Application>

… to make images available as dynamic resources across the whole application:

<Image Source="{DynamicResource about_menu}" />

In terms of maintainability however this is still not satisfactory as there is no design or compile time checking to ensure that the key is correct. To improve on this, we can introduce a new ImageLibrary class in the project to help us specify the image resource key in XAML:

namespace Tbf.Presentation.Common.UI.Images
{
    #region Using Directives 

    using System.Windows; 

    #endregion 

    public class ImageLibrary
    {
        public static ComponentResourceKey AboutMenu
        {
            get
            {
                return new ComponentResourceKey(typeof(ImageLibrary), "about_menu");
            }
        } 
    }
} 
 

Next we have to go back to the ImageResources.xaml file and modify it to make use of the new helper class:

<ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                    xmlns:Images="clr-namespace:Tbf.Presentation.Common.UI.Images">

    <!-- Menu -->
    <ImageSource 
x:Key="{ComponentResourceKey TypeInTargetAssembly={x:Type Images:ImageLibrary}, ResourceId=about_menu}">
Tbf.Presentation.Common;component/UI/Images/menu/about.png
    </ImageSource> 

</ResourceDictionary> 

Et voilà! We have the support of intellisense for selecting images:Component key and Intellisense.A big improvement then? Yes but not quite perfect yet as now we have to define the key in two places: the ImageResources.xaml file and the ImageLibrary.cs file. To reduce further the amount of work we need to do, we can create a T4 template to automatically generate the ImageLibrary component keys:

1. Add a new item ImageLibrary.tt item in your project.

2. Copy and paste the code below (making the necessary adjustments for the namespace and ImageResources.xaml file path).

<#@ template debug="false" hostspecific="false" language="C#" #>
<#@ output extension=".cs" #>
<#@ assembly name="System.Core" #>
<#@ import namespace="System" #>
<#@ import namespace="System.Collections.Generic" #>
<#@ import namespace="System.IO" #>
<#@ import namespace="System.Text" #>
<#@ import namespace="System.Text.RegularExpressions" #>
<#@ import namespace="System.Linq" #> 

namespace Tbf.Presentation.Common.UI.Images
{
    #region Using Directives 

    using System.Windows; 

    #endregion 

    public static class ImageLibrary
    {
<#
foreach (string key in this.GetComponentResourceKeys())
{
    string name = this.GetPropertyname(key);
#> 

        public static ComponentResourceKey <#= name #>
        {
            get
            {
                return new ComponentResourceKey(typeof(ImageLibrary), "<#= key #>");
            }
        }
<#
}
#>
    }
}<#+ 

public List<string> GetComponentResourceKeys()
{
    // Get the image resources file
    string file = @"<PATH>\ImageResources.xaml"; 

    // Read the image resources file
    string content; 

    using(System.IO.StreamReader sr = new System.IO.StreamReader(file))
    {
        content = sr.ReadToEnd();
    } 

    // Extract the keys
    Regex regex = new Regex(
                    "(?<=ResourceId=).*(?=})",
                    RegexOptions.CultureInvariant
                    | RegexOptions.IgnorePatternWhitespace
                    | RegexOptions.Compiled); 

    List<string> results = new List<string>();
    MatchCollection matches = regex.Matches(content); 

    for(int i = 0; i < matches.Count; i++)
    {
        results.Add(matches[i].Value);
    } 

    return results;
} 

public string GetPropertyname(string text)
{
    text = Regex.Replace(text, @"[\W-[\s]]", string.Empty);
    string[] words = text.Split('_', ' '); 

    for (int i = 0; i < words.Length; i++)
    {
        if (words[i].Length > 0)
        {
            string word = words[i];
            char firstLetter = char.ToUpper(word[0]);
            words[i] = firstLetter + word.Substring(1).ToLower();
        }
    } 

    return string.Join(string.Empty, words);
}
#> 

 

3. Run the TextTemplatingFileGenerator tool on the newly created .tt file.

Run TextTemplatingFileGenerator tool.

All done. The image library class is auto-generated and you can now set images in XAML knowing that any errors will be picked up either at design or compile time.

A couple of weeks ago, I started getting a VerificationException on a newly created unit test project which had already a bunch of tests in it. The full message was:

method [TEST_METHOD_NAME] threw exception. System.Security.VerificationException: Operation could destabilize the runtime.

For the story, my work project is currently using MSTest, VS2010 RC1 and targets .NET 4.

Heading straight to MSDN for more details, I got the following information:

"The exception that is thrown when the security policy requires code to be type safe and the verification process is unable to verify that the code is type safe".

I don't know about you but this didn't give me much clue about who/what exactly was causing that error. This was rather puzzling as thus far the tests were running perfectly well on my local Dev environment and on the build server. What I noticed however was that switching code coverage on seemed to cause this error to crop up. Since code coverage is a must have, I had to find a way of resolving this.

Another MSDN entry Troubleshooting Exceptions: System.Security.VerificationException looked promising. The only thing that it suggested though was to ensure that the “application is not loading two conflicting versions of a class library”. I couldn't really imagine this to be the reason the VerificationException was thrown as without code coverage it all worked fine on exactly the same code base and environments. No code coverage, no problem; code coverage on, tests aborted!

So my next step was to identify the project and the assembly that was triggering the exception. After a while I managed to track this down to one of the solution's project that was reusing some libraries written against previous versions of the .NET Framework. They in turn were referencing the System.Configuration v2 assembly. My first thought was to add a binding redirect in the configuration file as shown below:

<configuration>
...
   <runtime>
      <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
         <dependentAssembly>
            <assemblyIdentity name="System.Configuration" publicKeyToken="B03F5F7F11D50A3A" culture="neutral"/>
            <bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0"/>
         </dependentAssembly>
      </assemblyBinding>
   </runtime>
...
</configuration> 

Unfortunately MSTest would still refuse to run the tests under code coverage. I then recalled some 'trust' issues I had in the past with System.Configuration on a .NET 3.5 application. More specifically this assembly requires full trust from the calling assembly otherwise a security exception is thrown. Here is an excerpt from an MSDN article that mattered to me:

There is no programmatic way for partially trusted code to call a library that does not have the AllowPartiallyTrustedCallersAttribute. If an application does not receive full trust by default, an administrator must choose to modify security policy and grant the application full trust before it can call such a library.

Only a few .NET Framework libraries installed in the GAC will allow partially trusted callers and System.Configuration is not one of them! So marking the assembly with the AllowPartiallyTrustedCallers attribute (APTCA) would not work (*).

[assembly: AllowPartiallyTrustedCallers(PartialTrustVisibilityLevel = PartialTrustVisibilityLevel.VisibleToAllHosts)] 

I could only conclude from the above that MSTest Code Coverage - presumably through the vshost.exe process? - was not, for reasons I still don't know, fully trusted and did not therefore have the right set of permissions to instrument the code. In the 'old' days of CAS (Code Access Security), I might have been able to apply an assembly level attribute in the AssemblyInfo.cs file to circumvent that with a SkipVerification permission request which tells the CLR to skip the type safety verification that happens during JIT compilation:

[assembly: SecurityPermission(SecurityAction.RequestMinimum, UnmanagedCode = true, SkipVerification = true, Execution = true)] 

But .NET 4 has changed all of that (Security Changes in the .NET Framework 4). Security policy decisions are now handed over to the host and managed desktop applications run automatically with full trust, leaving system administrators the responsibility of managing permissions at the operating system level. More importantly CAS policy has been disabled by default and is no longer the 'preferred security supplier'. This also means that the SecurityAction.RequestMinimum and others are now obsolete. Visual Studio will display a friendly warning when you add it:

SecurityAction.RequestMinimum Note that you can re-enable CAS in your configuration file as shown below:

<configuration>
...
   <runtime>
      <NetFx40_LegacySecurityPolicy enabled="true" />
   </runtime>
...
</configuration> 

However since I've always found CAS confusing and rather difficult to grok, it's not an avenue I wanted to even explore.

After some further reading (**) on the new security model in .NET 4 and in particular a short post on the .NET Security Blog Transparency Models: A tale of two levels, it dawned on me that what was required was to apply the level 1 rule set to my .NET 4 assembly calling the .NET 2 code. Level 1 corresponds to the security transparency model baked in the CLR v2 and effectively allows for backward compatibility with .NET 4. Level 2 is the model that comes with the .NET 4 CLR.

The follow-up post Differences Between the Security Rule Sets describes the effect of the APTCA attribute as follows:

Allows partial trusted callers access to the assembly by removing an implicit link demand for full trust on all code in signed assemblies.

I therefore added the explicit attribute below in my AssemblyInfo.cs file:

using System.Security; 

[assembly: SecurityRules(SecurityRuleSet.Level1)] 

Although the application I am working on is for internal use only and I probably could have left it at that, I decided to surround the SecurityRules attribute with a ‘COVERAGE’ conditional compilation symbol as I still want to be warned of any other potential issues.

using System.Security; 

#if COVERAGE 

[assembly: SecurityRules(SecurityRuleSet.Level1)] 

#endif

After that all my tests were passing with code coverage enabled. Result!

I don't know for sure whether my diagnosis is even close to being 50% correct as I honestly can’t say I fully understand .NET security. Not as much as I should do anyway. Like a majority of Devs, I suspect, I develop most of the time in a fully trusted environment with Admin privileges. I only had to worry about CAS on a few rare occasions. I know, I can hear some say “develop with a user account instead” but let's face it there is a reason most programmers don't: it’s hard and really a pain in the @~!#$. That could also be part of the reason CAS is being superseded.

At least this experience gave me an opportunity to start learning about .NET 4 security and being more aware of potential issues when developing a mixed solution with assemblies compiled against different versions of the framework. Hopefully this might also help some other people who are facing the same problem.

For now I need to return to my tests and get that code coverage back up to an acceptable level. Until next time,

Happy Programming!

(*)  You can find more details on Allowing Partially Trusted Callers.
(**) For a good introductory article on the new security model, check out Exploring the .NET Framework 4 Security Model.

As I was running a macro to increase or decrease the text font size (see previous post), I noticed that the macro balloon kept on flashing in the system tray. The reason for this is that in Visual Studio 2008, a balloon tip is shown every time you run a macro, until you click on it 5 times that is. Thereafter it will be no longer visible. The problem is that your macro might be running too quickly, giving you no time to click on it. For some background on this and why it is behaving like this by design, read Stopping the “Click here balloon” by Craig Skibo.

macro_balloon  

While I sort of understand why the VS team did this, I actually don’t care much for this feature. So I thought I’ll disable it altogether. This is easily done by adding a new registry key (HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\DontShowMacrosBalloon) and setting its value to 6. Note that you will still see the spinning cassette icon in the system tray but this is a lot less intrusive.

Instead of doing this manually I wrote a macro to disable this feature as otherwise I’ll probably forget I ever done this.

' Suppresses the macros balloon.
Public Sub DontShowMacrosBalloon()
	Dim key As Microsoft.Win32.Registry Key
	Dim subKey As Microsoft.Win32.Registry Key

	key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\VisualStudio\9.0", True)
	If (Not key Is Nothing) Then
		subKey = IIf(key.OpenSubKey("DontShowMacrosBalloon") Is Nothing, key.CreateSubKey("DontShowMacrosBalloon"), key.OpenSubKey("DontShowMacrosBalloon"))
		key.SetValue("DontShowMacrosBalloon", "00000006", Microsoft.Win32.RegistryValueKind.DWord)
		subKey.Close()
		key.Close()
	End If
End Sub

Should you ever want to re-enable it, simply delete the registry key or run the macro below:

' Enables the macros balloon simply by deleting the key
Public Sub ShowMacrosBalloon()
	Dim key As Microsoft.Win32.RegistryKey

	key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\Microsoft\VisualStudio\9.0", True)
	If (Not key Is Nothing) Then
		key.DeleteValue("DontShowMacrosBalloon", False)
		key.Close()
	End If
End Sub

Warning
The macros above modify the Registry and therefore the usual precautions apply.

The other day I grew increasingly frustrated with the amount of code I could or rather couldn’t see on my screen at work, even when working in full screen mode. I therefore wanted to write a Visual Studio macro to zoom in and out of the text editor. However while browsing through the sample macros that come with Visual Studio 2008, I found two macros that are doing just what I wanted: DecreaseTextEditorFontSize and IncreaseTextEditorFontSize. To check whether they are installed on your machine, simply go to Tools > Macros > Macro Explorer or type in ALT + F8 and then drill down to Macros > Accessibility.

Macro Explorer: Decrease Increase Text Editor Font Size 

Here is the Visual Basic code (after I changed fontSizeIncrement from 2 to 1):

' Set the font size increment and minimum font size
Private Const fontSizeIncrement As Integer = 1
Private Const minimumSupportedEditorSize As Integer = 3

' Increases the font size used within the editor.
Public Sub IncreaseTextEditorFontSize()
	Dim textEditorFontsAndColors As Properties

	textEditorFontsAndColors = DTE.Properties(“FontsAndColors”, “TextEditor”)
	textEditorFontsAndColors.Item(“FontSize”).Value += fontSizeIncrement
End Sub

' Decreases the font size used within the editor.
Public Sub DecreaseTextEditorFontSize()
	Dim textEditorFontsAndColors As Properties
	Dim fontSize As [Property]

	textEditorFontsAndColors = DTE.Properties(“FontsAndColors”, “TextEditor”)
	fontSize = textEditorFontsAndColors.Item(“FontSize”)
	If fontSize.Value >= minimumSupportedEditorSize Then
		fontSize.Value -= fontSizeIncrement
	End If
End Sub

If you don’t have the Visual Studio samples, follow the steps below to add these two macros:

  1. Open the Macro IDE (Tools > Macros > Macro IDE or ALT + F11).
  2. In Project Explorer, right-click on My Macros and select Add New Item…
  3. In the Add New Item… dialog, choose Module, give it a name (e.g. MyModule) and click Add.
  4. Simply copy and paste the code above in the newly added module.
  5. Save and close the Macro IDE.

 Add new module

All I had to do after that was to bind these macros to a keyboard shortcut. I chose ALT + [ to decrease the text font size and ALT + ] to increase it.

 Decrease text font size key binding

Now, I can easily zoom code in and out in the Visual Studio Text Editor.

In my previous post, I introduced NDepend and talked about how to get started. Now I’d like to review why I want to use it on my projects.

First of all, I really like the analysis reports. Not only do they show you instantly the current state of your application and how healthy it is (or not), but it also gives you an objective and systematic way of introspecting your code base. In conjunction with the code query constraints and metrics, they really help you monitor the quality of your .NET components. Even more so if you can run them as part of your build process.

As Mark Needham pointed out in this blog post, remembering to follow some of the OO design principles is not always an easy task when you’re coding. However by having the tool check for adherence to pre-defined rules/best practices, you can automate the identification step of the refactoring process thereby giving the Dev team more time to focus on the overall design, behaviour and functionality of the system.

Visual Studio already includes code analysis and FxCop but NDepend goes a lot further and one of its strength is that it let’s you visualize your code in a way that no other tool does. Napoleon said “un bon croquis vaut mieux qu’un long discours” (which more or less is the same as “a picture is worth a thousand words” in English) and so the diagrams produced by NDepend can help you digest complex architectures more easily.

NDepend Diagrams 

Now you might also ask what is wrong with just using the built-in Visual Studio 2008 code metrics? Well nothing but NDepend gives you much more than just cyclomatic complexity, depth of inheritance, class coupling and lines of code. There’s more than 80 code metrics out-of-the-box and if one is not applicable or you feel is inadequate for your particular application, you can easily customize the report by amending existing code queries or creating new ones to suit your needs. Also Visual Studio is not as granular and does not let you drill down the dependencies.

Note that NDepend has some rules defined around naming conventions but I think StyleCop is probably better suited to enforce a specific coding style and ensure consistency. Nonetheless NDepend includes some useful additional constraints such as the ones setting limits on the length of method or field names. Moreover it is relatively easier to add your own custom naming conventions for your particular project with NDepend.

What initially sparked my interest in NDepend is that it really complements ReSharper as a refactoring tool. In particular there are a few key design concepts that ReSharper’s code analysis simply does not cover, yet can be evaluated using NDepend: cyclomatic complexity, number of method parameters, class cohesion, total coupling and inheritance depth to name just a few. But with both tools in my arsenal I feel better equipped to write cleaner and more SOLID code.

I probably sound like an NDepend fanboy but I am passionate about using the right tools for delivering quality software. Yet NDepend can still improve in some areas and I have put below a wish list of the things that IMO would help make the tool even better:

  • Better integration with Visual Studio as I don’t like to leave my IDE and flip between the two all the time.
  • Code duplication analysis to reduce code clutter and abide by the DRY principle. Note that some of my colleagues have used Simian in the past to do this but I would personally prefer to do this with a tool I’m already using and familiar with.
  • Full screen mode for graph and dependency matrix windows.
  • Easier navigation between views and better shortcut support. There’s no shortcut for example to close an active window or to cycle through open windows (similar to Ctrl + Tab in visual Studio).
  • Automatic filtering of test projects when adding assemblies from a Visual Studio solution.
  • Being able to delete NDepend projects from the start-up page as at the moment you have to mess around with xml files to do that instead.
  • Quick search textbox in the Class Browser window similar to the one found in Visual Studio so that I can quickly go to a known type rather than drill down the treeview.
  • Cheaper single user licenses as I think the current pricing model is a barrier to entry for most Developers.

Finally I’d love to see some sort of integration with ReSharper. It would be great to be able to define code queries using NDepend and have ReSharper flag them as solution errors if the constraints are not met. This is probably fiction at the moment but one can dream!

Overall NDepend is a terrific product to pick up. It should save time over the lifecycle of a project, facilitate communication and increase productivity by aiding refactoring and generally making maintenance tasks easier to perform. Did I mention that it is also a cool way of learning about code metrics and some fundamental OO design principles?

I haven’t fully grokked NDepend yet but practice makes perfect and I’m really looking forward to use it on my next project. With the upcoming release of Visual Studio 2010, StyleCop + FxCop + ReSharper + NDepend will be a killer combination for developing .NET apps.

Disclaimer: This evaluation of Visual NDepend is based on a copy of the Professional edition supplied by Patrick Smacchia.

Caring about quality is not just about producing great code but it is also about producing great software.

NDepend is a static code analysis tool that offers some really unique features to help you improve the quality of your .NET applications. It can be used for conducting code reviews, highlighting areas that should be refactored, finding out dependencies and visualizing a complex code base. Ultimately NDepend aims to assist Developers in making more manageable and maintainable software.

NDepend is one of these rare tools I wanted to use for a long time but always found the limitations of the trial version too frustrating to live with. Now that I have a working copy of the professional edition, courtesy of NDepend creator Patrick Smacchia, I have been spending some more time with it, learning how it can help me write clean code along the way.

You only have to google “ndepend” and follow some of the links to find out how well regarded NDepend is within the .NET community. So what surprises me is that its adoption does not seem as wide spread as something like ReSharper, a tool which also aims at increasing code quality and Developer productivity. So why is it that a product with so many rave reviews has not gained the same traction as that of other coding tools out there?

Probably part of the answer lies in the perceived complexity of NDepend. It is indeed an intimidating tool and as soon as you open the start-up screen you are left wondering what to do next. This is not a tool that can be tamed in 10 minutes. It does require a certain amount of time, effort and experimentation to start enjoying its benefits. So where should you start to make that learning curve a little bit more gentle?

The amount of information provided by NDepend can be quite overwhelming at first and therefore a good starting point is to simply generate a report for a small project you’ve been working on. Using a code base that is familiar and relatively simple to follow will help you get a rough idea of the kind of information NDepend can provide without getting too bogged down into all the details. You can follow the steps below to quickly generate a report (I’m using the BlogEngine.NET source code here):

1. First build the Visual Studio solution for the application you want to analyse in debug mode - NDepend uses both the dll and pdb files (for linking back to the source code) to carry out the code analysis.

2. Open NDepend and click on ‘Create Project’ on the Start Page.

NDepend Create Project

3. In the ‘New NDepend Project’ dialog, enter name and location, and OK:

NDepend New Project

Once the new NDepend project is created, the ‘Project Properties’ window will be displayed.

4. Select the Visual Studio solution you want to analyse:

NDepend Add Assemblies

5. The loaded assemblies should now be displayed:

NDepend Loaded Assemblies

6. Either press F5 or click on NDepend Run Button to run the analysis report.

After a few seconds, the report will automatically be displayed in your browser.

NDepend Report

Once you’ve ran the report, you can use the VisualNDepend UI to browse your code.

VisualNDependNow you can either spend some time in the UI trying to work out what it all means or, preferably, head straight to the NDepend Web site and watch the online demos. There’s loads of documentation on the site showing you how to navigate the UI and to help you understand the information NDepend generates. Unfortunately the screencasts are not available for off-line viewing but they are however all relatively short (the longest one lasting no more than 5 minutes). After that you will be ready to explore and make sense of your code base armed with your newly found knowledge of code metrics.

There’s a couple of things I’d like to point out at this stage. First the NDepend install does not setup an entry in your start menu or a shortcut on your desktop so you might want to either create a shortcut for it or add it to your app launcher - I’m using Launchy for quickly accessing all my favourite applications. Second, by default the results of the CQL (Code Query Language) queries are evaluated automatically. I personally found this confusing at the beginning and you might want to turn that off to start with. To do that go to Tools > Options and uncheck "Execute automatically the query edited as soon as it compiles" as shown below. Once you’ve gained more confidence with the UI and how CQL works you will probably want to switch that option back on.

NDepend CQL Option

Finally, don’t dismiss the Info window took quickly. I initially ignored it without realising how useful it can be. Not only does it display detailed information about assemblies, types and members but it also gives you the description of dependencies in plain English; very convenient when you’re not familiar with the Dependency Matrix.

NDepend Info 

I won’t go into the details of what NDepend can do as there’s a well documented list of features on the site and other people have already done it better than I could - read NDepend: code metrics at your service for example. For more in-depth coverage of NDepend you can also follow Patrick Smacchia on CodeBetter.

Creating Extension Methods only takes a few steps with ReSharper :

1. Declare your intent

First tell ReSharper what you want to do. Note that in the line below, I have specified a local variable and an input parameter for the method to create. This will allow ReSharper to infer both the return type and the method parameter type.

Declare your intent  

 
 
2. Create static class

With your cursor on “StringExtensions”, press ALT + Enter (if you are using the Visual Studio shortcut keyboard bindings). In the Context Actions dialog, choose “Create static class” and press enter.

Create static class 

 ReSharper will generate the new class for you.

New StringExtensions class

 

3. Create method

Move your cursor to the method for which you want to generate the Extension Method. Open again the Context Actions dialog, select the first option and press enter.

Create method 

The method is automatically added to the new class.

New method

 

4. Static to Extension Method

Finally we need to convert our new static method to an Extension method. Highlight or set the cursor on the static method to convert, then open the “Refactor This” menu (Ctrl + Shift + R). Choose the last item to complete the process.

Convert Static to Extension Method   

ReSharper will not only refactor the method’s signature to add the ‘this’ keyword but also replace the original line to use the new Extension Method.

result

All you have to do now is to focus on the new method’s implementation.

Now in action:R# in Action: Creating Extension Methods Note: The screencast is heavily edited as my Dev machine simply can’t cope with Visual Studio and Camtasia running at the same time.

“Progress is made by lazy men looking for easier ways to do things”
Robert A. HeinleinW (American science-fiction writer, 1907-1988)

Let ReSharper do the work!

For those of you who don't know, BlogEngine.NET is a great, free and open-source blogging platform for .NET developers and less-technical people alike.

Apart from the fact that BlogEngine.NET is highly customisable, extensible and has many other neat features such as syndication, what attracted me to it was that it uses ASP.NET and XML as the default data store. This last point is fairly important as most hosting companies will charge you extra for setting up databases even for small web sites. By using XML you can keep the overall cost of maintaining a personal web site to a minimum.

Now that I have completed the installation process, I thought I'll briefly outline the steps I took to be up and running with BlogEngine.NET. Note that it is relatively easy to setup but if you really don't want to get your hands 'dirty' go to WordPress or Posterous; you will be blogging for free literally within minutes. For others, follow on...

Step 0: Backup, Backup, Backup

Before you do anything with BlogEngine.NET, you should first ensure that you have a quick and easy way to backup your blog. As you build up your site and make significant infrastructure or cosmetic changes, chances are that at some point you will want to restore it to a previously known working state. So to be safe either put your files under source control - you can either use Git or Subversion for that - or simply use a batch file like the one shown below. Just replace "<BLOG_ENIGNE_FOLDER>" and "<BACKUP_FOLDER>" in the script and it will copy your BlogEngine folder into a backup folder appended with the current date and time.

echo on  
for /f "tokens=1" %%u in ('echo %time%') do set t=%%u  
if "%t:~1,1%"==":" set t=0%t%  
set now=%date:~-4,4%%date:~-7,2%%date:~0,2%T%t:~0,2%%t:~3,2%%t:~6,2%  
C:  
xcopy /e "<BLOG_ENGINE_FOLDER>\*.*" "<BACKUP_FOLDER>\%now%\" 
echo Done!  
pause

Step 1: Basic installation

To get an idea of what the installation process involves, I recommend you watch this screencast before you start. Assuming you already have chosen a hosting company and registered a domain name, the first obvious step is to download the latest version and follow the installation instructions. No need for me to rehash here what's already covered in the documentation as it is pretty comprehensive and easy to follow. If you went along with these instructions step-by-step, you should have effectively an up and running blog on your local machine.

Step 2: Check your Web.Config settings

In the root of your web application, you should have a file called Web.Config as shown below.

 

BlogEngine.NET files  

Unless you need to troubleshoot some issues with the site, you should not run in debug mode (Debug Mode in ASP.NET Applications) as this will affect performance. Instead set the the debug attribute to "false".

<system.web>
	<compilation debug="false">
	   ...
	</compilation>
	   ...
</system.web>

The other attribute you will need to check in the Web.Config file is the customErrors element and its mode attribute which should be set to RemoteOnly. This ensures that your visitors get the BlogEngine.NET user-friendly custom error message if there is a problem with your site and also prevents potentially sensitive information from being displayed. For more on this refer to the MSDN documentation on "customErrors Element".

<system.web>
      ...
	<customErrors mode="RemoteOnly" defaultRedirect="~/error404.aspx">
		<error statusCode="404" redirect="~/error404.aspx"/>
	</customErrors>
	  ...
</system.web>

Although these attributes are set as above by default on version 1.5 of BlogEngine.NET, it is worth checking that this is the case before you release your blog.

Step 3: Choose a data storage type

BlogEngine.NET stores data as XML by default but you are not restricted to XML. You can switch to other blog providers such as Microsoft SQL Server, MySql, SQLite or VistaDB. As I wanted to be able to save all my data (posts, settings, etc.) into a single file that I could copy back and forth between multiple machines and my FTP site, and I did not want to pay extra for using either SQL Server or MySql, I decided to try out SQLite. SQLite is a free and popular self-contained database engine. Setting it up for BlogEngine.NET only requires two files. Instructions can be found in the "BlogEngine.Web\setup\SQLite" folder. As soon as I deployed my site, which was running fine with SQLite on my local machine, I was baffled to see that it did not work in my shared hosting environment. I kept on getting security exceptions. As it happens most shared hosting plans (including mine) will only let you run your application with medium trust level. However because SQLite calls native code (P/Invoke), your ASP.NET application needs to run in a full trust environment if you want to use it. At the end I had to turn to VistaDB instead. Like SQLite, VistaDB is a file based embedded database engine but the main difference is that it is fully managed. You can therefore run your site with partial trust, which seems to work for my hosting environment. To avoid a lot of frustration either stick with XML or make sure you have considered the other data storage options carefully.

Step 4: Theme and customize your site

OK. If you’ve gone this far in the installation process, the fun starts here. This is where you can make your site your own. Once you’re logged in, head straight to the admin control panel and review the options. There you can modify settings such as your blog title, your contact information, enable comments, manage users, etc. Among other things you will be able to change the theme, that is the look and feel, of your blog. BlogEngine.NET comes with a few pre-loaded themes but you are not limited to them. Check out the other themes available or if you'd like to showcase your Designer skills, you can create your own.

Step 5: Install Extensions and Widgets

You can easily add functionality to your site by installing extensions. In most cases this simply consists of dropping a few files in the "\App_Code\Extensions" folder and configuring the newly installed extension using the BlogEngine admin control panel. I suggest you add Justin Etheredge's anti-spam extension first. As soon as I published my first post, I started receiving quite a few spam in the comments and this extension prevents this from happening. It certainly seems to work for me so far.

For a good example of how widgets work in BlogEngine.NET, have a look at the TwitterFeed-Widget on CodePlex.

Step 6: Uploading your site

You can now upload your site to your hosting environment. The easiest way to do this is to use an FTP client. I find FileZilla very handy and reliable to transfer my blog and manage all the BlogEngine.NET files remotely. Did I mentioned that it is also free?

FileZilla FTP Client  

Step 7: Setup Google Analytics (optional)

Once your blog is out there, you might want to monitor your web site traffic. That's where Google Analytics (GA) comes in. GA is a free service that generates detailed reports, graphs and loads of statistics about your visitors. To set this up all you need is a Google email account and register your site on GA. After you've logged in you will find the tracking code (how to find Google Analytics tracking code) which you can then paste in the BlogEngine.NET tracking script pane under the Settings tab in the admin control panel.

 Tracking script pane

Step 8: Download and install Live Writer

BlogEngine.NET includes an online text editor which is relatively useful for making small changes to your blog entries but is frankly not up to the task for writing full-blown blog posts. Instead use the brilliant Windows Live Writer. Not only has it got a lot of formatting options but more importantly it lets you edit your blog posts offline. Follow this short and excellent guide to install it and integrate it with BlogEngine.NET.

Step 9: Start blogging

That is it. But this was the easy part! What you have to do now is think of something to say...

Final Thoughts

Looking back at the above it does seem like there was quite a bit involved in setting up BlogEngine.NET. However this was a good learning experience and fortunately each step was well documented - I've tried to provide all the relevant links that helped me during the installation process. BlogEngine.NET (and the other free tools) make it affordable to create, manage and maintain a personal blog in relatively little time. But more than anything else what I really like about BlogEngine.NET is that it puts you in full control of your site content, look and feel. If you're a .NET Developer looking for a simple and extensible blogging platform, look no further!

Finally a big thanks to all the team at BlogEngine.NET for giving me the satisfaction of having my own site.

Happy Blogging!

Last week I was fortunate enough to attend the Nothin' but .NET Developer Boot Camp in London. The course lead by JP Boodhoo covers a lot of ground with topics ranging from core .NET concepts, applied design patterns, Behaviour Driven Development and testability, Domain Driven Design, top-down development, project setup and automation, programmer productivity. JP also packs in some motivational and self-improvement talks to round it all up.

Fourteen people attended the boot camp with varying levels of .NET expertise. Although anybody can take something away from this course (JP's passion for his work and life if nothing else), it is not really suitable for 'junior' programmers. This is an intense course and even the most experienced Developers in the class had difficulties keeping up with the pace. Saying that if you love coding then you will have a blast. One coding session and probably the best we had the whole week lasted till 3 o'clock in the morning.

My advice before anybody attends is to be prepared. Also make sure you tune up and get your laptop ready for this. Mine (which I have not used extensively for months) decided to have a fit from day one and simply could not cope throughout the week. This was tremendously frustrating and bordering on computer rage at times. I can no longer postpone the upgrade and I have started to save for a new high speced machine. I am fed up of trying to develop on sub-standard equipment!

Last week really highlighted a number of fundamental areas I still need to work on. In particular I realised how naïve my use of generics, lambdas, and expressions, is. JP demonstrated brilliantly throughout the week that smarter use of these basic .NET language constructs can help improve your code base significantly.

Aside from all the OO and DDD concepts covered that I still need to digest, the other big think for me was to get a bit of BDD love as thus far I have never managed to get into it. Although I am not yet fully converted to the BDD style of unit testing, I fully embrace it as an Agile Development practice which involves more than just Developers. I have definitely gained a much better understanding of BDD techniques and one of my next steps in this area will be to look at the MSpecs and RSpecs BDD frameworks.

Other things I took away from the course are:

  • Better understanding of some fundamental patterns - Command, Chain of Responsibility, Adapter, Event Aggregator, Strategy, Registry, Null Object, Chaining, Pipeline, Static Gateway, Visitor.
  • Project structure and organisation - one test project, avoid structuring physical assemblies along the lines of logical structure and namespaces.
  • Move over to Git - Subversion did not play too well in the class environment and as a result I'll be giving Git a try and see how it compares.
  • Top down development - I wish I'd done that on a few projects I worked on.
  • Learn functional programming techniques.
  • Start using Vim to improve my productivity at the keyboard.
  • Use Ruby Rake for build automation.

Not everything went smoothly though. Some of the group lab exercises lacked focus and direction or they were simply too broad in scope. Often people lost track of what they were supposed to do and quickly turned away from the exercise altogether. However the ping-pong coding sessions and small code katas JP gave us made up for it. This was really fun. Moreover seeing your code ripped apart and refactored by JP was, in a masochistic kind of way, brilliant. Observing how a top coder approaches problems was truly fascinating. Another thing that worked well was to get students to write tests BDD style based on some made-up user stories. These helped me a lot to get acquainted with BDD unit testing. From time to time, JP would also use well-meaning multimedia artefacts (music, clips and videos) as a light relief from the coding and white-boarding design sessions.

Finally JP introduced us to Typer Shark, a cool little game to improve your typing skills and speed. Love it!

Overall the experience has been very positive and I believe I came out of it a stronger Developer with lots of new ideas and new things to learn.

Develop With Passion

When I first started putting my blog together one of the first thing I wanted to do was to have a page where I could keep track of all the tools, utilities and frameworks I use or are simply installed on my Dev machine. It's nothing really original as there have been many such lists before with the best known being probably Scott Hanselman Ultimate Developer and Power Users Tool List for Windows. However this is one of these .NET sticky notes I wanted to put on the site.

With more than 150 items on the list, it's no wonder I hate rebuilding my Dev machine. It takes days if not weeks to tweak all of these applications back to the way I like it.

I have to confess I am completely reliant on all of those tools to do even simple tasks like cut and paste (I use CLCL for that). I am a compulsive R# user and I spend a rather unhealthy amount of time trying new applications, attempting to write scripts in AuthoHotkey or PowerShell, and pimping my IDE. My Visual Studio workspace is so heavily customized that I wake up in a cold sweat every time I need to reinstall it.

This heavy dependency is the most noticeable when pair programming, conducting code reviews or driving someone else's machine. I quickly lose track of what I am doing and feel totally paralysed. Fear takes over!

JP Boodhoo is right in saying that forcing Developers to work on standardized machine is counterproductive (The fallacy of the standardized developer machine). Unfortunately the reality is that if you work as a consultant moving from project to project, client to client, you might not necessarily have the choice. Many organisations have policies in place to lock down users' environment and that includes Software Developers. I even worked in some places where anything that you wanted installed on your computer had to be approved by a committee; the whole process could take months without guarantee of success! I also heard (rumours?) of Developers working in Delivery Centres who were prevented from accessing the Internet and therefore could not even do a quick Google lookup for some sample code or MSDN help. If it's true that would be plain cruel! Getting some employers to allow you to use a particular application or spend a few extra $$ on a tool (that could save loads of time and money in the long-run) is not always an easy task, yet they would paradoxically accept that Developers cannot write .NET applications in Notepad.

And this is the biggest downside of working with a mutant Dev machine. Going back to basics is almost impossible or fairly costly as you lose most of your productivity when working with an unfamiliar toolset or environment.

Yet I don't really want to go cold turkey and give up on all the goodies that help me deliver. So what is the solution for tools junkie like me? Share the knowledge of what is out there to make .NET Developers more productive in the hope that these applications will become de-facto standards in most organisations and demand that projects are given the tools that are essential to produce the quality of work that our customers and users deserve.

Until this happens, check out the Ultimate Tool ListThe Productive .NET Programmer list and some of the following sites:

Note: If you know of a good tool that could help improve a programmer's productivity and is missing from the list, let me know and feed a tools junkie's addiction.