Category Archives: C#

PowerArgs, command line parser

I cannot tell you how many times I forgot the name of this project when looking for a command line parser, so I thought the best way to remember it is by writing a blog post on the subject.

The github repository for PowerArgs has excellent documentation, so I will simply cover a few of the basics here, just to get things started.

PowerArgs is available via Nuget using Install-Package PowerArgs.

With PowerArgs we can define a class for our command line arguments and using PowerArgs attribute we define required arguments, optional arguments, argument descriptions and many other options. One very useful options is ArgExistingFile which tells PowerArgs the argument is a filename and it should exist.

Let’s look at some simple code. This class acts as my command line arguments for a simple Csv to Xml file application

public class Arguments
{
   [ArgRequired]
   [ArgExistingFile]
   [ArgDescription("The mapping file")]
   public string MappingFile { get; set; }

   [ArgRequired]
   [ArgExistingFile]
   [ArgDescription("The CSV file to convert")]
   public string CsvFile { get; set; }

   [ArgRequired]
   [ArgDescription("The output XML file")]
   public string XmlFile { get; set; }
}

In our Main method we’d then having something like this

try
{
   var arguments = Args.Parse<Arguments>(args);
   // use the arguments
}
catch (ArgException e)
{
   Console.WriteLine(ArgUsage.GenerateUsageFromTemplate<Arguments>());
}

In the above, we parse the args using the Parse method which will ensure the ArgRequired properties are supplied and the files exist via ArgExistingFile. If any required arguments are missing an ArgException occurs and we use ArgUsage.GenerateUsageFromTemplate to output a list of the command line arguments expect, as well as description of the arguments and we can also list examples.

Go look at the github repository PowerArgs for further documentation.

Creating awaitable types

If you’ve used async/await in your applications, you’ll generally await a Task, but you can actually make your own type awaitable. Let’s look at how we’d do this.

Why are Task’s awaitable?

A Task is awaitable, not because it’s a Task type, but its because it supports a specific method name which returns a TaskAwaiter or TaskAwaiter for the Task type. So let’s take a look at what this method looks like

public TaskAwaiter GetAwaiter()

So it’s really that simple, if we want to make our object awaitable we simply define the same method in our type.

What is a TaskAwaiter?

A TaskAwaiter is a struct which implements the ICriticalNotifyCompletion interface and the INotifyCompletion interface (the ICriticalNotifyCompletion derives from the INotifyCompletion). But this still wouldn’t make the TaskAwaiter awaitable it also needs the property IsCompleted and the method GetResult – more on this in “the rules for an “Awaiter” type” below.

It does seem strange that these methods weren’t all put into a single interface, but there you have it.

How do I create a bare minimum awaitable type?

Let’s first review the rules for making our type awaitable

  • Our type should have a method named GetAwaiter which takes no arguments and returns a suitable “Awaiter” type

and now the rules for an “Awaiter” type

  • The type should implement the INotifyCompletion interface or the ICriticalNotifyCompletion interface
  • It should have a IsCompleted property of type boolean
  • It should have a GetResult method which returns void or a result value
    • and now let’s put this together into a somewhat pointless type which demonstrates a bare minimum set of requirements to get this type to be awaitable

      public class MyObject
      {
         public MyAwaiter GetAwaiter()
         {
            return new MyAwaiter();
         }
      }
      
      public struct MyAwaiter
      {
         public void OnCompleted(Action continuation)
         {
            continuation();
         }
      
         public bool IsCompleted { get; private set; }
      
         public void GetResult()
         {			
         }
      }
      

      and now in use, we would have something like this

      var o = new MyObject();
      await o;
      

      Note: if you do not call the conitnuation() action in the OnCompleted method the code will block indefinitely.

      The flow of this code goes as follows…

      await o is called, this calls GetAwaiter on MyObject which returns a MyAwaiter. Next IsCompleted is checked, if the awaiter has already completed then control returns to the line after the await, if it’s false OnCompleted is called which basically blocks until the continuation is called, finally the GetResult method is called.

      Extension methods that are awaitable

      So we’ve discussed creating our own type, making it awaitable and even creating an awaiter type, but another approach which one might use is creating extension methods and instead of going to the hassle of creating an awaiter type, we’ll simply reuse the TaskCompletionSource type which can be used as a puppet task.

      Let’s go straight to some code which I’ve unashamedly lifted from Stephen Toub’s blog post await anything.

      public static TaskAwaiter<int> GetAwaiter(this Process process)
      {
         var tcs = new TaskCompletionSource<int>();
         process.EnableRaisingEvents = true;
         process.Exited += (s, e) => tcs.TrySetResult(process.ExitCode);
         if (process.HasExited)
         {
            tcs.TrySetResult(process.ExitCode);
         }
         return tcs.Task.GetAwaiter();
      }
      

      and we would use this as follows

      await Process.Start(“notepad.exe”)
      

      Looking at the extension method you can see we’re going to use the TaskCompletion classes GetAwaiter to return the awaiter type (in this case a TaskAwaiter) and we simply try to set the result on the TaskCompletionSource if, or when, the process exits.

      References

      await anything
      Design change: new “await” pattern for greater efficiency

Dynamically extending an object’s properties using TypeDescriptor

The title of this post is slightly misleading in that what I’m really aiming to do is to “appear” to dynamically add properties to an object at runtime, which can then be discover-able by calls to the TypeDescriptor GetProperties method.

What’s the use case ?

The most obvious use for this “technique” is in UI programming whereby you might have an object that either you want to extend to “appear” to have more properties than it really has, or a more likely scenario is where an object has an array of values which you want it to appear as if the items were properties on the object. For example

public class MyObject
{
   public string Name { get; set; }
   public int[] Values { get; set; }
}

We might want this appear as if the Values are actually properties, named P1 to Pn. The is particularly useful when data binding to a Grid control of some sort, so wanting to see the Name and Values as columns in the grid.

Let’s look at how we achieve this…

Eh ? Can I see some code ?

The above use case is an actual one we have on the project I’m working on, but let’s do something a lot simpler to demonstrate the concepts. Let’s instead create an object with three properties and simply dynamically add a fourth property, the class looks like this

public class ThreeColumns
{
   public string One { get; set; }
   public string Two { get; set; }
   public string Three { get; set; }
}

I’ll now demonstrate the code that (when implemented) we’ll use to create an add a fourth property before looking at the actual code that achieves this

// this line would tend to be a class instance variable to ensure the dynamic propetries
// are not GC'd unexpectedly
DynamicPropertyManager<ThreeColumns> propertyManager;

propertyManager = new DynamicPropertyManager<ThreeColumns>();
propertyManager.Properties.Add(
   DynamicPropertyManager<ThreeColumns>.CreateProperty<ThreeColumns, string>(
      "Four",
      t => GetTheValueForFourFromSomewhere(),
      null
));

So the idea is that we’ll aim to create a property manager class which then allows us to add properties to the type, ThreeColumns – but remember these added properties will only be visible by code using the TypeDescriptor to get the list of properties from the object.

If we now created a list of ThreeColumn objects and databind to the DataSource of a grid (such as the Infragistics UltraGrid or XamDataGrid) it would show the four columns for the three real properties and the dynamically created one.

Implementation

Alright we’ve seen the “end game”, let’s now look at how we’re going to create the property manager which will be used to maintain and give access to an implementation of a TypeDescriptionProvider. The property manager looks like this

public class DynamicPropertyManager<TTarget> : IDisposable
{
   private readonly DynamicTypeDescriptionProvider provider;
   private readonly TTarget target;

   public DynamicPropertyManager()
   {
      Type type = typeof (TTarget);

      provider = new DynamicTypeDescriptionProvider(type);
      TypeDescriptor.AddProvider(provider, type);
   }

   public DynamicPropertyManager(TTarget target)
   {
      this.target = target;

      provider = new DynamicTypeDescriptionProvider(typeof(TTarget));
      TypeDescriptor.AddProvider(provider, target);
   }

   public IList<PropertyDescriptor> Properties
   {
      get { return provider.Properties; }
   }

   public void Dispose()
   {
      if (ReferenceEquals(target, null))
      {
         TypeDescriptor.RemoveProvider(provider, typeof(TTarget));
      }
      else
      {
         TypeDescriptor.RemoveProvider(provider, target);
      }
   }

   public static DynamicPropertyDescriptor<TTargetType, TPropertyType> 
      CreateProperty<TTargetType, TPropertyType>(
          string displayName, 
          Func<TTargetType, TPropertyType> getter, 
          Action<TTargetType, TPropertyType> setter, 
          Attribute[] attributes)
   {
      return new DynamicPropertyDescriptor<TTargetType, TPropertyType>(
         displayName, getter, setter, attributes);
   }

   public static DynamicPropertyDescriptor<TTargetType, TPropertyType> 
      CreateProperty<TTargetType, TPropertyType>(
         string displayName, 
         Func<TTargetType, TPropertyType> getHandler, 
         Attribute[] attributes)
   {
      return new DynamicPropertyDescriptor<TTargetType, TPropertyType>(
         displayName, getHandler, (t, p) => { }, attributes);
   }
}

In the above code you’ll notice we can create our dynamic properties on both a type and an instance of a type. Beware, not all UI controls will query for the properties on an instance, but instead will just get those on the type.

So as mentioned the property manager basically manages the lifetime of our TypeDescriptionProvider implementation. So let’s take a look at that code now

public class DynamicTypeDescriptionProvider : TypeDescriptionProvider
{
   private readonly TypeDescriptionProvider provider;
   private readonly List<PropertyDescriptor> properties = new List<PropertyDescriptor>();

   public DynamicTypeDescriptionProvider(Type type)
   {
      provider = TypeDescriptor.GetProvider(type);
   }

   public IList<PropertyDescriptor> Properties
   {
      get { return properties; }
   }

   public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)
   {
      return new DynamicCustomTypeDescriptor(
         this, provider.GetTypeDescriptor(objectType, instance));
   }

   private class DynamicCustomTypeDescriptor : CustomTypeDescriptor
   {
      private readonly DynamicTypeDescriptionProvider provider;

      public DynamicCustomTypeDescriptor(DynamicTypeDescriptionProvider provider, 
         ICustomTypeDescriptor descriptor)
            : base(descriptor)
      {
         this.provider = provider;
      }

      public override PropertyDescriptorCollection GetProperties()
      {
         return GetProperties(null);
      }

      public override PropertyDescriptorCollection GetProperties(Attribute[] attributes)
      {
         var properties = new PropertyDescriptorCollection(null);

         foreach (PropertyDescriptor property in base.GetProperties(attributes))
         {
            properties.Add(property);
         }

         foreach (PropertyDescriptor property in provider.Properties)
         {
            properties.Add(property);
         }
         return properties;
      }
   }
}

Note: In the inner class DynamicCustomTypeDescriptor we simply append our dynamic properties to the existing ones when creating the PropertyDescriptorCollection however we could replace/merge properties with the existing object’s. So for example replace/intercept an existing property. Also I’ve made the code as simple as possible, but it’s most likely you’d want to look to cache the properties when the PropertyDescriptorCollection is created to save having to get them every time.

So the purpose of the DynamicTypeDescriptionProvider is to basically build our property list and then intercept and handle calls to the GetProperties methods.

Finally, we want a way to create our new properties (via the CreateProperty methods on the DynamicPropertyManager, so now we need to implement our property descriptors

public class DynamicPropertyDescriptor<TTarget, TProperty> : PropertyDescriptor
{
   private readonly Func<TTarget, TProperty> getter;
   private readonly Action<TTarget, TProperty> setter;
   private readonly string propertyName;

   public DynamicPropertyDescriptor(
      string propertyName, 
      Func<TTarget, TProperty> getter, 
      Action<TTarget, TProperty> setter, 
      Attribute[] attributes) 
         : base(propertyName, attributes ?? new Attribute[] { })
   {
      this.setter = setter;
      this.getter = getter;
      this.propertyName = propertyName;
   }

   public override bool Equals(object obj)
   {
      var o = obj as DynamicPropertyDescriptor<TTarget, TProperty>;
      return o != null && o.propertyName.Equals(propertyName);
   }

   public override int GetHashCode()
   {
      return propertyName.GetHashCode();
   }

   public override bool CanResetValue(object component)
   {
      return true;
   }

   public override Type ComponentType
   {
      get { return typeof (TTarget); }
   }

   public override object GetValue(object component)
   {
      return getter((TTarget)component);
   }

   public override bool IsReadOnly
   {
      get { return setter == null; }
   }

   public override Type PropertyType
   {
      get { return typeof(TProperty); }
   }

   public override void ResetValue(object component)
   {
   }

   public override void SetValue(object component, object value)
   {
      setter((TTarget) component, (TProperty) value);
   }

   public override bool ShouldSerializeValue(object component)
   {
      return true;
   }
}

Much of this code is just creates default methods for the abstract class PropertyDescriptor, but as you can see the GetValue and SetValue call our interceptors which we registered with the property manager.

That’s basically that. So now anything calling TypeDescriptor.GetProperties will see our new properties (and their attributes) and interact with those properties through our inteceptor methods.

If you recall the code for creating the property manager we can use the following to confirm that, indeed TypeDescriptor.GetProperties see’s our ThreeColumns object as having four properties

static void Main(string[] args)
{
   DynamicPropertyManager<ThreeColumns> propertyManager;

   propertyManager = new DynamicPropertyManager<ThreeColumns>();
   propertyManager.Properties.Add(
      DynamicPropertyManager<ThreeColumns>.CreateProperty<ThreeColumns, string>(
         "Four",
         t => "Four",
         null
      ));

   var p = TypeDescriptor.GetProperties(typeof (ThreeColumns));
   Console.WriteLine(p.Count); // outputs 4 instead of the 3 real properties
}

Thread.CurrentPrincipal keeps getting reset in WPF

I’m porting an app. to WPF from Windows Forms. In the Windows Forms application we used to store our own IPrincipal implementation object which stored info. about the user and a security token.

For example

Thread.CurrentPrincipal = 
    new UserPrincipal("username", token);

Whilst porting the code I noticed that the CurrentPrincipal kept getting reset to a GenericPrincipal object.

Long story short, in WPF we need to call the SetThreadPrincipal on the current app domain to set the principal instead of via the CurrentPrincipal property, for example

AppDomain.CurrentDomain.SetThreadPrincipal(
    new UserPrincipal("username", token));

WPF behaviors

Behaviors came into WPF via Expression Blend. They’re basically a standardized way of adding extra functionality to WPF classes using XAML. So why not use attached properties you might ask. I’ll discuss the differences as we go.

Let’s look at a real world example…

I’m using Infragistics XamDataGrid to display rows of data, but I would like a simple filtering mechanism so that when the user enters text into a text box, all columns are filtered to show data with the filter text in it. I also want it so that when the text box is cleared the filters are cleared. Then I want a Button to enable me to clear the filter text for me with the click of the button.

How might we implement this ? Well the title of the post is a giveaway, but let’s look at some other possibilities first

  • We could write this in the code-behind but generally we try to stay clear of writing such code and instead would generally prefer use XAML to help make our code reusable across projects
  • We could derive a new class from the XamDataGrid and add dependency properties, but this means the code will only be usable via our new type, so it’s not as useful across other projects as it requires anyone wanting to use a XamDataGrid to use our version
  • We could use attached properties, which allow us to create “external” code, i.e. code not in code behind or in a derived class, which can work in conjunction with a XamDataGrid, but the problem here is that attached properties are written in static classes and we will want to store instance variables with the data (see my reasons for this requirement below). With a static class implementation we would have to handle the management of such data ourselves, not difficult, but not ideal.

The attached properties route looked promising – I’m going to need a property for the associated TextBox (acting as our filter text) and the Button (used to clear the filter) and ofcourse these may be different per instance of a XamDataGrid – I also need to handle the attachment and detachment of event handlers and any other possible state. As mentioned, we could implement such state management ourselves, but behaviors already give us this capability out of the box as they are created on a per instance basis.

So the best way for to think of a behavior is that it’s like attached properties but allows us to create multiple instances of the code and thus saves us a lot of the headaches that might occur managing multiple instance data.

Note: The code I’m about to show/discuss includes Reactive Extension code. I will not go into any depth on what it does or how it works but the main use here is to handle attachment and detachment of events and also to allow throttling of the input, this means as the user types in the filter text box, we do not update the filter until the user stops typing for half a second. This ensures we’re not continually updating the filters on the XamDataGrid as the user types

Creating a behavior

To create a behavior we simply create a class and derive it from the Behavior class which is part of the System.Windows.Interactivity namespace. The Behavior takes a generic argument which defines the type it can be used on. So to start off our code would look like this

public class XamDataGridFilterBehavior : Behavior<XamDataGrid>
{
   protected override void OnAttached()
   {
      base.OnAttached();
   }

   protected override void OnDetaching()
   {
      base.OnDetaching();
   }
}

So the key parts here (apart from the base class which has already been mentioned) are the OnAttached and OnDetaching overrides. So here we can attach and detach from events on the associated class (i.e. the XamDataGrid) and/or handle initialization/disposal of data/objects as required.

Before we look at a possible implementation of these methods, I wrote a simple list of requirements at the top of this post. One was the requirement for a TextBox to be associated with the XamDataGrid to act as the filter text and the other a Button to be associated to clear the filter. So let’s add the dependency properties to our class to implement these requirements.

public static readonly DependencyProperty FilterTextBoxProperty =
   DependencyProperty.Register(
   "FilterTextBox",
   typeof(TextBox),
   typeof(XamDataGridFilterBehavior));

public TextBox FilterTextBox
{
   get { return (TextBox)GetValue(FilterTextBoxProperty); }
   set { SetValue(FilterTextBoxProperty, value); }
}

public static readonly DependencyProperty ResetButtonProperty =
   DependencyProperty.Register(
   "ResetButton",
   typeof(Button),
   typeof(XamDataGridFilterBehavior));

public Button ResetButton
{
   get { return (Button)GetValue(ResetButtonProperty); }
   set { SetValue(ResetButtonProperty, value); }
}

So nothing exciting there, just standard stuff.

Now to the more interesting stuff, let’s implement the OnAttached and OnDetaching code. As I’m using Reactive Extensions we’ll need to have two instance variables, both of type IDisposable to allow us to clean up/detach any event handling. Let’s see all the code

private IDisposable disposableFilter;
private IDisposable disposableReset;

protected override void OnAttached()
{
   base.OnAttached();

   var filter = FilterTextBox;
   if (filter != null)
   {
      disposableFilter = Observable.FromEventPattern<TextChangedEventHandler, TextChangedEventArgs>(
         x => filter.TextChanged += x,
         x => filter.TextChanged -= x).
         Throttle(TimeSpan.FromMilliseconds(500)).
         ObserveOn(SynchronizationContext.Current).
         Subscribe(_ =>
         {
            var dp = AssociatedObject as DataPresenterBase;

            if (dp != null && dp.DefaultFieldLayout != null)
            {
               dp.DefaultFieldLayout.RecordFilters.Clear();
               dp.DefaultFieldLayout.Settings.RecordFiltersLogicalOperator = LogicalOperator.Or;

               foreach (var field in dp.DefaultFieldLayout.Fields)
               {
                  var recordFilter = new RecordFilter(field);
                  recordFilter.Conditions.Add(
                     new ComparisonCondition(ComparisonOperator.Contains, filter.Text));
								                  
                  dp.DefaultFieldLayout.RecordFilters.Add(recordFilter);
               }
           }
      });
   }

   var reset = ResetButton;
   if (reset != null)
   {
      disposableReset = Observable.FromEventPattern<RoutedEventHandler, RoutedEventArgs>(
         x => reset.Click += x,
         x => reset.Click -= x).
         ObserveOn(SynchronizationContext.Current).
         Subscribe(_ =>
         {
             FilterTextBox.Text = String.Empty;
             // whilst the above will clear the filter it's throttled so can
             // look delayed - better we clear the filter immediately
             var dp = AssociatedObject as DataPresenterBase;

             if (dp != null && dp.DefaultFieldLayout != null)
             {
                dp.DefaultFieldLayout.RecordFilters.Clear();
             }
        });
    }
}

protected override void OnDetaching()
{
   base.OnDetaching();

   if (disposableFilter != null)
   {
      disposableFilter.Dispose();
      disposableFilter = null;
   }
   if (disposableReset != null)
   {
      disposableReset.Dispose();
      disposableReset = null;
   }
}

This post isn’t mean’t to be about using the RX library or Infragistics, but the basics are that when OnAttached is called we use the RX FromEventPattern method to create our event handler attachment/detachment points. In the case of the TextBox we attach to the KeyDown event on the TextBox, we throttle the Observable for half a second so (as previously mentioned) we don’t update the filters on every change of the TextBox, we delay for half a second to allow the user to pause and then we filter. We also ensure the Subscribe code is run on the UI thread (well as the code that call OnAttached will be on the UI thread we’re simply observing on the current thread, which should be the UI thread). In the Subscribe method we get the AssociatedObject, this is where our Behavior generic argument comes in. The AssociatedObject is the object this behavior is applied to (we’ll see a sample of the XAML code next). Now we clear any current filters and create new ones based upon the supplied TextBox Text property. Finally we connect to the Click event on the supplied ResetButton. When the button is pressed we clear the FilterText and clear the filters.

In the code above I felt that the UX of a delay between clearing the FilterText and the filters clearing (the half a second delay) didn’t feel right when the user presses a button, so in this instance we also clear the filters immediately.

The OnDetaching allows us cleanup, so we dispose of our Observables and that will detach our event handlers and nicely clean up after usage.

How do we use this code in XAML

Finally, we need to see how we use this code in our XAML, so here it is

<TextBox x:Name="filter"/>
<Button Content="Reset" x:Name="reset" />

<XamDataGrid>
   <i:Interaction.Behaviors>
     <controls:XamDataGridFilterBehavior 
        FilterTextBox="{Binding ElementName=filter}" 
        ResetButton="{Binding ElementName=reset}" />
   </i:Interaction.Behaviors>
</XamDataGrid>

And that’s it, now we have a reusable class which a designer could use to add “behavior” to our XamDataGrid.

Comparing a generic to its default value

This is a very short post on something which, for some reason, I keep forgetting and having to find code I’ve written in the past to refresh my memory – so I thought I’d write a quick post to remind myself about this.

So you have a generic type T. Maybe it’s passed as an argument to a method and you want to check whether it’s set to its default value (in the case of classes this is equivalent to null).

To do this we use the following code (where o is the variable name of some generic type)

if(EqualityComparer<T>.Default.Equals(o, default(T))) 
{
   // do something
}

As previously stated – for class types, this is equivalent to null, for other types it depends upon their default value.

This code will handle structs and classes as well as Nullable types and also avoids boxing (see C# 5.0 in a Nutshell).

Using protobuf-net in C#

protobuf-net is a .NET library around the Google Protocol Buffers.

For information on the actual Google Protocol Buffers you can checkout the Google documentation.

To get the library via NuGet you can use Install-Package protobuf-net from the Package Manager Console or locate the same from the NuGet UI.

To quote Implementing Google Protocol Buffers using C#, “Protocol Buffers are not designed to handle large messages. If you are dealing in messages larger than a megabyte each, it may be time to consider an alternate strategy. Protocol Buffers are great for handling individual messages within a large data set. Usually, large data sets are really just a collection of small pieces, where each small piece may be a structured piece of data.”

So Protocol Buffers are best used on small sets of of data, but let’s start coding and see how to use Protocol Buffers using protobuf-net.

Time to code

There are a couple of ways of making your classes compliant with the protobuf-net library, the first is to use attributes and the second without attributes, instead setting up the meta data yourself.

Let’s look at an example from the protobuf-net website, a Person class which contains an Address class and other properties.

[ProtoContract]
public class Person 
{
   [ProtoMember(1)]
   public int Id { get; set; }
   [ProtoMember(2)]
   public string Name { get; set; }
   [ProtoMember(3)]
   public Address Address { get; set;}
}

[ProtoContract]
public class Address 
{
   [ProtoMember(1)]
   public string Line1 {get;set;}
   [ProtoMember(2)]
   public string Line2 {get;set;}
}

As can be seen the classes to be serialized are marked with the ProtoContractAttribute. By default protobuf-net expects you to mark your objects with attributes but as already mentioned, you can also use classes without the attributes as we’ll see soon.

The ProtoMemberAttribute marks each property to be serialized and should contain a unique, positive integer. These identifiers are serialized as opposed to the property name itself (for example) and thus you can change the property name but not the ProtoMemberAttribute number. Obviously, as this value is serialized the smaller the number the better, i.e. a large number will take up unnecessary space.

Serialize/Deserialize

Once we’ve defined the objects we want to serialize with information to tell the serializer the id’s and data then we can actually start serializing and deserializing some data. So here goes. Assuming that we’ve created a Person object and assigned it to the variable person then we can do the following to serialize this instance of the Person object

using (var fs = File.Create("test.bin"))
{
   Serializer.Serialize(fs, person);
}

and to deserialize we can do the following

Person serlizedPerson;
using (var fs = File.OpenRead("test.bin"))
{
   Person person = Serializer.Deserialize<Person>(fs);
   // do something with person
}

Note: Protocol Buffers is a binary serialization protocol

Now without attributes

As mentioned previously, we might not be able to alter the class definition or simply prefer to not use attributes, in which case we need to setup the meta data programmatically. So let’s redefine Person and Address just to be perfectly clear

public class Person 
{
   public int Id { get; set; }
   public string Name { get; set; }
   public Address Address { get; set;}
}
    
public class Address 
{
   public string Line1 {get;set;}
   public string Line2 {get;set;}
}

Prior to serialization/deserialization we would write something like

var personMetaType = RuntimeTypeModel.Default.Add(typeof (Person), false);
personMetaType.Add(1, "Id");
personMetaType.Add(2, "Name");
personMetaType.Add(3, "Address");

var addressMetaType = RuntimeTypeModel.Default.Add(typeof(Address), false);
addressMetaType.Add(1, "Line1");
addressMetaType.Add(2, "Line2");

as you can see we supply the identifier integer and then the property name.

RuntimeTypeModel.Default is used to setup the configuration details for our types and their properties.

Inheritance

Like the SOAP serialization and the likes, when we derive a new class from a type we need to mark the base type with an attribute telling the serializer what types it might expect. So for example if we added the following derived types

[ProtoContract]
public class Male : Person
{		
}

[ProtoContract]
public class Female : Person
{	
}	

we’d need to update our Person class to look something like

[ProtoContract]
[ProtoInclude(10, typeof(Male))]
[ProtoInclude(11, typeof(Female))]
public class Person 
{
   // properties
}

Note: the identifiers 10 and 11 are again unique positive integers but must be unique to the class, so for example no other ProtoIncludeAttribute or ProtoMemberAttribute within the class should have the same identifier.

Without attributes we simply AddSubType to the personMetaType defined previous, so for example we would add the following code to our previous example of setting up the metadata

// previous metadata configuration
personMetaType.AddSubType(10, typeof (Male));
personMetaType.AddSubType(11, typeof(Female));

// and now add the new types
RuntimeTypeModel.Default.Add(typeof(Male), false);
RuntimeTypeModel.Default.Add(typeof(Female), false);

Alternative Implementations of Protocol Buffers for .NET

protobuf-csharp-port is written by Jon Skeet and appears to be closer related to the Google code using .proto files to describe the messages.

Entity Framework & AutoMapper with navigational properties

I’ve got a webservice which uses EF to query SQL Server for data. The POCO’s for the three tables we’re interested in are listed below:

public class Plant
{
   public int Id { get; set; }

   public PlantType PlantType { get; set; }
   public LifeCycle LifeCycle { get; set; }

  // other properties
}

public class PlantType
{
   public int Id { get; set; }
   public string Name { get; set; }
}

public class LifeCycle
{
   public int Id { get; set; }
   public string Name { get; set; }
}

The issue is that when a new plant is added (or updated for that matter) using the AddPlant (or UpdatePlant) method we need to ensure EF references the LifeCycle and PlantType within its context. i.e. if we try to simply call something like

context.Plants.Add(newPlant);

then (and even though the LifeCycle and PlantType have an existing Id in the database) EF appears to create new PlantTypes and LifeCycles. Thus giving us multiple instances of the same LifeCycle or PlantType name. For the update method I’ve been using AutoMapper to map all the properties, which works well except for the navigational properties. The problem with EF occurs.

I tried several ways to solve this but kept hitting snags. For example we need to get the instance of the PlantType and LifeCycle from the EF context and assign these to the navigational properties to solve the issue of EF adding new PlantTypes etc. I wanted to achieve this in a nice way with AutoMapper. By default the way to create mappings in AutoMapper is with the static Mapper class which suggests the mappings should not change based upon the current data, so what we really need is to create mappings for a specific webservice method call.

To create an instance of the mapper and use it we can do the following (error checking etc. remove)

using (PlantsContext context = new PlantsContext())
{
   var configuration = new ConfigurationStore(
                     new TypeMapFactory(), MapperRegistry.AllMappers());
   var mapper = new MappingEngine(configuration);
   configuration.CreateMap<Plant, Plant>()
         .ForMember(p => p.Type, 
            c => c.MapFrom(pl => context.PlantTypes.FirstOrDefault(pt => pt.Id == pl.Type.Id)))
	 .ForMember(p => p.LifeCycle, 
            c => c.MapFrom(pl => context.LifeCycles.FirstOrDefault(lc => lc.Id == pl.LifeCycle.Id)));

   //... use the mapper.Map to map our data and then context.SaveChanges() 
}

So it can be seen that we can now interact with the instance of the context to find the PlantType and LifeCycle to map and we do not end up trying to create mappings on the static class.

The Vending Machine Change problem

I was reading about the “Vending Machine Change” problem the other day. This is a well known problem, which I’m afraid to admit I had never heard of, but I thought it was interesting enough to take a look at now.

Basically the problem that we’re trying to solve is – you need to write the software to calculate the minimum number of coins required to return an amount of change to the user. In other words if a vending machine had the coins 1, 2, 5 & 10, what is the minimum number of coins required to make up the change of 43 pence (or whatever units of currency you want to use).

The coin denominations should be supplied, so the algorithm is not specific to the UK or any other country and the amount in change should also be supplied to the algorithm.

First Look

This is a standard solution to the Vending Machine problem (please note: this code is all over the internet in various languages, I’ve just made a couple of unimpressive changes to it)

static int Calculate(int[] coins, int change)
{
   int[] counts = new int[change + 1];
   counts[0] = 0;

   for(int i = 1; i <= change; i++)
   {
      int count = int.MaxValue;
      foreach(int coin in coins)
      {
         int total = i - coin;
         if(total >= 0 && count > counts[total])
         {
            count = counts[total];
         }
      }
      counts[i] = (count < int.MaxValue) ? count + 1 : int.MaxValue;
   }
   return counts[change];
}

What happens in this code is that we create an array counts which will contains the minimum number of coins for each value between 1 and the amount of change required. We use the 0 index as a counter start value (hence we set counts[0] to 0).

Next we look through each possible change value calculating the number of coins required to make up each value, we use the int.MaxValue to indicate no coins could be found to match the amount of change.

This algorithm assumes an infinite number of coins of each denomination, but this is obviously an unrealistic scenario, so let’s have a look at my attempt to solve this problem for a finite number of each coin.

Let’s try to make things a little more complex

So, as mentioned above, I want to now try to calculate the minimum number of coins to produce the amount of change required, where the number of coins of each denomination is finite.

Let’s start by defining a Coin class

public class Coin
{
   public Coin(int denomition, int count)
   {
      Denomination = denomition;
      Count = count;
   }

   public int Denomination { get; set; }
   public int Count { get; set; }
}

Before I introduce my attempt at a solution, let’s write some tests, I’ve not got great names for many of the tests, they’re mainly for me to try different test scenarios out, but I’m sure you get the idea.

public class VendingMachineTests
{
   private bool Expects(IList<Coin> coins, int denomination, int count)
   {
      Coin c = coins.FirstOrDefault(x => x.Denomination == denomination);
      return c == null ? false : c.Count == count;
   }

   [Fact]
   public void Test1()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 100),
         new Coin(5, 100),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 15);
      Assert.Equal(2, results.Count);
      Assert.True(Expects(results, 10, 1));
      Assert.True(Expects(results, 5, 1));
   }

   [Fact]
   public void Test2()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 100),
         new Coin(5, 100),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 1);
      Assert.Equal(1, results.Count);
      Assert.True(Expects(results, 1, 1));
   }

   [Fact]
   public void Test3()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 1),
         new Coin(5, 1),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 20);
      Assert.Equal(4, results.Count);
      Assert.True(Expects(results, 10, 1));
      Assert.True(Expects(results, 5, 1));
      Assert.True(Expects(results, 2, 2));
      Assert.True(Expects(results, 1, 1));
   }

   [Fact]
   public void NoMatchDueToNoCoins()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 0),
         new Coin(5, 0),
         new Coin(2, 0),
         new Coin(1, 0),
      };

      Assert.Null(VendingMachine.Calculate(coins, 20));
   }

   [Fact]
   public void NoMatchDueToNotEnoughCoins()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 5),
         new Coin(5, 0),
         new Coin(2, 0),
         new Coin(1, 0),
      };

      Assert.Null(VendingMachine.Calculate(coins, 100));
   }

   [Fact]
   public void Test4()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 1),
         new Coin(5, 1),
         new Coin(2, 100),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 3);
      Assert.Equal(2, results.Count);
      Assert.True(Expects(results, 2, 1));
      Assert.True(Expects(results, 1, 1));
   }

   [Fact]
   public void Test5()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(10, 0),
         new Coin(5, 0),
         new Coin(2, 0),
         new Coin(1, 100),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 34);
      Assert.Equal(1, results.Count);
      Assert.True(Expects(results, 1, 34));
   }

   [Fact]
   public void Test6()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(50, 2),
         new Coin(20, 1),
         new Coin(10, 4),
         new Coin(1, int.MaxValue),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 98);
      Assert.Equal(4, results.Count);
      Assert.True(Expects(results, 50, 1));
      Assert.True(Expects(results, 20, 1));
      Assert.True(Expects(results, 10, 2));
      Assert.True(Expects(results, 1, 8));
   }

   [Fact]
   public void Test7()
   {
      List<Coin> coins = new List<Coin>
      {
         new Coin(50, 1),
         new Coin(20, 2),
         new Coin(15, 1),
         new Coin(10, 1),
         new Coin(1, 8),
      };

      IList<Coin> results = VendingMachine.Calculate(coins, 98);
      Assert.Equal(3, results.Count);
      Assert.True(Expects(results, 50, 1));
      Assert.True(Expects(results, 20, 2));
      Assert.True(Expects(results, 1, 8));
   }
}

Now, here’s the code for my attempt at solving this problem, it uses a “Greedy” algorithm, i.e. trying to find the largest coin(s) first. The code therefore requires that the coins are sorted largest to smallest, I have not put the sort within the Calculate method because it’s recursively called, so it’s down to the calling code to handle this.

There may well be a better way to implement this algorithm, obviously one might prefer to remove the recursion (I may revisit the code when I have time to implement that change).

public static class VendingMachine
{
   public static IList<Coin> Calculate(IList<Coin> coins, int change, int start = 0)
   {
      for (int i = start; i < coins.Count; i++)
      {
         Coin coin = coins[i];
         // no point calculating anything if no coins exist or the 
         // current denomination is too high
         if (coin.Count > 0 && coin.Denomination <= change)
         {
            int remainder = change % coin.Denomination;
            if (remainder < change)
            {
               int howMany = Math.Min(coin.Count, 
                   (change - remainder) / coin.Denomination);

               List<Coin> matches = new List<Coin>();
               matches.Add(new Coin(coin.Denomination, howMany));

               int amount = howMany * coin.Denomination;
               int changeLeft = change - amount;
               if (changeLeft == 0)
               {
                   return matches;
               }

               IList<Coin> subCalc = Calculate(coins, changeLeft, i + 1);
               if (subCalc != null)
               {
                  matches.AddRange(subCalc);
                  return matches;
               }
            }
         }
      }
      return null;
   }
}

Issues with this solution

Whilst this solution does the job pretty well, it’s not perfect. If we had the coins, 50, 20, 11, 10 and 1 the optimal minimum number of coins to find the change for 33 would be 3 * 11 coins. But in the algorithm listed above, the result would be 1 * 20, 1 * 11 and then 2 * 1 coins.

Ofcourse the above example assumed we have 3 of the 11 unit coins in the Vending machine

To solve this we could call the same algorithm but for each call we remove the largest coin type each time. Let’s look at this by first adding the unit test

[Fact]
public void Test8()
{
   List<Coin> coins = new List<Coin>
   {
      new Coin(50, 1),
      new Coin(20, 2),
      new Coin(11, 3),
      new Coin(10, 1),
      new Coin(1, 8),
   };

   IList<Coin> results = VendingMachine.CalculateMinimum(coins, 33);
   Assert.Equal(1, results.Count);
   Assert.True(Expects(results, 11, 3));
}

To just transition the previous solution to the new improved solution, we’ve simply added a new method named CalculateMinimum. The purpose of this method is to try and find the best solution by calculate with all coins, then we reduce the types of available coins by remove the largest coin, then find the best solution, then remove the next largest coin and so on. Here’s some code which might better demonstrate this

public static IList<Coin> CalculateMinimum(IList<Coin> coins, int change)
{
   // used to store the minimum matches
   IList<Coin> minimalMatch = null;
   int minimalCount = -1;

   IList<Coin> subset = coins;
   for (int i = 0; i < coins.Count; i++)
   {
      IList<Coin> matches = Calculate(subset, change);
      if (matches != null)
      {
         int matchCount = matches.Sum(c => c.Count);
         if (minimalMatch == null || matchCount < minimalCount)
         {
            minimalMatch = matches;
            minimalCount = matchCount;
         }
      }
      // reduce the list of possible coins
      subset = subset.Skip(1).ToList();
   }

   return minimalMatch;
}

Performance wise, this (in conjunction with the Calculate method) are sub-optimal if we needed to calculate such minimum numbers of coins many times in a short period of time. A lack of state means we may end up calculating the same change multiple times. Ofcourse we might save such previous calculations and first check whether the algorithm already has a valid solution each time we calculate change if performance was a concern and/or me might calculate a “standard” set of results at start up. For example if we’re selling can’s of drinks for 80 pence we could pre-calculate change based upon likely inputs to the vending machine, i.e. 90p, £1 or £2 coins.

On and we might prefer to remove to use of the Linq code such as Skip and ToList to better utilise memory etc.

References

http://onestopinterviewprep.blogspot.co.uk/2014/03/vending-machine-problem-dynamic.html
http://codercareer.blogspot.co.uk/2011/12/no-26-minimal-number-of-coins-for.html
http://techieme.in/techieme/minimum-number-of-coins/
http://www.careercup.com/question?id=15139685

Debugging a release build of a .NET application

What’s a Release Build compared to a Debug build

Release builds of a .NET application (by default) add optimizations, remove any debug code from the build, i.e. anything inside #if DEBUG is remove as well as Trace. and Debug. calls being removed. You also have reduced debug information. However you will still have .PDB files…

PDB files are generated by the compiler if a project’s properties allow for .PDB file to be generated. Simply check the project properties, select the Build tab and the Advanced… button. You’ll see Debug Info, which can be set to full, pdb-only or none. Obviously none will not produce any .PDB files.

At this point, I do not know the differences between pdb-only and full, if I find out I’ll amend this post, but out of the box, Release builds used pdb-only whilst Debug use full.

So what are .PDB files ?

Simply put – PDB files contain symbol information which allows us to map debug information to source files when we attach a debugger and step through the code.

Debugging a Release Build

It’s often the case that we’ll create a deployment of a Release build without the PDB files, this may be due to a desire to reduce the deployment foot print or some other reason. If you cannot or do not wish to deploy the PDB’s with an application then we should store them for a specific version of a release.

Before attaching our debugger (Visual Studio) we ned to add the PDB file locations to Visual Studio. So select the Debug menu, then Options and Settings. From here select Debugging | Symbols from the tree view on the left of the Options dialog. Click on the add folder button and type in (or paste) the folder name for the symbols for the specific Release build.

Now attach Visual Studio using Debug | Attach Process and the symbols will get loaded for the build and you can now step through the source code.

Let’s look at a real example

An application I work on deploys over the network and we do not include PDB files with it so we can reduce the size of the deployment. If we find a bug only repeatable “production” we cannot step through the source code related to the build without both a version of the code related to the release and without the PDB files for that release.

What we do is, when our continuous integration server runs, it builds a specific version of the application as a release build. We embed the source repository revision into the EXE version number. This allows us to easily check out the source related to that build if need be.

During the build process, we the copy the release build to a deployment folder, again using the source code revision in the folder name. We (as already mentioned) remove the PDB files (and Tests and other such files are also obviously removed). However we don’t just throw away the PDB’s, we instead copy them to a folder similarly named to the release build but with the name Symbols within the folder name (and ofcourse with the same version number). The PDB’s are all copied to this folder and now accessible if we need to debug a release build.

Now if the Release (or a production) build is executed and an error occurs or we just need to step through code for some other reason, we can get the specific source for the deployed version, direct Visual Studio to the PDB files for that build and now step through our code.

So don’t just delete your PDB’s store them in case you need to use them in the future.

Okay, how do we use the symbol/PDB files

So, in Visual Studio (if you’re using that to debug/step through your code). Obviously open your project with the correct source for your release build.

In the Tools | Options dialog, select the Debugging parent node in the dialog and then select Symbols or ofcourse just type Symbols into the search text box in Visual Studio 2013.

Now press the folder button and type in the location of your PDB files folder. Note that this option doesn’t have a folder browse option so you’ll need to type (or copy and paste) the folder name yourself.

Ensure the folder is checked so that Visual Studio will load the symbols.

Now attach the debugger to your release build and Visual Studio will (as mentioned) locate the correct symbols and attach them and then allow you to step through your source.

See Specify Symbol (.pdb) and Source Files in the Visual Studio Debugger for more information and some screen shots of the process just described.