Category Archives: Programming

MarkupExtension revisited

In a previous post I looked at using the MarkupExtension to remove the need for adding Converters as resources, see MarkupExtension. For this post I’m going to look at implement a MarkupExtension to in place of a Binding, i.e.

Disclaimer: All the code listed works, but I’ve not tested in all scenarios

<TextBox Text="{Binding SomeProperty}"/>

What are we going to implement ?

WPF in .NET 4.5 has the concept of Delay property on a Binding which is used as follows

<TextBox Text="{Binding SomeProperty, Delay=500}"/>

This is used on a Binding to only update the source (after a change on the target) after a user-specified delay. The most obvious use of such a mechanism is when the user types into a search or filter text box and you don’t want to be searching and filtering for every change. Preferably code will wait for the user to pause for a short time then carry out the search or filter functionality.

Now .NET 4.0 doesn’t have such a property on the Binding class, so we’re going to implement a very basic approximation of the Binding class in .NET 4.0 (mainly because the current project I’m working on targets .NET 4.0).

Why can’t be simply inherit from the Binding class ?

Unfortunately we cannot simply inherit from the Binding class to add our new code. The ProvideValue method of the MarkupExtension is marked as sealed and not override-able. But hey, where would the fun be if it was all that easy…

Let’s write some code

By convention, as with .NET Attributes, we suffix our extension class name with “Extension” but when it’s used, in XAML, the “Extension” part can be ignored. So first up let’s create the barest of bare bones for our DelayBindingExtension.

[MarkupExtensionReturnType(typeof(object))]
public class DelayBindingExtension : MarkupExtension
{
   public override object ProvideValue(IServiceProvider serviceProvider)
   {
      // To be implemented
      return null;
   }
}

Note: The MarkupExtensionReturnType simply gives WPF information on what to expect as the return type from the ProvideValue method.

Let’s take a quick look at how we expect to use this extension in XAML (which should look pretty similar to the .NET 4.5 implementation show earlier)

<TextBox Text="{markupExtensionTest:DelayBinding Path=MyProperty, Delay=500}"/>

Before we implement the ProvideValue method, let’s add the other binding properties which most people will expect to see

[MarkupExtensionReturnType(typeof(object))]
public class DelayBindingExtension : MarkupExtension
{
   public DelayBindingExtension()
   {			
   }

   public DelayBindingExtension(PropertyPath path) 
   {
      Path = path;
   }

   [ConstructorArgument("path")]
   public PropertyPath Path { get; set; }
   public IValueConverter Converter { get; set; }
   public object ConverterParameter { get; set; }
   public string ElementName { get; set; }
   public RelativeSource RelativeSource { get; set; }
   public object Source { get; set; }
   public bool ValidatesOnDataErrors { get; set; }
   public bool ValidatesOnExceptions { get; set; }
   [TypeConverter(typeof(CultureInfoIetfLanguageTagConverter))]
   public CultureInfo ConverterCulture { get; set; }

   public int Delay { get; set; }

   public override object ProvideValue(IServiceProvider serviceProvider)
   {
      // To be implemented
      return null;
   }
}	

Right, those properties will make our extension appear like a Binding object, obviously with our addition of the Delay property.

Now it’s time to implement the ProvideValue method. I’m going to use Reactive Extensions to handle the actual delay (throttling) of the property change events. I’ll list the code and then discuss it afterwards

public override object ProvideValue(IServiceProvider serviceProvider)
{
   var pvt = serviceProvider.GetService(typeof(IProvideValueTarget)) as IProvideValueTarget;
   if (pvt == null)
      return null;

   var targetObject = pvt.TargetObject as DependencyObject;
   if (targetObject == null)
      return null;

   var targetProperty = pvt.TargetProperty as DependencyProperty;
   if (targetProperty == null)
      return null;

   var binding = new Binding
   {
      Path = Path, 
      Converter = Converter,
      ConverterCulture = ConverterCulture,
      ConverterParameter = ConverterParameter,
      ValidatesOnDataErrors = ValidatesOnDataErrors,
      ValidatesOnExceptions = ValidatesOnExceptions,
      Mode = BindingMode.TwoWay,
      UpdateSourceTrigger = UpdateSourceTrigger.Explicit
   };

   if (ElementName != null)
      binding.ElementName = ElementName;
   if (RelativeSource != null)
      binding.RelativeSource = RelativeSource;
   if (Source != null)
      binding.Source = Source;
  
   var expression = BindingOperations.SetBinding(targetObject, targetProperty, binding);

   var subject = new Subject<EventArgs>();

   var descriptor = DependencyPropertyDescriptor.FromProperty(
                       targetProperty, targetObject.GetType());
   descriptor.AddValueChanged(targetObject, (sender, args) => subject.OnNext(args));

   subject.Throttle(TimeSpan.FromMilliseconds(Delay)).
      ObserveOn(SynchronizationContext.Current).
      Subscribe(_ => expression.UpdateSource());

   return targetObject.GetValue(targetProperty);
}

Note: The first line where we see if the IServiceProvider supports the IProvideValueTarget interface uses the GetService method. If you use the serviceProvider as IProvideValueTarget way of obtaining the interface you’ll find the MarkupExtension will not be able to cast from an InstanceBuilderServiceProvider to the IProvideValueTarget meaning the code will return null and not the actual bound property at design time. At runtine all will work.

So the first few lines of code are all about getting the interfaces and objects we want before proceeding to the interesting part of the method. This is the point where we create a binding object and supply all the information it expects.

Notice also that for ElementName, RelativeSource and Source we check whether the user actually supplied these values before overwriting the default values. This is important. If we set one of these properties to null we might appear to be supplying the properties with the same value they already have (and ordinarily we’d expect nothing to change) but in fact we’ll be causing the Binding to change from an unset state to set and with the value null. This will stop the property using it’s default behaviour.

So for example setting Source to null (even though it will say it’s null), will stop it using any parent DataContext and ofcourse not bind to anything.

Note: we can return a property to it’s default state using DependencyProperty.UnsetValue

After creating the Binding and applying the properties we call BindingOperations.SetBinding to associate the binding with the target object and target property.

Next we’re going to basically connect to the target property value change events on it’s dependency property. This allows us to handle a dependency property’s value changed event in a generic way, so for a TextBox Text property we’ll respond to the TextChanged event whilst if we use this code on a CheckBox we’ll handle the IsChecked change event and so on.

I’m using the Reactive Extensions in this example as it makes things so much simpler. We’re going to create a Subject and then from this we’ll be using Throttle so we can implement the delay, i.e. Throttle will not call the Action associated with the Subscribe method until a period of inactivity on the property change event – the inactivity timeout obviously being the Delay we set, in milliseconds.

When the Subscribe method’s Action method is called we simply tell the binding expression to Update the source and the data is written to the view model.

You’ll notice we return the property value for the target object at the end of the method. Obviously if the property has data when the binding is first created, this will now be displayed when the control is instantiated.

References

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.

Query expressions in F#

Not quite the same as LINQ in syntax terms, F# includes query expressions which are in essence it’s own style of LINQ.

If we assume we have a simple example of some code in C# which uses LINQ to get strings from an array where their length is 3. In C# this might look like the following

string[] sample = {"One", "Two", "Three", "Four", "Five"};

IEnumerable<string> result = 
   from s in sample 
   where s.Length == 3 
   select s;

Note: I’ve purposefully put each part of the LINQ query on a new line for easier comparison with the equivalent F# query expression.

So here’s the same in F#

let sample = [| "One" ; "Two" ; "Three" ; "Four" ; "Five" |]

let result = query {
   for s in sample do
   where (s.Length = 3)
   select s
}

The main differences are the use of the query expression syntax query { … } and the use of the for s in sample do instead of from s in sample

References

See Query Expressions (F#) for a few examples of different query expressions and how they relate to SQL queries (and more).

Type extensions in F#

We can extend F# types by adding the equivalent of C# extension methods or something similar to partial classes in C#.

Let’s not waste time but instead get straight into the code

The type extension syntax is taken from Type Extensions (F#) which is well worth a read

type typename with
   member self-identifier.member-name =
      body
   ...
   [ end ]

[ end ] is optional in lightweight syntax.

Here’s an example of a type method for the System.String type, we’re going to add a simple Reverse function

type System.String with
    member __.Reverse = String(__.ToCharArray() |> Array.rev)

also we can create new functions like adding to a partial class

type System.String with
    member __.Append s = __.Substring(0) + s

A slightly pointless method, but at the time of writing I couldn’t think of anything more interesting.

Creating an F# WinForms application

I wanted to mess around with the FSharp.Charting library and needed to create an F# WinForms application to use it.

It’s pretty simple but there’s no template by default in Visual Studio (well not in 2013).

So here the steps to create a WinForms F# application

  • Create a new Project and select F# Application
  • This will be a console application, so next select the project properties and change the Application | Output type from Console Application to Windows Application
  • Add a reference to System.Windows.Forms
  • Change your main function to look like the following
    open System
    open System.Windows.Forms
    
    [<EntryPoint>]
    [<STAThread>]
    let main argv = 
    
        Application.EnableVisualStyles()
        Application.SetCompatibleTextRenderingDefault false
    
        use form = new Form()
    
        Application.Run(form);
    
        0 
    

Obviously this example shows us creating an empty Form. By default F# (at least in Visual Studio 2013) doesn’t include WinForm design surfaces or the likes. So it’s probably best to design your forms in a C# library and reference from your F# applications. Or, alternatively, you can hand code your WinForms.

A quick example of using FSharp.Charting

This is not mean’t to be anything other than a quick example, but as I wanted to get a F# WinForms application specifically to try out some FSharp.Charting, here’s the steps…

  • Using NuGet add a reference to FSharp.Charting to your project (developed above)
  • Add open FSharp.Charting to your Program.fs file
  • I’m going to simple use some code from the FSharp.Charting github samples, so first we need to add a reference to System.Drawing
  • Add a reference to System.Windows.Forms.DataVisualization
  • Finally change the Application.Run method to look like the following
    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())
    

Now your code should look like the following

open System
open System.Windows.Forms
open FSharp.Charting

[<EntryPoint>]
[<STAThread>]
let main argv = 

    Application.EnableVisualStyles()
    Application.SetCompatibleTextRenderingDefault false

    Application.Run (Chart.Line([ for x in 0 .. 10 -> x, x*x ]).ShowChart())

    0

and this should (when run) display a line chart.

Operator overloading in F#

More adventures with F#…

Operator overloading is documented perfectly well in Operator Overloading (F#) but to summarize I’ve created this post…

Operators in F# can be overloaded at the class, record type or global level.

Overloading an operator on a class or record type

Let’s look at the syntax for overloading an operator on a class or record type.

Note: Reproduced from the Operator Overloading (F#) page

static member (operator-symbols) (parameter-list> =
    method-body

Overloading an operator which is globally accessible

Let’s look at the syntax for overloading an operator at a global level.

Note: Reproduced from the Operator Overloading (F#) post

let [inline] (operator-symbols) parameter-list = 
    function-body

More…

You can overload the “standard” operators but you can also create your own operators. For example FAKE creates it’s own global operator to combine two file paths using the @@ operator

The below is taken from the FAKE source code available in github

let inline (@@) path1 path2 = combinePaths path1 path2

As it’s pretty obvious, this is a global level overload of a newly created operator, the @@ which takes two parameters.

Where an operator may be used for binary or unary (infix or prefix), such as + or – (+., -., &, &&, %, and %% may also be used for infix or prefix operators) we need to prefix the operator with a tilde ~, hence to overload the + and use as a unary operator we’d write something like

let inline (~+) x = [ x ]

// in use we'd have

let v = + "hello"

Whereas using the + as a binary operator we’d write something like

let inline (+) x y = [ x, y ]

// in use we'd have

let v = "hello" + "world"

If you’re coming from C# to F# you’ll have already noticed the “funky” set of operators that F# supports. As already shown with the @@ operator sample (taken from FAKE) you can combine operators to produce all sorts of new operators, for example

let (<==>) x  y = [ x, y]

Describing my tables, views, stored procs etc.

Having become a little too reliant (at times) on great GUI tools for interacting with my databases, I had to remind myself it’s pretty easy to use code to do this, sure good old Aqua Studio does it with CTRL+D on a data object in the editor, or both Oracle SQL Developer and the MS SQL Server Management Studio allow us to easily drill down the item in the data object tree, but still. Here it is in code…

Tables and views

For Oracle

desc TableName

For SQL Server

exec sp_columns TableName

Stored Procs

For Oracle

desc StoredProceName

For SQL Server

exec sp_help StoredProceName

In fact sp_help can be used for Stored Procs and Tables/Views.

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.