Category Archives: Programming

How to exclude code from code coverage

In Visual Studio 2012 we can run code coverage analysis across our code (for example across our unit test suite). But we might not want to have all code analysed. For example I don’t really want to see the test classes as part of the analysis but do want to see the code under test.

So we can exclude code from the code coverage analysis using the ExcludeFromCodeCoverageAttribute. This can be applied to methods, properties, classes, structs etc.

An attempt was made to access a socket in a way forbidden by its access permissions

Was implementing a WCF service and found that I was getting the following error

A TCP error (10013: An attempt was made to access a socket in a way forbidden by its access permissions) occurred while listening on IP Endpoint=0.0.0.0:8733

In this case the problem was down to an existing service running on the port, use

netstat -a

to see if the port has already been taken

Mixed mode assemblies exception

Occasionally I get caught out by an assembly in .NET having been compiled in, say, .NET 2.0 and now wanting to use it in a newer version of .NET, for example .NET 4.0.

You’ll probably see an error like the following

System.IO.FileLoadException: Mixed mode assembly is built against version ‘v2.0.50727’ of the runtime and cannot be loaded in the 4.0

Obviously if I could recompile the offending 2.0 assembly I would, but this occasionally happens with libraries such as those imported into an application via NuGet and I really don’t need the headache of finding the original source and rebuilding.

So to fix this simple add the following to the App.Config in the configurations section

<startup useLegacyV2RuntimeActivationPolicy="true">
   <supportedRuntime version="v4.0"/>
</startup>

xUnit in Action

I’ve not really seen any major purpose to use anything other than NUnit for unit testing in .NET since I switched 100% to it from a combination of mbUnit and NUnit a fair few years back. But recently I’ve had that urge we developers get, to try something different. So here’s a very brief post on using xUnit.

First off, if you need a VS2012 test runner for xUnit check out http://visualstudiogallery.msdn.microsoft.com/463c5987-f82b-46c8-a97e-b1cde42b9099.

So with NUnit we marked are test classes with [TestFixture]. xUnit doesn’t use anything to mark the class itself as a test class, it solely relies on the use of attributes on the test methods themselves (see http://xunit.codeplex.com/wikipage?title=Comparisons for a comparison of all the features between NUnit and xUnit).

The SetUp and TearDown of NUnit have been replaced with the ctor and IDisposable.Dispose on a test class and the TestFixtureSetUp and TestFixtureTearDown require you to implement IUseFixture on your test class.

So a simple example of a test is

[Fact]
public void Clear_MultipleBits_ShouldClearAllBits()
{
   Binary b = new Binary(4);
   b.Set(2, 4);
   b.Clear(2, 4);
   Assert.Equal(0, b.ToNumber());
}

So we use the Fact attribute to declare a test and Assert to verify the test. The Fact attribute also allows us to assign a DisplayName, test Name, a way to ignore (in this case Skip) a test and assign a string to this to tell everyone why the test was skipped and a timeout. So a Fact is pretty comprehensive.

On top of Fact the xUnit extensions library (available through NuGet) also adds some useful additions such as the Theory attribute which allows us to supply data to the test, for example

[
Theory, 
InlineData("1", 1),
InlineData("10", 2),
InlineData("11", 3),
InlineData("100", 4),
]
public void ToNumeric_TestVariousNumbers_BinaryStringShouldMatchDecimalValue(string s, int value)
{
   Assert.Equal(value, Binary.Parse(s).ToNumber());
}

In the above case we’ve marked the test as a Theory (which is also a Fact, hence no need for the Fact attribute). The InlineData attribute allows us to specify the arguments that will be passed into our method as arguments. So obviously you need the same number of values in the InLineData attribute as you have arguments on the method.

The Trait attribute is useful for grouping our tests (particularly if you’re using the xUnit test runner). So for example

[Fact, Trait("Bug", "1234")]
public void SomeTest()
{
}

In the above we create a new trait named Bug. In xUnit’s test runner this will create a new group within the Traits: window named Bug and add the item 1234.

The xUnit extensions project add a whole load of more attributes for use with xUnit tests, including various methods for bringing data into the test from different sources, such as from a separate class, a property on the test class, OleDb data, Excel and more.

One of the key difference with writing tests in xUnit comes with the way it handles exceptions. In NUnit we use the ExpectedException attribute. In xUnit the Assert.Throws wraps a specific method expecting an exception. For example

[Fact]
public void Divide_ExpectDivideByZeroException()
{
   Calculator c = new Calculator();
   Assert.Throws<ArgumentException>(() => c.Divide(4, 0));
}

xUnit also supports testing of async await code in the following manner

[Fact]
public async Task SomeAsyncAwaitTest()
{
   MyObject o = new MyObject();
   await o.Run();   
   Assert.True(MyObject.Completed);
}

Operator Overloading in C#

I don’t use operator overloading as much in C# as I did in my C++ days. Part of this might simply be down to the types of application I write nowadays where using operating overloading is less useful. Anyway, every time I need to overload an operator I seem to have forgotten the format/syntax. So this post is my memory dump on this subject.

Not all operators can be overloaded. To save myself some typing, check this link for a full list of the operators and what may or may not be overloaded, http://msdn.microsoft.com/en-us/library/8edha89s(v=vs.80).aspx.

Unary Operators

Unary operators, such as +, -, !, ~, ++, –, true, false (yes even true and false) can be overloaded. The syntax is as follows:

public static ReturnType operator Operator(ContainingType)
{
}

For +, -, ++ and — The ReturnType might be the actual object that the code is associated with on another valid type which makes sense for the operation (for example an int).

For the !, ~, true, false the return type must be a boolean.

The Operator is obviously the operator +, -, !, ~, ++, –, true, false and finally the ContainingType must be, well the containing type. You must overload both true and false if you want to overload either of these.

Binary Operators

Binary operators, such as +, -, *, /, %, |, &, ^, << and >> can be overloaded. The syntax is as follows:

public static ReturnType operator Operator(ContainingType, Type)
{
}

The difference being that two arguments are supplied, the two arguments may both be the ContaingType or the second argument might be a different type, for example when using a + b, a might be a complex number and b an int. In the case of the << and >> bit shift operators the second argument must be an int.

Comparison Operators

Comparison operators, such as ==, != <, <=, >, >= can be overloaded. The syntax is as per the binary operator’s syntax. The == and != must both be implemented as pairs of operators as must the > and < operators and the >= and <= operators. Implicit and Explicit operators

If you want to implement cast operators, you can implement an implicit cast should be used if the operation is guaranteed to not lose information and explicit should be used for scenarios where a loss of information is possible and/or where you want to ensure the user is aware of the possible cast.

The syntax for both implicit and explicit cast is the same

public static CastOperator operator CastType(ContainingType)
{
}

The CastOperator is either implicit or explicit, the CastType is the returning type that you’re casting to and the ContainingType is the type that contains the overloaded operator.

For a full, if somewhat pointless example, here’s a Number class that wraps and int

public class Number
{
   private int number;

   public Number(int value)
   {
      number = value;
   }

   public int Value
   {
      get { return number; }
   }

   // format for implicit cast but disabled to ensure it doesn't 
   // affect other operators, i.e. casting to in int automatically.
   //public static implicit operator int(Number n)
   //{
   //	return n.number;
   //}

   public static explicit operator int(Number n)
   {
      return n.number;
   }

   // unary operators
   public static Number operator +(Number n)
   {
      n.number = +n.number;
      return n;
   }

   public static Number operator -(Number n)
   {
      n.number = -n.number;
      return n;
   }

   public static bool operator !(Number n)
   {
      return n.number == 0;
   }

   public static bool operator ~(Number n)
   {
      return !n;
   }

   public static Number operator ++(Number n)
   {
      n.number++;
      return n;
   }

   public static Number operator --(Number n)
   {
      n.number--;
      return n;
   }

   public static bool operator true(Number n)
   {
      return n.number != 0;
   }

   public static bool operator false(Number n)
   {
      return n.number != 0;
   }

   // binary operators
   public static Number operator +(Number a, Number b)
   {
      return new Number(a.number + b.number);
   }

   public static Number operator -(Number a, Number b)
   {
      return new Number(a.number - b.number);
   }

   public static Number operator *(Number a, Number b)
   {
      return new Number(a.number * b.number);
   }

   public static Number operator /(Number a, Number b)
   {
      return new Number(a.number / b.number);
   }

   public static Number operator %(Number a, Number b)
   {
      return new Number(a.number % b.number);
   }

   public static Number operator &(Number a, Number b)
   {
      return new Number(a.number & b.number);
   }

   public static Number operator |(Number a, Number b)
   {
      return new Number(a.number | b.number);
   }

   public static Number operator ^(Number a, int b)
   {
      return new Number(a.number ^ b);
   }

   public static Number operator <<(Number a, int shiftBy)
   {
      return new Number(a.number << shiftBy);
   }

   public static Number operator >>(Number a, int shiftBy)
   {
      return new Number(a.number >> shiftBy);
   }

   // comparison operators
   public static bool operator ==(Number a, Number b)
   {
      return a.Value == b.Value;
   }

   public static bool operator !=(Number a, Number b)
   {
      return a.Value != b.Value;
   }

   public static bool operator <(Number a, Number b)
   {
      return a.Value < b.Value;
   }

   public static bool operator <=(Number a, Number b)
   {
      return a.Value <= b.Value;
   }

   public static bool operator >(Number a, Number b)
   {
      return a.Value > b.Value;
   }

   public static bool operator >=(Number a, Number b)
   {
      return a.Value >= b.Value;
   }
}

Basics of async and await

In .NET 4.5 Microsoft added the async and await keywords.

Important: By prefixing a method with the async keyword we’re telling the .NET compiler that you want to use the await keyword. The async keyword does NOT mean your method is automatically asynchronous, i.e. the compiler will not automatically assign a thread to it or a task. It simple indicates that the compiler to compile the code so that it can be suspended and resumes at await points.

If you wrote a simple async method which carried out some long running calculation the method would still be synchronous. Even if we await the result (you can have a async method without an await but this is equivalent to any other type of synchronous method and will result in compiler warnings).

So what’s the point of async and await ?

We basically use async on a method to allow us to use await. If there’s no async then we cannot use await. So the await is really where the magic happens.

The await keyword can be thought of as a continuation on a Task. It allows us to break a method into parts where we can suspend and resume a method. Below is an example of a call to some LongRunningTask

// simulation of a method running on another thread
private Task LongRunningTask()
{
   return Task.Delay(10000);
}

private async void Button_Click(object sender, RoutedEventArgs e)
{
   textBox.Text = "";
   await LongRunningTask();
   textBox.Text = "Completed";
}

What happens with the above is that a button click event takes place and the textbox is set to an empty string, then a LongRunningTask occurs on a different task. The await keyword suspends operation of this method now until the LongRunningTask completes but the UI in this case remains responsive. When the LongRunningTask ends the text is set to “Completed”. As the button was called from the UI thread the code after the await line is run on the UI thread, i.e. the synchronization context for the code after the await line is the same as the synchronization context used before the await line.

An async method may have one of three types of return, a Task (non-generic) and Task<> (generic) and a void. The return should be either of the Task objects to allow for a calling method to await the method. Void should only be used for things like event handlers.

We can implement code similar to await using Task ContinueWith, but one neat feature of async/await is in WinForms/WPF The code after the await is executed on the same thread as the async method was called on. ContinueWith, by default, is executed on another thread. Obviously this feature of async/await is very useful with the likes of WinForms as a button click might await a webservice call or the likes, then return onto the GUI thread upon return.

Writing a Windows Service

Creating

The steps for creating a Windows Services are pretty simple.

Open Visual Studio and create a new Windows Service Project. This will create a Program.cs with the relevant code to instantiate the service and then run it. The defaults service files (Service1.cs) contains an object derived from the ServiceBase. Here we implement our code. So when the Service starts the Onstart method is called, here we run whatever code we require to run the service and the OnStop (as the name suggests) we stop the code. There’s also OnPause and OnContinue overrides if needed.

Next we need to create an installer to allow the service to be installed in the Services control app.

Open the Service1.cs (or whatever the service is now called) designer and right mouse click on the background. Select Add Installer. An installer has been added which has the service name of your service and is set-up by default to install on the user’s account and in Manual startup mode. Obviously changes these to suit, plus add a description of the service which will be displayed in the Service control app.

If, on the other hand, you don’t have a Service1 designer or you wish to add an installer by hand, simple create a new C# class and add the following (bare minimum) code

[RunInstaller(true)]
public partial class MyInstaller : Installer
{
   private ServiceProcessInstaller serviceProcessInstaller;
   private ServiceInstaller serviceInstaller;

   public MyInstaller()
   {
      serviceProcessInstaller = new ServiceProcessInstaller();
      serviceInstaller = new ServiceInstaller();

      serviceProcessInstaller.Password = null;
      serviceProcessInstaller.Username = null;
			
      serviceInstaller.ServiceName = "Orchestator.Service";

      Installers.AddRange(new Installer[] { serviceProcessInstaller, serviceInstaller });
   }
}

Note: The username and password are set to null, hence when you try to install this service it will ask you for the username and password to login with. Alternatively you can set the Account on the serviceInstaller to ServiceAccount.LocalService which will not require the username/password dialog to be displayed as per the following code

serviceProcessInstaller.Account = ServiceAccount.LocalService;

Installing

To install the service without creating a fully fledged setup application simply run

installutil.exe

and to uninstall

installutil.exe /u

If you have no supplied the username and password you’ll be prompted to supply it, you will need to supply the fully qualified username, including domain or for a local user account use .\username (where .\ indicates the local machine). .\ on it’s own can be used to indicate the local machine but in the Services applet it will display .\ as Log On As, whereas you might notice other local service logins show Local Service. We can easily alter out Installer class to allow for this as outlined previously.

Debugging

Due to the time limit for startup (30 seconds) it can be difficult to debug a service as it starts. The best solution to this is to create a console app which mimics the startup process. Once the service is running we can attach to it’s instance like any other app.

A using clause inside a namespace is different to a using clause outside a namespace

For some reason I always forget the difference between using a using clause inside a namespace as opposed to outside. Occasionally I come across other people’s code where they’ve obviously explicitly copied their using clauses inside their namespace, being that by default creating a new C# file will place the default using clauses at the top of the file (outside the namespace).

So what’s the difference ?

If we have a class sitting in a namespace such as MyNamespace.MyClasses (with using System; outside the namespace) such as

using System;

namespace MyNamespace.MyClasses
{
   class MyClass
   {
      void MyMethod()
      {
         String s = String.Empty;
         // do something
      }
   }
}

It’s happily using the System.String object, but then along comes a new developer on the project who creates a String class specific to the project.

So the new class is added to the MyNamespace namespace in the following way

namespace MyNamespace
{
   class String
   {
   }
}

At this point our previous code will fail with a ‘MyNamespace.String’ does not contain a definition for ‘Empty’. This is because when the compiler searches for the String class it starts in the MyNamespace.MyClasses namespace then the MyNamespace namespace and then finally the using clauses outside of the namespace. So in this instance it finds a matching String class in the namespace MyNamespace and unless the String is fully qualified (i.e. System.String s = System.String.Empty; will try to use this. Obviously this is the wrong String class.

If we move the using System; inside the namespace of MyClass, such as

namespace MyNamespace.MyClasses
{
   using System;
   
   class MyClass
   {
      void MyMethod()
      {
         String s = String.Empty;
      }
   }
}

In this instance the compiler searches the MyNamespace.MyClasses namespace and then the using clauses within that namespace and so can resolve the String.Empty const and the newly added String class can still be implemented without being mistakenly used.

Handling data in WCF headers (service-side)

So my previous post looked at adding data into the headers of the WCF service calls from the client-side perspective.

Ofcourse for this to be of any use we need the service to handle the extraction of this header data. So this post is mean’t to cover the basics of this. First we need to create the extension, so we inherit from BehaviorExtensionElement (just as we did on the client)

public class SecurityTokenEndpointBehaviourExtensionElement : BehaviorExtensionElement
{
   public override Type BehaviorType
   {
      get { return typeof(SecurityTokenServiceBehaviour); }
   }
   protected override object CreateBehavior()
   {
      return new SecurityTokenServiceBehaviour();
   }
}

Now we need to create an implementation of the IServiceBehavior (on the client this is the IEndpointBehavior)

public class SecurityTokenServiceBehaviour : IServiceBehavior
{
   public void Validate(ServiceDescription serviceDescription, 
                        ServiceHostBase serviceHostBase)
   {
   }

   public void AddBindingParameters(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase, 
                         Collection<ServiceEndpoint> endpoints, 
                         BindingParameterCollection bindingParameters)
   {
   }

   public void ApplyDispatchBehavior(ServiceDescription serviceDescription, 
                         ServiceHostBase serviceHostBase)
   {
      foreach(ChannelDispatcher cd in serviceHostBase.ChannelDispatchers)
      {
         foreach(EndpointDispatcher epd in cd.Endpoints)
         {
            epd.DispatchRuntime.MessageInspectors.Add(new SecurityTokenMessageInspector());
         }
      }
   }
}

and finally we implement an IDispatchMessageInspector (on the client this would be the IClientMessageInspector)

public class SecurityTokenMessageInspector : IDispatchMessageInspector
{
   public object AfterReceiveRequest(ref Message request, 
                     IClientChannel channel, 
                     InstanceContext instanceContext)
   {
      return null;
   }

   public void BeforeSendReply(ref Message reply, object correlationState)
   {
   }
}

Okay so we’ve got all the code in place but now we need to tie this into WCF using the configuration (ofcourse if you prefer you can do this in code).

Just as we need to do in the client, we need to register the extension in an extensions element and again as per the client we then need to link the behaviour to the extension, see the App.config for this service below

<system.serviceModel>
   <behaviors>
      <serviceBehaviors>
         <behavior name="MyBehavior">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="true" />
            <!--our extension -->
            <securityTokenExtension /> 
         </behavior>
      </serviceBehaviors>
   </behaviors>
   <services>
      <service behaviorConfiguration="MyBehavior" name="SimpleService.MyService">
        <endpoint address="MyService" binding="basicHttpBinding"
          bindingConfiguration="" contract="SimpleService.IMyService" />
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:9095/" />
          </baseAddresses>
        </host>
      </service>
   </services>
   <extensions>
      <behaviorExtensions>
        <add name="securityTokenExtension" 
           type="SimpleService.SecurityTokenEndpointBehaviourExtensionElement, SimpleService" />
      </behaviorExtensions>
   </extensions>
</system.serviceModel>

Finally, how do we get the value stored in the header on the service ?

The following code shows how we extract the value from the header named “myToken”, the generic argument shown in the method call GetHeader represents the type we expect the data to be.

public object AfterReceiveRequest(ref Message request, 
                  IClientChannel channel, 
                  InstanceContext instanceContext)
{
   int idx = request.Headers.FindHeader("myToken", String.Empty);
   if(idx >= 0)
   {
      Console.WriteLine(String.Format("Header value: {0}", 
                       request.Headers.GetHeader<string>(idx));
   }
   return null;
}

Adding data to WCF message headers (client-side)

When working with WCF you may find a need to add data to the message headers, for example maybe you wish to add some form of authentication token or the likes.

The first thing we need to do is create a BehaviorExtensionElement and add the relevant configuration to the App.Config.

public class SecurityTokenEndpointBehaviourExtensionElement : BehaviorExtensionElement
{
   public override Type BehaviorType
   {
      get { return typeof(SecurityTokenEndpointBehaviour); }
   }
   protected override object CreateBehavior()
   {
      return new SecurityTokenEndpointBehaviour();
   }
}

Now we need the corresponding entry in the config file for the extension and also the behaviour that our endpoint will map to

<behaviors>
   <endpointBehaviors>
      <behavior name="serviceEndpointBehaviour">
         <securityTokenExtension />
      </behavior>
   </endpointBehaviors>
</behaviors>
<extensions>
   <behaviorExtensions>
      <add name="securityTokenExtension"
	type="PutridParrot.SecurityTokenEndpointBehaviourExtensionElement, PutridParrot" />
   </behaviorExtensions>
</extensions>

As you can see the configuration basically tells WCF to use our BehaviorExtensionElement which then creates the behaviour. This behaviour then adds inspectors to the client as in the sample below

public class SecurityTokenEndpointBehaviour : IEndpointBehavior
{
   public void AddBindingParameters(ServiceEndpoint endpoint, 
                   BindingParameterCollection bindingParameters)
   {
   }

   public void ApplyClientBehavior(ServiceEndpoint endpoint, 
                   ClientRuntime clientRuntime)
   {
      clientRuntime.MessageInspectors.Add(new SecurityTokenMessageInspector());
   }

   public void ApplyDispatchBehavior(ServiceEndpoint endpoint, 
                    EndpointDispatcher endpointDispatcher)
   {
   }

   public void Validate(ServiceEndpoint endpoint)
   {
   }
}

So this code is very simple. In this case we’re simply adding a new message inspector and it’s this IClientMessageInspector implementation that adds the token to the WCF headers. As shown below

public class SecurityTokenMessageInspector : IClientMessageInspector
{
   public object BeforeSendRequest(ref Message request, IClientChannel channel)
   {
      request.Headers.Add(MessageHeader.CreateHeader("myToken", 
                          String.Empty, SecurityToken.Token));
      return null;
   }

   public void AfterReceiveReply(ref Message reply, object correlationState)
   {
   }
}

The code above adds a new message header with the name “myToken” and a value of SecurityToken.Token (just assume this is a singleton which creates and stores a security token).

Before this will work on the client we need to configure the end point to use the behaviorConfiguration defined previously, so now in the endpoint add

behaviorConfiguration="serviceEndpointBehaviour"

So the client configuration will look something like

<client>
   <endpoint address="http://localhost:9095/MyService" 
            binding="basicHttpBinding" contract="MyService.IMyService"                    
            behaviorConfiguration="serviceEndpointBehaviour"/>
</client>