Wintellect  

Browse by Tags

All Tags » silverlight   (RSS)

The visual state aggregator. What is it?

How many times have you found yourself adding freak methods and commands to your Silverlight projects just to manage some animations? It's a common issue, and I've even built solutions like the IAnimationDelegate to help solve the problem. While it works, one thing always bothered me.

I know it's a ViewModel, so it does do things with the view, but should I really be that concerned with what's going on with the UI? In other words, while it's nice that I can abstract the firing of an animation behind an Action call and use a command to set it off and then unit test without a real Storyboard object, it has always felt just a little bit dirty to do it that way.

Download the source code for this post

I also am a big fan of the VisualStateManager and got to thinking about whether I ever really need a named story board outside of VSM other than programmatic or complex ones that have to be built at runtime. Looking at the current application I'm working with, which uses some very heavy animated transitions, I realized that all of these could be boiled down to the VSM.

Consider this scenario: we have two panels. Panel A is active, Panel B is collapsed and off the screen. These are independent controls that probably don't even share the same view model.

In this case, I'm going to give Panel A a visual state of "Foreground" and Panel B a visual state of "Offscreen". If you're scratching your head about the visual state manager, take a look at Justin Angel's excellent post on the topic. You can create your own groups and states and have both "final" states and transition states.

Quick Tip: Visibility

Probably more people abuse visibility by wiring in delegates or commands that set visibility to visible or collapsed (I'm guilty as well) when it's not needed. Stop thinking in terms of visible, collapsed, etc, and start thinking in terms of states. With the visual state manager, this is what your states might look like:

<VisualStateGroup x:Name="TransitionStates">
    <VisualStateGroup.States>
        <VisualState x:Name="Show">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.00000" Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Visibility)">
                    <DiscreteObjectKeyFrame KeyTime="00:00:00">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Visible</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
            </Storyboard>
        </VisualState>
        <VisualState x:Name="Hide">
            <Storyboard>
                <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Visibility)">                                
                    <DiscreteObjectKeyFrame KeyTime="00:00:00">
                        <DiscreteObjectKeyFrame.Value>
                            <Visibility>Collapsed</Visibility>
                        </DiscreteObjectKeyFrame.Value>
                    </DiscreteObjectKeyFrame>
                </ObjectAnimationUsingKeyFrames>
             </Storyboard>
        </VisualState>
    </VisualStateGroup.States>
</VisualStateGroup>

Now you can simply go to a hide or show state, and if you want transitions, you add them to the VSM and voilĂ ! It works ... no need to hard code the transition from collapsed to visible. Now back to our regularly scheduled program ...

When an event happens on Panel A, it goes to the "Background" state and the Panel B goes to the "Onscreen" state. It looks like this:

Then, when we close Panel B, it goes back to "Offscreen" and the Panel A comes back to foreground. By using visual states, we can manipulate the plane projection and scale transform properties as well as the visibility to achieve our results, and use animations.

But here's the rub: how can I fire the event in "A" and then let "B" know it's time to change states?

The most common way I've seen goes something like this:

Put an Action or delegate of some sort in a view model. In the code behind or using a behavior (more clever than code behind), attach the desired visual state to the action. Make a command object, and while the command does it's thing, go ahead and call the delegate which in turn flips the visual state. For example, my view model might have:

...
public Action SwapPanelA { get; set; }
...

And in the code-behind, I can wire it up like this:

...
ViewModel.SwapPanelA = () => VisualStateManager.GoToState(this, "Foreground", true);
...

And so on and so on. While this certainly decouples it a bit, it also forces us to change the design of our view model to accommodate the transitions. What if we have four controls participating in the same event? Do we wire up a bunch of references for the view model? Does a control bring in a view model only for the sake of wiring in it's animations?

No, no, no. All wrong (but again, let me elaborate these are things I've tried and worked with in the past, so don't feel bad if you've been doing the same things).

It hit me that I really needed to decouple view actions from business actions. When I click Panel A, the business action might be to call out to a web service to get data to populate in Panel B. I shouldn't care about any transitions.

The view action would be the movement of the panels.

So how do we decouple this? Enter the Visual State Aggregator. What I decided to do was build an aggregator that could respond to published events by flipping view states. This includes a behavior to participate in an event, and a trigger to push the event out. The first piece is a subscription. A subscription contains a weak reference to a control, an event the control is listening for, and the state the control should go to when the event fires (including whether or not to use transitions). Here is VisualStateSubscription:

public class VisualStateSubscription
{
    private readonly WeakReference _targetControl;
    private readonly string _state;
    private readonly bool _useTransitions;
    private readonly string _event;
    private Guid _id = Guid.NewGuid();

    public VisualStateSubscription(Control control, string vsmEvent, string state, bool useTransitions)
    {
        _targetControl = new WeakReference(control);
        _event = vsmEvent;
        _state = state;
        _useTransitions = useTransitions; 
    }

    public bool IsExpired
    {
        get
        {
            return _targetControl == null || !_targetControl.IsAlive || _targetControl.Target == null; 
        }
    }

    public void RaiseEvent(string eventName)
    {
        if (!IsExpired && _event.Equals(eventName))
        {
            var control = _targetControl.Target as Control;
            VisualStateManager.GoToState(control, _state, _useTransitions); 
        }
    }

    public override bool Equals(object obj)
    {
        return obj is VisualStateSubscription && ((VisualStateSubscription) obj)._id.Equals(_id);
    }

    public override int GetHashCode()
    {
        return _id.GetHashCode();
    }
}

Next comes the aggregator. It contains the list of subscriptions. It will provide a means to subscribe, as well as a means to publish the event. I decided to use the Managed Extensibility Framework (MEF) to wire it in, so it also gets exported:

[Export]
public class VisualStateAggregator
{
    private readonly List<VisualStateSubscription> _subscribers = new List<VisualStateSubscription>();

    public void AddSubscription(Control control, string eventName, string stateName, bool useTransitions)
    {
        _subscribers.Add(new VisualStateSubscription(control, eventName, stateName, useTransitions));
    }

    public void PublishEvent(string eventName)
    {
        var expired = new List<VisualStateSubscription>();
        
        foreach(var subscriber in _subscribers)
        {
            if (subscriber.IsExpired)
            {
                expired.Add(subscriber);
            }
            else
            {
                subscriber.RaiseEvent(eventName);
            }
        }

        expired.ForEach(s=>_subscribers.Remove(s));
    }
}

Notice that I take advantage of the event to iterate the subscriptions and remove any that have expired (this means the control went out of scope, and we don't want to force it to hang on with a reference).

Now there is a behavior to subscribe. First, I want to indicate when a control should participate. This behavior can be attached to any FrameworkElement. Because the visual state manager only operates on controls, I'll walk the visual tree to find the highest containing control for that element. This way, if you have a grid (which is not a control) inside a user control, it will find the user control and use that as the target. If you don't want to use MEF, just give the aggregator a singleton pattern and reference it here instead of using the import.

public class VisualStateSubscriptionBehavior : Behavior<FrameworkElement> 
{        
    public VisualStateSubscriptionBehavior()
    {
        CompositionInitializer.SatisfyImports(this);
    }

    [Import]
    public VisualStateAggregator Aggregator { get; set; }

    public string EventName { get; set; }

    public string StateName { get; set; }

    public bool UseTransitions { get; set; }

    protected override void OnAttached()
    {
        AssociatedObject.Loaded += AssociatedObject_Loaded;
    }

    void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
    {
        Control control = null;

        if (AssociatedObject is Control)
        {
            control = AssociatedObject as Control;
        }
        else
        {
            DependencyObject parent = VisualTreeHelper.GetParent(AssociatedObject);
            while (!(parent is Control) && parent != null)
            {
                parent = VisualTreeHelper.GetParent(parent);
            }
            if (parent is Control)
            {
                control = parent as Control; 
            }
        }

        if (control != null)
        {
            Aggregator.AddSubscription(control, EventName, StateName, UseTransitions);
        }
    }
}

Notice we hook into the loaded event so the visual tree is built prior to walking the tree for our hooks.

Of course, this implementation gives us a weak or "magic string" event, you could wire that to an enumeration to make that strongly typed. Let's call the event of swapping out Panel A "ActivatePanelB" and the event of bring it back "DeactivatePanelB". Panel A subscribes like this:

<UserControl>
   <Grid x:Name="LayoutRoot">
   <i:Interaction.Behaviors>
      <vsm:VisualStateSubscriptionBehavior EventName="ActivatePanelB" StateName="Background" UseTransitions="True"/>
      <vsm:VisualStateSubscriptionBehavior EventName="DeactivatePanelB" StateName="Foreground" UseTransitions="True"/>
   </i:Interaction.Behaviors>
   </Grid>
</UserControl>

Then Panel B may subscribe like this:

<UserControl>
   <Grid x:Name="LayoutRoot">
   <i:Interaction.Behaviors>
      <vsm:VisualStateSubscriptionBehavior EventName="ActivatePanelB" StateName="Onscreen" UseTransitions="True"/>
      <vsm:VisualStateSubscriptionBehavior EventName="DeactivatePanelB" StateName="Offscreen" UseTransitions="True"/>
   </i:Interaction.Behaviors>
   </Grid>
</UserControl>

I'm assuming the visual states are wired up with those names.

Now we need something to trigger an event. We use a trigger action for that. The trigger class is very simple, as it simply needs to publish the event. Because we are using a trigger action, we can bind to any routed event in order for the transition to fire, so this would work for a mouseover that had to animate a separate control for example.

public class VisualStateTrigger : TriggerAction<FrameworkElement> 
{
    public VisualStateTrigger()
    {
        CompositionInitializer.SatisfyImports(this);
    }

    [Import]
    public VisualStateAggregator Aggregator { get; set; }

    public string EventName { get; set; }

    protected override void Invoke(object parameter)
    {
        Aggregator.PublishEvent(EventName);
    }
}

To trigger this, let's say we have a fancy grid with information and clicking on the grid itself fires the event. In Panel A, we'd wire the event like this:

<Grid>
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="MouseLeftButtonUp">
         <vsm:VisualStateTrigger EventName="ActivatePanelB"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
</Grid>

In Panel B, we might have a close button:

<Button Content="Close">
   <i:Interaction.Triggers>
      <i:EventTrigger EventName="Click">
         <vsm:VisualStateTrigger EventName="DeactivatePanelB"/>
      </i:EventTrigger>
   </i:Interaction.Triggers>
</Button>

And that's it! Without any view models involved, entirely in the UI with the help of our behaviors, we've aggregated the visual state transitions. When you click on the grid, panel A will flip to the "Background" state and animate away, while panel B will flip to the "Onscreen" state and slide in.

Here is an example for you to have fun with:

When you grab the source, you'll find there are absolutely no code-behinds whatsoever other than what is automatically generated. While Panel A and Panel B are completely separate controls that know nothing about each other, the common subscription to a aggregate event coordinates their actions when Panel A is clicked or the close button on Panel B is clicked.

The standalone project for this is included in the download. Enjoy!

Download the source code for this post

Jeremy Likness

This is a video tutorial to introduce beginners to how to use both MVVM (Model-View-ViewModel) and MEF (Managed Extensibility Framework) with Silverlight (should work for versions 3 and 4). Of course, some "veterans" may want to watch as well in case you've missed some of the fundamentals, or have a clever way to do something that you can share in the comments for future visitors to the page.

In this edition, I build a simple application that allows the user to check a preference on the screen (whether they prefer squares over circles) and then displays a square or a circle. We use MVVM and wire everything together with MEF.

Download the source code: MEFMVVMDemoSln.zip

Click here to watch the video directly if it doesn't appear in the frame below (recommended to watch in full screen): Watch the video in a separate window

Here is the final application:

Download the source code: MEFMVVMDemoSln.zip

Jeremy Likness

A few weeks ago, I had the privilege of presenting a talk entitled, "Silverlight Line of Business Applications" at the Atlanta Silverlight Meetup Group. This talk focused on several aspects of building line of business applications, ranging from the principles that belong in the foundation or architecture, to specific frameworks and methodologies.

You can view the video below, or link directly by clicking here. I did take some time to encode chapters, so if you click the chapter icon in the player, you can jump to sections. I was hesitant to post this because there was not a microphone at the event. I spoke loud and recorded the talk via the built-in laptop microphone but the sound quality suffered as a result and there is plenty of background noise.

I hope the value of the content makes up for the poor audio quality. Here is the table of contents:

  • What is "Line of Business"?
  • Frameworks and Tools
  • Demo: Unit Testing Framework
  • Data Access Strategies
  • WCF RIA Services
  • Demo: RIA with POCO
  • UI Modularity and Scalability
  • Silverlight 4 and Beyond

I hope you enjoy the video and appreciate any comments or feedback you may have!

Jeremy Likness

We often trip over ourselves trying to minimize code behind and abstract behaviors in the UI from the models, etc. This is important for clean separation, but sometimes behaviors may add too much abstraction. The real fact is many applications require some sort of transition or animation based on events, and while we can try to put as many of those as possible into the VisualStateManager, there may be instances such as dynamically created animations or special triggers that end up involving the view model somehow.

What I'm proposing here is a very simple solution to allowing your view model to fire and respond to animations without having to know about those animations. The view model knows it has to fire some event, and may want notification when the event is done, but how that event is implemented is up to you. This way, the live version can contain Storyboard objects while the unit tests can contain mocks.

First, let's create a simple interface that our view model can talk to. It simply begins the animation and provides a callback when the animation is complete. (If you like, you can make it even more generic and call it a transition or an event).

public interface IAnimationDelegate
{
    void BeginAnimation(Action animationComplete);
}

That's pretty simple. Now, in my view model, I can fire the event and react. In this totally contrived example, whenever our first value changes, we fire a transition and only when the transition is complete, we move it with some changes to a second value.

public class MyViewModel : BaseNotify 
{
   public IAnimationDelegate Value1Transition { get; set; }

   private string _value1; 

   public string Value1 
   { 
      get { return _value1; } 
      set {
              _value1 = value;
              Value1Transition.BeginAnimation(_Value1Transitioned);
              RaisePropertyChanged("Value1"); 
          }
    }

    private string _value2; 

    public string Value2 
    {
       get { return _value2; }
       set {
             _value2 = value; 
             RaisePropertyChanged("Value2");
           }       
    }

    private void _Value1Transitioned()
    {
       Value2 = "This was the first value: " + Value1; 
    }
}    

The implementation of the animation delegate class might look like this:

public class AnimationDelegate : IAnimationDelegate
{
    private readonly Storyboard _storyboard;

    private Action _animationComplete;

    public AnimationDelegate(Storyboard storyboard)
    {
        _storyboard = storyboard;
        _storyboard.Completed += StoryboardCompleted;
    }

    void StoryboardCompleted(object sender, EventArgs e)
    {
        if (_animationComplete != null)
        {
            _animationComplete();
        }
    }

    public void BeginAnimation(Action animationComplete)
    {
        _animationComplete = animationComplete;
        _storyboard.Begin();
    }
}

We could unregister the event when completed, add other parameters to stop it when completed, etc, but this is a good staring point.

Now I simply need to wire the delegate. If my animation is called AnimateValue1 then with the Managed Extensibility Framework (MEF), I'd do something like this in the code behind for my control:

[Import]
public MyViewModel ViewModel
{
   get {  return LayoutRoot.DataContext as MyViewModel; }
   set {
          value.Value1Transition = new AnimationDelegate(AnimateValue1); 
          LayoutRoot.DataContext = value;          
       }
}

... and there you have it.

Jeremy Likness

In my last post, I showed you how to dynamically load modules on demand using the latest MEF release in Silverlight 3. This post, I will take you through managing regions with MEF. This will enable us to have a 100% MEF-based solution in Silverlight 3 if the only pieces of PRISM we were using were the dynamic module loading and region management.

Download the Source Code for this Post

Quick note: technically, the Composite Application Guidance (PRISM) is more of a guidance than an actual library. The library that is often used is the reference library for the guidance. I only mention this because in using the concept of the region manager and views, technically we are implementing the PRISM concept here and using CAG, we're just using MEF as the engine instead of the included reference library.

OK, let's get going ...

The first thing I did this time around was to rip out all of the IModuleInitialization pieces. They aren't needed because MEF will initialize what we need, as it's loaded. I destroyed the classes in the modules (it was good to see them load, anyway) and updated the navigation class to look like this:

[Export(typeof(INavigation))]
public class ViewNavigator : INavigation 
{        
    [Import]
    public ICatalogService CatalogService { get; set; }
    
    private readonly Dictionary<ViewType, string> _viewMap =
        new Dictionary<ViewType, string>
            {
                { ViewType.MainView, "DynamicModule.xap" },
                { ViewType.SecondView, "SecondDynamicModule.cs.xap" }
            };   

    private readonly List<string> _downloadedModules = new List<string>();
                                                                   
    public void NavigateToView(ViewType view)
    {
        if (!_downloadedModules.Contains(_viewMap[view]))
        {
            var catalog = new DeploymentCatalog(_viewMap[view]);
            CatalogService.Add(catalog);
            catalog.DownloadAsync();
            _downloadedModules.Add(_viewMap[view]);
        }
    }           
}

Thanks to Glenn Block for pointing out the excellent sample that comes included with the MEF bits (the deployment sample) ... this shows a different way of abstracting even the XAP file from the action of loading the catalog. In this case, I'm assuming I have prior knowledge of the controls and want to make my application more official by loading them dynamically as the user selects them.

So, now we've re-factored. That's a lot cleaner! Next, I want strongly-typed regions. I created a new project just for the regions, and added this class to define the enumeration:

public enum ViewRegion
{
    MainRegion,
    SubRegion 
}

public static class ViewRegionExtensions
{
    private static readonly List<ViewRegion> _regions = new List<ViewRegion> { ViewRegion.MainRegion, ViewRegion.SubRegion };       

    public static ViewRegion AsViewRegion(this string regionName)
    {
        foreach(var region in _regions)
        {
            if (regionName.Equals(region.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                return region;
            }
        }
        return ViewRegion.MainRegion; 
    }
}

Unfortunately, I don't believe the Silverlight version of the Enum class allows you to enumerate the values of an enumeration. Therefore, I'm simply providing a static class to hold those and putting it next to the enum so it's easy to remember for maintenance. I also added an extension method that allows me to take a string and do AsViewRegion() to convert it to the enum.

In order to make the enum appear in XAML, we need to give Silverlight a hint that tells it how to convert from the string we'll key in the XAML to an actual enum we use in code. Here is the type converter, it basically says it only knows how to convert from strings, and uses the extension method to cast the string when called:

public class ViewRegionConverter : TypeConverter 
{        
    public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
    {
        return sourceType.Equals(typeof (string));
    }

    public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
    {
        return ((string) value).AsViewRegion();
    }
}

Now we can create our behavior. The behavior is an attached property we'll use to tag a container as a region. Eventually this can become complex as we support lists and content controls, but for the sake of this blog series I'm keeping it simple and limiting our containers to panels. Panels all have children, so it is easy to add an item to the children. The behavior will simply keep a static dictionary that maps the view region to the panel it was tagged to, and exposes a method that lets us request the panel for a view region. Here it is:

public static class RegionBehavior
{
    private static readonly Dictionary<ViewRegion, Panel> _regions = new Dictionary<ViewRegion, Panel>();
    
    public static readonly DependencyProperty RegionNameProperty = DependencyProperty.RegisterAttached(
        "RegionName",
        typeof (ViewRegion),
        typeof (RegionBehavior),
        new PropertyMetadata(ViewRegion.MainRegion, null));

    public static ViewRegion GetRegionName(DependencyObject obj)
    {
        return (ViewRegion) obj.GetValue(RegionNameProperty);
    }

    [TypeConverter(typeof(ViewRegionConverter))]
    public static void SetRegionName(DependencyObject obj, ViewRegion value)
    {
        obj.SetValue(RegionNameProperty, value);
        var panel = obj as Panel;
        if (panel != null)
        {
            _regions.Add(value, panel);
        }
    }
   
    public static Panel GetPanelForRegion(ViewRegion region)
    {
        return _regions[region];
    }

}

Notice the type converter hint I give the setter. That lets the XAML know how to convert. In fact, this will even give us intellisense in the XAML, so it knows what the valid enumerations are! Now I can go into my main shell and create my first region (the intellisense quickly gave me a list to choose from ... right now there are only two choices!)

<StackPanel Orientation="Vertical" Grid.Row="2" Regions:RegionBehavior.RegionName="MainRegion"/>

We can debug at this point and see that indeed the panel is registered with the dictionary with the behavior, so we're set on that front. Now we need to get our views into the region. We're still in the special "Regions" project and namespace. For now, I'm simply going to export type UserControl for my view, and specify the region with an attribute. In MEF, we can create a strongly typed attribute for metadata:

[MetadataAttribute]
[AttributeUsage(AttributeTargets.Class, AllowMultiple = false)]
public class TargetRegionAttribute : ExportAttribute 
{        
    public TargetRegionAttribute() : base(typeof(UserControl))
    {
        
    }

    public ViewRegion Region { get; set; }
}

So the type is UserControl but we can specify a region in the meta data. Now I can add a view to my dynamic module. I'm also specifying a region here for a nested view.

<UserControl x:Class="DynamicModule.View"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:Regions="clr-namespace:RegionsWithMEF.Regions;assembly=RegionsWithMEF.Regions" 
    >
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="1*"/>
            <ColumnDefinition Width="1*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Column="0" Text="Left Column of Outer View"/>
        <StackPanel Grid.Column="1" Orientation="Vertical" Regions:RegionBehavior.RegionName="SubRegion">
            <TextBlock Text="Right Column of Outer View"/>
        </StackPanel>
    </Grid>
</UserControl>

We then tag the view for export with our custom attribute, like this:

[TargetRegion(Region=ViewRegion.MainRegion)]
public partial class View
{
    public View()
    {
        InitializeComponent();
    }
}

Very easy and readable. I went ahead and added another control for the second view, and tagged it to the "sub region" view.

Now we've got our custom attributes and exports, but we still need to glue it together. When the catalog is loaded, the views will be tagged as exports. We just need something to import them and we can then inspect the meta data and put them in their proper places. For this, I created the RegionManager.

First, let me back up. We want to read our meta data, so I need an interface with read only properties to pull it in:

public interface ITargetRegionCapabilities
{
    ViewRegion Region { get;  }
}

Great! Now I can define region manager. We'll use the Lazy object so we can define the capabilities with the import and inspect the meta data. I put it into an observable collection and listen to the collection. When it fires, I inspect the data for new controls, and then route them to their region based on the meta data:

[Export]
public class RegionManager
{
    private readonly List<UserControl> _controls = new List<UserControl>();

    [ImportMany(AllowRecomposition = true)]
    public ObservableCollection<Lazy<UserControl, ITargetRegionCapabilities>> Controls { get; set; }

    public RegionManager()
    {
        Controls = new ObservableCollection<Lazy<UserControl, ITargetRegionCapabilities>>();
        Controls.CollectionChanged += Controls_CollectionChanged;
    }

    void Controls_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach(var item in e.NewItems)
            {
                var controlInfo = item as Lazy<UserControl, ITargetRegionCapabilities>;

                if (controlInfo != null)
                {
                    if (!_controls.Contains(controlInfo.Value))
                    {
                        ViewRegion region = controlInfo.Metadata.Region;
                        Panel panel = RegionBehavior.GetPanelForRegion(region);
                        panel.Children.Add(controlInfo.Value);
                        _controls.Add(controlInfo.Value);
                    }
                }
            }
        }
    }
}

Note: if you are wondering why I use a list and an observable collection, it's because with recomposition, MEF is free to rebuild the entire list. I need to know specifically what changed and the "new items" might include older items that were recomposed. So the internal list allows me to keep track of what I've processed while I can parse out the newer items. With custom items you'll want to make sure you have a good implementation of Equals and GetHashCode, and if you have items that will go out of focus and disappear, you'll want to switch the internal list to a list of WeakReference instead.

That's it! The last step is to make sure that the region manager participates in the entire chain of imports and exports. I could wire it up in the container, but I know the shell view model is the top of the hierarchy, so to speak, so I'll just import the region manager directly. I haven't interfaced it because it doesn't expose any methods or properties: all of the work is internal and interfaces with the static dictionary we put into our behavior.

[Import]
public RegionManager Manager { get; set; }

OK, let's fire it up. I made a short video to show you the results.

Download the Source Code for this Post

Jeremy Likness

Recently I've been having lots of conversations about the Managed Extensibility Framework (MEF), the Composite Application Library (CAL or PRISM), and how they relate. One point of confusion that many people has comes when they try to force the two solutions to work together. In a recent conversation, I mentioned that PRISM has some great features, but that if you are only using it for dynamic module loading and view management, MEF should do fine. Then I promised to post a blog with a reference project ... and here it is.

Download the source for this project

First, let me share that I love PRISM and have been working with it in almost all of my projects for the past year. My Wintellect colleague Rik Robinson has an excellent article on PRISM you can read here. You can also scan this blog with the PRISM tag. However, I've started to really enjoy working with MEF and believe it is quickly becoming the solution of choice for composite Silverlight applications ... especially with it's inclusion in the upcoming 4.0 release. In these 2 posts I'll show you how to tackle dynamic module loading and region management using exclusively MEF instead of PRISM.

I'm working with the preview 9 of the bits and showing what can be done in the current production release of Silverlight which is version 3. To start with, I simply create a new Silverlight Application. I add a folder called "MEF" and throw the bits in there, which is really two DLLs: System.ComponentModel.Composition and System.ComponentModel.Composition.Initialization. I reference those.

The "Bootstrapper" in MEF

Next I create a new empty user control called Shell.xaml (sound familiar?) that just has a grid and a text block so I know it's there. If you are familiar with PRISM, you are familiar with the concept of the Bootstrapper class to wire everything up. With MEF, we'll do it a little different. First, I go inside the shell and simply decorate it with the "export" attribute:

[Export]
public partial class Shell
{
    public Shell()
    {
        InitializeComponent();
    }
}

Next, I go into my main application class (App.cs) and add a property to import the Shell, like this:

...
[Import]
public Shell RootView { get; set; }
...

Finally, in the application start-up method, instead of newing up a "main page" which no longer exists, I simply ask MEF to satisfy my import of the shell, then assign it to the root visual:

private void Application_Startup(object sender, StartupEventArgs e)
{
    CompositionInitializer.SatisfyImports(this);
    RootVisual = RootView;
}

That's it! When I hit F5 I see the text I placed in the shell, so I know it's being placed in the root visual. We're good to go! I'm going to tackle dynamic loading first, then look at region management. I'll need some buttons to trigger the loading, so we'll want to roll a command behavior. This is one of the nice things that comes with PRISM (the commands), but let's see how easy or difficult it is to roll our own.

Custom Commands

Microsoft Expression Blend provides a set of base triggers and behaviors that make it easy to add new functionality like commanding. If you don't have the full tool, don't despair - these are also included in the free SDK you can download. I'm including a reference to System.Windows.Interactivity.

I want to do a trigger action. A trigger action allows me to act on any event, which I prefer over hard-coding just to a button click.

Before I get ahead of myself, though, let's create our command. While Silverlight 3 doesn't have a built-in command object, it does provide the ICommand interface. I'm going to do a partial implementation. I say "partial" because the interface allows for something to be passed to the command, and I'm simply raising the command and assuming null for the sake of this blog post:

public class CommandAction : ICommand 
{
    private readonly Func<bool> _canExecute;

    private readonly Action _execute; 

    public CommandAction(Action action, Func<bool> canExecute)
    {
        _execute = action;
        _canExecute = canExecute;
    }

    public bool CanExecute(object parameter)
    {
        return _canExecute();
    }

    public void Execute(object parameter)
    {
        _execute();
    }

    public void RaiseCanExecuteChanged()
    {
        EventHandler handler = CanExecuteChanged;
        if (handler != null)
        {
            handler(this, EventArgs.Empty);
        }
    }

    public event EventHandler CanExecuteChanged;
}

While I haven't looked at the code in PRISM, I assume this is very close to how they wire the DelegateCommand. We hold a function that determines if the command is enabled, and an action to call when the command is invoked. Whoever creates the CommandAction is responsible for passing those delegates in and raising "can execute changed" when appropriate.

Now I can start to work on the command behavior. Because of my unique command type, I'm just going to allow you to pass the name of the command on the data bound object and will dissect the rest. If you bind a view model with "ActionCommand" then I'll let you wire up it up that way. Because we're using MEF to bind our view models, my behavior will get wired well before the bindings happen. I'll need to know when the data context changes, so I build a data context helper. It basically uses dependency properties to listen to a "dummy" binding for changes, then calls an action when the changes happen. It looks like this and is loosely based on a previous post I made on data context changed events:

public static class DataContextChangedHandler
{
    private const string INTERNAL_CONTEXT = "InternalDataContext";
    private const string CONTEXT_CHANGED = "DataContextChanged";

    public static readonly DependencyProperty InternalDataContextProperty =
        DependencyProperty.Register(INTERNAL_CONTEXT,
                                    typeof(Object),
                                    typeof(FrameworkElement),
                                    new PropertyMetadata(_DataContextChanged));

    public static readonly DependencyProperty DataContextChangedProperty =
        DependencyProperty.Register(CONTEXT_CHANGED,
                                    typeof(Action<Control>),
                                    typeof(FrameworkElement),
                                    null);

    
    private static void _DataContextChanged(object sender, DependencyPropertyChangedEventArgs e)
    {
        var control = (Control)sender;
        var handler = (Action<Control>) control.GetValue(DataContextChangedProperty);
        if (handler != null)
        {
            handler(control); 
        }
    }

    public static void Bind(Control control, Action<Control> dataContextChanged)
    {
        control.SetBinding(InternalDataContextProperty, new Binding());
        control.SetValue(DataContextChangedProperty, dataContextChanged); 
    }
}

In this case, I'm scoping specifically to a control, which is where I believe the lowest level of "is enabled" gets implemented for controls that can react to changes, so that makes sense for our behavior. When I call bind, I pass it a control and a delegate to call when that control's data context changes. Now we can build in our behavior:

public class CommandBehavior : TriggerAction<Control>
{
    public static readonly DependencyProperty CommandBindingProperty = DependencyProperty.Register(
        "CommandBinding",
        typeof(string),
        typeof(CommandBehavior),
        null);

    public string CommandBinding
    {
        get { return (string)GetValue(CommandBindingProperty); }
        set { SetValue(CommandBindingProperty, value); }
    }

    private CommandAction _action; 

    protected override void OnAttached()
    {
        DataContextChangedHandler.Bind(AssociatedObject, obj=>_ProcessCommand());
    }

    private void _ProcessCommand()
    {
        if (AssociatedObject != null)
        {

            var dataContext = AssociatedObject.DataContext;

            if (dataContext != null)
            {
                var property = dataContext.GetType().GetProperty(CommandBinding);
                if (property != null)
                {
                    var value = property.GetValue(dataContext, null);
                    if (value != null && value is CommandAction)
                    {
                        _action = value as CommandAction;
                        AssociatedObject.IsEnabled = _action.CanExecute(null);
                        _action.CanExecuteChanged += (o, e) => AssociatedObject.IsEnabled = _action.CanExecute(null);

                    }
                }
            }
        }
    }

    protected override void Invoke(object parameter)
    {
        if (_action != null && _action.CanExecute(null))
        {
            _action.Execute(null);
        }
    }      
}

OK, let's step through it. I'm using the System.Windows.Interactivity namespace to define a trigger action, which can be bound to any event. I'm scoping it to a control. When my behavior is attached, I'm binding to the data context changed event. I ask it to call my method to process the command when the data context changes (presumably to bind our command). When that fires, I grab the property that is named in my behavior from the data context, cast it to a command, and wire it up to automatically change whether the host control is enabled based on the CanExecute method of the control. When my behavior is invoked, I check this again and then execute.

ViewModel Glue

There's been a lot of discussion (including in this blog) around how to glue the view model to the view. I personally like to keep it simple and straightforward. Here's a view model stubbed out for the shell that lets me click a button to dynamically load a view. I want to disable the button once clicked so they don't load the view more than once.

[Export]
public class ShellViewModel
{
    public ShellViewModel()
    {
        ViewEnabled = true;
        ViewClick = new CommandAction(_ViewRequested,
                                      () => ViewEnabled);
    }

    private bool _viewEnabled;

    public bool ViewEnabled
    {
        get { return _viewEnabled; }
        set
        {
            _viewEnabled = value;
            
            if (ViewClick != null)
            {
                ViewClick.RaiseCanExecuteChanged();
            }
        }
    }

    public CommandAction ViewClick { get; set; }

    private void _ViewRequested()
    {
        ViewEnabled = false;
    }
}

Note I use a property to determine if the command is enabled, then call a method to process it when fired. We'll add more to that method in a minute. Let's get this into our shell. Because the shell is wired up in the application through the initializer, there is no need to initialize or compose again. This is done recursively. So, let me add a little bit to my shell:

<UserControl x:Class="RegionsWithMEF.Shell"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:interactivity="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
    xmlns:command="clr-namespace:RegionsWithMEF.Common.Command;assembly=RegionsWithMEF.Common"
    >
    <Grid x:Name="LayoutRoot" Background="White">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <TextBlock Text="Main MEF Shell"/>
        <Button Content="Load Dynamic View into Region" Width="Auto" Height="Auto" Grid.Row="1">
            <interactivity:Interaction.Triggers>
                <interactivity:EventTrigger EventName="Click">
                    <command:CommandBehavior CommandBinding="ViewClick"/>
                </interactivity:EventTrigger>
            </interactivity:Interaction.Triggers>
        </Button>
    </Grid>
</UserControl>

Notice how I use the interactivity namespace to define a trigger for the button. The trigger is for the "click" event, but the way we built the behavior, it can easily fire based on other events as well. I bring in my command behavior, and point it to the "ViewClick" property on my view model. A more advanced implementation would turn that into a full blown binding property and allow binding syntax but for now we'll stick with the simple property name.

In the code behind, I wire in my view model:

[Import]
public ShellViewModel ViewModel
{
    get { return LayoutRoot.DataContext as ShellViewModel; }
    set { LayoutRoot.DataContext = value; }
}

That's it! I run the project to test it, and get a nice text block with a button. When I click the button, it disables immediately. Now let's tackle that dynamic view!

Controlling the Catalog and Container

We want to dynamically load some modules, but first we'll need to tweak our container. By default, MEF is going to create a container in our main application and compose parts to it. Unfortunately, that means when we load other modules/xap files, they won't have access to the container! We need to fix this.

First, I'll create a service to expose an AggregateCatalog that I can add other catalogs to. I want to get the catalog and add parts to it:

public interface ICatalogService
{
    void Add(ComposablePartCatalog catalog);

    AggregateCatalog GetCatalog();

}

Next, I will implement this by creating an aggregate catalog. I'm going to assume when the service is created that we want to include the currently loaded assemblies. This assumption may be wrong and down the road we might inject the catalog, but for now we'll iterate the current deployment (set of running assemblies) and pull them in to parse into our catalog:

public class CatalogService : ICatalogService
{
    private read-only AggregateCatalog _catalog = new AggregateCatalog();

    public CatalogService()
    {
        foreach (AssemblyPart ap in Deployment.Current.Parts)
        {
            StreamResourceInfo sri = Application.GetResourceStream(new Uri(ap.Source, UriKind.Relative));

            if (sri != null)
            {
                Assembly assembly = ap.Load(sri.Stream);
                _catalog.Catalogs.Add(new AssemblyCatalog(assembly));
            }
        }
    }    

    public void Add(ComposablePartCatalog catalog)
    {
        _catalog.Catalogs.Add(catalog);
    }

    public AggregateCatalog GetCatalog()
    {
        return _catalog; 
    }
}

Now we just need to tweak the main application. We'll instantiate the service, then tell it how to expose itself (sounds weird, I know, but when I bring in a module, I want it to be able to add itself to the aggregate catalog, so the catalog service must be exported). We'll let MEF know we want to use this specific container moving forward, and then we'll initialize as before. The new method looks like this:

private void Application_Startup(object sender, StartupEventArgs e)
{
    ICatalogService service = new CatalogService();
    var container = new CompositionContainer(service.GetCatalog());
    container.ComposeExportedValue(service);
    CompositionHost.Initialize(container); 
    CompositionInitializer.SatisfyImports(this);
    RootVisual = RootView;
}

Dynamic Loading of Modules

MEF Preview 9 comes with a deployment catalog that gives us what we need. First, I want to hide the implementation details of loading a view. I'll create an enumeration of views that are available (in this case, only one) and an interface to call when I'm ready to navigate to a view.

For now, I want to just grab the view and verify it's loaded. Then we'll wrap up for today and tackle the region management in the next post.

I extended my shell view model to anticipate two views. In fact, to make the example more interesting, I will load the second view into the first view. Therefore, the second button is only enabled once the first button has been clicked, like this:

SecondViewClick = new CommandAction(
    _SecondViewRequested,
    () => !ViewEnabled && SecondViewEnabled);

Here's our views:

public enum ViewType
{
    MainView,
    SecondView
}

And the interface for our view navigation:

public interface INavigation
{
    void NavigateToView(ViewType view);
}

So now I can go back to my view model and wire in the navigation, as well as make the call. Here is the modified code:

[Import]
public INavigation Navigation { get; set; }

private void _ViewRequested()
{
    ViewEnabled = false;
    Navigation.NavigateToView(ViewType.MainView);
}

private void _SecondViewRequested()
{
    SecondViewEnabled = false;
    Navigation.NavigateToView(ViewType.SecondView);
}

Now I will add my modules. As I mentioned, I just want them to load for now. I can deal with the views later. So I create two more Silverlight applications in my solution called "DynamicModule" and then "SecondDynamicModule.cs" ... yes, the second is a typo because I thought I was adding a class, and was too lazy to re-factor it. So there. I imagine when I load a module I'll want it to do perform some "introductory" functions, so let's define an initialization interface:

public interface IModuleInitializer
{
    void InitModule();
}

In both of my dynamic modules, I add a class that implements this interface and export it. I gave them different names to show it's the interface the matters, but here's what one looks like (right now I just return, but I can set the breakpoint there to test when and if the module is loaded and called):

[Export(typeof(IModuleInitializer))]
public class ModuleInitializer : IModuleInitializer
{
    public void InitModule()
    {
        return; 
    }              
}

OK, now I can implement my INavigation interface. We're going to do two things. First, we'll map views to modules so we can dynamically load them using the DeploymentCatalog. Second, we'll import a collection of module initializers. This is the super-cool feature of MEF: recomposition. When we load the module and put it in our main catalog, it will recompose. This should fire a change to our collection of initializers. We can take the new items and call them, and we'll be initialized. Here's what it looks like:

[Export(typeof(INavigation))]
public class ViewNavigator : INavigation 
{        
    [Import]
    public ICatalogService CatalogService { get; set; }

    [ImportMany(AllowRecomposition = true)]
    public ObservableCollection<IModuleInitializer> Initializers { get; set; }

  private readonly List<IModuleInitializer> _modules = new List<IModuleInitializer>();

    private readonly Dictionary<ViewType, string> _viewMap =
        new Dictionary<ViewType, string>
            {
                { ViewType.MainView, "DynamicModule.xap" },
                { ViewType.SecondView, "SecondDynamicModule.cs.xap" }
            };   

    private readonly List<string> _downloadedModules = new List<string>();

    public ViewNavigator()
    {
        Initializers = new ObservableCollection<IModuleInitializer>();
        Initializers.CollectionChanged += Initializers_CollectionChanged;
    }
    
    void Initializers_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
    {
        if (e.NewItems != null)
        {
            foreach(var item in e.NewItems)
            {
                var initializer = item as IModuleInitializer; 
                if (initializer != null)
                {
                    if (!_modules.Contains(initializer))
                    {
                        initializer.InitModule();
                        _modules.Add(initializer);
                    }
                }
            }
        }
    }                                                                                              
  
    public void NavigateToView(ViewType view)
    {
        if (!_downloadedModules.Contains(_viewMap[view]))
        {
            var catalog = new DeploymentCatalog(_viewMap[view]);
            CatalogService.Add(catalog);
            catalog.DownloadAsync();
            _downloadedModules.Add(_viewMap[view]);
        }
    }               
}

Right now the navigate to view isn't very flexible. It loads the catalogs but doesn't do anything with the views. I'm also not handling errors when the XAP isn't loaded. We are tracking modules and xaps that were already loaded, so we don't load them again or re-initialize the module. We'll get to that in the next installment when we wire in regions. For now, we can put a breakpoint in the "return" of the init modules, fire up the application, and click our buttons to watch them get dynamically loaded into the system (you can use Fiddler to watch the packets come over the wire). Pretty exciting!

In the next installment, I'll show you how MEF will handle region management.

Download the source for this project

Jeremy Likness

The Silverlight team recently posted a blog entry entitled "Vancouver Olympics - How'd we do That?" in which they detailed the massive effort across multiple partners to pull together the on-line solution for streaming HD videos, both live and on demand.

This was an exciting post for Wintellect and me because it detailed the effort we contributed to making the project a success. What's more important to me for the Silverlight community, however, is that you don't overlook the key detail they posted on the blog:

Development of a Silverlight application to interface with the service agents via WCF. This tool allows Microsoft to quickly publish new configuration files (such as web.config and clientaccesspolicy.xml) to groups of servers, as well as dynamically manipulate configuration settings through a visual interface (for example, turning off compression on a remote smooth streaming server when required) on multiple remote servers at once.

This is important because as a Silverlight developer I am constantly bombarded with questions about how viable Silverlight is, if it is ready for the enterprise and what practical application it has for business. This is a specific example where it was the right tool for the right job.

I won't go into more details about the tool other than what Microsoft has publicly shared, but I wanted to emphasize that this is another example of how Silverlight helps to solve real world problems. When looking at the requirements for the health monitoring, we had several options for a solution. In this case, WPF wouldn't have worked because they would have had to remote into the environment in order to access the tool. However, using ASP.NET and JavaScript would have required jumping through some major hoops and use of heavy controls to correctly render the user interface they required. The tool essentially parses any XML-base configuration file and allows on-line navigation and updates to that document. While this would have been possible using script, it would have taken much longer and required an extended cycle of testing to stabilize.

Due to Silverlight's unique data-binding model and full LINQ to XML support, we were able to build a solution quickly and effectively. We were also able to use the unit testing framework to build hundreds of unit tests that helped ensure a stable, thorough, and well-tested solution. Again, using scripting would have required more complicated tools that simulated user-clicks, etc. With Silverlight, we can place controls on a test surface and simulate the click events to test everything from behaviors down to internal class methods.

PRISM, or the Composite Application Library, was also crucial with the success of keeping the module light weight. There were literally dozens of functions the tool could provide but only a few might be used at any given time, so we separated the functions into independent modules that dynamically loaded as needed to provide a streamlined experience.

While I was excited to work on the project with my company, I am even more excited that it demonstrates yet again how Silverlight is the right tool, right here, right now for enterprise class applications. This is another "case study" to add to your arsenal as you answer questions about, "Is it ready?" or "Has it been done before." I believe the fact that it was so crucial both in the front end (with the live streaming experience) and back-end (with the management tools) for an incredible event like the Olympics really proves how mature and ready Silverlight is for business class applications.

Jeremy Likness

NDepend is a product that analyzes large code bases and provides information about dependencies, complexity of code, best practices, and more. While designed to help manage large code bases, it also works well as a "reality check" as you are developing new projects. The latest release supports Silverlight and I'll be using it to clean up my RSS reader a little bit.

The first thing I did was download and install the product. There is an option to integrate with Visual Studio. I chose this option, then opened the RSS reader solution. In the lower right I now have an option to create a new NDepend project and link it to my solution:

A new dialog pops up that prompts me for the projects/assemblies to scan and some other information. In this case, I simply take all of the defaults and click OK.

This creates the new project and analyzes my project immediately. Eventually, I'm brought to a new web page that has a detailed report of the analysis of my solution.

The report is very comprehensive. For example, I receive summary statistics at the top:

Number of IL instructions: 1003
Number of lines of code: 120
Number of lines of comment: 265
Percentage comment: 68
Number of assemblies: 3
Number of classes: 15
Number of types: 16
Number of abstract classes: 0
Number of interfaces: 1
Number of value types: 0
Number of exception classes: 0
Number of attribute classes: 1
Number of delegate classes: 0
Number of enumerations classes: 0
Number of generic type definitions: 1
Number of generic method definitions: 6
Percentage of public types: 81.25% 
Percentage of public methods: 76.81% 
Percentage of classes with at least one public field: 6.25% 

The visual map gives me a quick idea of what the dependencies of the project are (click for a larger view):

Visual NDepend

I also get a nice chart showing the dependencies ... you can imagine how powerful this visualization becomes when you have far more projects than the ones in our little RSS reader:

OK, that's all good and pretty, but how does this help us? We need to dive deeper into the report. Scrolling down the report, the first thing that happens is I am scolded for not commenting my SecurityToken method well enough. There is a lot of code but I'm not explaining what the code is doing ... that's fine. It'll certainly help other developers down the road, but what about performance and code quality?

The report indicates that my Item, RSSElementAttribute, and Channel classes are candidates to be sealed. Why would I want to seal the classes? Many C# developers mistakenly believe that you only seal a class when you want to prevent someone else from deriving from it. Not true.

As Wintellect's own Jeffrey Richter explains in CLR via C#, there are three key reasons why a sealed class is better than an unsealed one:

  1. Versioning — if you need to unseal it in the future, you can do so without breaking compatibility
  2. Performance — because the class is sealed, the compiler can generate non-virtual calls (which have less overhead) rather than virtual calls (virtual calls are required to analyze the inheritance chain and find the correct instance of the actual method to call)
  3. Security and Predictability — classes should manage and protect their state. Allowing a class to be derived exposes that class to corruption via the deriving code.

Turns out NDepend has given us a pretty good pointer there. We'll come back to these classes in a bit.

Next, I find out two of my classes, Channel and RssReader, are candidates for structures. Structures have certain performance benefits (read more about them here) but if they are too large they may actually degrade performance. A class that is relatively small, has no derived types, and derives directly from System.Object is a candidate for a structure. For the Channel class, we can kill two birds with one stone: structures are also implicitly sealed.

I could go on and on ... my next step is to continue finding areas that the Code Query Language constraints are fired and see if it makes sense to correct them. You can read more about the CQL here. This language allows you to write your own constraints for quality checking your code. Let's jump out of the constraints and look at a few more metrics that the report provides.

Fortunately, most of the items on the report contain hyperlinks to explanations of what the metric or query is. The list of basic metrics is explained here. These are important ones to look into:

Afferent Coupling — this is how many types outside of an assembly depend on the current type. A high afferent coupling means the type has a larger responsibility because more external types depend on it. In our case, only the common project generates this type of dependency.

Efferent Coupling — this is simply how many external types to the current assembly are depended upon by types within the assembly. A high efferent coupling means we have many dependencies on other types. There will always be efferent coupling, because in the basic sense your string, int, and other framework types have a dependency on the core library.

Poor design results in efferent coupling increasing as you move from the database to the presentation layer. This is because more dependencies on database, business, and other types accumulate. A quality design will ensure consistency across the layers, because the presentation layer will only couple to models and types defined in the business layer, but will be completely abstracted from the data layer, etc.

Relational Cohesion — this refers to interdependencies within an assembly. Typically, related types should be grouped together. A low relational cohesion means there are very few interdependencies. This is not always bad. For example, if you have your domain models in a single assembly, the relational cohesion will depend on how many of those classes aggregate or compose other classes ... it is perfectly normal to have several unrelated types defined. On the flip side, a high cohesion means perhaps the classes are too interrelated and should be broken out for better de-coupling. There is no hard, set rule for this and really is a judgment call based on the specific project being analyzed.

Instability is an important metric to consider. It is the ratio of efferent coupling to total coupling. On a scale from 0 to 1, this describes the "resistance to change" for the assembly. A 0 means it is highly resistant to change, while a 1 means it is extremely instable, or highly sensitive to changes. Because I have grouped models, services, and interfaces together in my project, it fails with a score of 1. This means I need to re-factor and break some elements out so they are more independent.

Abstractness is another important measure. This measures the ratio of abstract (interfaces and abstract classes) types to concrete types. It is again on a scale from 0 to 1. I try to target a combination of 0 and 1 for this metric ... the "1" or completely abstract being independent projects that define interfaces, with the "0" being the implementations of those interfaces. We'll re-factor the RSS reader to pull the interfaces and abstract classes to separate projects and then re-analyze. This will also help me with my testing efforts because it's very hard to write quality unit tests for highly coupled classes.

Based on the report, I need to do some refactoring and change the types and modifiers of some of my entities, as well as split these out into separate projects.

Doing this from within the project is simple. You can click on the NDepend icon and get a summary (click for full-sized view):

Next, I click on one of the warning rows to view the detail (for example unused code -> potentially dead methods). This gives me the detail of the violation and where potential violations occurred. I can easily click on the member or class to navigate to the code and fix it directly:

NDepend Navigation

Following the advice of the tool, I created a new "model" project where I moved the basic domain entities (item, channel) and the custom attribute. I followed the advice to seal the classes but left them as classes due to the reflection used to generate instances from the RSS feeds.

A new service project was created to implement the service. Note how important this is because now for unit tests of classes that depend on the service contract, I can simply mock the interface rather than having to pull in an assembly with an actual implementation (read about Using Moq for Silverlight for Advanced Unit Tests).

I also flattened my structure a bit. I had namespaces with only one class simply because I was dumping these into folders, rather than simply grouping them together and refactoring down the road when it makes sense.

After all of this, I ended up with the new dependency diagram:

My new assemblies no longer have instability ratings of "1" which means the solution as a whole is moving toward better stability and long term maintainability.

Obviously this was a small project with few changes. The power of the tool increases exponentially as you build more complex and involved projects. It can help you sort dependencies, optimize your code, enforce naming conventions, and much more.

Now we've got the reader a little better suited for future expansion. My next step will be to build the unit tests (that should have gotten there a lot sooner, I know, I know) and then see if it makes sense to introduce any type of dependency injection.

Jeremy Likness

One of the most common examples to help learn a language or framework is an RSS Reader. This is an ideal mini-project because it includes networking, parsing XML, and binding to data elements such as lists. I wanted to provide an example that shows some more interesting solutions that are possible using C# in Silverlight. This is the first part in a series. By the end of this post, we'll have a working reader. What I'll then do is add some more detailed error handling, provide unit tests, tackle skinning and visual states, and hopefully end up with a fairly advanced client.

Today, let's focus on getting a client where we can enter a feed and get some listings. A perfect way to test this will be a Twitter feed. If you would like to read my recent tweets as RSS, for example, you can simply navigate to http://twitter.com/statuses/user_timeline/46210370.rss. By viewing the source, you can see the basic structure of an RSS feed. It is fairly straightforward.

Download the source for this project

Domain Entities

The first step is to define some domain entities. These are the "models" for our application, and represent the actual data we are working with. With an RSS feed, it is fairly simple. We'll work our way backward from the item up to the channel. Our item to start with looks like this:

 
public class Item
{
    public string Title { get; set; }

    public string Description { get; set; }

    public DateTime PublishDate { get; set; }

    public string Guid { get; set; }

    public Uri Link { get; set; }
}

A channel is simply some header information with a collection of items. For starters, we'll make it look like this:

public class Channel
{
    public Channel()
    {
        Items = new ObservableCollection<Item>();
    }

    public string Title { get; set; }

    public Uri Link { get; set; }

    public string Description { get; set; }

    public ObservableCollection<Item> Items { get; set; }
}

Note that I build my entities based on the actual content, not how the content is delivered. In other words, even though the RSS stream may encode a link or a date as text, I want my domain entity to be able to work with the property as it was intended. Therefore, there are no "hacks" to force something into a Uri that doesn't belong: we use that type for the links. Similarly, the date time is handled as a date, and we can worry about how to display it when the time is right. The point is this keeps the data we're dealing with abstracted from the way we receive it, so if down the road we are reading a database or connecting to a different type of service, we only need to change the way we adapt from the service into our domain.

De-serialization

One of the challenges we'll face with RSS feeds is taking the feed data and turning it into our domain objects (de-serializing the data). There are a number of different approaches, but I wanted to present one that I think makes it extremely easy to expand and extend entities that are mapped to XML documents. It involves using Silverlight's powerful LINQ to XML features.

The concept is relatively simple: XML data is mostly strings in elements and attributes. For RSS feeds, the data is entirely in elements. Therefore, it should be relatively straightforward to parse an XML element into an entity. We'll know the target property and the type of that property, so all we need is the element and the conversion.

To tackle the element, I decided to create a custom attribute called RssElement that allows me to tag a property with the name of the element the property's value is contained within. Here is the attribute:

[AttributeUsage(AttributeTargets.Property,AllowMultiple = false)]
public class RssElementAttribute : System.Attribute
{
    public readonly string ElementName; 

    public RssElementAttribute(string elementName)
    {
        ElementName = elementName;
    }
}

Now I can circle back to my entities and tag them with the source elements. First, the item:

public class Item
{
    [RssElement("title")]
    public string Title { get; set; }

    [RssElement("description")]
    public string Description { get; set; }

    [RssElement("pubDate")]
    public DateTime PublishDate { get; set; }

    [RssElement("guid")]
    public string Guid { get; set; }

    [RssElement("link")]
    public Uri Link { get; set; }
}

And then the channel:

public class Channel
{
    public Channel()
    {
        Items = new ObservableCollection();
    }

    [RssElement("title")]
    public string Title { get; set; }

    [RssElement("link")]
    public Uri Link { get; set; }

    [RssElement("description")]
    public string Description { get; set; }

    public ObservableCollection<Item> Items { get; set; }
}

Now that we have a way of tagging the properties, we can create a fluent extension to move from an XElement (what LINQ gives us) to an actual type.

I created a static class called LinqExtensions to extend my LINQ classes. Again, working backward, let's consider what happens to the value of an element in XML when we move it to our entity. We'll need to take that value (which is a string) and convert it based on the target type. It has a consistent method signature: receive a string, return a type. Therefore, I decided to implement a dictionary to map the conversion process to the target types. Working with the types I know I'll need, my dictionary looks like this:

public static class LinqExtensions
{
    private static readonly Dictionary<Type, Func<string, object>> _propertyMap;

    static LinqExtensions()
    {
        _propertyMap = new Dictionary<Type, Func<string, object>>
                           {
                               {typeof (string), s => s},
                               {typeof (Uri), s => new Uri(s)},
                               {typeof (DateTime), s => DateTime.Parse(s)}
                           };
    }

This is very simple when you see where I'm going. Everything is mapped to a function that takes a string and returns an object. A string is a pass-through (s => s). A Uri converts the string to a Uri (s => new Uri(s)) and a date time attempts to parse the date (s => DateTime.Parse(s)). By using the type as the key to the dictionary, I can do this:

...
DateTime date = _propertyMap[typeof(DateTime)]("1/1/2010") as DateTime; 
...

Of course, part of what we can do down the road is add some better error handling and contract checking. Next, let's use this conversion. I am taking in an element, then using the property information that I have to set the value onto an instance of the target class. Given a class instance T, an element, and the information about a property, I can inspect the custom attribute to find the element name, then use the conversion for the type of the property to set the value. My method looks like this:

private static void _ProcessProperty<T>(T instance, PropertyInfo property, XContainer element)
{
    var attribute =
        (RssElementAttribute) (property.GetCustomAttributes(true)
                                  .Where(a => a is RssElementAttribute))
                                  .SingleOrDefault();

    XElement targetElement = element.Element(attribute.ElementName);

    if (targetElement != null && _propertyMap.ContainsKey(property.PropertyType))
    {
        property.SetValue(instance, _propertyMap[property.PropertyType](targetElement.Value), null);
    }
}

As you can see, we grab the element, find the value in the XML fragment we're passed, then use the property's SetValue method to set the value based on the conversion we find in the property map.

How do we get the property info? Take a look at this fluent extension. It takes an element and is typed to a target class. It will create a new instance of the class and iterate the properties to set the values. By using it as a fluent extension, I can write this in code, which I think makes it very readable:

...
var widget = xmlElement.ParseAs<Widget>(); 
...

The "parse as" method looks like this:

public static T ParseAs<T>(this XElement element) where T : new()
{
    var retVal = new T();

    ((from p in typeof (T).GetProperties()
      where (from a in p.GetCustomAttributes(true) where a is RssElementAttribute select a).Count() > 0
      select p).AsEnumerable()).ForEach(p => _ProcessProperty(retVal, p, element));

    return retVal;
}

I basically grab all properties with the custom attribute, then pass the class, element, and property to the method we developed earlier to set the value. Finally, I return the new instance of the class. The ForEach is available with the toolkit, but you can roll your own enumerator extension like this:

public static class IteratorExtensions
{
    public static void ForEach<T>(this IEnumerable<T> list, Action<T> action)
    {
        foreach(var item in list)
        {
            action(item);
        }
    }
}

To me, it saves code and makes it easier to read what's going on if you have to perform a simple action and use the ForEach extension to do it.

While we're having fun with our fluent extensions, we're almost ready to take an RSS feed and turn it into a group of objects. We need a way to get the text we receive from the call into an XDocument, so I made this extension:

public static XDocument AsXDocument(this string xml)
{
    return XDocument.Parse(xml);
}

We also need to take the XDocument and iterate the elements to build channels and items. Because we already built our ParseAs method and have tagged the entities for channels and elements, this becomes as simple as:

public static List<Channel> AsRssChannelList(this XDocument rssDoc)
{
    var retVal = new List<Channel>();

    if (rssDoc.Root != null)
    {
        foreach(var c in rssDoc.Root.Elements("channel"))
        {
            var channel = c.ParseAs<Channel>();
            c.Elements("item").ForEach(item => channel.Items.Add(item.ParseAs<Item>()));
            retVal.Add(channel);                    
        }
    }

    return retVal;
}

Again, I believe the fluent extensions are making our life easier because one logical layer builds on the next. We already have our entities tagged and our parsing worked out, so now we simply iterate the channels and parse those as channels, then iterate the items and parse those as items. Could it be an easier? Now, if I have the text of an RSS feed in a variable called rssFeed, the only thing I need to do in order to turn it into a list of channels and items is this:

...
var channelList = rssFeed.AsXDocument().AsRssChannelList(); 
...

We've done most of the heavy lifting, so let's tackle actually going out and fetching the feed. If you've worked with Silverlight and tried to fetch any type of information from another website, you'll be familiar with the strict cross-domain policies that Silverlight has. You can read the Microsoft article on Network Security Access Restrictions in Silverlight to get the full scoop.

In a nutshell, it says most likely we won't be able to reach out from our Silverlight client to touch the RSS feeder and bring back the information. How do you like that twist? Fortunately, there is a workaround.

Using a Handler to Bypass Cross Domain Concerns

Silverlight is allowed to pull information from the same server that it is hosted from. One simple way to bypass the issue with going out directly from the client to the reader is to create a proxy. We don't have the same restrictions on the server with going across domains, so we can have Silverlight "ask" the server to pull the feed for us, and deliver it back.

This, however, has its own issues. I can make a handler that takes a Uri and then returns the data, but this would expose a potential security risk in my web application. It would open the door for malicious attackers to hit other websites and make it look like it is coming from my server! It's sort of like the old "call-forwarding" techniques that old school phreakers would use to hide their illicit telecommunications activities.

I am going to use the handler approach, but make it a little more difficult to abuse. In a production system, I'd implement a full brown encryption scheme. The issue with the Silverlight side is that it gets downloaded to the browser, so a would-be hacker can easily pull apart the code and dissect what's going on. You'll want a fairly strong algorithm to circumvent foul play. For this blog example, I'm going to implement a very light security piece that will thwart any casual foul play by preventing someone from guessing how to pull a feed without knowing the algorithm. OK, so it's not very secret because I'm letting you in on the deal.

For the sake of illustration, I'm simply going to have the Silverlight client generate a guid, then generate a hash on the GUID using SHA1. Again, for a more secured solution, I'd have a SALT and keywords, etc, but this at least shows a way to secure the communication and should get you thinking about security concerns when you start exposing services for Silverlight to consume.

In order for this to work, both the client and the server need to implement the same algorithm. I am a big fan of DRY (Don't Repeat Yourself) so I don't want to duplicate the algorithm in both places. Instead, I'll build this simple piece on the Silverlight side:

public static class SecurityToken
{        
    public static string GenerateToken(string seed)
    {
        Encoder enc = Encoding.Unicode.GetEncoder();

        var unicodeText = new byte[seed.Length * 2];
        enc.GetBytes(seed.ToCharArray(), 0, seed.Length, unicodeText, 0, true);

        System.Security.Cryptography.SHA1 sha = new System.Security.Cryptography.SHA1Managed();

        byte[] result = sha.ComputeHash(unicodeText);

        var sb = new StringBuilder();

        for (int i = 0; i 

It's a simple method that takes a string and returns the hash as digits. On the web server side, I go into my project and use "add existing item."

Then, I navigate to the security class in my Silverlight project, highlight it, then choose "add as link."

This allows me to share the code between the two sides. I can make a change once and ensure both are always in sync. I call this "poor man's WCF RIA." OK, bad joke. Let's move along.

In the ClientBin folder, I add a handler. I do it here because it makes it easy for Silverlight to reference the handler using a relative Uri. Otherwise, I'll have to hack around with the application root and parse strings and do lots of work I just don't care to do. This way, I can reference it as:

...
var handlerUri = new Uri("RssHandler.ashx"); 
...

And be done with it. Silverlight will pass the guid, the key, and the desired Uri. My handler will generate the key from the guid, make sure it matches what was passed, and then proxy the feed. The code looks like this:

[WebService(Namespace = "http://jeremylikness.com/rssReader")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
public class RssHandler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "text/xml";

        if (context.Request.QueryString["key"].Equals(SecurityToken.GenerateToken(context.Request.QueryString["guid"])))
        {
            using (var client = new WebClient())
            {
                context.Response.Write(client.DownloadString(context.Request.QueryString["rssuri"]));
            }
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

Now we need to the build the service on Silverlight.

The Reader Service

First, let's start with the interface for the service. What we want is to pass in the URL of the RSS feed, and receive a list of channels with corresponding items that were fetched from the feed. That ends up looking like this:

public interface IRssReader
{
    void GetFeed(Uri feedUri, Action<List<Channel>> result);
}

Notice I'm making life easy for classes that use the service. They won't have to worry about the asynchronous nature of the service calls or how the result comes back, etc. All that is needed is to pass a method that will accept the list of channels when it becomes available.

As I mentioned earlier, we already did most of the heavy lifting with parsing out the feed, so wiring in the service is very straightforward. The implementation looks like this:

public class RssReader : IRssReader 
{
    private const string PROXY = "RssHandler.ashx?guid={0}&key={1}&rssuri={2}";

    public void GetFeed(Uri feedUri, Action<List<Channel>> result)
    {

        var client = new WebClient();

        Guid guid = Guid.NewGuid();
       
        client.DownloadStringCompleted += ClientDownloadStringCompleted;
        client.DownloadStringAsync(new Uri(
                                       string.Format(PROXY,
                                                     guid,                                                         
                                                     SecurityToken.GenerateToken(guid.ToString()),
                                                     feedUri), UriKind.Relative), result);
    }

    static void ClientDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        var client = sender as WebClient;
        
        if (client != null)
        {
            client.DownloadStringCompleted -= ClientDownloadStringCompleted;
        }

        if (e.Error != null)
        {
            throw e.Error; 
        }

        var result = e.UserState as Action<List<Channel>>; 

        if (result != null)
        {
            result(e.Result.AsXDocument().AsRssChannelList()); 
        }
    }
}

Walking through the steps, we first get the Uri and the method to call when we're done. We wire up a web client and pass it the URL of our handler. This has parameters for the guid and our key, as well as the Uri we want to fetch. We also pass the method to call when we're done. The asynchronous calls all provide a generic object to pass state, so when the call returns we know which version of the call we're dealing with (nice of them, hey?)

When the call is completed, we unhook the event to avoid any dangling references. If there was an error, we throw it. (Yeah, part of our refactoring in future posts will be dealing with all of the errors I'm either throwing or not catching throughout the example). We take the state object and turn it back into an action, then pass the received value as the list of channels using our fluent extensions.

So now we can get it and load it into our models. We need a view model to host all of this!

The View Model

For the first pass on this, I'm going to wire everything myself. No fancy PRISM or MEF extensions, we can refactor those later. Let's get to showing something on the screen.

Our view model should be able to accept the URL of a feed, let the user click "load" and possibly "refresh" on the feed, then show it to us. We want to give them some feedback if the feed isn't a valid Uri, and we probably should keep the load button disabled until there is a valid feed. I ended up creating this for phase one:

public class RssViewModel : INotifyPropertyChanged
{
    private readonly IRssReader _reader; 

    public RssViewModel(IRssReader reader)
    {
        _reader = reader;
        Channels = new ObservableCollection<Channel>();
    }

    private Uri _feedUri;

    private string _uri; 

    public string FeedUri
    {
        get { return _uri; }
        set
        {
            // this will throw an error if invalid, for validation
            _feedUri = new Uri(value);
            _uri = value;
            RaisePropertyChanged("FeedUri");
            RaisePropertyChanged("CanRefresh");
        }
    }

    public bool CanRefresh { get { return _feedUri != null; }}

    public void RefreshCommand()
    {
        if (CanRefresh)
        {
            Channels.Clear();
            _reader.GetFeed(_feedUri, LoadChannels);
        }
    }

    public void LoadChannels(List<Channel> channelList)
    {
        channelList.ForEach(channel=>Channels.Add(channel));
    }

    public ObservableCollection<Channel> Channels { get; set; }

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

    public event PropertyChangedEventHandler PropertyChanged;
}

The view model implements INotifyPropertyChanged to support binding. In lieu of using a converter for the Uri, I decided to deal with it as a string, then cast it to a Uri. If the cast fails, it throws an error, so we can use the Silverlight validation engine to display the error. Only if the text was successfully cast to a valid Uri will we enable the refresh button. When it's clicked, we call the service and clear the list of channels, then populate the list on the return call.

A Basic Page

Now we can throw together some XAML to show it. In this first iteration I'm not about getting stylish or fancy, so I tossed together something fast. I'm using grids in lieu of stack panels so they auto-size well, and a custom ItemsControl that allows vertical scroll bars. We simply add the scroll viewer around the items presenter using a style, like this:

<Style 
    TargetType="ItemsControl" 
    BasedOn="{StaticResource ItemsControlStyle}"
    x:Name="ItemsControlOuterStyle">
    <Setter Property="ItemsControl.Template">
        <Setter.Value>
            <ControlTemplate>
                <ScrollViewer x:Name="ScrollViewer" Padding="{TemplateBinding Padding}">
                    <ItemsPresenter />
                </ScrollViewer>
            </ControlTemplate>
        </Setter.Value>
    </Setter>            
</Style>

I know the high priests of MVVM are going to try and burn me for blasphemy with this next move, but we're still in the proof of concept, OK? So far we have no testing, IoC, nor beautiful command extensions. Yes, you are about to see a plain old code-behind event:

<TextBlock
    Grid.Column="0"
    Margin="5"
    Text="RSS Feed URL:"/>
<TextBox 
    Grid.Column="1"
    Width="200"
    Margin="5"
    Text="{Binding Path=FeedUri,Mode=TwoWay,NotifyOnValidationError=True,ValidatesOnExceptions=True}"/>
<Button
    Grid.Column="2"
    Margin="5"
    IsEnabled="{Binding Path=CanRefresh}"
    Content="Refresh"
    Click="Button_Click"/>

Here you can enter the feed. When you tab out, it will validate it and show an error if it is invalid. If it passes, the button will be enabled.

This next chunk of XAML shows the items. We'll do more refactoring as well. I will introduce the concept of formatters than will parse things like hyperlinks and Twitter hash terms to provide more interactive functionality, but for now let's just get it out there:

<ItemsControl
    Style="{StaticResource ItemsControlOuterStyle}"
    Grid.Row="1" 
    ItemsSource="{Binding Channels}">
    <ItemsControl.ItemTemplate>
        <DataTemplate>
            <Grid 
                Margin="5"
                HorizontalAlignment="Stretch"
                VerticalAlignment="Top">
                <Grid.RowDefinitions>
                    <RowDefinition/>
                    <RowDefinition/>
                    <RowDefinition/>
                </Grid.RowDefinitions>
                    <HyperlinkButton 
                        Grid.Row="0"
                        Margin="5"
                        FontWeight="Bold"
                        Content="{Binding Title}"
                        NavigateUri="{Binding Link}"/>
                    <TextBlock 
                        Grid.Row="1"
                        Margin="5"
                        TextWrapping="Wrap"
                        Text="{Binding Description}"/>
                <ItemsControl 
                    Grid.Row="2"
                    Style="{StaticResource ItemsControlStyle}"
                    ItemsSource="{Binding Items}">
                    <ItemsControl.ItemTemplate>
                        <DataTemplate>
                            <Grid HorizontalAlignment="Stretch"
                                  VerticalAlignment="Top"
                                  Margin="5">
                                <Grid.RowDefinitions>
                                    <RowDefinition/>
                                    <RowDefinition/>
                                </Grid.RowDefinitions>
                                <Grid.ColumnDefinitions>
                                    <ColumnDefinition Width="Auto"/>
                                    <ColumnDefinition Width="Auto"/>
                                </Grid.ColumnDefinitions>
                                <TextBlock 
                                    Margin="5"
                                    Grid.Row="0"
                                    Grid.Column="0"
                                    Text="{Binding PublishDate}"/>
                                <HyperlinkButton
                                    Margin="5"
                                    Grid.Row="0"
                                    Grid.Column="1" 
                                    Content="{Binding Title}"
                                    NavigateUri="{Binding Link}"/>
                                <TextBlock 
                                    Grid.Row="1"
                                    Grid.Column="0"
                                    Grid.ColumnSpan="2"
                                    TextWrapping="Wrap"
                                    Text="{Binding Description}"/>
                            </Grid>
                        </DataTemplate>
                    </ItemsControl.ItemTemplate>
                </ItemsControl>
            </Grid>                   
        </DataTemplate>
    </ItemsControl.ItemTemplate>
</ItemsControl>

Whew! Now we just need to put in a little bit of code behind. We'll enrage the dependency injection purists by creating hard coded instances and further stoke the ire of MVVM evangelists by wiring in a code behind for the button click:

public partial class MainPage
{
    public MainPage()
    {
        InitializeComponent();
        LayoutRoot.DataContext = new RssViewModel(new RssReader());
    }

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        ((RssViewModel)LayoutRoot.DataContext).RefreshCommand();
    }
}

Upon publishing and hitting the service, I was able to pull up my Twitter feed:

That's it. Now we have a proof of concept, and it worked. We have a lot more to do ... making it expandable to handle different types of feeds including HTML, styling it, perhaps looking at using multiple feeds, tests, and the lot (yes, I know, I know, the tests should have come earlier). I hope you enjoyed this first look into my process of creating a basic reader and we'll continue to evolve the project with time!

Download the source for this project

Jeremy Likness

Moq is a library that assists with running unit tests by providing easily mocked objects that implement interfaces and abstract classes. You can learn more about Moq on their website. There is a distribution for Silverlight, and in this post I'll focus on some ways to use Moq for some more involved testing scenarios.

Download the source code for the example project

I started with the Simple Dialog Service in Silverlight and extended the example a bit. In the post, I promised that abstracting the dialog function behind an interface would facilitate unit testing. In this post, I'll deliver on the promise.

Adhering to the pattern I described in Simplifying Asynchronous Calls in Silverlight using Action, I created the interface for a "Thesaurus" service. In this contrived example, we are showing a list of words. You can highlight a word and see the related synonyms in another list. You may also delete the words from the list.

Because we assume in the real word that there are thousands upon thousands of available words and synonyms, the view model won't try to hold a complex object graph. I won't have a special "word" entity that has a nested list of synonyms. Instead, I'll maintain two lists: one of words, and one of the current synonyms. The service will be called when a word is selected to retrieve the list of synonyms for that word.

Enough set up ... let's take a refresher and look at the dialog service interface, along with the new thesaurus interface:

public interface IDialogService
{
   void ShowDialog(string title, string message, bool allowCancel, Action<bool> response);
}

public interface IThesaurus
{
    void GetSynonyms(string word, Action<List<string>> result);

    void ListWords(Action<List<string>> result);

    void Delete(string word);
}

As you can see, the interface is straightforward. In the sample project, I've implemented the dialog using the same code as my previous post (which involves a ChildWindow). The "implementation" of the thesaurus service actually only provides a few words and synonyms but is enough to run the application and see how it would function in the real world.

To run the actual "live" code, right-click on SimpleDialog.Web and choose "Set as startup project." Then, right-click on SimpleDialogTestPage.aspx and choose "Set as start page." Hit F5 and you'll be in business. In this screenshot, I've selected a word that we run into quite often in the development world, and you can see that it has synonyms listed for it:

The view model is straightforward. It expects an implementation of the dialog service and the thesaurus service, then manages well on its own:

public class ViewModel : INotifyPropertyChanged
{
    private readonly IThesaurus _thesaurus;

    private readonly IDialogService _dialog;

    public ViewModel()
    {
        Words = new ObservableCollection<string>();
        Synonyms = new ObservableCollection<string>();
       
        DeleteCommand = new DelegateCommand<object>( o=>ConfirmDelete(), o=>!string.IsNullOrEmpty(CurrentWord));
    }

   public ViewModel(IThesaurus thesaurus, IDialogService dialogService) : this()
    {
        _thesaurus = thesaurus;
        _dialog = dialogService;

        _thesaurus.ListWords(PutWords); 
    }

    public DelegateCommand<object> DeleteCommand { get; set; }

    public ObservableCollection<string> Words { get; set; }

    public void PutWords(List<string> words)
    {
        Words.Clear();
        foreach(string word in words)
        {
            Words.Add(word);
        }

        // default first word
        if (Words.Count > 0)
        {
            CurrentWord = Words[0]; 
        }
    }

    public ObservableCollection<string> Synonyms { get; set; }

    public void PutSynonyms(List<string> synonyms)
    {
        Synonyms.Clear();
        foreach (string synonym in synonyms)
        {
            Synonyms.Add(synonym);
        }
    }

    public void ConfirmDelete()
    {
        _dialog.ShowDialog("Confirm Delete", string.Format("Do you really want to delete {0}?", CurrentWord),
            true, b =>
                      {
                          if (b)
                          {
                              _thesaurus.Delete(CurrentWord);
                              _thesaurus.ListWords(PutWords);
                          }
                      });
    }

    private string _currentWord = string.Empty; 

    public string CurrentWord
    {
        get { return _currentWord; }
        set
        {
            _currentWord = value;
            _thesaurus.GetSynonyms(value, PutSynonyms);
            OnPropertyChanged("CurrentWord");
            DeleteCommand.RaiseCanExecuteChanged();
        }
    }

    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;
        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
}

Let's walk through it briefly. The constructor initializes the lists and the delete command, which requires that there is a CurrentWord selected. When the services are passed in, it requests the list of words and asks the service to call PutWords with the list. This will load the results and set a default "current word" based on the first item in the list.

The current word is interesting, because when it is set, it goes out to request a list of synonyms. This is populated to the synonym list. When the view model is constructed and the list of words is received, it will automatically fire a request for the synonyms by setting the current word. The current word also updates the DeleteCommand so it can be enabled or disabled based on whether or not a word is currently selected.

The delete command itself calls the dialog service for confirmation, and only if the user confirms will it then call the service, delete the word, and then request a new list of words.

This view model is written so that I need almost zero code behind in my user control. The XAML looks like this, and is driven completely by data-binding:

<UserControl x:Class="SimpleDialog.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    xmlns:cal="clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation"
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot" 
        HorizontalAlignment="Center"
        VerticalAlignment="Center">
        <Grid.RowDefinitions>
            <RowDefinition/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition/>
            <ColumnDefinition/>
        </Grid.ColumnDefinitions> 
        <ListBox 
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            ItemsSource="{Binding Words}"
            SelectedItem="{Binding CurrentWord, Mode=TwoWay}"
            SelectionMode="Single"
            Grid.Row="0"
            Grid.Column="0"/>
        <ListBox
            HorizontalAlignment="Center"
            VerticalAlignment="Center"            
            Width="Auto"
            ItemsSource="{Binding Synonyms}"
            Grid.Row="0"
            Grid.Column="1"/>
        <Button 
            HorizontalAlignment="Center"
            VerticalAlignment="Center"            
            Width="Auto"
            Content="Delete"
            Grid.Row="1"
            Grid.Column="0"
            cal:Click.Command="{Binding DeleteCommand}"/>
  </Grid>
</UserControl>

The key here is the bindings from the delete button to the delete command, and the list box of words to the "current word." This allows all of the other updates to cascade accordingly. I said I had "almost no" code behind. This is because I'm traveling light and decided not to drag an IoC container into the example. Therefore, in the code behind, I manually wire up the view model like this:

public MainPage()
{
    InitializeComponent();
    DataContext = new ViewModel(new Thesaurus(), new DialogService());
}  

Now that we've set the stage, the real focus of this post is how to test what we've just created. I have a view model that does quite a bit, and want to make sure it is behaving. To make this happen, I'll do two things. First, I'll add the Silverlight Unit Testing Framework. I first discussed it in my post about unit testing views AND view models. Next, I'll navigate to the Moq page and download the Silverlight bits (all of this is included in the reference project).

My test class is "view model tests." The first thing I need to do is set up some support for the tests. We want a pretend list of words and synonyms, and mocks for the services the view model depends on. Our class starts out like this:

[TestClass]
public class ViewModelTests
{
    private readonly List<string> _words = new List<string> {"test", "mock"};

    private readonly List<string> _synonyms = new List<string> {"evaluation", "experiment"};

    private readonly List<String> _mockSynonyms = new List<string> {"counterfeit", "ersatz", "pseudo", "substitute"};

    private Mock<IDialogService> _dialogMock;

    private Mock<IThesaurus> _thesaurusMock;

    private ViewModel _target;
}

We created two words with synonym lists. The mocking of the services is as simple as declaring Mock<T>. There is more to it that we'll cover, but this gets us started. I like to always have a reference to the object I am testing as target to make it clear what the test is run for.

Now we will need to set up the view model for all of our tests. Just like with the standard unit testing framework, we can flag a method as TestInitialize to do set up before each test is run. Take a look at my setup:

[TestInitialize]
public void InitializeTests()
{
    _dialogMock = new Mock<IDialogService>();

    _thesaurusMock = new Mock<IThesaurus>();

    _thesaurusMock.Setup(
        t => t.ListWords(It.IsAny<Action<List<string>>>()))
        .Callback((Action<List<string>> action) => action(_words));

    _thesaurusMock.Setup(
        t => t.GetSynonyms(It.Is((string s) => s.Equals(_words[0])), It.IsAny<Action<List<string>>>()))
        .Callback((string word, Action<List<string>> action) => action(_synonyms));

    _thesaurusMock.Setup(
        t => t.GetSynonyms(It.Is((string s) => s.Equals(_words[1])), It.IsAny<Action<List<string>>>()))
        .Callback((string word, Action<List<string>> action) => action(_mockSynonyms));

    _target = new ViewModel(_thesaurusMock.Object, _dialogMock.Object);
}

We create a new mock for every test so the internal counters are reset. Then, it gets a little interesting. The setup command allows you to determine what an expected call will be, and to provide results. Many methods return values, and there is a Result method to use for providing what those values should be. In our case, however, the methods do not return anything because they call the Action when complete. Therefore, we set up a callback so that we can perform an action when the method is fired.

To see how that works, take a look at the first set up. We are setting up our mock for the thesaurus service. The lambda expression indicates we expect the ListWords to be called, and the parameter can be any action that acts on a list of a strings. Now the important part: the callback. The callback has the same signature as the method. When the method is called, Moq will fire the callback and send the parameters. In our case, we take the action that was passed in, and call it with our list of words. This will mock the process of the view model requesting the word list, then having the PutWords method called with the actual list.

Next, we set up the GetSynonyms method twice. This is because we want to pass a different result based on the word that the method is called with. Instead of IsAny, we'll use Is with a lambda that determines what will pass. In this way, we can compare specific values or even ranges. If the passed value is the first word, we call the action with the synonym list. If the passed value is the second word ("mock"), we call the action with the list of mocks. If any other value is passed in, we simply don't care so we haven't set that up.

The first test we'll make is for setup. In other words, after the view model is constructed, we simply want to test that everything was set up appropriately. The view model promises to provide us with lists and commands, so we need to ensure these will be available when we bind to it.

[TestMethod]
public void TestConstructor()
{
    // make sure it made the call
    _thesaurusMock.Verify(t => t.ListWords(_target.PutWords), Times.Exactly(1),
                          "List words method was not called.");
    _thesaurusMock.Verify(
        t => t.GetSynonyms(It.Is((string s) => s.Equals(_words[0])), It.IsAny<Action<List<string>>>()),
        Times.Exactly(1),
        "Synonym method never called for first word.");
    Assert.AreEqual(_target.CurrentWord, _words[0], "View model did not default target word.");
    Assert.IsNotNull(_target.DeleteCommand, "Delete command was not initialized.");
    Assert.IsTrue(_target.DeleteCommand.CanExecute(null),
                  "Delete command is disabled when selected word exists.");
    CollectionAssert.AreEquivalent(_words, _target.Words, "Words do not match.");
    CollectionAssert.AreEquivalent(_synonyms, _target.Synonyms, "Synonyms do not match.");
}

The setup commands "rigged" what we expect when a method is called. If these were the only actions we took, this would really be a "stub" (something there to make it happen) rather than a mock (something that changes and can be inspected after the test to determine the outcome). With Moq, we use verify to inspect the state of the mocked object. First, we verify that the word list was called exactly once. Next, we verify that the synonym list was called specifically with the first word. Next, we are comparing values, lists, and commands to make sure they are as we expect. For example, the view model should have already populated a list of synonyms that matches the first word, so we use the CollectionAssert to make sure the lists are equivalent.

Now we can do a little more in depth test. Let's test selection. When we select the second word by setting the CurrentWord property, the view model should call the thesaurus service to retrieve the list of synonyms for 'mock.' The test looks like this:

[TestMethod]
public void TestSelection()
{
    _target.CurrentWord = _words[1]; 

    CollectionAssert.AreEquivalent(_mockSynonyms, _target.Synonyms, "Synonyms did not update.");
}

Technically, I could have verified the call as well and if you feel that is necessary, then by all means include that test. In this case, I know the synonym list simply won't update itself, so if it ends up changing to the list I'm expected, I'm confident that the call took place. Therefore, I simply test that the mock synonyms were updated to the collection of synonyms on the view model.

What about a more complicated test? Our delete command requires confirmation, so the user doesn't accidentally delete a word they did not intend to. Therefore, we need to set up the dialog service to return the results we want. We'll have two tests: one that ensures the delete service is called when the user confirms, and another that ensures it is NOT called when the user cancels. The confirm test looks like this:

[TestMethod]
public void TestDeleteConfirm()
{
    _thesaurusMock.Setup(t => t.Delete(It.IsAny<string>())); 

    _dialogMock.Setup(
        d => d.ShowDialog(It.IsAny<string>(),
                          It.IsAny<string>(),
                          It.IsAny<bool>(),
                          It.IsAny<Action<bool>>()))
        .Callback(
        (string title, string message, bool cancel, Action<bool> action) => action(true));

    _target.DeleteCommand.Execute(null);

    _thesaurusMock.Verify(
        t => t.Delete(It.Is((string s) => s.Equals(_words[0]))),
        Times.Exactly(1),
        "The delete method was not called on the service.");
}

First we set up the service to expect the delete call. Next, we set up the dialog. We don't care about the parameters passed in. All we care about is that we call the action with "true" to simulate a user confirming the dialog. Once this is set up, we trigger the delete command, and verify that the delete service was called for the appropriate word.

For the cancel, we pass false in the action, and use Times.Never() on the method signature to ensure the delete service was not called.

Finally, because our delete command is only enabled when a current word is selected, we need to test that it is disabled with no words:

[TestMethod]
public void TestDeleteEnabled()
{
    _target.CurrentWord = string.Empty; 

    Assert.IsFalse(
        _target.DeleteCommand.CanExecute(null),
        "Delete command did not disable with empty word selection.");
}

We already tested for the positive case in the constructor. Now, we simply clear the selection and confirm that the command is no longer allowed to execute.

If you ran the application earlier, you simply need to set the "test" project as the start-up project to run the unit tests. They will run directly in the browser.

As you can see, using the MVVM pattern appropriately ensures straightforward XAML (mostly binding-driven without cluttered code-behind) and very granular testing. Tools like Moq can make it much easier to test complicated scenarios by allowing you to easily set up dependencies, mock returns, and ultimately validate that the view model is behaving the way it is expected to.

Download the source code for the example project

Jeremy Likness

Live Smooth Streaming is a Microsoft technology that allows you to take a live, encoded, incoming video stream and rebroadcast it using Smooth Streaming technology. This technology multicasts the video stream in segments of varying bandwidths. This can then be played with a Silverlight-based client like the built-in MediaElement or more advanced player like the Silverlight Media Framework.

The incoming streams could be from your web cam or third party sources, or even from a file encoded on disk that is being webcast at a particular point in time. The live smooth streaming allows the client to adjust to the current network load and gracefully degrade quality when the network slows to avoid having to pause the playback and force the user to wait for a new buffer. The user can also rewind the "live content," and there are options to archive it to play on demand at a later date.

A content network with many live streams might have multiple servers and cabinets in their data centers to serve content. In that scenario, programmatic management of endpoints becomes essential to effectively scale the operation. If you find yourself needing to automate some aspects of starting, stopping, shutting down or creating publishing points for live streaming, you're in luck!

Let's start with a few entities to help us handle publishing points. A publishing point can have a stream state (the status of the encoding stream it is listening to), and archive state (the status of the stream it is archiving to) and a fragment stream that enables insertion of other content to the stream. These various nodes on the publishing point share a common set of states:


public enum State
{
    Disabled,
    Started,
    Stopped,
    Unknown
}

These are fairly self-explanatory. "Unknown" simply means the publishing point is in a status, such as stopped or shut down, when it doesn't make sense for the node to have a valid status.

The publishing point itself has a more involved list of states. For an excellent overview, read this article on creating and managing publishing points. Here are the states:


public enum PublishingPointState
{
    Idle,
    Starting,
    Started,
    Stopping,
    Stopped,
    Shuttingdown,
    Error,
    Unknown
}

Again, these are fairly self-explanatory. Idle happens when the publishing point has been created, but no action has been taken against it, or it is shut down. Starting indicates it is ready to receive a feed, and started means it is actively processing one.

Let's go ahead and build an entity to represent the publishing point:


public class PublishingPoint
{        
    public State StreamState { get; set; }

    public State ArchiveState { get; set; }

    public State FragmentState { get; set; }

    public PublishingPointState PubState { get; set; }

    public string SiteName { get; set; }

    public string Path { get; set; }

    public string Name { get; set; }
}

The first few properties are the various states of the nodes and the publishing point itself. The site name is the website it is configured on. This will usually be "Default Web Site." The Path is the virtual path (not the physical path) the publishing point resides in (also known as the Application), and the name is the actual name of the publishing point.

While there is not a strongly typed API to interface directly with the live smooth streaming configuration as of this writing, we can easily reach it through the new administration classes. With IIS 7.0 and smooth streaming installed, you should be able to find Microsoft.Web.Administration.dll in your %windir%\system32\inetsrv directory. Reference this DLL, and you can programmatically access web sites. You can also interact with configurations through a reflection-style interface that we'll cover here.

Get the List of Publishing Points

Our first task is to get a list of publishing points.


private const string LIVESTREAMINGSECTION = "system.webServer/media/liveStreaming";
private const string METHODGETPUBPOINTS = "GetPublishingPoints";
private const string ATTR_SITENAME = "siteName";
private const string ATTR_VIRTUALPATH = "virtualPath";
private const string ATTR_NAME = "name";
private const string ATTR_ARCHIVES = "archives";
private const string ATTR_FRAGMENTS = "fragments";
private const string ATTR_STREAMS = "streams";
private const string ATTR_STATE = "state";
        
public List<PublishingPoint> GetPublishingPoints()
{
    var retVal = new List<PublishingPoint>();

    using (var serverManager = new ServerManager())
    {
        Configuration appHost = serverManager.GetApplicationHostConfiguration();

        try
        {
            ConfigurationSection liveStreamingConfig = appHost.GetSection(LIVESTREAMINGSECTION);

            foreach (Site site in serverManager.Sites)
            {
                foreach (Application application in site.Applications)
                {
                    try
                    {
                        ConfigurationMethodInstance instance =
                            liveStreamingConfig.Methods[METHODGETPUBPOINTS].CreateInstance();

                        instance.Input[ATTR_SITENAME] = site.Name;
                        instance.Input[ATTR_VIRTUALPATH] = application.Path;

                        instance.Execute();

                        ConfigurationElement collection = instance.Output.GetCollection();

                        foreach (var item in collection.GetCollection())
                        {
                            retVal.Add(new PublishingPoint
                                           {
                                               SiteName = site.Name,
                                               Path = application.Path,
                                               Name = item.Attributes[ATTR_NAME].Value.ToString(),
                                               ArchiveState = (State) item.Attributes[ATTR_ARCHIVES].Value,
                                               FragmentState = (State) item.Attributes[ATTR_FRAGMENTS].Value,
                                               StreamState = (State) item.Attributes[ATTR_STREAMS].Value,
                                               PubState =
                                                   (PublishingPointState) item.Attributes[ATTR_STATE].Value
                                           });
                        }
                    }
                    catch (COMException ce)
                    {
                        Debug.Print(ce.Message);
                    }
                }
            }
        }
        catch (COMException ce)
        {
            Debug.Print(ce.Message);
        }
    }

    return retVal;
}

The ServerManager is our hook into administration. All of the configuration for the live smooth streaming is in the APPHOST section of the configuration, which we fetch at the beginning of the method by grabbing the configuration and then navigating to system.webServer/media/liveStreaming.

The method to fetch publishing points requires a web site and an application (virtual directory). We iterate through these and use the ConfigurationMethodInstance to ask for the this. The new IIS configuration extensions allow methods and API hook points to be defined in the configuration itself, with a set of inputs and outputs. You can read more about the ConfigurationMethod. We use this and pass in the web site name and application, to receive the list of publishing points. Notice how we get a generic collection of ConfigurationElement and reference the attributes to build our more strongly-typed PublishingPoint object.

Of course, there are multiple areas where exceptions may be thrown. In the example, I capture the COM errors and just print them to debug. You can interrogate the error code and provide more specific feedback as to why the call failed.

Starting, Stopping, and Shutting Down Publishing Points

Now that we have a publishing point, we can stop, start, and shut it down. This is also done through a configuration method. The method names for the action are:


public enum PublishingPointCommand
{
    Start,
    Stop,
    Shutdown
}

The method names are the actual text, so we can use the ToString() method on the enum to pass the command. Issuing a command against a specific publishing point now looks like this:


private static void _IssueCommand(PublishingPoint publishingPoint, PublishingPointCommand command)
{
    using (var serverManager = new ServerManager())
    {
        Configuration appHost = serverManager.GetApplicationHostConfiguration();

        ConfigurationSection liveStreamingConfig = appHost.GetSection(LIVESTREAMINGSECTION);

        if (liveStreamingConfig == null)
        {
            throw new Exception("Couldn't get to the live streaming section.");
        }

        ConfigurationMethodInstance instance =
            liveStreamingConfig.Methods[METHODGETPUBPOINTS].CreateInstance();

        instance.Input[ATTR_SITENAME] = publishingPoint.SiteName;
        instance.Input[ATTR_VIRTUALPATH] = publishingPoint.Path;

        instance.Execute();

        // Gets the PublishingPointCollection associated with the method output
        ConfigurationElement collection = instance.Output.GetCollection();

        foreach (var item in collection.GetCollection())
        {
            if (item.Attributes[ATTR_NAME].Value.ToString().Equals(publishingPoint.Name))
            {
                var method = item.Methods[command.ToString()];
                var methodInstance = method.CreateInstance();
                methodInstance.Execute();
                break;
            }
        }
    }
}

Of course, you can probably see a place where it makes sense to refactor some code, because we're spinning through the collection again. This time, instead of turning it into a concrete type, we are taking the specific item in the collection for the publishing point we're targeting, then creating an instance of the command method and firing it off. Simple as that!

Creating the Publishing Point

So now we can manipulate and gather information about a point, but what about creating it? If you are frustrated trying to find where in the API you can call a "Create" method, take a deep breath and step away from the configuration collection. It's not there. To create a publishing point, we simply drop a file on the system! That's right. If you create a new publishing point, you can navigate to the file system and set an .isml file. Open it in notepad and you'll find the format is straightforward:

<?xml version="1.0" encoding="utf-8"?>
   <smil xmlns="http://www.w3.org/2001/SMIL20/Language">
      <head>
         <meta name="title" content="Pub Point Title" />
         <meta name="module" content="liveSmoothStreaming" />
         <meta name="sourceType" content="Push" /><!-- or Pull -->
         <meta name="publishing" content="Fragments;Streams;Archives" />
         <meta name="estimatedTime" content="00:11:22" />
         <meta name="lookaheadChunks" content="2" />
         <meta name="manifestWindowLength" content="0" />
         <meta name="startOnFirstRequest" content="False" />
         <meta name="archiveSegmentLength" content="0" />
      </head>
   <body/>
</smil>

That's it ... very straightforward. Give it a title, make it push or pull, and estimate the time. Of course, you can manipulate some of the more advanced features as well, but for a basic interface, this is all we need. We'll store the XML with a constant that holds the template called ISML_TEMPLATE. When the user requests a new publishing point, we'll find the right virtual directory, get the physical path, and then write out the file:

public enum LiveSourceType
{
    Push,
    Pull
}

public bool CreatePublishingPoint(PublishingPoint publishingPoint, string title, string duration, LiveSourceType type)
{

    bool retVal = false;

    using (var manager = new ServerManager())
    {
        Site site = manager.Sites[publishingPoint.SiteName];

        Application application = site.Applications[publishingPoint.Path];

        string template =
            string.Format(ISML_TEMPLATE, title, type, duration ?? string.Empty);

        try
        {
            string path = string.Format(@"{0}\{1}", application.VirtualDirectories[0].PhysicalPath,
                                        publishingPoint.Name);

            File.WriteAllText(path, template);

            retVal = true;
        }
        catch (Exception ex)
        {
            Debug.Print(ex.Message);
        }
    }

    return retVal;
}

This is fairly straightforward to give you the point. In production, you'll need to test for nulls (i.e. if the site doesn't exist, a null template is passed in, etc) and may want to validate that it was created successfully by enumerating the list after creation. I'd also recommend creating an XmlDocument or XDocument for more advanced titles ... in this example, using string format, we can make it fast but must make sure the title is clean or escape it before making it part of the source XML.

That's it ... in a nutshell, you now have all of the bits and pieces needed to interface programmatically with the Live Smooth Streaming APIs. I have no sample project because this is intended to be a guideline for your own explorations and use of the system. I would also suggest the excellent blog by Ezequiel Jadib which contains loads of information about smooth streaming.

Jeremy Likness

I've had a few users ask me about finding memory leaks and understanding what happens with references in Silverlight. One very powerful tool to use when debugging Silverlight applications is the Windows Debugging Tools. You can download the 32-bit (x86) version side-by-side with the 64-bit (x64) version.

Both WPF and Silverlight ship with an extension DLL you can load called SOS. This extension contains many powerful commands.

In the video, Silverlight Debugging with WinDbg (30 minutes long), I walk through a debugging scenario using my Fractal Koch Snowflakes.

I show how to dump the heap, walk object references, see which references are targetted for garbage collection and which ones still have root references, examine event handlers and delegates to trace back to the target methods, an unroll lists and arrays. It's sort of a "firehose" approach but with a real world example that I hope helps drive home how powerful it can be.

Watch the video by clicking here (30 minutes).

Jeremy Likness

I noticed on the forums there are a lot of users not comfortable with asynchronous programming who struggle a bit in Silverlight with getting their arms around the concept of a dialog box. In other environments, you can simply shoot out a dialog, wait for the response, and continue. In Silverlight, of course, the action is asynchronous. I would argue it should be this way most of the time.

The problem is that many people tend to take the approach of trying to force the process into a synchronous one, instead of changing the way they think and approach the application. There is a reason why processes are asynchronous in Silverlight. There is one main UI thread, and a blocking process would block the entire thread and effectively freeze the Silverlight application. Having the process asynchronous allows you to continue to render graphics elements, perform actions in the background, even display a soothing animation while you await the user's response.

I spoke to a more highly decoupled approach in a post awhile ago that was more an experiment with the event aggregator: Decoupled Child Window Dialogs with Silverlight and PRISM. Here, I want to show the more straightforward approach.

The first step is to choose what the dialog will be displayed with. In Silverlight, the ChildWindow makes perfect sense because it is a modal dialog that appears, waits for the user response, and then saves the response. We'll create a new child window and call it Dialog.xaml. It looks like this:

<controls:ChildWindow x:Class="SimpleDialog.Dialog"
           xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
           xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
           xmlns:controls="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls"
           Width="400" Height="300" 
           Title="{Binding Title}">
    <Grid x:Name="LayoutRoot" Margin="2">
        <Grid.RowDefinitions>
            <RowDefinition />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBlock TextWrapping="Wrap" Grid.Row="0" Text="{Binding Message}"/>
        <Button x:Name="CancelButton" Content="Cancel" Click="CancelButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,0,0" Grid.Row="1" />
        <Button x:Name="OKButton" Content="OK" Click="OKButton_Click" Width="75" Height="23" HorizontalAlignment="Right" Margin="0,12,79,0" Grid.Row="1" />
    </Grid>
</controls:ChildWindow>

You'll notice I made very few changes from the provided template. The key here is that I changed the title to bind with the Title property, and added a text block to display a message from the Message property.

Because this is a simple dialog box, I really feel a view model is overkill. Some purists will insist on this but I argue the functionality is simple enough that we don't need the extra overhead. We'll be using an interface to the solution down the road that we can easily unit test, and this makes the dialog function (which lives entirely in the UI) a self-contained implementation.

Next, I made a few changes to the code behind:

public partial class Dialog : ChildWindow
{
    public Action<bool> CloseAction { get; set; }

    public static readonly DependencyProperty MessageProperty = DependencyProperty.Register(
        "Message",
        typeof(string),
        typeof(Dialog),
        null);


    public string Message
    {
        get { return GetValue(MessageProperty).ToString(); }
        set { SetValue(MessageProperty, value); }
    }

    public Dialog()
    {
        InitializeComponent();
        DataContext = this;
    }        

    public Dialog(bool allowCancel)
        : this()
    {
        CancelButton.Visibility = allowCancel ? Visibility.Visible : Visibility.Collapsed;
    }

    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = true;            
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        this.DialogResult = false;           
    }
}

Again, not too many changes here. I added the Message property as a dependency property, and in the constructor I set the data context to itself. This allows me to bind to the title and message. This allows us to simply set the message on the dialog and have it appear. I also added an action for it to retain when closed. This will store a callback so that it can notify the host of the user's final actions. Finally, there is a method that conditions whether or not there is the option for a cancel button. For alerts, we'll simply show an OK button. For confirmations, we'll show the Cancel button as well.

Next is a simple interface to the dialog. Nothing in our application should know or care how the dialog is displayed. There is simply a mechanism to display the dialog and possibly acquire a response. The interface looks like this:

public interface IDialogService
{
    void ShowDialog(string title, string message, bool allowCancel, Action<bool> response);
}

In our simple demonstration, I'm allowing for a title, a message, whether or not you want to show the cancel button for confirmations, and then an action to call with the response. With this simple interface we have all we need to wire in unit tests for services and controls that rely on the dialog. You can create your own mock object that implements the IDialogService interface and returns whatever response you want to stage for the unit test.

In the production application, we'll need to show a real dialog. Here is the class that handles it:

public class DialogService : IDialogService
{
    #region IDialogService Members

    public void ShowDialog(string title, string message, bool allowCancel, Action<bool> response)
    {
        var dialog = new Dialog(allowCancel) {Title = title, Message = message, CloseAction = response};
        dialog.Closed += DialogClosed;
        dialog.Show();
    }

    static void DialogClosed(object sender, EventArgs e)
    {
        var dialog = sender as Dialog;
        if (dialog != null)
        {
            dialog.Closed -= DialogClosed; 
            dialog.CloseAction(dialog.DialogResult == true);
        }
    }

    #endregion
}

This is fairly straightforward. When called, we'll create an instance of the dialog and set the various properties, including the callback. We wire into the closed event. Whether the user responds by clicking a button or closing the dialog, this event is fired.

There is a reason why we are using the snippet DialogResult == true. The result is null-able, so we cannot simply refer to the value itself and make a true/false decision (null, by definition, is unknown). So only if the user explicitly provides a true response by clicking the OK button will the expression evaluate to true. Otherwise, we assume false and call back with the response.

There is also a very important step here that is important to recognize. Many beginners fail to catch this subtle step and end up with memory leaks. When the closed event fires, the dialog box effectively closes. Typically, there would be no more references to it (it is no longer in the visual tree) and it can be cleaned up by garbage collection. However, there is a fatal mistake you can make that will result in the dialog box never going away.

That mistake has to do with how events work. When we register the closed event, the thought process is often that the dialog box has an event, and therefore knows to call back to the dialog service. This is flawed, however. A reference exists from the dialog service to the dialog box. The dialog service effectively "listens" for the event, and when it is raised, will respond. We must unregister the event like this:

dialog.Closed -= DialogClosed;

Otherwise, the reference remains and garbage collection will never claim the dialog box resource. In a long running application, this could prove to be a serious flaw. This line is not included in the code sample download. I encourage you to run with windbg or even step through debug in Visual Studio and watch the object graphs and reference counts as you fire multiple dialogs. Then, add the line of code above and re-run it to see the difference when you appropriately unregister the event.

To demonstrate the use of the service, I put together a quick little page with a few buttons and a text block:

<UserControl x:Class="SimpleDialog.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
    mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
  <Grid x:Name="LayoutRoot">
        <StackPanel Orientation="Vertical">
            <Button x:Name="ToggleEnabled" 
                    HorizontalAlignment="Center"
                    Margin="5" Width="Auto" Content="Disable Dialog Button" Click="ToggleEnabled_Click"/>
            <Button x:Name="DialogButton" 
                    HorizontalAlignment="Center"
                    Margin="5" Width="Auto" Content="DialogButton" Click="DialogButton_Click"/>
            <TextBlock x:Name="TextDialog" 
                       HorizontalAlignment="Center"
                       Margin="5" Width="Auto" Text="Result Will Show Here"/>
        </StackPanel>
    </Grid>
</UserControl>

The first button is a toggle to enable or disable the second button. It shows how to receive a response and act based on the user input. If the user confirms, the button is toggled to enabled or disabled. If the user cancels or closes the dialog, the state of the button remains the same. The second button raises a dialog, and simply shows the result. Because it is an alert dialog, we know a false response indicates the user closed the window instead of clicking OK.

Here is the code behind:

public partial class MainPage : UserControl
{
    private bool _toggleState = true;
    private readonly IDialogService _dialog = new DialogService();

    public MainPage()
    {
        InitializeComponent();
    }

    private void ToggleEnabled_Click(object sender, RoutedEventArgs e)
    {
        _dialog.ShowDialog(
            _toggleState ? "Disable Button" : "Enable Button",
            _toggleState
                ? "Are you sure you want to disable the dialog button?"
                : "Are you sure you want to enable the dialog button?",
            true,
            r =>
                {
                    if (r)
                    {
                        _toggleState = !_toggleState;
                        DialogButton.IsEnabled = _toggleState;
                        ToggleEnabled.Content = _toggleState ? "Disable Dialog Button" : "Enable Dialog Button";
                    }
                });
    }

    private void DialogButton_Click(object sender, RoutedEventArgs e)
    {
        _dialog.ShowDialog(
            "Confirm This",
            "You have to either close the window or click OK to confirm this.",
            false,
            r => { TextDialog.Text = r ? "You clicked OK." : "You closed the dialog."; });
    }
}

Notice that in the click events, we call to the dialog service and pass it anonymous methods for the return types. We could point to real methods on the class as well. The important part is to change your thought process from synchronous step one => wait => step two to asynchronous step one => delegate to step two, then step two is called when ready.

In a production application, instead of creating an instance of the dialog box, we would either register it with a container:

Container.RegisterInstance<IDialogService>(Container.Resolve<DialogService>());

And inject it in a constructor, or use something like MEF and import the dialog service:

[Import]
public IDialogService Dialog { get; set; }

We would simply flag the implementation as the export or use the InheritedExport attribute on the interface itself.

Click here to download the source code for this example.

Jeremy Likness

A new version of Silverlight 3 has been released.

You can download the latest control here. If you are a developer, then you'll want to use the developer installer that is available here.

This version fixes some issues related to hardware acceleration in the graphics processing unit (GPU), certain cases that cause Deep Zoom to take on high CPU, and issues with downloads from Silverlight applications.

Read Microsoft's Knowledge Base article for this release: Description of the update for Silverlight: January 19, 2010.

Jeremy Likness

One concern with the Silverlight Unit Testing Framework is that it runs on a UI thread and requires a browser to function. This makes it difficult to integrate into automated or continuous integration testing. Difficult, but not impossible.

A solution is provided by the project called StatLight which not only supports Silverlight testing automation, but actually integrates with several different unit test providers. I am focusing on the Silverlight UT for this post. The program is very flexible and will even run as an continuous test server by watching a XAP file for changes and triggering the tests when it does. It will output to the console and to an XML formatted file, making it easy to grab and process test results.

I decided to run the tests I made in the Unit Testing Asynchronous Behaviors in Silverlight post. First, I headed over to the StatLight web site and downloaded the project. I simply unzipped it into a folder to "install."

Next, I copied the XAP file for my tests, called PRISMMEF.Tests.xap, into the folder with StatLight (you can reference the full path, this was just for convenience). I created a subdirectory called reports.

I launched a command line as administrator. StatLight launches its own web service so elevated permissions are required to allow it to bind to the appropriate ports. At the command line, I ran the following. It started the test run, placed a dot on my screen for every test run, and then completed.

Silverlight Unit Test Automation

This resulted in the following output as a file called report.xml:

<StatLightTestResults xapFileName="PRISMMEF.Tests.xap" total="6" ignored="0" failed="0" dateRun="2010-01-08 19:15:18">
  <tests>
    <test name="PRISMMEF.Tests.Common.PartModuleTest.TestConstructor" passed="True" timeToComplete="00:00:00.0290016" />
    <test name="PRISMMEF.Tests.Common.PartModuleTest.TestInitialization" passed="True" timeToComplete="00:00:00.1300074" />
    <test name="PRISMMEF.Tests.Common.ViewModelBehaviorTest.TestAttach" passed="True" timeToComplete="00:00:00.0340020" />
    <test name="PRISMMEF.Tests.Common.ViewModelBehaviorTest.TestFromXaml" passed="True" timeToComplete="00:00:00.1100063" />
    <test name="PRISMMEF.Tests.Common.ViewModelProviderTest.TestConstruction" passed="True" timeToComplete="00:00:00.0630036" />
    <test name="PRISMMEF.Tests.Common.ViewModelProviderTest.TestPropertyChange" passed="True" timeToComplete="00:00:00.0520030" />
  </tests>
</StatLightTestResults>

From this, you can quickly see what I do with my Friday evenings. Seriously, it's a nice, simply, easy to iterate XML format that I can plug into my build scripts, parse with a program or even use simple XSLT and generate nice automated reports for the results of testing and even fail a build based on failed results.

Jeremy Likness

More Posts Next page »