Brian Genisio's House of Bilz

  Home  |   Contact  |   Syndication    |   Login
  72 Posts | 0 Stories | 186 Comments | 0 Trackbacks

News

Locations of visitors to this page

Archives

Post Categories

Who am I?

Friday, June 04, 2010 #

More Adventures in MVVM Shout it

In this post, I am going to explore how I prefer to attach ViewModels to my Views.  I have published the code to my ViewModelSupport project on CodePlex in case you'd like to see how it works along with some examples. 

Some History

My approach to View-First ViewModel creation has evolved over time.  I have constructed ViewModels in code-behind.  I have instantiated ViewModels in the resources sectoin of the view. I have used Prism to resolve ViewModels via Dependency Injection. I have created attached properties that use Dependency Injection containers underneath.  Of all these approaches, I continue to find issues either in composability, blendability or maintainability. 

Laurent Bugnion came up with a pretty good approach in MVVM Light Toolkit with his ViewModelLocator, but as John Papa points out, it has maintenance issues.  John paired up with Glen Block to make the ViewModelLocator more generic by using MEF to compose ViewModels.  It is a great approach, but I don’t like baking in specific resolution technologies into the ViewModelSupport project.

I bring these people up, not to name drop, but to give them credit for the place I finally landed in my journey to resolve ViewModels.  I have come up with my own version of the ViewModelLocator that is both generic and container agnostic.  The solution is blendable, configurable and simple to use.  Use any resolution mechanism you want: MEF, Unity, Ninject, Activator.Create, Lookup Tables, new, whatever.

How to use the locator

1. Create a class to contain your resolution configuration:

public class YourViewModelResolver: IViewModelResolver
{
    private YourFavoriteContainer container = new YourFavoriteContainer(); 

    public YourViewModelResolver()
    {
        // Configure your container
    } 

    public object Resolve(string viewModelName)
    {
        return container.Resolve(viewModelName);        
    }
} 

Examples of doing this are on CodePlex for MEF, Unity and Activator.CreateInstance.

2. Create your ViewModelLocator with your custom resolver in App.xaml:

<VMS:ViewModelLocator x:Key="ViewModelLocator">
    <VMS:ViewModelLocator.Resolver>
        <local:YourViewModelResolver />
    </VMS:ViewModelLocator.Resolver>
</VMS:ViewModelLocator> 

3. Hook up your data context whenever you want a ViewModel (WPF):

<Border DataContext="{Binding YourViewModelName, Source={StaticResource ViewModelLocator}}"> 

This example uses dynamic properties on the ViewModelLocator and passes the name to your resolver to figure out how to compose it.

4. What about Silverlight?

Good question.  You can't bind to dynamic properties in Silverlight 4 (crossing my fingers for Silverlight 5), but you CAN use string indexing:

<Border DataContext="{Binding [YourViewModelName], Source={StaticResource ViewModelLocator}}"> 

But, as John Papa points out in his article, there is a silly bug in Silverlight 4 (as of this writing) that will call into the indexer 6 times when it binds.  While this is little more than a nuisance when getting most properties, it can be much more of an issue when you are resolving ViewModels six times.  If this gets in your way, the solution (as pointed out by John), is to use an IndexConverter (instantiated in App.xaml and also included in the project):

<Border DataContext="{Binding Source={StaticResource ViewModelLocator}, 
    Converter={StaticResource IndexConverter}, ConverterParameter=YourViewModelName}">

It is a bit uglier than the WPF version (this method will also work in WPF if you prefer), but it is still not all that bad. 

Conclusion

This approach works really well (I suppose I am a bit biased).  It allows for composability from any mechanisim you choose.  It is blendable (consider serving up different objects in Design Mode if you wish... or different constructors… whatever makes sense to you).  It works in Cider.  It is configurable.  It is flexible.  It is the best way I have found to manage View-First ViewModel hookups.  Thanks to the guys mentioned in this article for getting me to something I love using.  Enjoy.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Wednesday, June 02, 2010 #

I am currently working on a multi-touch application using WPF.  One thing that has been irritating me with this development is an automatic navigation forward/back command that is bound to forward and backwards flicks.  Many of my touch-based interactions were being thwarted by gestures picked up by WPF as navigation.  I just wanted to disable this behavior.

My programmatic back/forward calls are not affected by this change, which is nice.  Here is how I did it:  In my main window, I added the following command bindings:

<NavigationWindow.CommandBindings>
    <CommandBinding Command="NavigationCommands.BrowseBack" Executed="DoNothing" />
    <CommandBinding Command="NavigationCommands.BrowseForward" Executed="DoNothing" />
</NavigationWindow.CommandBindings>

Then, the DoNothing method in the code-behind does nothing:

private void DoNothing(object sender, ExecutedRoutedEventArgs e) { }



There may be a better way to do this, but I haven’t found one.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Friday, May 14, 2010 #

More Adventures in MVVM Shout it kick it on DotNetKicks.com

EDIT: Here is why I love blogging and sharing code so much: Putting your ideas and code out into the public space always manages to add value to the ideas that were originally posted.  Case in point: Tobias Richling commented on this post with a fantastic refinement to the Silverlight dynamic property binding.  There is a much more simple way to bind against these dynamic properties (including automatic commanding) than my first approach.  I have incorporated the changes to the CodePlex site and I have edited this post to reflect the changes.  Thanks again, to Tobias for the suggestion.

In my last post, I outlined the powerful features that are available in the ViewModelSupport.  It takes advantage of the dynamic features of C# 4.0 (as well as some 3.0 goodies) to help eliminate the plumbing that often comes with writing ViewModels.  If you are interested in learning about the capabilities, please take a look at that post and look at the code on CodePlex

When I wrote about the ViewModel base class, I complained that the features did not work in Silverlight because as of 4.0, it does not support binding to dynamic properties.  Although I still think this is a bummer, I am happy to say that there is a workaround.  In the Silverlight version of my base class, I include a string indexer for getting and setting properties that lets you bind to dynamic properties in the ViewModelBase, especially the convention-based commands that the base class supports.

For example, with a View Model that looks like this:

public class ExampleViewModel : ViewModelBase
{
    public void Execute_MyCommand()
    {
        Set("Text", "Foo");
    }
}

The view can bind to the dynamic property (Text) and the convention-based command (MyCommand) with the following XAML.

<TextBlock Text="{Binding [Text]}" Margin="5" />
<Button Content="Execute MyCommand" Command="{Binding [MyCommand]}" Margin="5" />

Notice the square brackets around the name of the property.  Of course, it is not as perfect as binding to Text and MyCommand like you can in WPF, but it is better than having a failed feature.  This allows you to share your ViewModels between WPF and Silverlight very easily. 

<BeatDeadHorse>Hopefully, in Silverlight 5.0, we will see binding to dynamic properties more directly????</BeatDeadHorse>

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Saturday, May 08, 2010 #

More Adventures in MVVM Shout it kick it on DotNetKicks.com

First, I’d like to say: THIS IS NOT A NEW MVVM FRAMEWORK. I tend to believe that MVVM support code should be specific to the system you are building and the developers working on it.  I have yet to find an MVVM framework that does everything I want it to without doing too much.  Don’t get me wrong… there are some good frameworks out there.  I just like to pick and choose things that make sense for me.  As of Silveright 4, they don’t support binding to dynamic properties, so some of the capabilities are lost, but with a little hacking we can make it work.

That being said, I want to share my ViewModel base class with the world.  I have had several conversations with people about the problems I have solved using this ViewModel base.  A while back, I posted an article about some experiments with a “Rails Inspired ViewModel”.  What followed from those ideas was a ViewModel base class that I take with me and use in my projects.  It has a lot of features, all designed to reduce the friction in writing view models. I have put the code out on Codeplex under the project: ViewModelSupport.

Finally, this article focuses on the ViewModel and only glosses over the View and the Model.  Without all three, you don’t have MVVM.  But this base class is for the ViewModel, so that is what I am focusing on.

Features:

  1. Automatic Command Plumbing
  2. Property Change Notification
  3. Strongly Typed Property Getter/Setters
  4. Dynamic Properties
  5. Default Property values
  6. Derived Properties
  7. Automatic Method Execution
  8. Command CanExecute Change Notification
  9. Design-Time Detection
  10. What about Silverlight?

Automatic Command Plumbing

This feature takes the plumbing out of creating commands.  The common pattern for commands in a ViewModel is to have an Execute method as well as an optional CanExecute method.  To plumb that together, you create an ICommand Property, and set it in the constructor like so:

Before

public class AutomaticCommandViewModel
{
    public AutomaticCommandViewModel()
    {
        MyCommand = new DelegateCommand(Execute_MyCommand, CanExecute_MyCommand);
    }

    public void Execute_MyCommand()
    {
        // Do something
    }

    public bool CanExecute_MyCommand()
    {
        // Are we in a state to do something?
        return true;
    }

    public DelegateCommand MyCommand { get; private set; }
}

With the base class, this plumbing is automatic and the property (MyCommand of type ICommand) is created for you.  The base class uses the convention that methods be prefixed with Execute_ and CanExecute_ in order to be plumbed into commands with the property name after the prefix.  You are left to be expressive with your behavior without the plumbing.  If you are wondering how CanExecuteChanged is raised, see the later section “Command CanExecute Change Notification”.

After

public class AutomaticCommandViewModel : ViewModelBase
{
    public void Execute_MyCommand()
    {
        // Do something
    }

    public bool CanExecute_MyCommand()
    {
        // Are we in a state to do something?
        return true;
    }
}

 

Property Change Notification

One thing that always kills me when implementing ViewModels is how to make properties that notify when they change (via the INotifyPropertyChanged interface).  There have been many attempts to make this more automatic.  My base class includes one option.  There are others, but I feel like this works best for me.

The common pattern (without my base class) is to create a private backing store for the variable and specify a getter that returns the private field.  The setter will set the private field and fire an event that notifies the change, only if the value has changed.

Before

public class PropertyHelpersViewModel : INotifyPropertyChanged
{
    private string text;
    public string Text
    {
        get { return text; }
        set
        {
            if(text != value)
            {
                text = value;
                RaisePropertyChanged("Text");
            }
        }
    }

    protected void RaisePropertyChanged(string propertyName)
    {
        var handlers = PropertyChanged;
        if(handlers != null)
            handlers(this, new PropertyChangedEventArgs(propertyName));
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

This way of defining properties is error-prone and tedious.  Too much plumbing.  My base class eliminates much of that plumbing with the same functionality:

After

public class PropertyHelpersViewModel : ViewModelBase
{
    public string Text
    {
        get { return Get<string>("Text"); }
        set { Set("Text", value);}
    }
}

 

Strongly Typed Property Getters/Setters

It turns out that we can do better than that.  We are using a strongly typed language where the use of “Magic Strings” is often frowned upon.  Lets make the names in the getters and setters strongly typed:

A refinement

public class PropertyHelpersViewModel : ViewModelBase
{
    public string Text
    {
        get { return Get(() => Text); }
        set { Set(() => Text, value); }
    }
}

 

Dynamic Properties

In C# 4.0, we have the ability to program statically OR dynamically.  This base class lets us leverage the powerful dynamic capabilities in our ecosystem. (This is how the automatic commands are implemented, BTW)  By calling Set(“Foo”, 1), you have now created a dynamic property called Foo.  It can be bound against like any static property.  The opportunities are endless.  One great way to exploit this behavior is if you have a customizable view engine with templates that bind to properties defined by the user.  The base class just needs to create the dynamic properties at runtime from information in the model, and the custom template can bind even though the static properties do not exist. All dynamic properties still benefit from the notifiable capabilities that static properties do.

For any nay-sayers out there that don’t like using the dynamic features of C#, just remember this: the act of binding the View to a ViewModel is dynamic already.  Why not exploit it?  Get over it :)

Just declare the property dynamically

public class DynamicPropertyViewModel : ViewModelBase
{
    public DynamicPropertyViewModel()
    {
        Set("Foo", "Bar");
    }
}

Then reference it normally

<TextBlock Text="{Binding Foo}" />

 

Default Property Values

The Get() method also allows for default properties to be set.  Don’t set them in the constructor.  Set them in the property and keep the related code together:

public string Text
{
    get { return Get(() => Text, "This is the default value"); }
    set { Set(() => Text, value);}
}

 

Derived Properties

This is something I blogged about a while back in more detail.  This feature came from the chaining of property notifications when one property affects the results of another, like this:

Before

public class DependantPropertiesViewModel : ViewModelBase
{
    public double Score
    {
        get { return Get(() => Score); }
        set
        {
            Set(() => Score, value);
            RaisePropertyChanged("Percentage");
            RaisePropertyChanged("Output");
        }
    }

    public int Percentage
    {
        get { return (int)(100 * Score); }
    }

    public string Output
    {
        get { return "You scored " + Percentage + "%."; }
    }
}

The problem is: The setter for Score has to be responsible for notifying the world that Percentage and Output have also changed.  This, to me, is backwards.    It certainly violates the “Single Responsibility Principle.” I have been bitten in the rear more than once by problems created from code like this.  What we really want to do is invert the dependency.  Let the Percentage property declare that it changes when the Score Property changes.

After

public class DependantPropertiesViewModel : ViewModelBase
{
    public double Score
    {
        get { return Get(() => Score); }
        set { Set(() => Score, value); }
    }

    [DependsUpon("Score")]
    public int Percentage
    {
        get { return (int)(100 * Score); }
    }

    [DependsUpon("Percentage")]
    public string Output
    {
        get { return "You scored " + Percentage + "%."; }
    }
}

 

Automatic Method Execution

This one is extremely similar to the previous, but it deals with method execution as opposed to property.  When you want to execute a method triggered by property changes, let the method declare the dependency instead of the other way around.

Before

public class DependantMethodsViewModel : ViewModelBase
{
    public double Score
    {
        get { return Get(() => Score); }
        set
        {
            Set(() => Score, value);
            WhenScoreChanges();
        }
    }

    public void WhenScoreChanges()
    {
        // Handle this case
    }
}

After

    public class DependantMethodsViewModel : ViewModelBase
    {
        public double Score
        {
            get { return Get(() => Score); }
            set { Set(() => Score, value); }
        }

        [DependsUpon("Score")]
        public void WhenScoreChanges()
        {
            // Handle this case
        }
    }

 

Command CanExecute Change Notification

Back to Commands.  One of the responsibilities of commands that implement ICommand – it must fire an event declaring that CanExecute() needs to be re-evaluated.  I wanted to wait until we got past a few concepts before explaining this behavior.  You can use the same mechanism here to fire off the change.  In the CanExecute_ method, declare the property that it depends upon.  When that property changes, the command will fire a CanExecuteChanged event, telling the View to re-evaluate the state of the command.  The View will make appropriate adjustments, like disabling the button.

DependsUpon works on CanExecute methods as well

public class CanExecuteViewModel : ViewModelBase
{
    public void Execute_MakeLower()
    {
        Output = Input.ToLower();
    }

    [DependsUpon("Input")]
    public bool CanExecute_MakeLower()
    {
        return !string.IsNullOrWhiteSpace(Input);
    }

    public string Input
    {
        get { return Get(() => Input); }
        set { Set(() => Input, value);}
    }

    public string Output
    {
        get { return Get(() => Output); }
        set { Set(() => Output, value); }
    }
}

 

Design-Time Detection

If you want to add design-time data to your ViewModel, the base class has a property that lets you ask if you are in the designer.  You can then set some default values that let your designer see what things might look like in runtime.

Use the IsInDesignMode property

public DependantPropertiesViewModel()
{
    if(IsInDesignMode)
    {
        Score = .5;
    }
}

 

What About Silverlight?

Although you cannot bind directly to dynamic properties and convention-based commands, you CAN bind using a value converter.  This little hack is explained in more detail in my next post.  Other than that slight difference, all of these features work in Silverlight just as they do in WPF.  You don’t need to code your ViewModels any differently to get it to work, which aids in the sharing of behavior between WPF and Silverlight.

 

Good to go?

So, that concludes the feature explanation of my ViewModel base class.  Feel free to take it, fork it, whatever.  It is hosted on CodePlex.  When I find other useful additions, I will add them to the public repository.  I use this base class every day.  It is mature, and well tested.  If, however, you find any problems with it, please let me know!  Also, feel free to suggest patches to me via the CodePlex site.  :)

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Friday, April 16, 2010 #

Tomorrow, I will be speaking in Grand Rapids at the Silverlight Firestarter.  It is a one day event intended to get people bootstrapped with Silverlight.  I will be giving the “Advanced Topics” presentation.  I have decided to run it as a series of “Lightning Talks”.  The idea is to give a lot of breadth so you know that the topic exists and move quickly between them.  To go along with the talks, here are a bunch of links that you might find useful:

MVVM

http://msdn.microsoft.com/en-us/magazine/dd458800.aspx
http://msdn.microsoft.com/en-us/magazine/dd419663.aspx
http://channel9.msdn.com/shows/Continuum/MVVM/
http://karlshifflett.wordpress.com/2008/11/08/learning-wpf-m-v-vm/
http://johnpapa.net/silverlight/5-minute-overview-of-mvvm-in-silverlight/


Good MVVM Frameworks
http://www.galasoft.ch/mvvm/getstarted/
http://caliburn.codeplex.com/Wikipage

 

Prism

http://compositewpf.codeplex.com/
http://mtaulty.com/CommunityServer/blogs/mike_taultys_blog/archive/2009/10/27/prism-and-silverlight-screencasts-on-channel-9.aspx
http://www.grumpydev.com/2009/07/04/why-shouldn%E2%80%99t-i-use-prism/

 

Unit Testing

Silverlight Unit Testing Framework
http://code.msdn.microsoft.com/silverlightut
http://silverlight.codeplex.com/
http://www.jeff.wilcox.name/2008/03/silverlight2-unit-testing/


NUnit Testing with Silverlight
http://weblogs.asp.net/nunitaddin/archive/2008/05/01/silverlight-nunit-projects.aspx

Useful Testing Tools
http://testdriven.net/
http://nunit.org/
http://code.google.com/p/moq/
http://www.ayende.com/projects/rhino-mocks.aspx

 

Navigation Framework

http://www.silverlightshow.net/items/The-Silverlight-3-Navigation-Framework.aspx
http://www.silverlight.net/learn/videos/silverlight-videos/navigation-framework/

 

Farseer Physics Engine

http://farseerphysics.codeplex.com/Wikipage
http://physicshelper.codeplex.com/Wikipage http://www.andybeaulieu.com/Home/tabid/67/Default.aspx

 

Windows Phone 7

http://www.silverlight.net/getstarted/devices/windows-phone/
http://msdn.microsoft.com/en-us/library/ff402535%28VS.92%29.aspx

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Saturday, March 27, 2010 #

Shout it kick it on DotNetKicks.com

Part 1

After I explained my motivation for using YAML instead of XML for my data, I got a lot of people asking me what type of tooling is available in the .Net space for consuming YAML.  In this post, I will discuss a nice tooling option as well as describe some small modifications to leverage the extremely powerful dynamic capabilities of C# 4.0.  I will be referring to the following YAML file throughout this post

Recipe:
  Title:         Macaroni and Cheese
  Description:   My favorite comfort food.
  Author:        Brian Genisio
  TimeToPrepare: 30 Minutes
  Ingredients:
    -
      Name:     Cheese
      Quantity: 3
      Units:    cups
    -
      Name:     Macaroni
      Quantity: 16
      Units:    oz
  Steps:
    -
      Number: 1
      Description: Cook the macaroni
    -
      Number: 2
      Description: Melt the cheese
    -
      Number: 3
      Description: Mix the cooked macaroni with the melted cheese

Tooling

It turns out that there are several implementations of YAML tools out there.  The neatest one, in my opinion, is YAML for .NET, Visual Studio and Powershell.  It includes a great editor plug-in for Visual Studio as well as YamlCore, which is a parsing engine for .Net.  It is in active development still, but it is certainly enough to get you going with YAML in .Net. 

Start by referenceing YamlCore.dll, load your document, and you are on your way.  Here is an example of using the parser to get the title of the Recipe:

var yaml = YamlLanguage.FileTo("Data.yaml") as Hashtable;
var recipe = yaml["Recipe"] as Hashtable;
var title = recipe["Title"] as string;

In a similar way, you can access data in the Ingredients set:

var yaml = YamlLanguage.FileTo("Data.yaml") as Hashtable;
var recipe = yaml["Recipe"] as Hashtable;
var ingredients = recipe["Ingredients"] as ArrayList;

foreach (Hashtable ingredient in ingredients)
{
    var name = ingredient["Name"] as string;
}

You may have noticed that YamlCore uses non-generic Hashtables and ArrayLists.  This is because YamlCore was designed to work in all .Net versions, including 1.0.  Everything in the parsed tree is one of two things: Hashtable, ArrayList or Value type (usually String).  This translates well to the YAML structure where everything is either a Map, a Set or a Value. 

Taking it further

Personally, I really dislike writing code like this.  Years ago, I promised myself to never write the words Hashtable or ArrayList in my .Net code again.  They are ugly, mostly depreciated collections that existed before we got generics in C# 2.0.  Now, especially that we have dynamic capabilities in C# 4.0, we can do a lot better than this.  With a relatively small amount of code, you can wrap the Hashtables and Array lists with a dynamic wrapper (wrapper code at the bottom of this post).  The same code can be re-written to look like this:

dynamic doc = YamlDoc.Load("Data.yaml");
var title = doc.Recipe.Title;

And

dynamic doc = YamlDoc.Load("Data.yaml");
foreach (dynamic ingredient in doc.Recipe.Ingredients)
{
    var name = ingredient.Name;
}

I significantly prefer this code over the previous.  That’s not all… the magic really happens when we take this concept into WPF.  With a single line of code, you can bind to the data dynamically in the view:

DataContext = YamlDoc.Load("Data.yaml");

Then, your XAML is extremely straight-forward (Nothing else.  No static types, no adapter code.  Nothing):

<StackPanel>
    <TextBlock Text="{Binding Recipe.Title}" />
    <TextBlock Text="{Binding Recipe.Description}" />
    <TextBlock Text="{Binding Recipe.Author}" />
    <TextBlock Text="{Binding Recipe.TimeToPrepare}" />
    
    <TextBlock Text="Ingredients:" FontWeight="Bold" /> 
    <ItemsControl ItemsSource="{Binding Recipe.Ingredients}" Margin="10,0,0,0">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Quantity}" />
                    <TextBlock Text=" " />
                    <TextBlock Text="{Binding Units}" />
                    <TextBlock Text=" of " />
                    <TextBlock Text="{Binding Name}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

    <TextBlock Text="Steps:" FontWeight="Bold" />
    <ItemsControl ItemsSource="{Binding Recipe.Steps}" Margin="10,0,0,0">
        <ItemsControl.ItemTemplate>
            <DataTemplate>
                <StackPanel Orientation="Horizontal">
                    <TextBlock Text="{Binding Number}" />
                    <TextBlock Text=": " />
                    <TextBlock Text="{Binding Description}" />
                </StackPanel>
            </DataTemplate>
        </ItemsControl.ItemTemplate>
    </ItemsControl>

</StackPanel>

This nifty XAML binding trick only works in WPF, unfortunately.  Silverlight handles binding differently, so they don’t support binding to dynamic objects as of late (March 2010).  This, in my opinion, is a major lacking feature in Silverlight and I really hope we will see this feature available to us in Silverlight 4 Release.  (I am not very optimistic for Silverlight 4, but I can hope for the feature in Silverlight 5, can’t I?)

Conclusion

I still have a few things I want to say about using YAML in the .Net space including de-serialization and using IronRuby for your YAML parser, but this post is hopefully enough to see how easy it is to incorporate YAML documents in your code.

Codeplex Site for YAML tools

Dynamic wrapper for YamlCore

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Thursday, March 11, 2010 #

I recently gave a presentation on Prism at the Ann Arbor .Net Users Group.  I have made my slides and demo available for download:

Slides   Demo

Some interesting links associated with prism:

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Tuesday, March 02, 2010 #

Thanks to all who came to the MVVM jam tonight.  In case you wanted to see what a completed solution looks like, you can download it here.  There are many tweaks that can be made, and it is certainly not the only solution… but hopefully, it helps to understand how the MVVM pattern can be applied.

Next week (Wednesday, March 9th) , I will be giving a presentation on Prism for Silverlight and WPF at the Ann Arbor .Net Users’ Group.  It is an eyes-forward talk about more patterns similar to MVVM.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Saturday, February 27, 2010 #

For those in the Ann Arbor, Michigan area, you might be familiar with the “Come Jam With Us” project.  Every week, we get together for an hour and code on a particular topic.  It is usually led by one or two people and the rest of the group codes along in order to learn about the topic at hand.  It is a really great forum for learning new concepts and technologies.

This week, on Tuesday, March 2nd, I will be hosting an MVVM jam session at 5:30 (directions).  I will be taking you through the process of transforming a “Ball of Mud” application to use the MVVM architecture.  We will do this in a test-driven way, so you can see the testability story of MVVM.

The prerequisites are very simple:

1. Visual Studio 2008 or 2010 or Visual Studio Express (free)

2. Download the sample project.  It is a rudimentary Twitter search application written with WPF.

3. You should have some way of running NUnit tests from Visual Studio.  If you have ReSharper or TestDriven.Net (or any similar plug-in), then you are all set.  ReSharper has a free 30 day trial and TestDriven.Net has a free version for personal use.

I hope to see you there!

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati

Sunday, February 21, 2010 #

Part 2

This is the first in a many-part series in which I will be writing about using YAML in the .Net space – particularly within C#.  I will cover the whys, the hows, and show some tricks using the dynamic capabilities of C# when using YAML.  I might even explore IronRuby a bit.

Why YAML?

I got the chance to sit in on four days of Ruby on Rails (RoR) training from Joe Obrien a few weeks ago.  I hadn’t played with RoR in a few months, and this training was amazingly useful.  I always like to see what I can take away from an environment like this for the work I do more regularly.

In this case, one of the things I took away with me was YAML.  Let me start with some background.

Over 10 years ago, when XML was touted as a human-readable data format, I had to scoff.  Was XML really human readable?  Well, from a software developer’s perspective, it sure is a lot nicer than binary.  But, from a REAL human’s perspective, XML is just barely more readable than Klingon.  This is mostly due to the verbose nature of XML and the often ranted about “angle bracket tax”.   

10 years later, we are still using XML as our primary data transfer/persistence/definition format.  I certainly don’t mind using XML in a world where I (a human) rarely need to read the data.  I am fine with keeping the data in my REST services as XML, for instance.  In that case, my tools abstract it away and I don’t have to read it very often.

Currently, my colleague Mike Woelmer and I have a client who needs us to develop an engine where the business rules will be entered by a human (not a developer) and will change as the project evolves.  The data/rules will be set in stone once the project is complete.  XML is a bad choice for this, since a non-technical person will be entering the rules.  At the same time, developing a UI for this is too time consuming and out of the scope of the project.  My first thought: a Doman Specific Language (DSL)!  That would certainly lend well to my requirements.  As much as I liked that idea, I didn’t have time to create a DSL either, especially while spiking.  Then I remembered back to my RoR training.  I remembered a data format called YAML that they used for some of the configuration files.  It was a VERY easy-to-read, hierarchical data format.

To illustrate the difference between XML and YAML, here is a simple example of some rather easy-to-read XML defining the data for a recipe (unrelated to my current project):

<recipe>
  <title>Macaroni and Cheese</title>
  <description>My favorite comfort food.</description>
  <author>Brian Genisio</author>
  <timeToPrepare>30 Minutes</timeToPrepare>
  <ingredients>
    <ingredient>
      <name>Cheese</name>
      <quantity>3</quantity>
      <units>cups</units>
    </ingredient>
    <ingredient>
      <name>Macaroni</name>
      <quantity>16</quantity>
      <units>oz</units>
    </ingredient>
  </ingredients>
  <steps>
    <step>
      <number>1</number>
      <description>Cook the macaroni</description>
    <step>
    <step>
      <number>2</number>
      <description>Melt the cheese</description>
    </step>
    <step>
      <number>3</number>
      <description>Mix the cooked macaroni with the melted cheese</description>
    </step>
  </steps>
</recipe>

Here is the exact same data described with YAML:

Recipe:
  Title:         Macaroni and Cheese
  Description:   My favorite comfort food.
  Author:        Brian Genisio
  TimeToPrepare: 30 Minutes
  Ingredients:
    -
      Name:     Cheese
      Quantity: 3
      Units:    cups
    -
      Name:     Macaroni
      Quantity: 16
      Units:    oz
  Steps:
    -
      Number: 1
      Description: Cook the macaroni
    -
      Number: 2
      Description: Melt the cheese
    -
      Number: 3
      Description: Mix the cooked macaroni with the melted cheese

Although this is a very simple example, I would ask you: Which one would you rather present to a customer when talking about the data and business rules?  Which one would YOU rather look at when developing your software?

In my next couple of posts, I will discuss some tools available to you in the .Net space and some nifty C# 4.0 techniques for working with the data.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati