Using Structuremap to resolve ViewModels

One of the things I find myself doing over and over again when working in xaml-based applications is to create a ViewModelFactory based on Jeremy D. Miller’s StructureMap.

All my ViewModel classes are based on a class BaseViewModel:

    public class BaseViewModel : INotifyPropertyChanged

The fun, of course, begins when your viewmodels need to know about other viewmodels. Lets say, for instance that your main view contains a Container control in which you would like to swap views in. Using structuremap, it is easy to inherit the Registry class in order to stitch together associations between views and models:

public class ViewModelsRegistry : Registry
{
    public ViewModelsRegistry()
    {
        Rig<MainWindowView, MainVindowViewModel>(Registered.MainWindow);
        Rig<TrioEventsView, TrioEventsViewModel>(Registered.TrioEvents);
        Rig<NewsContentView, NewsContentViewModel>(Registered.NewsContent);
    }

    private void Rig<TControl, TViewModel>(Registered name) 
        where  TControl : ContentControl where TViewModel : BaseViewModel
    {
        For<ContentControl>().Singleton().Use<TControl>().Named(name.ToString());
        For<BaseViewModel>().Singleton().Use<TViewModel>().Named(name.ToString());
    }
}
 

The Registered reference is an enum that I use to keep tabs on what views/viewmodels that are implemented:

    public enum Registered
   
{
        Unknown = 0,
        MainWindow,
        TrioEvents,
        NewsContent,
        Locations
    }

As you can tell, the ViewModelsRegistry uses ContentControl as it’s container type. This makes it  compatible with all derivates, including Window and UserControl.
Following the factory pattern, the result follows:

public static class ViewModelFactory
{
    public static void Initialize(Registry registry)
    {
        ObjectFactory.Configure(o => o.AddRegistry(registry));            
    }

    public static ContentControl Get(Registered name)
    {
        var control = ObjectFactory.GetNamedInstance<ContentControl>(name.ToString());
        control.Loaded += (s, e) => {
            control.DataContext = GetDataContextFor(name);
        };
        return control;
    }

    public static BaseViewModel GetDataContextFor(Registered name)
    {
        return ObjectFactory.GetNamedInstance<BaseViewModel>(name.ToString());
    }
}
 

The ViewModelFactory basically leans on structuremap providing the method Get() that stitches together a view and it’s model. One example of such use:

 

        public void LoadEvents(object dummy)
        {
            SetViewModel(Registered.TrioEvents);
        }

        private void SetViewModel(Registered name)
        {
            if(!_loadedControls.ContainsKey(name))
                _loadedControls.Add(name, ViewModelFactory.Get(name));
                
            CurrentContent = _loadedControls[name];
        }

In the above snippet, taken from the MainWindowViewModel,  LoadEvents is bound to a button click on the Main Window. Once clicked, If I haven’t already loaded the control, I use the factory.Get() method to create a UserControl with initalized datacontext, before I finally set the ContentPresenter (CurrentContent) on the Main window viewmodel.

The factory can easilly be expanded to swap out datacontexts, provide different views. This blog post is mainly about using structuremap to make it happen.

Jeg bare tøyser

 

Running CasperJs scripts from a C# console app

I recently came across the need to write a console application that can take a CasperJs script (or folder) and run it with console output on. I wanted to make this tool in order to integrate it with Visual Studio External tools, so that whenever I am editing a casperJs script, I can hit my keyboard shortcut to verify that all is ok.

Doing this in C# is mostly straightforward:

  • You recieve the CasperJs file or folder to run as an argument to your console app
  • Inspect the environment variables to find:
    • Where Python is installed (by inspecting your path variable)
    • Where CasperJs is installed
  • You start a Process.Process() and provide it with enough details to run the script

 

Challenge: Output

The tricky bit, is to grab the output, and display it in your own app. Here’s my go at it:

private static void ExecutePythonScript(DirectoryInfo workingDir, FileInfo pythonPath, 
string casperArguments)
{
    var p                              = new Process();
    p.StartInfo.WorkingDirectory       = workingDir.FullName;
    p.StartInfo.FileName               = pythonPath.FullName;
    p.StartInfo.Arguments              = casperArguments;
    p.StartInfo.UseShellExecute        = false;
    p.StartInfo.CreateNoWindow           = true;
    p.StartInfo.RedirectStandardError  = true;
    p.StartInfo.RedirectStandardInput  = true;
    p.StartInfo.RedirectStandardOutput = true;

    p.ErrorDataReceived += (s, e) => {
        if (!string.IsNullOrEmpty(e.Data))
            Console.WriteLine("e> " + e.Data);
    };

    p.OutputDataReceived += (s, e) => {
        if (!string.IsNullOrEmpty(e.Data))
            Console.WriteLine("->" + e.Data);
    };

    p.Start();
        p.BeginOutputReadLine();
        p.BeginErrorReadLine();
        p.WaitForExit();
    p.Close();
}

 

The tricky bit to figure out was that after you start the processs (p.Start()), you need to call the asynchronous methods BeginOutputReadLine() and BeginErrorReadLine(), otherwise, events will never be posted. Sarching the internet for invoking processes did not include this little gem, hence this post.

Happy coding!

Jeg bare tøyser

Smart Reflection with dynamic type in .Net 4.0

A collegue of mine at my current project in NRK showed me how to use the dynamic keyword in C# to perform dynamic casting from a base type to a derived type. I just had to share!

The example starts with the following hierarchy of types:

public class Person{
}

public class Police : Person {
}

public class Fireman : Person{
}

The heart of the matter

Typically, you will have a controller/manager class that calls different workers based on the type of object at hand. In ASP.NET, for example, you may have a controller that will return a different rendering of a view based on the 
type of person to render. In its simplest form, the following 3 functions could form such a controller:
public void Draw(Person p) {
    Console.WriteLine("Drawing a generic person");
}

public void Draw(Police police)    {
    Console.WriteLine("Drawing the police");
}

public void Draw(Fireman fireman) {
    Console.WriteLine("Drawing a firefighter");
}
Easy peasy, you say and proceed to write some test code: 
// Arrange
var people = new List<Person>{
    new Person(),
    new Police(),
    new Fireman()
};
// Act
foreach (Person p in people)
    Draw(p);
Do you see the problem?

…the above code will issue 3 calls to the function that draws the base person type. The other two functions are never called. This is self-explanatory, since the foreach loop defines a Person reference. Using var has the same effect, because it is getting populated from a list of Person objects. The compiler simply does not see the Police or Firemen objects.

Now, if you change the foreach-loop to this:

// Act
foreach (dynamic p in people)
    Draw(p);

(use of the dynamic keyword requires that you add a reference to Microsoft.CSharp and System.Core)

The dynamic keyword is strongly typed, but, the compiler is told that the type of object, p will be determined at runtime, and not during compile time, thus each person object in the list will become a strongly typed police and fireman during runtime, similar to dynamic_cast in c++ (damned near identical if you ask me!)

Concerns

Any type of run-time-type checking will involve reflection in some form or another, however, Microsoft has gone a long way in ensuring that this is second-generation reflection, using a funky named tri-state cache to keep things fast. Another concern, of course, is that you can always cast any type to dynamic without compile-time checking, so you basically want to ensure 100% coverage by unit tests as well as ensure that the unit tests will catch type-mismatches.

Conclusion

Using the dynamic keyword will clean up the code considerably at the cost of having to keep in mind that you wil have no compile time checking of any lines of code that involve the dynamic keyword, so make sure you write those unit tests. Additionally, because this is run-time checking, you should consider other options if you depend on faster code, but for most of your code, the performance impact is non-measurable.

More on dynamic keyword here – Official documentation on MSDN

Dissecting the C# 4.0 Dynamic programming – Good article about the inner workings of dynamic