Skip to content

2009

Code coverage with Visual Studio

Code coverage is used to determine how effectively your tests exercise the code in your application. This way you can identify sections of code that are covered, not covered or partially covered by your tests.

Visual Studio uses 2 different types of analysis, block-based statement coverage (C1 coverage) and line-based coverage.

  • Block-based statement coverage

    A block is defined as a sequence of instructions that have a single entry point and a single exit point. Exit points include branch instructions, a function call, a return instruction, or, for managed code, a throw instruction.

  • Line-based coverage

    For line-based coverage, the tools identify all of the blocks that make up a line and then use this information to determine the level of coverage for the line. If all of the blocks that make up the line are covered, then the tools report that the line is covered. If no blocks in the line are covered, then the tools report that the line is not covered. If some, but not all, of the blocks in the line are covered, then the tools report that the line is partially covered.

Take for example the following class that reside in MyProject.BusinessLogic assembly

public class Foo
{
   public int Calculate(int x, int y)
   {
      if (x > 0 && y < 0)
      {
         return -1;
      }
      else
      {
         return 1;
      }
   }
}

And a unit test that reside in MyProject.BusinessLogic.Test assembly

[TestClass]
public class FooTest
{
   [TestMethod]
   public void Calculate()
   {
      Foo foo = new Foo();
      Assert.AreEqual(1, foo.Calculate(3, 4));
   }
}

To enable code coverage you need to double-lick on the LocalTestRun.testrunconfig file that is located in the 'Solution Items' folder.

testrunconfig_2

Inside the 'Code Coverage' tab you select the assembly that you want to instrument. In this case we select MyProject.BusinessLogic.dll assembly.

codecoverage_1

Now you will need to run your unit tests again. Note that code coverage doesn't work when you debug your unit tests, so you will need to run your unit tests through the menu 'Test –> Run –> All Tests in Solution (CTRL+R, A)'. After that you can view a report about the code coverage results through the menu 'Test –> Windows –> Code Coverage Results'.

codecoverageresults_4

From the results we notice that we don't have 100% code coverage because our unit test only reached one part of the condition inside the Calculate method. If you open the Foo class and enable the code coloring you see the parts that are covered, not covered or partially covered.

CodeCoverageColoring_2

  • Light Blue: Indicates that the entire line of code was exercised in the test run.
  • Beige: Indicates that only a portion of the code blocks within the line of code were exercised in the test run.
  • Reddish Brown: Indicates that the line was not exercised in the test run.

Code coverage inside Visual Studio uses statement coverage and in this case the number of IL instructions reached is taken into account. If we add some statements in the Foo class and run again our code coverage we notice that the coverage has been raised form 71,43% to 92,59%. It's important to notice, that when you refactor your class it influences the code coverage even when the contract of the class is the same! This is very different from Branch coverage where each control structure is evaluated to true and false. In this case we would have 50% code coverage.

public class Foo
{
   public int Calculate(int x, int y)
   {
      if (x > 0 && y < 0)
      {
         return -1;
      }
      else
      {
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());
         Console.WriteLine(x.ToString());

         return 1;
      }
   }
}

Enumerating project items in a Visual Studio solution

Often you have the need to iterate through a collection and most of the time the iteration logic is weaved with the action that need to be done. This is because we are used to program in an imperative approach. In some scenarios it's better to use a functional approach and let other functions decide which action need to be applied. This way we can for example reuse our iteration logic.

Below is an iterator that starts from a solution or project and iterates through all project items inside the solution.

public class ProjectItemIterator : IEnumerable<EnvDTE.ProjectItem>
{
    IEnumerable<EnvDTE.Project> projects;

    public ProjectItemIterator(EnvDTE.Solution solution)
    {
        if (solution == null)
            throw new ArgumentNullException("solution");

        projects = solution.Projects.Cast<EnvDTE.Project>();
    }

    public ProjectItemIterator(IEnumerable<EnvDTE.Project> projects)
    {
        if (projects == null)
            throw new ArgumentNullException("projects");

        this.projects = projects;
    }

    public IEnumerator<EnvDTE.ProjectItem> GetEnumerator()
    {
        foreach (EnvDTE.Project currentProject in projects)
            foreach (var currentProjectItem in Enumerate(currentProject.ProjectItems))
                yield return currentProjectItem;
    }

    IEnumerable<EnvDTE.ProjectItem> Enumerate(EnvDTE.ProjectItems projectItems)
    {
        foreach (EnvDTE.ProjectItem item in projectItems)
        {
            yield return item;

            if (item.SubProject != null)
            {
                foreach (EnvDTE.ProjectItem childItem in Enumerate(item.SubProject.ProjectItems))
                    yield return childItem;
            }
            else
            {
                foreach (EnvDTE.ProjectItem childItem in Enumerate(item.ProjectItems))
                    yield return childItem;
            }
        }
    }

    System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
    {
        return GetEnumerator();
    }
}

Customize code generation in .NET RIA Services

Quote

Microsoft .NET RIA Services simplifies the traditional n-tier application pattern by bringing together the ASP.NET and Silverlight platforms. RIA Services provides a pattern to write application logic that runs on the mid-tier and controls access to data for queries, changes and custom operations. It also provides end-to-end support for common tasks such as data validation, authentication and roles by integrating with Silverlight components on the client and ASP.NET on the mid-tier.

To get started with .NET RIA Services you need Visual Studio 2008 SP1 and you need to install the following packages

  • Microsoft Silverlight 3 Tools Beta 1 for Visual Studio 2008 SP1
  • Microsoft .NET RIA Services March '09 Preview

On the download page of .NET RIA Services there is a great PDF document (riaservicesoverviewpreview.pdf) that gives you a step-by-step guide.

Every time you compile a solution with .NET RIA Services, an MSBuild task is executed that generates code in your Silverlight project from the domain services (DomainService class) that reside in your ASP.NET server. After some investigation through reflector, you can actually modify or extend the code generation using CodeDom! For this you need to add an attribute called DomainIdentifier where you specify a type that inherits from CodeProcessor. Both classes reside in the System.Web.Ria.Data namespace.

[EnableClientAccess()]
[DomainIdentifier("Comment", CodeProcessor = typeof(CommentCodeProcessor))]
public class CityService : DomainService
{
   //...
}

In this example, we simply add some documentation in the summary tag.

public class CommentCodeProcessor : CodeProcessor
{
    public CommentCodeProcessor(CodeDomProvider codeDomProvider)
        : base(codeDomProvider)
    {
    }

    public override void ProcessGeneratedCode(
        DomainServiceDescription domainServiceDescription,
        System.CodeDom.CodeCompileUnit codeCompileUnit,
        IDictionary<Type, System.CodeDom.CodeTypeDeclaration> typeMapping)
    {
        Type domainServiceType = domainServiceDescription.DomainServiceType;
        CodeTypeDeclaration declaration = typeMapping[domainServiceType];

        declaration.Comments.Add(new CodeCommentStatement("<summary>", true));

        foreach (var entityType in domainServiceDescription.EntityTypes)
        {
            declaration.Comments.Add(
                new CodeCommentStatement(
                    string.Format("Entity Type: {0}", entityType.FullName), true));
        }

        foreach (var operationEntry in domainServiceDescription.DomainOperationEntries)
        {
            declaration.Comments.Add(
                new CodeCommentStatement(
                    string.Format("Operation Entry: {0}", operationEntry.MethodInfo.Name), true));
        }

        declaration.Comments.Add(new CodeCommentStatement("</summary>", true));
    }
}

Below you find a sample of the generated file using the CommentCodeProcessor

/// <summary>
/// Entity Type: SilverlightApplication.Web.DataModels.City
/// Operation Entry: GetCities
/// Operation Entry: ReturnAllCities
/// </summary>
[DomainIdentifier("Comment")]
public sealed partial class CityContext : DomainContext
{
   //...
}

Intercepting your WCF messages in Silverlight 2.0

In many applications you want to intercept WCF messages for doing stuff like, logging, tracing, passing a user context, language identifier, etc. Typically this can be done through the IClientMessageInspector that resides in the System.ServiceModel.Dispatcher. Unfortunately this interface doesn’t exist in Silverlight 2.0.

Thankfully WCF is very extensible, and there is a sample Silverlight Web Services Samples on MSDN Code Gallery that shows how you can still use the IClientMessageInspector by implementing a custom binding. You simple use the BasicHttpMessageInspectorBinding that receives in the constructor an instance of type IClientMessageInspector. For example:

BasicHttpMessageInspectorBinding binding = new BasicHttpMessageInspectorBinding(new TraceInspector());

Note that the sample only allows you to pass one inspector, if you need to pass several inspectors you can use the decorator pattern to pass multiple.

public class ClientMessageInspectorDecorator : IClientMessageInspector
{
    IClientMessageInspector[] inspectors;

    public ClientMessageInspectorDecorator(params IClientMessageInspector[] inspectors)
    {
        this.inspectors = inspectors;
    }

    public object BeforeSendRequest(ref Message request, IClientChannel channel)
    {
        foreach (var item in inspectors)
        {
            item.BeforeSendRequest(ref request, channel);
        }

        return null;
    }

    public void AfterReceiveReply(ref Message reply, object correlationState)
    {
        foreach (var item in inspectors)
        {
            item.AfterReceiveReply(ref reply, correlationState);
        }
    }
}

AOP in Action - Dirty Tracking using Mixins with Castle’s DynamicProxy

In Part 1, we used the Unity block to intercept properties for dirty tracking. Our target class needed to implement the IDirty interface, and the setter properties (annotated with the Dirty attribute) assigned the Dirty flag (of IDirty) when the value has changed. Take for example the following classes:

[AttributeUsage(AttributeTargets.Method, AllowMultiple = false, Inherited = true)]
public class DirtyAttribute : System.Attribute
{
}

public interface IDirty
{
    bool IsDirty { get; set; }
}

public class Customer
{
    public virtual string FirstName { get; [Dirty] set; }
    public virtual string LastName { get; [Dirty] set; }
}

Note that in contrast to Part 1, the Customer object doesn’t implement the IDirty interface. In this example we are going to use a mixin for dirty tracking, a mixin is a class that provides a certain functionality to be inherited by a subclass, but is not meant to stand alone. That’s exactly what we want to achieve, that is to provide extra functionality, namely dirty tracking, to our Customer object.

We simply have to implement the IDirty interface once and for all and call it for example DirtyMixin.

[Serializable]
public class DirtyMixin : IDirty
{
   public bool IsDirty { get; set; }
}

As interception and mixin mechanism we use Castle’s DynamicProxy, the latest build can be found here. To intercept our (dirty) properties we need to implement an interface called IInterceptor. In the implementation we write the code that need to be executed (advice) at particular points (pointcut) in the program. Note that with Unity we have the notion of IMatchingRule for defining Pointcuts, whereas in DynamicProxy we have to do it manually.

public class DirtyInterceptor : Castle.Core.Interceptor.IInterceptor
{
    public void Intercept(Castle.Core.Interceptor.IInvocation invocation)
    {
        if (PointCut(invocation.Proxy, invocation.Method))
        {
            Advise(invocation.Proxy, invocation.Method, invocation.GetArgumentValue(0));
        }

        invocation.Proceed();
    }

    bool PointCut(object target, MethodInfo methodInfo)
    {
        if (IsSetter(methodInfo) && target is IDirty)
        {
            object[] dirtyAttributes = methodInfo.GetCustomAttributes(typeof(DirtyAttribute), true);
            return (dirtyAttributes != null && dirtyAttributes.Length > 0);
        }
        else
        {
            return false;
        }
    }

    void Advise(object target, MemberInfo methodInfo, object value)
    {
        string propertyName = methodInfo.Name.Substring("set_".Length);
        PropertyInfo info = target.GetType().GetProperty(propertyName);

        if (info != null)
        {
            object oldValue = info.GetValue(target, null);

            if (!IsEqual(value, oldValue))
                ((IDirty)target).IsDirty = true;
        }
    }

    bool IsSetter(MethodInfo methodInfo)
    {
        return (methodInfo.Name.StartsWith("set_")) && (methodInfo.GetParameters().Length == 1);
    }

    bool IsEqual(object valueX, object valueY)
    {
        if (valueX == null && valueY != null)
            return false;

        if (valueX != null && valueY == null)
            return false;

        if (valueX == null && valueY == null)
            return true;

        return valueX.Equals(valueY);
    }
}

To generate our proxy we use the ProxyGenerator class that reside in the Castle.DynamicProxy2 assembly. Adding a mixin is done through the ProxyGenerationOptions which is passed to the CreateClassProxy method.

var generator = new ProxyGenerator();

ProxyGenerationOptions options = new ProxyGenerationOptions();
options.AddMixinInstance(new DirtyMixin());

Customer customer = generator.CreateClassProxy(typeof(Customer), options, new DirtyInterceptor()) as Customer;

var firstname = customer.FirstName;
Debug.Assert(!((IDirty)customer).IsDirty);
customer.FirstName = "Piet";
Debug.Assert(((IDirty)customer).IsDirty);

The customer object that we receive from the generator is a proxy through subclassing and you will see that it now implements the IDirty interface.

MixinReflector_2

You can use the PersistentProxyBuilder to save the generated assembly. It renders an assembly called CastleDynProxy2.dll. Below you find an example how you can use PersistentProxyBuilder.

var generator = new ProxyGenerator(new PersistentProxyBuilder());

ProxyGenerationOptions options = new ProxyGenerationOptions();
options.AddMixinInstance(new DirtyMixin());

Customer customer = generator.CreateClassProxy(typeof(Customer), options, new DirtyInterceptor()) as Customer;

string proxyAssemblyPath = ((PersistentProxyBuilder)generator.ProxyBuilder).SaveAssembly();

var firstname = customer.FirstName;
Debug.Assert(!((IDirty)customer).IsDirty);
customer.FirstName = "Piet";
Debug.Assert(((IDirty)customer).IsDirty);

You can go a bit further and use an extension method that enables you to ask for a certain service. Internally it will simply try to cast to the given interface.

public static class ObjectExtensions
{
    public static T GetService<T>(this object instance) where T : class
    {
        return instance as T;
    }
}

Given the GetService extension method, we use our customer as follow

IDirty dirty = customer.GetService<IDirty>();
if (dirty != null)
{
    var firstname = customer.FirstName;
    Debug.Assert(!dirty.IsDirty);
    customer.FirstName = "Piet";
    Debug.Assert(dirty.IsDirty);
}

The source code of this article can be downloaded here

WPF for data-driven applications?

The last couple of days, I was converting my add-in visual studio called Component Dropper to WPF. One thing I noticed, is that the text in my WPF application was blurry, certainly when the font is small. It is harder to read and very unpleasant to work with.

After some research, it appears to be a known problem. Check out the following threads, How to turn off anti aliasing for small text? and Blurry text in WPF – current status? and a very good explanation about the problem.

It’s an issue that is already known for 2 years and there is still no solution for this particular problem. In my experience, enterprise applications are data-driven, which means there is a lot of text (= data) that need to be displayed typically in a grid (master-detail). WPF is really a great technology, but this is not a minor issue. I don’t think that your customers will be happy if they receive a new application that is hard to read.