Category Archives: C#

Populating random data

I was working on a small utility which generates XML based upon a given class (which is already XML serializable). I wanted to generate random data just so I could see how the end XML looked in case I needed to tweak the XSD.

Source for the utility is available on AutoGenXml.

I figured somebody must have already approached such a problem, and thankfully I was right. There are a few solutions for populating object data. I ended up trying out two different libraries, AutoFixture and NBuilder.

Disclaimer: I have literally only just started using these libraries, so I’ve yet to find all the good and/or bad points of each library.

Let’s take a real quick look at what these libraries can do.

Test object

Let’s start out by defining an object hierarchy to test this two libraries out on. Mine looks like this

public class Album
{
   public string Title { get; set; }
   public string RecordLabel { get; set; }
   public Artist Artist { get; set; }
   public string Genre { get; set; }
}

public class Artist
{
   public string Name { get; set; }
   public BandMember[] Band { get; set; }
}

public class BandMember
{
   public string FirstName { get; set; }
   public string LastName { get; set; }
   public string Talent { get; set; }
}

AutoFixture

AutoFixture source can be found on AutoFixture.

We can create objects with AutoFixture (hence using it as the factory for our objects) and it returns a populated object hierarchy.

Let’s look at the code (it’s pretty simple)

var fixture = new Fixture();
var album = fixture.Create<Album>();

The album will now have data in all fields and the Artist and BandMember properties are also created and data supplied.

Whilst it’d obviously be easy enough for us to create an object multiple times if we wanted a list of Albums but AutoFixture also supplies this code to do the same thing

var fixture = new Fixture {RepeatCount = 10};
var albums = fixture.
                 Repeat(fixture.Create<Album>).
                 ToArray();

NBuilder

NBuilder source can be found on NBuilder.

NBuilder also supplies a factory pattern for both creating our objects and populating the object.

Here’s the code

var album = Builder<Album>
               .CreateNew()
               .Build();

NBuilder uses a fluent style interface and offers options for creating multiple items (i.e. an IList<> of objects). There’s also a mechanism for us to intercept the object population step and supply our own data. So whilst in the usage shown above, we don’t have the object heriarchy created, we can create this ourselves fairly easily using

var albums = Builder<Album>
   .CreateListOfSize(10)
   .All()
      .With(a => a.Artist = Builder<Artist>.CreateNew()
         .With(b => b.Band = Builder<BandMember>
                    .CreateListOfSize(3)
                       .Build().ToArray())
	.Build())
   .Build();

References

This is a great post on using NBuilder with Faker which allows us to populate the objects with more realistic data than the default process.

Compiling C# code at runtime

Occasionally we might come across a problem which lends itself well to the idea of C# code being compiled at runtime, maybe we’ve created some script like plug-in or in my case I wanted to generate sample XML data from xsd.exe generated classes at runtime.

We can use the CSharpCodeProvider to do exactly this, it can compile some code, create an assembly (in my case in-memory) and then allow us to instantiate the code within that assembly. Let’s jump straight into some code and then we’ll look at how the code works

var param = new CompilerParameters
{
   GenerateExecutable = false,
   IncludeDebugInformation = false,
   GenerateInMemory = true
};
param.ReferencedAssemblies.Add("System.dll");
param.ReferencedAssemblies.Add("System.Xml.dll");
param.ReferencedAssemblies.Add("System.Data.dll");
param.ReferencedAssemblies.Add("System.Core.dll");
param.ReferencedAssemblies.Add("System.Xml.Linq.dll");

var codeProvider = new CSharpCodeProvider();
var results = codeProvider.CompileAssemblyFromFile(param, filename);

if (results.Errors.HasErrors)
{
   foreach (var error in results.Errors)
   {
      Console.WriteLine(error);
   }
}
else
{
   object o = results.
               CompiledAssembly.
               CreateInstance(typeName);
}

In the code above, we’re assuming that the source code we want to compile exists in a seperate C# source code file stored in the variable filename.

Firstly we create the CompilerParameters. I don’t want an executable to be generated and debug information will be of little use to me. I’m going to create the resultant assembly in memory as we’re not intending to write this to disc.

Next up we need to tell the compiler what assemblies will be required, ofcourse this might be best supplied in some alternate way, such as the script itself could be parsed or we might have another file with the assemblies listed, but for my purposes I’ll just list the “standard” assemblies.

We create a CSharpCodeProvider (as we’re working in C#) and passing the compiler parameters and the source code filename we get the code provider to compile the code. If any errors occur we simply list them (in this example, to the console).

Assuming all compiles we use the CompiledAssembly and create an instance of the type we’re interested in. In my example I supplied the typeName (i.e. class name) in the command line arguments to the application which uses obviously allows this code to be a little more flexible.

Once we’ve got the instance of the type we can obviously start interacting with it.

Invoking with generics using reflection

Sometimes we need to run methods or create types with generic parameters at runtime. For example, situation where the type is not known at compiler time but the method(s) we want to use expect the generic parameter to be supplied.

Let’s take a look at the syntax of various scenarios and you’ll get the idea.

Calling an instance method

So let’s assume we have some code like this

public class Runner
{
   public T Create<T>()
   {
      // do something
      return default(T);
   }
}

and we want to invoke this at runtime with an “unknown” (i.e. discovered at runtime) type. We can write something like this

object unknown = CreateType(); // generates some type at runtime

var runner = new Runner();

typeof (Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(runner, null);

This code would also work if the Create method was a static.

Note: we can ofcourse use typeof(Runner) or runner.GetType() in the above depending upon your preference or use.

Next up, let’s look at the same code but where we need to also pass the method a generic parameter.

public class Runner
{
   public T Create<T>(T type)
   {
      // do something
      return type;
   }
}

So the only real difference here is that we also need to pass the type into the method, a simple addition of the parameters to the invoke will allow this to work, here’s the code

object unknown = CreateType(); // generates some type at runtime

var runner = new Runner();

typeof(Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(runner, new []{ unknown });

Calling methods on a static class or extension methods

As you will know, extension methods are really just static classes with syntactic sugar to allow them to appear like instance methods, so the procedure for invoking them is the same as the normal static classed, but we’ll cover examples here all the same.

Let’s first look at a static class

public static class Runner
{
   public static T Create<T>()
   {
      // do something
      return default(T);
   }
}

The only real difference to the code for the instance method on a non-static class is that we do not pass a instance to the first parameter of the invoke method, like this

object unknown = CreateType(); // generates some type at runtime

typeof(Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(null, null);

As extension methods expect a “this” argument, they’re no different to the above code, expect that we need to ensure the first argument is the instance of an object

public static class Runner
{
   public static T Create<T>(this DoSomething doSomething)
   {
      // do something
      return default(T);
   }
}

public class DoSomething
{		
}

So this assumes Create is an extension method for the class, DoSomething. To invoke this Create method we can simply write

object unknown = CreateType(); // generates some type at runtime

var doSomething = new DoSomething();

typeof(Runner).
   GetMethod("Create").
   MakeGenericMethod(unknown.GetType()).
   Invoke(null, new object[]{ doSomething });

Classes with generic parameters

So now let’s move the generic parameter onto the class itself. We’ll begin by looking at static classes

public static class Runner<T>
{
   public static T Create()
   {
      // do something
      return default(T);
   }
}

So now we need to make the generic on the type not the method. We get this

typeof(Runner<>).
   MakeGenericType(unknown.GetType()).
   GetMethod("Create").
   Invoke(null, null);

Notice how the MakeGenericType is used to generate our generic class and the syntax of the typeof.

Obviously we might wish to create non-static classes with generic parameters as well, something like this

public class Runner<T>
{
   public T Create()
   {
      // do something
      return default(T);
   }
}

ofcourse we can’t simply create an instance to this class and use the same techniques of previous because the type of the generic parameter is not known, so we need to create an instance of this class via reflection then invoke the method – this can be accomplished with

var genericType = typeof (Runner<>).
	MakeGenericType(unknown.GetType());

var runner = Activator.CreateInstance(genericType);

genericType
	.GetMethod("Create").
	Invoke(runner, null);

In the above we need to use the genericType twice, so we store it in a local variable. The first time we use it is with Activator.CreateInstance this creates an instance of the class with a generic parameter. Next we use the same type but with the GetMethod call and ofcourse pass the instance variable into Invoke.

What about when we have more than one generic parameter

So what if we had something like this

public class Runner<T1, T2>
{
   public T1 Create()
   {
      var t2 = default(T2);
      // do something
      return default(T1);
   }
}

Obviously this is assuming T2 actually does something of use in our code.

All of the previous sample code will work, the difference is that we declare the typeof(Runner<>) as typeof(Runner<,>) and need to pass the extra parameters in the MakeGenericType method, for example

var genericType = typeof (Runner<,>).
   MakeGenericType(unknown1.GetType(), unknown2.GetType());

var runner = Activator.CreateInstance(genericType);

genericType
   .GetMethod("Create").
   Invoke(runner, null);

Increasing the maximum number of connections with maxconnection

By default when calling webservices etc. we’re limited to 2 maximum connections at a time in an application, so it doesn’t matter if you (for example) create multiple background threads to run webservice calls as you’ll still be limited to two connections.

We can change this using the App.config for our application and adding the following

<system.net>
   <connectionManagement>
      <add address="*" maxconnection="20"/>
   </connectionManagement>
</system.net>

See ConnectionManagementElement.MaxConnection Property

Note: The maxconnection does not apply to local web service calls

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).