TypeConverters and XAML

When we’re setting margins, backgrounds etc. in XAML we use string representations which get converted to the actual objects. For example

<Button Margin="0,3,0,3" />

in this example the string 0,3,0,3 is converted into a Margin object by the MarginConverter.

Strings are converted to types using TypeConverters. A simple example of one is listed below

public class AbbreviatedNumberConverter : TypeConverter
{
   public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
   {
      return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
   }

   public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
   {
      return destinationType == typeof(InstanceDescriptor) || 
                 base.CanConvertTo(context, destinationType);
   }

   public override object ConvertFrom(ITypeDescriptorContext context, 
                            CultureInfo culture, object value)
   {
      string text = value as string;
      if (text == null)
      {
         return base.ConvertFrom(context, culture, value);
      }

      if (String.IsNullOrWhiteSpace(text))
      {
         return 0.0;
      }

      if (culture == null)
      {
         culture = CultureInfo.CurrentCulture;
      }

      double number;
      if (AbbreviatedNumeric.ValidateDouble(text, out number, culture))
         return number;

      return 0.0;
   }

   public override object ConvertTo(ITypeDescriptorContext context, 
                     CultureInfo culture, object value, Type destinationType)
   {
      if (destinationType != null && value is Double)
      {
         if (destinationType == typeof(string))
         {
            return value.ToString();
 	 }
      }
      return base.ConvertTo(context, culture, value, destinationType);
   }
}

So the above demonstrated a very simple TypeConverter that converts strings like “134m” into 134000000 or the likes of “10k” to 10000. The actual code for the conversion occurs in the AbbreviatedNumeric.ValidateDouble method which I’ll list at the end of this post but will exclude the tests just to save space. This is not an all encompassing converter, it will only convert k for thousands, m for millions and b for billions and also doesn’t handle multiple languages, but it’s here as an example.

Now let’s assume we’ve created some edit control which has an Amount dependency property which we want to allow the user to enter abbreviated numeric strings into. So the dependency property might look like

public Double Amount
{
   get { return (Double)GetValue(AmountProperty); }
   set { SetValue(AmountProperty, value); }
}

public static readonly DependencyProperty AmountProperty =
                    DependencyProperty.Register("Amount", typeof(Double), 
                    typeof(OnlineStatusControl), new PropertyMetadata(0.0));

To apply our type converter we simple add the TypeConverterAttribute to the Amount property as below

[TypeConverter(typeof(AbbreviatedNumberConverter))]
public Double Amount
{
   get { return (Double)GetValue(AmountProperty); }
   set { SetValue(AmountProperty, value); }
}

and finally when using this new control we can do the following

<Controls:AbbreviatedNumericEditor Amount="123m" />

The type converter is called on this and 123m is converted to 123000000 which is now stored as a Double in the dependency property Amount.

For completeness, here’s the simple AbbreviatedNumeric class

public static class AbbreviatedNumeric
{
   public static bool ValidateDouble(string value, out double? numeric, 
              CultureInfo cultureInfo = null)
   {
      double result;
      if(ValidateDouble(value, out result, cultureInfo))
      {
         numeric = result;
         return true;
      }
      numeric = null;
      return false;
   }

   public static bool ValidateDouble(string value, out double numeric, 
              CultureInfo cultureInfo = null)
   {	
      if (String.IsNullOrEmpty(value))
      {
         numeric = 0;
         return false;
      }

      if (Double.TryParse(value, out numeric))
      {
         return true;
      }
      if (value.Length > 0)
      {
         if (cultureInfo == null)
         {
	    cultureInfo = CultureInfo.CurrentCulture;
	 }

	 NumberFormatInfo numberFormat = cultureInfo.NumberFormat;
 	 if (value.Substring(0, 1) == numberFormat.NumberDecimalSeparator)
	 {
	    value = "0" + value;
	 }
	 if (Double.TryParse(value.Substring(0, value.Length - 1), 
                     NumberStyles.AllowLeadingWhite | 
                     NumberStyles.AllowTrailingWhite |                      
                     NumberStyles.AllowLeadingSign |
 		     NumberStyles.AllowDecimalPoint | 
                     NumberStyles.AllowThousands | 
		     NumberStyles.AllowExponent, cultureInfo, out numeric))
	 {
	    switch (Char.ToUpper(value[value.Length - 1]))
	    {
	        case 'B':
		   numeric = numeric * 1000000000;
		   break;
		case 'M':
		   numeric = numeric * 1000000;
		   break;
		case 'K':
		   numeric = numeric * 1000;
		   break;
		default:
		   return false;
	    }
            return true;
	 }
      }
      return false;
   }
}

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>

What to do with NuGet packages and source control

I’ve been wondering about the best strategy with using NuGet packages and source control. For example, I don’t like to have to get the source for a project then spend ages installing all the different pre-requisites from NuGet if I can help it. Also checking in all the binaries from the packages seems a waste of space plus the problems if ever merge issues come up and the general nastiness of binaries in source control. So what to do…

Well VS2012 has a very neat feature, the Enable NuGet Package Restore option on the context menu of the solution (in solution explorer). If you select this option and you mark the NuGet packages folder as being ignored from your source control system. Then VS2012 will automatically grab the correct versions of the packages for you, but you’ll also need to go into Tools | Options | Package Manager and tick the All NuGet to download missing packages during build and then when you build the project the missing packages will be downloaded as part of the pre-build step (note: this step will not need to be repeated on a per solution basis, unlike the Enable NuGet Package Restore step).

See Using NuGet without committing Packages for a far better explanation.

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.

Self hosting SignalR

I’ve covered the steps needed to host SignalR within a web application, but we’ve also seen we can connect to SignalR through a .NET client (in my case a simple Console app.). So next we’ll cover self-hosting SignalR.

Requirements

At the time of writing you’ll need to install the following NuGet packages from Package Manager Console in Visual Studio

Install-Package Microsoft.AspNet.SignalR
Install-Package Microsoft.Owin.Hosting -Pre
Install-Package Microsoft.Owin.Host.HttpListener -Pre

You can delete the scripts folder added by SignalR, we’re really just after the assemblies

Microsoft.AspNet.SignalR.Core
Microsoft.AspNet.SignalR.Owin
Microsoft.Owin.Host.HttpListener
Microsoft.Owin.Hosting
Owin

So if you feel like only deploying the minimal assemblies you can remove anything else installed from those packages.

Edit: Since writing the above a couple of things seems to have changed on those packages, you’ll now need Microsoft.Owin assembly and WebApplication (in the below code) is now WebApp.

The Server

public class MyHub : Hub
{
   public void Send(string message)
   {
      Clients.All.sendMessage(message);
   }
}

internal class MyStartUp
{
   public void Configuration(IAppBuilder app)
   {
      // the line below works fine with the console client but not the browser client
      // app.MapHubs();
      // use the following to enable the browser client to work with the server
      HubConfiguration config = new HubConfiguration();
      config.EnableCrossDomain = true;
      config.EnableDetailedErrors = true;
      app.MapHubs(config);   
   }
}

class Program
{
   // just for demo purposes, will "beep" every 5 seconds
   private static Timer timer = new Timer(o =>
   {
      var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
      context.Clients.All.sendMessage(DateTime.Now.ToLongTimeString() + " beep");
   });

   static void Main(string[] args)
   {
      using (WebApplication.Start<MyStartUp>("http://localhost:9100"))
      {
         // just for this demo
         TimeSpan ts = TimeSpan.FromSeconds(5);
 	 timer.Change(ts, ts);

	 Console.WriteLine("Server is running, Press <Enter> to stop");
	 Console.ReadLine();
      }
   }
}

I’ve listed all the code above, it’s all pretty self-explanatory. The URL in the start method is the URL for the server and port etc. The timer is solely used to send out a message every 5 seconds for out client to see. I’ve listed the code for a simple client below (see my post on creating a .NET client for SignalR if you need more info. on this).

Client

A simple .NET Console client…

static void Main(string[] args)
{
   HubConnection connection = new HubConnection("http://localhost:9100");
   IHubProxy proxy = connection.CreateHubProxy("myHub");
   connection.Start().ContinueWith(task =>
   {
      proxy.Invoke("Send", ".NET Client Connected");

      proxy.On<string>("sendMessage", (message) =>
      {
         Console.WriteLine(message);
      });
   });
   Console.Read();
}

If, you wish to access the server hub via JavaScript then the following is a simple example of the required JavaScript, note we create the proxy to the hub in the same way to the way we do this in the console client.

<script>
   $(function () {
      var connection = $.hubConnection("http://localhost:9100");
      var proxy = connection.createHubProxy('myHub');

      proxy.on("sendMessage", function (message) {
         $('#discussion').append('<li><strong>' + message + '</strong></li>');
      });

      connection.start().done(function () {
         proxy.invoke("Send", "Webpage client");
      }).fail(function () {
         $('#discussion').append('<li><strong>Failed to start</strong></li>')
      });
   });
</script>

Note: The at least one proxy.on event handler must be set before the connection.start or you will be able to send messages but not receive them (see http://www.asp.net/signalr/overview/hubs-api/hubs-api-guide-javascript-client#establishconnection for more information).

SignalR Minimal Server

Here’s the minimal steps required to create a SignalR server.

  • Create a new ASP.NET Empty Web Applications
  • Use NuGet to add Microsoft ASP.NET SignalR to the project
  • Right mouse click on the project select Add | Global Application Class
  • Edit the Global.asax.cs file to look like the following
    public class Global : System.Web.HttpApplication
    {
       protected void Application_Start(object sender, EventArgs e)
       {
          RouteTable.Routes.MapHubs();
       }
    }
    
  • A a new class file named MyHub and edited it to look like this
    public class MyHub : Hub
    {
       public void Send(string message)
       {
          Clients.All.sendMessage(message);
       }
    }
    
  • Finally we need an index.html pages so right mouse click on the project and select Add | HTMLPage – name it index and press ok. Then edit the file as follows
    <!DOCTYPE html>
    <html>
    <head>
        <title>Minimal SignalR</title>
    
        <script src="../Scripts/jquery-1.6.4.js"></script>
        <script src="../Scripts/jquery.signalR-1.1.2.js"></script>
        <script src="../signalr/hubs"></script>
    
        <script>
            $(function () {
               var monitor = $.connection.myHub;
               monitor.client.sendMessage = function (message) {
                  $('#discussion').append('<li><strong>' + message + '</strong></li>');
              }
              $.connection.hub.start().done(function () {
                  monitor.server.send("Starting...");
              });
            });
        </script>
    </head>
    <body>
        <h2>Minimal SignalR</h2>
    
        <div class="container">
           <ul id="discussion"></ul>
       </div>
    </body>
    
    </html>
    

The above has all the parts required to create a SignalR capable server and script in the HTML file but it doesn’t do anything, that’s for the user to implement, but just as an example to give something to see, let’s edit Global.asax.cs again and change the code to the following

private Timer timer = new Timer(o =>
{
   var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();
   context.Clients.All.sendMessage(DateTime.Now.ToLongTimeString() + " beep");
});

protected void Application_Start(object sender, EventArgs e)
{
   RouteTable.Routes.MapHubs();

   TimeSpan ts = TimeSpan.FromSeconds(5);
   timer.Change(ts, ts);
}

The code above will simply send a message every 5 seconds to any listening clients.

Note: You’ll notice how the JavaScript has the MyHub methods etc. in camel case, the proxy automatically does this for us. Also notice the JavaScript call, monitor.server.send uses the Hub method to push a message out when the script starts whereas we subscribe our function to a “known” name, one used in the MyHub (Clients.All.sendMessage). As this is dynamic there’s no compile time check on this, so make sure you get the name and case correct.