Category Archives: Programming

DataTemplates and DataTriggers in WPF

One of the cool features of WPF is the way we can define a UI based upon the data type used.

For example, assuming a very simple view model

public class PersonViewModel : ReactiveObject
{
   private string firstName;
   private string lastName;
   private int age;

   public string FirstName
   {
      get { return firstName; }
      set { this.RaiseAndSetIfChanged(ref firstName, value); }
   }

   public string LastName
   {
      get { return lastName; }
      set { this.RaiseAndSetIfChanged(ref lastName, value); }
   }

   public int Age
   {
      get { return age; }
      set { this.RaiseAndSetIfChanged(ref age, value); }
   }
}

We might have a parent view model returning a PersonViewModel type or maybe an ItemsControl that has an ObservableCollection of PersonViewModel types. We can handle the bindings in the standard way but we can also associate a UI with a data type using DataTemplates.

A simple example of this is seem with the following code

<ResourceDictionary>
   <Model:PersonViewModel x:Key="model"/>
</ResourceDictionary>

<Button Content="{Binding Source={StaticResource model}}"/>

With the above the button content will display the namespace.objecttype, i.e. MyTestApp.PersonViewModel which is of little use, but if we create a DataTemplate as per the following XAML, we get something more useable

<DataTemplate DataType="{x:Type ta:PersonViewModel}">
   <TextBlock>                    
      <TextBlock.Text>
         <MultiBinding StringFormat="{}{0} {1} aged {2}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
            <Binding Path="Age" />
         </MultiBinding>
      </TextBlock.Text>
   </TextBlock>
</DataTemplate>

Now our button will display the “FirstName LastName aged Age” text, where obviously FirstName, LastName and Age are taken from our view model.

Note: You can use a DataTemplate against any ContentControl, so we can see this template used on a button, a label or other control that expects/handles a ContentControl. Whereas the likes of a TextBlock’s Text property expects a string, so this will not work there.

The DataTemplate is also used in the ItemTemplate of a ListBox (for example)

<ListBox ItemsSource="{Binding People}" />

Using the above, where People is an ObservableCollection property. The ItemTemplate of the ListBox uses the DataTemplate previously defined. Alternatively we can create the DataTemplate within the ItemTemplate as per

<ListBox ItemsSource="{Binding People}">
   <ListBox.ItemTemplate>
      <DataTemplate>
         <TextBlock>
            <TextBlock.Text>
               <MultiBinding StringFormat="{}{0} {1} aged {2}">
                  <Binding Path="FirstName" />
                  <Binding Path="LastName" />
                  <Binding Path="Age" />
               </MultiBinding>
            </TextBlock.Text>
         </TextBlock>
      </DataTemplate>
   </ListBox.ItemTemplate>
</ListBox>

Along with DataTemplate we can define DataTemplate Triggers, for example

<DataTemplate DataType="{x:Type ta:PersonViewModel}">
   <TextBlock x:Name="text">                    
      <TextBlock.Text>
         <MultiBinding StringFormat="{}{0} {1} aged {2}">
            <Binding Path="FirstName" />
            <Binding Path="LastName" />
            <Binding Path="Age" />
         </MultiBinding>
      </TextBlock.Text>
   </TextBlock>
   <DataTemplate.Triggers>
      <Trigger SourceName="text" Property="IsMouseOver" Value="True">
         <Setter TargetName="text" Property="Background" Value="GreenYellow" />
      </Trigger>
   </DataTemplate.Triggers>
</DataTemplate>

So now anything use the DataTemplate will also apply the trigger code to the UI view of this data.

Styles in WPF

Styles in WPF allow us a reusable means of applying styling properties to controls. So for example, if we’ve decided that all the text boxes within a control, window or our app. should be displayed with a LemonChiffon background colour, instead of having something like this

<TextBox Background="LemonChiffon" x:Name="FirstName"/>
<TextBox Background="LemonChiffon" x:Name="LastName"/>
<TextBox Background="LemonChiffon" x:Name="Age"/>

we could create a style that’s applied to all TextBoxes, like the following

<ResourceDictionary>
   <Style TargetType="{x:Type TextBox}">
      <Setter Property="Background" Value="Gray" />
   </Style>
</ResourceDictionary>

...

<TextBox x:Name="FirstName"/>
<TextBox x:Name="LastName"/>
<TextBox x:Name="Age"/>

The style is defined as part of the ResourceDictionary and in this instance as no x:Key is set on the style resource it’s applied to all TextBoxes. If you were to create more than one style for a TextBox in this way, the last one defined is the one that will be used to style the TextBoxes. In such a situation where no key is defined, implicitly the key of x:Key=”{x:Type TextBox}” is used instead.

Note: We set the properties of the UIElement we wish to change using the Setter tag and the Property is obviously the property on the UIElement and the value is the value we wish to apply. I know, it’s obvious but I thought I’d mention it anyway.

So if you had a desire to have multiple background colours, for example maybe one colour for required fields and another for options, you would need to give one or both styles a key name to be used by the TextBox. For example

<Style x:Key="Required" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
   <Setter Property="Background" Value="LemonChiffon" />
</Style>

<Style x:Key="Optional" TargetType="{x:Type TextBox}">
   <Setter Property="Background" Value="BlanchedAlmond" />
</Style>

...

<TextBox x:Name="FirstName" Style="{StaticResource Required}"/>
<TextBox x:Name="LastName" Style="{StaticResource Required}"/>
<TextBox x:Name="Age" Style="{StaticResource Optional}"/>

If the Optional key didn’t exist then all TextBoxes without a style applied will take on the style without a x:Key.

Styles can also inherit from other styles, so let’s say we want to inherit from the newly created Required style for a TextBox and create a style based on it but which also adds a Bold font. We use the BasedOn attribute

<Style x:Key="Important" TargetType="{x:Type TextBox}" BasedOn="{StaticResource Required}">
   <Setter Property="FontWeight" Value="Bold" />
</Style>

So the “Important” style now inherits the LemonChiffon background and adds the Bold font.

Styles, of course, can be placed in other assemblies and referenced via an application using the Pack URI for example, in my App.xaml I could reference the xaml from an assembly as follows

<Application.Resources>
   <ResourceDictionary Source="pack://application:,,,/MyAssembly;component/Themes/generic.xaml" />-->
</Application.Resources>

Note: Whilst this code works, it doesn’t display the style at design time via the XAML designer. It will display at runtime.

Along with the “basic” styles of a control we can declare other styling attributes such as Triggers.

<Style x:Key="Required" TargetType="{x:Type TextBox}" BasedOn="{StaticResource {x:Type TextBox}}">
   <Setter Property="Background" Value="LemonChiffon" />
   <Style.Triggers>
      <Trigger Property="IsMouseOver" Value="True">
         <Setter Property="Background" Value="GreenYellow" />
      </Trigger>
   </Style.Triggers>
</Style>

In the above we not add the trigger to change the background colour when the mouse is over the control.

Note: IsMouseOver comes from the UIElement.

Basics of extending a WPF control

Occasionally we need to extend an existing WPF control. We might apply a different style to the control, or applying a new control template both using XAML. Or maybe this isn’t sufficient and we need to add functionality to the control itself using code.

In this post we’ll not be touching the style, but we will be looking at extending an existing control’s functionality and changing the control template to use the new functionality. This result is not mean’t to be a production ready control (although hopefully it will be) but is more aimed at the steps required to create our new control etc.

Through this post we’ll create a simple watermark text box. In other word a text box which displays text, then when the control gets focus the text will disappear and when the control loses focus and only if no text has been typed in, the watermark will reappear.

The steps….

  1. Create a new control and derive from the WPF TextBox, create an initial style for the control and expose this to allows us to reference and use the control elsewhere.
  2. Add our new properties, such as a string property for the Watermark text and a flag to state whether text exists in the TextBox
  3. Create the new control template to work with the new control properies

Step 1

We’ve already decided that we want to simply added some functionality to an existing TextBox, so first we create a new class (in the file named WatermarkTextBox,cs) and derive it from TextBox.

public class WatermarkTextBox : TextBox
{
   static WatermarkTextBox()
   {
      DefaultStyleKeyProperty.OverrideMetadata(typeof(WatermarkTextBox), 
             new FrameworkPropertyMetadata(typeof(WatermarkTextBox)));
   }
}

The important addition here is the static constructor and the DefaultStyleKeyProperty.OverrideMetadata. Without this the WatermarkTextBox will get the default theme for the TextBox, but we know we’re going to need to change this, so this line sets the default style to one with a target type of WatermarkTextBox.

If you ran code with this class as it is, you’d seen no output as we’ve not defined the default style yet. If you comment out the line in DefaultStyleKeyProperty.OverrideMetadata you’ll obviously see the default style for a TextBox.

So to complete step 1. We need to create a .xaml file (named WatermarkTextBox.xaml), so in VS2012 add a new Resource Dictionary and then add the following code to it

<Style TargetType="Controls:WatermarkTextBox" BasedOn="{StaticResource {x:Type TextBox}}">
</Style>

You’ll obviously need to add the namespace, which I’ve named as Controls.

I’ve in essence defined a style for this control which obviously adds nothing and thus looks like a TextBox’s default style. But we’ll flesh this out later. For now this will display nothing unless we create a Generic.xaml file.

Themes\Generic.xaml

By default WPF expects any generic styles etc. to be stored in a folder named Themes off of the project. Here we create another Resource Dictionary file name Generic.xaml. To this we add the following code

<ResourceDictionary.MergedDictionaries>
   <ResourceDictionary Source="/SimpleControl;component/WatermarkTextBox.xaml" />
</ResourceDictionary.MergedDictionaries>

We’re telling WPF to merge the WatermarkTextBox.xaml file into the Themes\Generic.xaml Resource Dictionary.

Step 2

Step 1 was basically about getting the plumbing in place to allow us to work with our new control, so let’s now added some new functionality to the WatermarkTextBox. This step will write all the code in the .cs file so go to that file and type dpp and tab (twice) within the class to use the DependencyProperty code snippet that ships with VS2012. Select 0 — Dependency Property — default value.

Give the property the name Watermark. This will be the text displayed as the watermark. VS should fill in the name and create the snippet. We need to change the text new FrameworkPropertyMetadata((bool)false) to new FrameworkPropertyMetadata(String.Empty) so that this property is a string and by default displays an empty string, i.e. nothing. Also we need to change the from bool to string elsewhere.

So the code should look like this (comments and regions removed)

public static readonly DependencyProperty WatermarkProperty =
         DependencyProperty.Register("Watermark", typeof(string), 
                      typeof(WatermarkTextBox),
		      new FrameworkPropertyMetadata(String.Empty));

   public string Watermark
   {
      get { return (string)GetValue(WatermarkProperty); }
      set { SetValue(WatermarkProperty, value); }
   }

Now we want the watermark to disappear when the control gains focus which is easy enough, but we also want it so that when the control loses focus the watermark is redisplayed but only if no text exists. So we need a property to tell us whether text exists. It’s not something that can be altered outside of the class so under the Dependency Property we just added (and within the class) type dp and tab twice selecting the Read-Only Dependency Property — default value option. To added a read only dependency property.

Give the name RemoveWatermark and let the snippet fill in the rest. This code snippet added a SetRemoveWatermark method, we don’t need this as the value is going to be determined by whether there’s text in the TextBox and therefore cannot be set directly. The code added should therefore look like this (comments and regions removed).

private static readonly DependencyPropertyKey RemoveWatermarkPropertyKey = 
            DependencyProperty.RegisterReadOnly("RemoveWatermark", typeof(bool), 
                typeof(WatermarkTextBox),
                new FrameworkPropertyMetadata((bool)false));

public static readonly DependencyProperty RemoveWatermarkProperty =                 
            RemoveWatermarkPropertyKey.DependencyProperty;

public bool RemoveWatermark
{
   get { return (bool)GetValue(RemoveWatermarkProperty); }
}

Finally for the code we need to put the code in place to update RemoveWatermark. So we’ve already mentioned that this code will depend on there being text in the TextBox. So naturally we’ll need to override the TextPropertyChanged event. To do this we need to add the following code to the static constructor

TextProperty.OverrideMetadata(typeof(WatermarkTextBox),
	new FrameworkPropertyMetadata(new PropertyChangedCallback(TextPropertyChanged)));

This tells TextBox TextProperty to call our TextPropertyChanged event for WatermarkTextBox types. So now let’s add the TextPropertyChanged code

static void TextPropertyChanged(DependencyObject sender, 
                  DependencyPropertyChangedEventArgs args)
{
   WatermarkTextBox watermarkTextBox = (WatermarkTextBox)sender;

   bool textExists = watermarkTextBox.Text.Length > 0;
   if (textExists != watermarkTextBox.RemoveWatermark)
   {
      watermarkTextBox.SetValue(RemoveWatermarkPropertyKey, textExists);
   }
}

This is simple enough. The sender should always be of type WatermarkTextBox so we simply cast it. We then check whether the Text.Length is greater than zero to see whether text exists. If the RemoveWatermark property differs from the new value we set the value on the RemoveWatermarkPropertyKey.

If we run a test app with the WatermarkTextBox it will still look like a TextBox but now has extra properties so if you’re working through this example go to your test app and add a Watermark string to your WatermarkTextBox ready for the next step. So it looks something like this

<Controls:WatermarkTextBox Watermark="Search" />

Step 3

We now need to fill in the control’s style. Open the WatermarkTextBox.xaml file and insert the following code into the Style created previously

<Setter Property="Template">
   <Setter.Value>
      <ControlTemplate TargetType="Controls:WatermarkTextBox">
                    
         <Border BorderThickness="{Binding Path=BorderThickness, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}" 
                 BorderBrush="{Binding Path=BorderBrush, RelativeSource={RelativeSource TemplatedParent}, Mode=OneWay}">
            <Grid>
               <ScrollViewer x:Name="PART_ContentHost" Margin="3"/>
                  <TextBlock x:Name="watermarkText" 
                        Text="{TemplateBinding Watermark}" 
                        FontStyle="Italic" 
                        VerticalAlignment="Center"
			Margin="5,0,0,0" 
                        FontWeight="Bold" 
                        Foreground="Gray"/>
             </Grid>
          </Border>
                    
         <ControlTemplate.Triggers>
            <MultiTrigger>
               <MultiTrigger.Conditions>
                  <Condition Property="IsFocused" Value="True"/>
               </MultiTrigger.Conditions>
               <Setter Property="Visibility" Value="Collapsed" TargetName="watermarkText" />
            </MultiTrigger>

            <MultiTrigger>
               <MultiTrigger.Conditions>
                  <Condition Property="RemoveWatermark" Value="True"/>
                  <Condition Property="IsFocused" Value="False"/>
               </MultiTrigger.Conditions>
               <Setter Property="Visibility" Value="Collapsed" TargetName="watermarkText" />
            </MultiTrigger>
         </ControlTemplate.Triggers>
      </ControlTemplate>
   </Setter.Value>
</Setter>

There’s a lot to take in there, but basically we’re setting the Template for the WatermarkTextBox. The first part is the ControlTemplate whereby we replace the TextBox’s default look with out own, adding a TextBlock which will display our Watermark text.

Note: The Textbox’s actually Template is far larger than the one shown above but basically we’re only really interested in the PART_ContentHost for this sample. But feel free to use Blend or whatever you prefer to edit the whole template if you wish.

As originally decided, we need this text to disappear when the control gets focus and reappear if the control loses focus AND there’s no text in the text box. So we create the two triggers.

The fist checks the IsFocused property and if it’s true collapses the water mark text. The second trigger checks whether we need to remove the watermark AND the IsFocused is False. If it is then the water mark is collapsed.

And that’s it, we’ve created a simple control, added properties, created the default style for the control and made it available to other code (outside it’s assembly).

Settings the DataContext in XAML and the ObjectDataProvider

I was updating a Tips & Tricks post on setting the DataContext via XAML and realised the post was getting way too large for a Tips & Tricks, so here’s the content in its own post.

So to set the DataContext in XAML we can do the following

<Window.DataContext>
   <Thermometer:ConversionViewModel />
</Window.DataContext>

This is simple enough, but there are various other ways to do this in XAML

ObjectDataProvider

The ObjectDataProvider allows us to create an object for use as a binding source within XAML. Unlike the Datacontext shown above, we declare the XAML for the ObjectDataProvider within the Window.Resources section as per

<Window.Resources>
   <ObjectDataProvider ObjectType="{x:Type Thermometer:ConversionViewModel}" x:Key="data">
      <ObjectDataProvider.ConstructorParameters>
         <system:Double>30</system:Double>
      </ObjectDataProvider.ConstructorParameters>
   </ObjectDataProvider>
</Window.Resources>

In the example above you’ll notice we can supply constructor parameters also.

We give the object a key for use in our bindings where we could just do something like

<Grid DataContext="{StaticResource data}">
...
</Grid>

or

<TextBlock Text={Binding Source={StaticResource data}, Path=Name}" />

The ObjectDataProvider also allows us to bind to a Method return value. So for example, what if we have the ObjectDataProvider similar to the one previously declared and we have a method named GetAge which takes a parameter (the name of the person who’s age we want returned). Like the previous example we can declare our ObjectDataProvider in the Resources section and it might look like this

<ObjectDataProvider ObjectInstance="{StaticResource data}" MethodName="GetAge" x:Key="age">
   <ObjectDataProvider.MethodParameters>
      <system:String>Bob</system:String>
   </ObjectDataProvider.MethodParameters>
</ObjectDataProvider>

Now we can bind to this data in the following way

<Label Content="{Binding Source={StaticResource age}}" />

Note: Just remember that the binding source is one way. So if you were to assign it to a two way by default control such as a TextBox, you’d get an error requiring you to set the binding to one way (not much use really on a text box).

But it would be much cooler if you could bind to the method and yet interact with the parameters at runtime, i.e. the user enters a person’s name (in our example) and the label updates to show the age of that person.

This can be achieved by creating a binding to the ObjectDataProvider object itself. By default we’ve seen that the interaction with the binding source allows us to pass straight through to the actual data the binding source contains, i.e. we do not appear to be using an ObjectDataProvider to bind to but instead the data source we assigned to it. If we could bind somehow to the ObjectDataProvider itself we could change the arguments passed to the method. This is how we do this…

<TextBox>
   <TextBox.Text>
      <Binding Source="{StaticResource age}" Path="MethodParameters[0]" BindsDirectlyToSource="true" />
   </TextBox.Text>
</TextBox>

As you can see above, we bind to the source as we’ve done previously but we now have a Path that points to the MethodParameters list and we’ve set the BindsDirectlyToSource to true. This tells the binding to evaluate the path on DataSourceProvider object (the ObjectDataProvider) as opposed to our data which is wrapped within the ObjectDataProvider.

Another thing to note about the code above, is that this works fine if the method parameter is a string (as in our example), but if it’s not then you’ll need to convert the type within the TextBox.Text binding source to the type expected by the method or you’ll simply find the method doesn’t get called.

For example

<TextBox.Text>
   <Binding Source="{StaticResource name}" 
                 Path="MethodParameters[0]" BindsDirectlyToSource="true" 
                 Converter="{MyConverters:ConvertTypeConverter To={x:Type system:Int32}}"/>
</TextBox.Text>

And finally…
Just to conclude this tip by also stating that you can also declare your view model in XAML as a resource as in the following

<Window.Resources>
   <Thermometer:ConversionViewModel InitialValue="30" x:Key="data" />
</Window.Resources>

The above shows how we can set properties on the view model as well.

void return methods in WCF (IsOneWay)

Don’t forget, if you’re implementing a fire and forget style method call in WCF, to mark it as one way.

In situations where you do not need or want to return a value from the server or handle exceptions from the client. You must mark the method’s operation contract as IsOneWay=true.

For example (if this is the service contract)

[ServiceContract]
public interface IProjectManager
{
   [OperationContract(IsOneWay=true)]
   void Run();
}

Without the IsOneWay=true the method will get called by the client but will block and may eventually timeout.

Basically with a one way operation the client calls the service and the service may queue the call to be dispatched one at a time. If the number of queued calls exceeds the queue’s capacity the client will block. In the case of a one way call the message is queued but the client unblocked. It is not an async call but may appear that way.

By default IsOneWay is false, hence the need to add the option to the attribute explicitly.

WPF Tips & Tricks

This idea of the tips & tricks is just as a scratch pad for code snippets etc. relating to the subject that don’t warrant a whole post to themselves. Here’s a few WPF tips & tricks.

StringFormat

I seem to always forget this, basically a simple way to apply string formatting to a TextBox (for example) is to use StringFormat

<TextBox Text="{Binding Fahrenheit, StringFormat={}{0:#.##}}" />

The above formats the TextBox string to 2 dp. Fahrenheit in this instance being a float.

Another example with DateTime formatting

<TextBlock Text="{Binding LastUpdateDateTime, StringFormat={}{0:HH:mm:ss dd/MM/yyyy}}" />

Setting the DataContext in XAML

Another one I seem to forget a lot. Admittedly I only tend to use it for simple apps. but still.

<Window.DataContext>
   <Thermometer:ConversionViewModel />
</Window.DataContext>

So we can set the data context on the main window easily enough using this method but there’s also a couple of other ways to create a view model in XAML…

See Settings the DataContext in XAML and the ObjectDataProvider

Order of XAML attributes

A little gotcha to watch out for. Take something like a ComboBox which has the SelectedValue and ItemsSource attributes.

Beware that if SelectedValue appears before ItemsSource you may well find the SelectedValue not set when the binding first takes place. Switch the two around so ItemSource appears first and this should fix the problem.

Detecting whether you’re in design mode

If you need to check whether your control (or general UI) is currently being displayed in design mode, i.e. maybe to not waste time displaying animation or the likes, use

if(!!DesignerProperties.GetIsInDesignMode(this))
{
   // not in design mode
}

Beware d:DesignWidth & d:DesignedHeight as opposed to Height and Width

This is a stupid tip and everyone should know but it’s funny how easy it is to miss this.

I was designing a simple little UI in WPF using both XAML code and the WPF Designer. I made a change to the Width and Height of the control. Unbeknown to me the actual control’s Width and Height were set, not the DesignWidth & DesignHeight. Hence when I placed the control onto another control I couldn’t understand initially why the control was not expanded correctly, when I resized the app.

So beware the WPF designer switching to setting your actual Width and Height as opposed to the d:DesignWidth and d:DesignHeight as it can lead to some head scratching when views are not resizing as expected.

Ix/Interactive Extensions

I’m a bit late to the party with this one – Ix or Interactive Extensions.

Available on NuGet via the Ix-Main package. This will give us the System.Interactive assembly.

Ix are basically a bunch of extension methods for IEnumerable and the
EnumerableEx class. I’m sure many of us have written IEnumerable extensions to supply a ForEach extension method or the likes. Well Ix gives us that and more.

In this post I will not be documenting each overload but will try to give an idea of what the methods might be used for and how to use them. Checking which overload is suitable is down to the reader.

Note: some of the examples may be less than useful, I will attempt to update with better examples as/when I come up with them.

Buffer

Basically takes an IEnumerable and creates an IEnumerable of IList of type T of the given buffer size.

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76, 45, 32, 1, 6, 3, 89, 100 };
IEnumerable<IList<int>> lists = items.Buffer(3);

The above would result in an IEnumerable with 4 ILists of type T each containing up to 3 items each. An overload of this method exists which allows you to skip a number of elements at the start of each buffer.

Case

Case is a static method on EnumerableEx and allows us to pass in an argument to compare against and an IDictionary of keys – which will be used to match with the argument passed into the Case method and it will return an IEnumerable relating to the values which appear in the dictionary against the given key. So for example

IDictionary<int, IEnumerable<string>> d = new Dictionary<int, IEnumerable<string>>
{
   {5, new[] {"Five"}},
   {4, new[] {"Four"}},
   {1, new[] {"One"}},
   {2, new[] {"Two"}},
   {3, new[] {"Three"}},
};

var matches = EnumerableEx.Case(() => 4, d);

In the above, matches will contain the IEnumerable of the values stored in the dictionary against the key 4, in other words the IEnumerable containing the string “Four”.

An overload of this method allows you to supply an IEnumerable to act as the default values should a match against the selector not be found.

Create

Create is a static method on the EnumerableEx class which allows us to create an IEnumerable from a IEnumerator (or via an overload from an IYielder).

Let’s assume we have a method that returns an IEnumerator of integers, here’s a mock up of such a method

private static IEnumerator<int> Factory()
{
   yield return 1;
   yield return 2;
   yield return 3;
   yield return 4;
}

Now using Ix we can create an IEnumerable of integers using

var items = EnumerableEx.Create(Factory);

Defer

As the name suggests Defer will defer the creation of an enumerable sequence until a call to GetEnumerator, so for example

var items = EnumerableEx.Defer(() => new [] { 3, 5, 6, 2 });

the code above will not call the enumerable factory method (in this case the anonymous method creating an array of integers) until the GetEnumerator is called.

Catch

Creates an IEnumerable sequence based on the source, but if the source has an exception will switch to the second IEnumerable.

A somewhat convoluted sample below

IEnumerable<int> GetNegatives()
{ 
   int[] items = new int[] { -1, -2, 0, -3 };
   for (int i = 0; i < items.Length; i++)
   {
      if (items[i] >= 0)
         throw new Exception();

      yield return items[i];
   }
}

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76, 45, 32, 1, 6, 3, 89, 100 };
IEnumerable<int> e = GetNegatives().Catch(items);

The above will create an IEnumerable e that contains -1, -2 and then the values from the items IEnumerable.

There are several overloads of the Catch method to check out.

Distinct

Returns an IEnumerable of the distinct values in a sequence

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76, 45, 32, 1, 6, 3, 89, 100 };
IEnumerable<int> distinct = items.Distinct();

The above will result in a sequence 3, 5, 6, 2, 76, 45, 32, 1, 89, 100 removing the duplicates.

DistinctUntilChanged

Returns consecutive distinct values

IEnumerable<int> items = new int[] { 3, 3, 3, 5, 5, 2, 76, 76, 100 };
IEnumerable<int> distinct = items.DistinctUntilChanged();

The above will return an sequence 3, 5, 2, 76, 100

Do

Several overloads of the Do method exist, we’ll just take a look at the one which takes an Action. Do will simply invoke some action on each item within the IEnumerable, so for example

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76 };
items.Do(Console.WriteLine);

the above code will simply call WriteLine on each integer within the items IEnumerable. However, this is lazy and hence we actually need to do something with the items returns enumerable.

DoWhile

The DoWhile method iterates over an IEnumerable whilst the supplied function is true, so for example

var items = new int[] { 3, 5, 6, 2 };

int i = 0;
var results = items.DoWhile(() => i++ < 2);
int len = results.Count();

If we run this code the len variable will be 12 as the DoWhile looped through the IEnumerable 3 times and the items array contained four items. So basically if we output to the console each item returned by results will see the array items output three times.

Expand

Expand, basically loops through the supplied IEnumerable (possibly infinitely if you do not use a Take or similar method to stop it). In essence is applies a selector function each time through the enumerable changing the values.

So imagine we have an array of values 1, 2 and 0 and apply Expand to this as follows

var items = new [] { 1, 2, 0 };
var results = items.Expand(i => new[] {i + 1}).Take(9);

what happens here is the output (if we ran results.ForEach(Console.WriteLine)) will output 1, 2, 0 (the values from items then 2, 3, 1 and finally 3, 4, 2. As you see each time we iterate through we add 1 to each element.

Finally

Finally can be used on a sequence so that an action may be invoked upon the termination or disposal, so for example the following will output the sequence to the console then output “Completed”

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };

items.Finally(() => Console.WriteLine("Completed")).ForEach(Console.WriteLine);

For

The For method takes a source enumerable and applies a supplied enumerable to it, so a simple example might be

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76 };
EnumerableEx.For(items, i => new []{i + 1, i + 2});

In this case each item in the items enumerable will have the new []{i + 1, i + 2} applied to it, thus output for this would be

4, 5, 6, 7, 7, 8, 3, 4, 77, 78

the first item 3 in the source enumerable is sent to the For method and we get back a transformed value as two values 3 + 1 and then 3 + 2 and so on.

ForEach

ForEach will invoke an action on each item within an IEnumerable, so a simple example might be to just write a more compact foreach to write output to the console, i.e.

IEnumerable<int> items = new int[] { 3, 5, 6, 2, 76 };
items.ForEach(Console.WriteLine);

Generate

As the name suggests, Generate can be used to generate a sequence in a similar way to a for loop might be used, here’s an example which creates an IEnumerable with the range [10, 20]

EnumerableEx.Generate(10, i => i <= 20, i => i + 1, i => i)

The first argument is the starting value, then we have the condition to stop the generator, next we have the state update function, in this case we’re incrementing the state by 1, finally we have the result function, in this case we’re just using the supplied state value.

Hide

To quote the documentation “Returns Enumerable sequence with the same behavior as the original, but hiding the source identity”.

I’m not wholly sure of the use cases for this, but basically if we have the following

List<int> items = new List<int> { 3, 5, 6, 2, 76 };

if we used items.AsEnumerable() the type returned would still be a List however using

var result = items.Hide();

result will be a funky EnumerableEx type hiding the underlying implementation.

If

The If method is self-explanatory, it allows us to return an IEnumerable if a condition is met or it will return an empty sequence or the overload shown below acts as an if..else returning the alternate sequence

EnumerableEx.If(() => someCondition, new[] { 3, 5, 6, 2, 76 }, new [] {6, 7});

So it’s probably obvious that if the someCondition is true the first array is returned else the second array is returned.

IgnoreElements

A slightly odd one, which probably is more useful when used in combination with other methods. IgnoreElements returns a source sequence without its elements

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.IgnoreElements();

result will be an empty sequence.

IsEmpty

As the name suggests, checks if the sequence is empty or not, obviously the following is not empty

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.IsEmpty();

whereas the following will be empty

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.IgnoreElements().IsEmpty();

Max

Returns the maximum value in the sequence

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.Max();

this will result in the result being 76.

MaxBy

In essence MaxBy returns a sequence of values less than the supplied comparer, for example

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
items.MaxBy(i => i < 50).ForEach(Console.WriteLine);

this will create a sequence with values less than 50 and in this case write them to the console, thus outputting the values 3, 6 and 2.

Memoize

Memoize creates a buffer over the source sequence to ensure that if we were to iterate over the items multiple times we would not call the source multiple times. Obviously this would be useful if we’ve got the data from some file system or remote source to stop us retrieving the data multiple times, in use we have

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.Memoize();

Min

Returns the minimum value in the sequence

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
var result = items.Max();

this will result in the result being 2.

MinBy

In essence MinBy returns a sequence of values greater than the supplied comparer, for example

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
items.MinBy(i => i < 50).ForEach(Console.WriteLine);

this will create a sequence with values greater or equal to 50 and in this case write them to the console, thus outputting the values 50 and 76.

OnErrorResumeNext

Concatenates the sequence with a second sequence regardless of whether an error occurred, used in situation where you might be getting data from a source that could fail, the example below just shows the syntax really as this wouldn’t need to use OnErrorResumeNext

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
var result = items.OnErrorResumeNext(new[] {9, 10});

result would contain the items sequence followed by the sequence { 9, 10 }.

Publish

To quote the documentation, “creates a buffer with a view over the source sequence, causing each enumerator to obtain access to the remainder of the sequence from the current index in the buffer”.

This allows the sequence to be shared via the buffer, in syntax terms this looks like

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
var buffer = items.Publish();

There is an overloaded method which allows you to supply a selector.

Repeat

Allows us to iterate through a sequence infinitely or with the overload, n times

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };

// iterate over three times
items.Repeat(3).ForEach(Console.WriteLine);

// iterate infinitely
items.Repeat().ForEach(Console.WriteLine);

Retry

This method allows us to retry enumerating a sequence whilst an error occurs or via the overload we can specify the maximum number of retries

items.Retry(2);

Return

The Return method returns a single element as a sequence, for example

EnumerableEx.Return(1);

this creates an IEnumerable of integers with the single value 1 in it.

Scan

Scan generates a sequence using an accumulator, so for example

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.Scan((i, j) => i + j).ForEach(Console.WriteLine);

will pass 3 (i) and 5 (j) into the accumulator method the result will be 8 this will then be pass into the accumulator as i followed by 6 (j) and so on.

SelectMany

Several overloads exist, the one shown here simply projects each element of the sequence with a given sequence. For example the following simply projects the array { 5, 6 } over the original sequence

IEnumerable<int> items = new [] { 3, 50, 6, 2, 76 };
items.SelectMany(new [] { 5, 6 }).ForEach(Console.WriteLine);

This will output { 5, 6 } the number of times matching the number of elements in the items sequence, i.e. 5 times.

Share

A couple of overloads. This method creates a buffer with a shared view over the sequence so mutiple enumerators can be used to fetch the next element from the sequence, this example is a little convoluted

IEnumerable<int> items = new [] { 20, 10, 60, 30 };
items.Share(x => x.Zip(x, (a, b) => a - b)).ForEach(Console.WriteLine);

The same sequence is used on Zip and passed into Zip hence we’re zipping the sequence with itself, the result selector simply subtracts one value from the other. When output to the console this will write a sequence 10, 30 because the first item (20) has the second item (10) subtracted from it, as then the next item (60) has the final item (30) subtracted.

SkipLast

Allows us to skip/bypass n elements from the end of in the sequence, thus

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.SkipLast(2).ForEach(Console.WriteLine);

lists values 3, 5, 6 but not the last 2 items.

StartWith

StartWith starts the sequence with the newly supplied enumerable, for example

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.StartWith(new []{9, 10}).ForEach(Console.WriteLine);

will output the sequence 9, 10 then follow with the items sequence.

TakeLast

In essence the opposite of SkipLast, TakeLast results in a sequence on the last n items, such as

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };
items.TakeLast(2).ForEach(Console.WriteLine);

which outputs 2 and 76.

Throw

With the Throw method we can create a sequence which throws an exception when we try to enumerate it, for example

EnumerableEx.Throw<int>(new NullReferenceException()).ForEach(Console.WriteLine);

will throw the NullReferenceException when ForEach attempts to enumerate the sequence.

Using

Using creates a sequence which has a resource who’s lifetime is determined by the sequence usage. The idea being the resource is created via the Using method’s first argument then passed to the second argument (in all likelihood to be used in some way) before an IEnumerable is returned. The key thing to note is the resource is not created until we use the returned IEnumerable, for example

IEnumerable<int> items = new [] { 3, 5, 6 };
IEnumerable<int> results = EnumerableEx.Using(() => new SomeDisposable(), resource => items);
results.ForEach(Console.WriteLine);

Assuming SomeDisposable implements IDisposable, when we call GetEnumerator the SomeDisposable is created and passed to the second argument – this rather simplistic example does nothing with the resource but hopefully you get the idea. We then return the IEnumerable and when the GetEnumerator completes the resources Dispose method is called.

While

Loops through the sequence whilst a condition is true, so for example

IEnumerable<int> items = new [] { 3, 5, 6, 2, 76 };

int i = 0;
EnumerableEx.While(() => i++ < 3, items).ForEach(Console.WriteLine);

will output the items sequence three times.

Enumerations in WCF

Like other data types designed to go over the WCF wire (as it were) we need to mark the enum with a DataContractAttribute. Unlike classes, which use the DataMemberAttribute for any published methods we use the EnumMemberAttribute. For example

[DataContract]
public enum Status
{
   [EnumMember]
   None,
   [EnumMember]
   Running,
   [EnumMember]
   Failed,
   [EnumMember]
   Succeeded
}

Don’t forget to add a FlagsAttribute if you are requiring the enum to work as flags otherwise you’ll get an error from WCF when combining your flags, as the value will be unexpected.

Derived and base classes in WCF

This is a short post on something that caught me out, primarily due to the awful client side error message.

The server did not provide a meaningful reply; this might be caused by a contract mismatch, a premature session shutdown or an internal server error.

I was implementing a WCF service to allow my client to get historic data from the service. But as the History object might become large I also wanted a HistorySummary object with the bare minimum data. So for example my client UI would list the history summary data and only when the user clicked on the summary would the full data get loaded.

So I implemented my HistorySummary (abridged version below)

[DataContract]
public class HistorySummary
{
   [DataMember]
   public string Name { get; set; }
   // ... other properties
}

From this I derived my History object (also abridged)

[DataContract]
public class History : HistorySummary
{
   [DataMember]
   public string[] Reports { get; set; }
   // ... other properties
}

If you’re experienced in WCF you’ll immediately spot the problem straight away.

I built the server and ran it, no problems. I regenerated the proxies and ran the client and bang ! I get the less than helpful error message shown above.

KnownTypes was the problem. Easy to forget. The base class, HistorySummary should have looked like this

[DataContract]
[KnownType(typeof(History))]
public class HistorySummary
{
   [DataMember]
   public string Name { get; set; }
   // ... other properties
}

TypeConverters and XAML

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

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

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

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

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

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

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

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

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

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

      return 0.0;
   }

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

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

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

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

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

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

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

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

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

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

For completeness, here’s the simple AbbreviatedNumeric class

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

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

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

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