Archive

Posts Tagged ‘C#’

C# Static Field Initializers

January 18th, 2012 No comments

I hit a problem recently where a singleton I was calling from an assembly resolver was throwing an exception. It turned out that the sync object used in the lock for the singleton pattern was null. How was this possible? Look at the code below:

using System;

public sealed class Singleton
{
   private static volatile Singleton instance;
   private static readonly object syncRoot = new Object();

   private Singleton() {}

   public static Singleton Instance
   {
      get
      {
         if (instance == null)
         {
            lock (syncRoot)
            {
               if (instance == null)
                  instance = new Singleton();
            }
         }

         return instance;
      }
   }
}

How can this be, my static readonly field should be set by the field initializer. This should be run before it’s first usage. Normally, this is true but for some reason this was not the case. The C#spec though gives us a workaround, implement a static constructor. The section on static constructors states:

If a class contains any static fields with initializers, those initializers are executed in textual order immediately prior to executing the static constructor.

Therefore, if we add a static constructor to our Singleton class, we get guaranteed initialization of the static field initializers before it is run, also:

The static constructor for a class executes at most once in a given application domain. The execution of a static constructor is triggered by the first of the following events to occur within an application domain:

  • An instance of the class is created.
  • Any of the static members of the class are referenced.

Therefore our static constructor will run before our singleton Instance property.

Categories: C#, Programming Tags:

Building an Auto Complete control with Reactive Extensions (Rx)

November 22nd, 2011 1 comment

I have been meaning to get into Rx for a while now and haven’t quite found the excuse or opportunity to do so. While playing with SignalR it became apparent that Rx was something that could help and while I was researching it I seen a lot of people talking about using Rx in UI frameworks and I thought, hmmm, that sounds interesting.

So I set myself a challenge, I wanted to use Rx to create an auto-complete WPF control with some of the major use cases I have seen in these types of controls.

The App Shell

First thing I was going to need was a WPF application with a MainWindow that would hold my text box, the results and a log window.

 CropperCapture[1]

The XAML looks something like this:

<Window
    x:Class="AutoCompleteWithRx.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="AutoComplete with Rx"
    Height="451"
    Width="825"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:AutoCompleteWithRx="clr-namespace:AutoCompleteWithRx"
    mc:Ignorable="d"
    d:DataContext="{d:DesignInstance AutoCompleteWithRx:AutoCompleteViewModel}"
    FocusManager.FocusedElement="{Binding ElementName=SearchBox}">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition
                Height="Auto" />
            <RowDefinition />
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition />
            <ColumnDefinition />
        </Grid.ColumnDefinitions>
        <TextBlock
            FontFamily="Segoe WP Light"
            FontSize="26.667"
            Text="Auto-Complete Sample"
            Grid.ColumnSpan="2" 

            />

        <StackPanel
            Grid.Row="2">
            <Label>Search</Label>
            <TextBox
                x:Name="SearchBox"
                Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}"/>
            <ProgressBar Height="19" IsIndeterminate="True"/>
            <ListBox
                ItemsSource="{Binding SearchResults}" />
        </StackPanel>
        <StackPanel Grid.Column="1" Orientation="Vertical" Grid.Row="1" d:LayoutOverrides="Height">
            <Label>Log</Label>
            <ListBox
                ItemsSource="{Binding LogOutput}" />
        </StackPanel>
    </Grid>
</Window>

So that is basically the view for now. I have cheated and just instantiated my viewmodel in the code behind class for now.

public partial class MainWindow : Window {
    public MainWindow() {
        InitializeComponent();
        DataContext = new AutoCompleteViewModel();
    }
}

Now that we have a window I need to get my view model up to scratch. I started with simply satisfying the data properties required by my form.

public class AutoCompleteViewModel : INotifyPropertyChanged {

    private string searchText;

    public string SearchText {
        get { return searchText; }
        set {
            if (searchText == value) {
                return;
            }
            searchText = value;
            NotifyPropertyChanged("SearchText");
        }
    }

    private readonly ObservableCollection<string> logOutput = new ObservableCollection<string>();

    public ObservableCollection<string> LogOutput {
        get { return logOutput; }
    }

    private readonly ObservableCollection<string> searchResults = new ObservableCollection<string>();

    public ObservableCollection<string> SearchResults {
        get { return searchResults; }
    }

    public event PropertyChangedEventHandler PropertyChanged;

    protected virtual void NotifyPropertyChanged(string propertyName) {
        if (PropertyChanged != null) {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

 

Subscribing to Property Changed Events using Rx

OK. So that is simple enough but now I need to make my textbox do something when the user types into it. Before I start doing this though I will need to add Rx to my project. Right click the project choose “Manage Nuget Packages” and search for Rx, install Rx-Main and Rx-WPF.

Let’s start by simply logging the fact that the user has typed something. Add a constructor to our view model class with the following code:

public AutoCompleteViewModel() {
    // Listen to all property change events on SearchText
    var searchTextChanged = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
        ev => PropertyChanged += ev,
        ev => PropertyChanged -= ev
        )
        .Where(ev => ev.EventArgs.PropertyName == "SearchText");

    // Transform the event stream into a stream of strings (the input values)
    var input = searchTextChanged
        .Select(args => SearchText);

    // Log all events in the event stream to the Log viewer
    input.ObserveOn(DispatcherScheduler.Instance)
        .Subscribe(e => LogOutput.Insert(0,
            string.Format("Text Changed. Current Value - {0}", e)));
}

The first section of slightly unwieldy syntax creates an IObservable from the PropertyChanged event of INotifyPropertyChanged which our view model implements. You can think of the IObservable as a stream of events that will happen or a collection of future objects that will be added to each time the event is raised. Our code will then filter those events to only those concerning the SearchText that our textbox is bound to.

The next line transforms the type of the events in our IObservable from PropertyChangeEventsArgs to string, the content of the textbox. Much more useful.

Finally we need to subscribe to the event stream and do something with the string, firstly though we tell the subscription that we want to observe the events on the WPF dispatcher (This helper singleton comes from the Rx-WPF package). Then we simply provide an inline function to execute for each event, in our case inserting into the log stack which our LogOutput list box is bound to.

The result looks like this.

CropperCapture[2]

OK. So far so good. Now let’s add an actual search to the mix.

Chaining the Asynchronous Search

Before I add my search function I want to create a structure that will encapsulate the search term and it’s result.

public struct SearchResult {
    public string SearchTerm { get; set; }
    public IEnumerable<string> Results { get; set; }
}

Next I add my search function. For now I’ve just created a synchronous function but chances are you would be calling an external service with Async methods (BeginXXX and EndXXX) for which you should use the FromAsyncPattern method instead of the ToAsync I am using.

private SearchResult DoSearch(string searchTerm) {
    return new SearchResult {
        SearchTerm = searchTerm,
        Results =
            phrases.Where(item => item.ToUpperInvariant().Contains(searchTerm.ToUpperInvariant())).ToArray()
    };
}

private readonly string[] phrases = new[] {
    "The badger knows something",
    "Your head looks like a pineapple",
    "etc...",
};

And now for the magic. To invoke our search we add the following to our constructor:

// Setup an Observer for the search operation
var search = Observable.ToAsync<string, SearchResult>(DoSearch);

// Chain the input event stream and the search stream
var results = from searchTerm in input
              from result in search(searchTerm)
              select result;

// Log the search result and add the results to the results collection
results.ObserveOn(DispatcherScheduler.Instance)
.Subscribe(result => {
    searchResults.Clear();
    LogOutput.Insert(0, string.Format("Search for '{0}' returned '{1}' items", result.SearchTerm, result.Results.Count()));
    result.Results.ToList().ForEach(item => searchResults.Add(item));
    }
);

Here we firstly call ToAsync, this will create a function that takes a string (our search term) and returns an Observable that will only ever produce one event (the Completed / End) and then close.

We chain the incoming input stream with the result of the search function using simplified LINQ syntax and produce a new observable of SearchResult. We then observe the result, logging and updating the autocomplete items.

The result is this:

CropperCapture[4]

OK. So this is round about where my mind exploded and grey matter started to leak out of my ears. Basically what is happening is we are treating these incoming events as collections before they actually happen, then we can manipulate them using LINQ and even chain the events much like pipelining in UNIX / Powershell.

We’re not done yet. We still have a number of issues.

Using Throttle to enforce an idle period before searching

One of the issues you can see in the above screenshot is that the search was done after every single key press. The owner of the service we are calling will not be too happy with us flooding them with unnecessary searches, so how do we stop this from happening. Typically we would create a timer that would wait for a period of inactivity before searching, we would have to reset the timer every time the user typed something so that the search is not performed for each of the previous characters and there would be quite a few lines of code required to actually do this.

With Rx we can use the Throttle operator which will quite effectively do exactly the behaviour we want for free. We change our previous declaration of the input stream to add the Throttle method.

var input = searchTextChanged
    .Throttle(TimeSpan.FromMilliseconds(400))
    .Select(args => SearchText);

Now if we test we should get something like the following:

CropperCapture[5]

That was too easy.

Merging two event streams

The next requirement was that I may want a larger throttle timeout for strings of less than 3 characters as people tend to type slower at the start of a search. To do this I needed to split my input stream into two different event streams that could be throttled differently.

var input = searchTextChanged
    .Where(ev => SearchText == null || SearchText.Length < 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev => SearchText != null && SearchText.Length >= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args => SearchText);

So above I have simply cut the searchTextChanged stream 2 different ways, throttled them differently and then I can use the Merge operator to join the streams back together again into one.

Creating a Reactive ICommand for MVVM

The next requirement is that the search should be executed immediately if the user hits the enter key. To do this I decided to use the MVVM ICommand pattern. We need to add the following Input KeyBinding to the TextBox in our XAML so that the enter key will be picked up and we point it at the command we will write below.

<TextBox
    x:Name="SearchBox"
    Text="{Binding SearchText, UpdateSourceTrigger=PropertyChanged}">
    <TextBox.InputBindings>
        <KeyBinding
            Command="{Binding TextBoxEnterCommand}"
            Key="Enter" />
    </TextBox.InputBindings>
</TextBox>

The next thing we need to do is create our own command type. If you use an MVVM framework that understands Rx like ReactiveUI then you should get this for free but implementing a simple version yourself is not difficult. We simply take the RelayCommand defined by Josh Smith and add a Subject<T> exposed as an Observable.

public class ReactiveRelayCommand : ICommand {
    private readonly Action<object> execute;
    private readonly Predicate<object> canExecute;

    public ReactiveRelayCommand(Action<object> execute)
        : this(execute, null) {
    }

    public ReactiveRelayCommand(Action<object> execute, Predicate<object> canExecute) {
        if (execute == null)
            throw new ArgumentNullException("execute");

        this.execute = execute;
        this.canExecute = canExecute;
    }

    [DebuggerStepThrough]
    public bool CanExecute(object parameter) {
        return canExecute == null || canExecute(parameter);
    }

    public event EventHandler CanExecuteChanged {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public void Execute(object parameter) {
        execute(parameter);
        executed.OnNext(parameter);
    }

    private readonly Subject<object> executed = new Subject<object>();

    public IObservable<object> Executed {
        get { return executed; }
    }
}

Notice that it exactly the same as the standard RelayCommand except that we use a Subject<object> as the backing implementation for our IObservable. We call OnNext whenever the command is Executed.

Add the following field and property to the viewmodel class to store our command:

private ReactiveRelayCommand textBoxEnterCommand;
public ReactiveRelayCommand TextBoxEnterCommand {
    get { return textBoxEnterCommand; }
    set { textBoxEnterCommand = value; }
}

Then at the start of our constructor we setup the command itself:

// Setup the command for the enter key on the textbox
textBoxEnterCommand = new ReactiveRelayCommand(obj => { });

Next we need to change our input event stream to take into account our command and merge that with our SearchText property change events so that either can fire our search:

// Transform the event stream into a stream of strings (the input values)
var input = searchTextChanged
    .Where(ev => SearchText == null || SearchText.Length < 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev => SearchText != null && SearchText.Length >= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args => SearchText)
    .Merge(
        textBoxEnterCommand.Executed.Select(e => SearchText));

Notice we have just added the last line to merge the Executed observable on our command. Now when we run we can type a single character and hit enter if we do not want to wait for the idle period. How easy was that? Are we done? Almost.

Removing duplicate consecutive events

We still have an issue that when the user presses Enter, the idle timeout will expire some time later and we will get another event firing, essentially performing our search twice. So how do we stop the second duplicate event from being fired, easy, we just use DistinctUntilChanged.

We want a distinct search but we still want to allow the same search to be done later if the user tries another search in between. In other words we can have the same search done twice as long as they aren’t consecutive searches.

// Transform the event stream into a stream of strings (the input values)
var input = searchTextChanged
    .Where(ev => SearchText == null || SearchText.Length < 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev => SearchText != null && SearchText.Length >= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args => SearchText)
    .Merge(
        textBoxEnterCommand.Executed.Select(e => SearchText))
    .DistinctUntilChanged();

 

Cancelling previous searches with TakeUntil

The last issue here is that when searches return out of sequence, we could get the wrong results displayed. For example, the user searches for cr hits enter but then types crazy and hits enter. If the first search is taking a long time because of the number of results then the results for it will end up being displayed after the actual current search term is displayed. To simulate this we could add some latency to our search.

private readonly Random random = new Random(5);
private SearchResult DoSearch(string searchTerm) {
    Thread.Sleep(random.Next(100, 500)); // Simulate latency
    return new SearchResult {
        SearchTerm = searchTerm,
        Results =
            phrases.Where(item => item.ToUpperInvariant().Contains(searchTerm.ToUpperInvariant())).ToArray()
    };
}

To solve this we need to stop the Async stream when more input is given, this is pretty easy with the TakeUntil operator. Take operators define a completion for an event stream. In the case of an Async operation this will effectively cancel the Async subscription. TakeUntil takes an observable as input such that an event on that stream will complete the current stream. To implement this change we simply say the we TakeUntil the input stream in our chaining code.

// Chain the input event stream and the search stream, cancelling searches when input is received
var results = from searchTerm in input
              from result in search(searchTerm).TakeUntil(input)
              select result;

Summary

So we have managed to create the guts of an auto-complete control using Rx in a much more declarative way by responding to events in observables instead of writing lots of imperative code with little items of state sitting about to represent our state machine.

All of the heavy work can be easily seen in a single declaration of intent:

// Setup the command for the enter key on the textbox
textBoxEnterCommand = new ReactiveRelayCommand(obj => { });

// Listen to all property change events on SearchText
var searchTextChanged = Observable.FromEventPattern<PropertyChangedEventHandler, PropertyChangedEventArgs>(
    ev => PropertyChanged += ev,
    ev => PropertyChanged -= ev
    )
    .Where(ev => ev.EventArgs.PropertyName == "SearchText");

// Transform the event stream into a stream of strings (the input values)
var input = searchTextChanged
    .Where(ev => SearchText == null || SearchText.Length < 4)
    .Throttle(TimeSpan.FromSeconds(3))
    .Merge(searchTextChanged
        .Where(ev => SearchText != null && SearchText.Length >= 4)
        .Throttle(TimeSpan.FromMilliseconds(400)))
    .Select(args => SearchText)
    .Merge(
        textBoxEnterCommand.Executed.Select(e => SearchText))
    .DistinctUntilChanged();

// Log all events in the event stream to the Log viewer
input.ObserveOn(DispatcherScheduler.Instance)
    .Subscribe(e => LogOutput.Insert(0,
        string.Format("Text Changed. Current Value - {0}", e)));

// Setup an Observer for the search operation
var search = Observable.ToAsync<string, SearchResult>(DoSearch);

// Chain the input event stream and the search stream, cancelling searches when input is received
var results = from searchTerm in input
              from result in search(searchTerm).TakeUntil(input)
              select result;

// Log the search result and add the results to the results collection
results.ObserveOn(DispatcherScheduler.Instance)
.Subscribe(result => {
    searchResults.Clear();
    LogOutput.Insert(0, string.Format("Search for '{0}' returned '{1}' items", result.SearchTerm, result.Results.Count()));
    result.Results.ToList().ForEach(item => searchResults.Add(item));
    }
);

 

Lots of the ideas and even the odd piece of code were taken from:

Categories: C#, Programming, Rx, WPF Tags: , ,

More efficient file enumeration in .Net 4

November 18th, 2011 No comments

This may be basics to some people but I thought it was worth mentioning. I was writing some simple code recently to compare the files in a remote directory with those in a local directory to determined if the remote was newer in any way. This seemed like a really simple problem so I made my first stab at it.

return (from remoteFile in Directory.GetFiles(remotePath)
        join localFile in Directory.GetFiles(localPath)
            on Path.GetFileName(remoteFile) equals Path.GetFileName(localFile)
        where File.GetLastWriteTimeUtc(remotePath) > File.GetLastWriteTimeUtc(localPath)
        select remoteFile).Any();

 

It became very apparent that there were some performance issues when running this code, especially when the remote location introduces any form of latency. The first issue is with Directory.GetFiles, if you actually reflect this method you will see that it ultimately calls the following:

return new List<string>(FileSystemEnumerableFactory.CreateFileNameIterator(path, userPathOriginal, searchPattern, includeFiles, includeDirs, searchOption)).ToArray();

The existence of the ToArray means the full file list will be enumerated before the method returns, however we only care if any file has changed so it would be better if we had an enumerator so we could exit early when the first newer file is found. This is also true when performing the join as this will enumerate the joined collection first before enumerating the full original collection of remote files and then joining them.

We could solve the above issues using the new Directory.EnumerateFiles method which will return an enumerator that will yield each file as it is enumerated. We could also get rid of the join and enumerate all the local files first before in a separate operation to allow the more expensive remote enumeration happen in sequence.

The next problem in the original attempt is that we are returning to the remote files to call another operation to evaluate the last write time stamp on the file metadata. This requires us to return to the remote file system and incur the same latency per file. I originally tried to solve this problem using the Fast Directory Enumerator on code project which allowed me to enumerate the list of remote files at the same time as retrieving the file info, thus removing the need to return to the scene of the crime. This seemed to work ok but I was having an issue with it not completing the remote file enumeration sequence and discovered that there is actually an implementation introduced in .Net 4. The very well hidden EnumerateFiles on DirectoryInfo was the answer.

var localFiles = new DirectoryInfo(localPath).GetFiles();

return new DirectoryInfo(remotePath).EnumerateFiles()
    .Any(remoteFile => (from localFile in localFiles
                        where localFile.Name == remoteFile.Name
                        && remoteFile.LastWriteTimeUtc > localFile.LastWriteTimeUtc
                        select remoteFile).Any());

Notice the remote files retrieval now uses the EnumerateFiles method on DirectoryInfo. This allows us to exit when the first item matches the condition in the Any clause.

Categories: C#, Programming Tags: , , ,

Code and slides for TechEd NZ 2011–DEV 404 Hardcore Workflow

August 29th, 2011 No comments

Below are the slides and the code for the talk Stef and I did at Teched NZ 2011. I hope to do a post in the future explaining this in more detail.

Categories: C#, Presentations, TechEd, WCF, WF4 Tags: , ,

Using JSON.Net to eval json into a dynamic variable in C#

October 26th, 2009 6 comments

So I thought this would be possible and finally decided to give it a shot in 2010 Beta 2. It turns a bunch of JSON into an ExpandoObject using JSON.Net.

Needs cleaning up but not too bad.

        [TestMethod]

        public void DeserializeTestObjectToDynamic(){

            TestObject testObject = new TestObject() {

                FirstName = “Peter”,

                LastName = “Goodman”,

                DateOfBirth = new DateTime(1979, 2, 3),

                Child = new TestChildObject {

                    Line1 = “child line 1″,

                    Line2 = “child line 2″,

                    Line3 = “child line 3″,

                    City = “child city”

                },

 

                Children = new Collection<TestChildObject>() {

                    new TestChildObject() {

                    Line1 = “children 1 line 1″,

                    Line2 = “children 1 line 2″,

                    Line3 = “children 1 line 3″,

                    City = “children 1 city”

                },

                new TestChildObject() {

                    Line1 = “children 2 line 1″,

                    Line2 = “children 2 line 2″,

                    Line3 = “children 2 line 3″,

                    City = “children 2 city”

                }

                             }

 

            };

 

            // Get our json string

            string json = JsonConvert.SerializeObject(testObject);

 

            // Create the json.Net Linq object for our json string

            JObject jsonObject = JObject.Parse(json);

 

            // eval into an expando

            dynamic dynObject = ConvertJTokenToObject(jsonObject);

 

 

 

            Assert.IsNotNull(dynObject);

 

            Assert.IsNotInstanceOfType(dynObject, typeof(TestObject));

            Assert.IsInstanceOfType(dynObject, typeof(ExpandoObject));

 

            Assert.AreEqual(testObject.FirstName, dynObject.FirstName);

            Assert.AreEqual(testObject.LastName, dynObject.LastName);

            Assert.AreEqual(testObject.DateOfBirth, dynObject.DateOfBirth);

 

            Assert.IsNotNull(dynObject.Child);

            Assert.AreEqual(testObject.Child.Line1, dynObject.Child.Line1);

            Assert.AreEqual(testObject.Child.Line2, dynObject.Child.Line2);

            Assert.AreEqual(testObject.Child.Line3, dynObject.Child.Line3);

 

            Assert.IsNotNull(dynObject.Children);

            Assert.AreEqual(testObject.Children.Count, dynObject.Children.Length);

            for (int i = 0; i < testObject.Children.Count; i++) {

                Assert.AreEqual(testObject.Children[i].Line1, dynObject.Children[i].Line1);

                Assert.AreEqual(testObject.Children[i].Line2, dynObject.Children[i].Line2);

                Assert.AreEqual(testObject.Children[i].Line3, dynObject.Children[i].Line3);

            }

        }

 

        public object ConvertJTokenToObject(JToken token) {

            if (token is JValue) {

                return ((JValue)token).Value;

            }

            if (token is JObject) {

                ExpandoObject expando = new ExpandoObject();

                (from childToken in ((JToken)token) where childToken is JProperty select childToken as JProperty).ToList().ForEach(property => {

                    ((IDictionary<string, object>)expando).Add(property.Name, ConvertJTokenToObject(property.Value));

                });

                return expando;

            }

            if(token is JArray){

                object[] array = new object[((JArray)token).Count];

                int index = 0;

                foreach (JToken arrayItem in ((JArray)token)) {

                    array[index] = ConvertJTokenToObject(arrayItem);

                    index++;

                }

                return array;

            }

            throw new ArgumentException(string.Format(“Unknown token type ‘{0}’”, token.GetType()), “token”);

        }

 

 

Categories: Uncategorized Tags: , ,

C# var – with great power comes great responsibility

December 9th, 2008 No comments

There are many heated discussions on the overuse of var and I’m not going to repeat the arguments here. Personally, I have no problem with var used in the declaration of a variable where the value is instantiated inline via a constructor, anything else (apart from LINQ) seems dangerous. Having said that, the following sample I came across today is simply stupid.

var controller = new MyController().GetValueX(foo);

Categories: Uncategorized Tags:

T4 Templating in C#3.0 / .Net 3.5 and its uses in DSL development

April 15th, 2008 No comments

Cut to the chase

OK. So you just want to know how to do it? Modify your template directives to the following.

<#@ template inherits=”Microsoft.VisualStudio.TextTemplating.VSHost.ModelingTextTransformation” language=”C#v3.5″ #>

What?..Why?

Recently I have been doing a lot of work in Microsoft’s Domain Specific Language Tools for Visual Studio. In fact for the past 8 months this has pretty much been my main focus. I’ve learned a lot of things on the way and it occurred to me that the development of T4 templates used in DSL tools would be made a lot easier with the use of extension methods. To understand why, you need to understand the concepts behind DSL tools and the development process involved in creating a model to define your problem domain and templating to create the desired output.

One of the problems that becomes apparent in the latter stages of developing a DSL tools implementation is that templating can become quite messy. In DSL tools you create a model of the API which will allow you to interact with the visual elements and this generates code containing the classes you defined in the pattern necessary for these visual elements to be able to use them. After you are happy with the model you move on to generating your output. Typically this takes the form of T4 templates which will generate C# classes.

T4 templating, despite the fact that the engine is now built into Visual Studio 2008, does not get any designer support. It is an ASP-like syntax which compiles at template-transform-time into C# class files used to generate the output into files in your solution. Even using editors like Clarius Consulting’s T4 Editor does not give you the intellisense you are used to in ordinary C# (well not yet anyway….see here). What tends to happen is that developers make extensions to the model API classes generated by the DSL tools using partial classes to support common scenarios in templating (don’t even go down the path of static helper classes…..eek). This seems a good idea at first but after some time your API classes tend to suffer from explosion of methods and properties. These methods and properties are not helpful in defining your domain and do not make sense in Domain Driven Design concepts, they have no place in the ubiquitous language of the domain, they only make sense to the text transformation process employed in your T4 templates.

The solution can be to add common base templates which are included in your task specific templates using an ASP-like include directive. An issue with this is you typically create new class structures to encapsulate the functionality you want to perform. This has an obvious overhead in setup and maintenance, also the code in the include template is compiled into the same class as the task specific template which simply adds to the issues.

No wonder then that I was interested in the possibility of using Extension Methods to extend the DSL generated API with templating specific methods. After asking the question in the VSX forum I submitted a Microsoft Connect issue and got the answer of the above undocumented feature in a reply email. Basically this undocumented (AFAIK) feature allows you to add “v3.5″ to the language definition in a template directive and it can be used, it seems like a bit of an after-thought but it does work.

One thing to note is that you can’t specify extension method classes inside nested classes so it won’t work in template include file, but you could externalise them to another assembly if required. So now you can add a class like the following to your code.

    1 namespace PGCodeWorks.Dsl.Test.TestDsl.TemplatingExtensions {

    2     public static class ExampleElementExtensions {

    3         public static string LowerCaseName(this ExampleElement element) {

    4             return element.Name.ToLower();

    5         }

    6     }

    7 }

And from your template code you can do the following.

   14     <#= element.LowerCaseName() #>

How nice is that? Should make templating a lot easier in VS2008.

Pete

Categories: Main Page, VS2008 Tags: ,

Concatenating Delimited Strings with Generic Delegates

December 4th, 2007 No comments

I knew this must be possible through generic delegates and eventually found this really useful post by Phil Haack which describes using a generic delegate Join method to concatenate strings. Saves a lot of ugly code if you are using T4 or A-N-Other templating language to produce code from a  Dsl or schema.

Categories: Main Page Tags:

HeadMelter of the week – Self-Constrained Generic Base Classes

November 4th, 2007 No comments

Melted my own brain for a few hours with this one today. Essentially a self-constrained generic base class looks like the following.

    public class MyEntity : EntityBase<MyEntity> {

    }

 

This allows me to put some generic implementations in a base class for code that I would simply duplicate otherwise. For example:

 

    public class EntityBase<T> : IEquatable<T>, IComparable<T>

    {

        public int CompareTo(T other) {

            // Insert compare code here

 

        }

 

        public bool Equals(T other) {

            // Insert Equality Code Here

        }

    }

 

Enjoy!

Categories: Head Melter, Main Page Tags:

Re-Throwing Exceptions

April 26th, 2007 No comments

I was going over some old code recently to try to resolve a production issue. The log of the stack trace was not providing enough information on the thrown exception and it reminded me of a good tip for throwing and specifically re-throwing exceptions.

Consider the following code:

 

try
{
  int x = 0;
  int y = 5 / x;
}
catch (Exception ex)
{
 
throw ex;
}

The stack trace at the time that the DivisionByZero is thrown will be different from the rethrow in the catch block. This is because the “throw ex” will create a new exception and throw it. Instead, you should try to use the code below.

try
{
 
int x = 0;
 
int y = x / 5;
}
catch (Exception ex)
{
 
throw;
}

In this case the original exception will be thrown with the correct stack trace. Of course wrapping the exception before it is thrown will also preserve the stack trace.

Categories: Main Page Tags: