Wintellect  

Browse by Tags

All Tags » codeproject   (RSS)

I am working on a project that involves a centralized UI that then coordinates with agents to send out instructions. The agents will be WCF endpoints and to ease deployment/minimize the install footprint, they will install as windows services with a nice installer rather than hanging onto an IIS webspace directly.

In this post I want to walk you through the process of creating that WCF host programmatically, as well as a small little tweak that will allow you to run and test without having to install the service. It's actually quite easy to do but it's one of those things that can produce an "ah-hah!" moment if you haven't done it before.

To start with, let's create a simple service and operation contract. Create a new interface, call it IHelloWorldService, and add a method, like this:


[ServiceContract(Namespace="http://wintellect.com/sample")]
public interface IHelloWorldService
{
    [OperationContract]
    [FaultContract(typeof(Exception))]
    string Hi();
}

You'll have to add references and usings for System.ServiceModel.

Next, implement the interface:


public class HelloWorldService : IHelloWorldService
{
    const string REPLY = "Hello, world."; 

    public string Hi()
    {
        return REPLY; 
    }

}

That's all it takes to make your WCF service. Now we just need a way to host it. Add another reference to System.ServiceProcess. Create a new class called HelloServiceHost and derive it from ServiceBase. Now we'll get a little interesting:


public class HelloServiceHost : ServiceBase
{
    const string CONSOLE = "console";

    public const string NAME = "HelloWorldService"; 

    ServiceHost _serviceHost = null;

    public HelloServiceHost()
    {
        ServiceName = NAME; 
    }

    public static void Main(string[] args)
    {
        if (args.Length == 1 && args[0].Equals(CONSOLE))
        {
            new HelloServiceHost().ConsoleRun();
        }
        else
        {
            ServiceBase.Run(new HelloServiceHost());
        }
    }

    private void ConsoleRun()
    {
        Console.WriteLine(string.Format("{0}::starting...",GetType().FullName));

        OnStart(null);

        Console.WriteLine(string.Format("{0}::ready (ENTER to exit)", GetType().FullName));
        Console.ReadLine();

        OnStop();

        Console.WriteLine(string.Format("{0}::stopped", GetType().FullName));
    }

    protected override void OnStart(string[] args)
    {
        if (_serviceHost != null)
        {
            _serviceHost.Close();
        }

        _serviceHost = new ServiceHost(typeof(HelloWorldService));
        _serviceHost.Open();
    }

    protected override void OnStop()
    {
        if (_serviceHost != null)
        {
            _serviceHost.Close();
            _serviceHost = null;
        }
    }
}

Let's break it down. We're derived from service base, and need a service host to actually present the WCF end point. In the constructor, we set the service name. In the Main class, which is called for both console applications and service applications, we check the arguments. If you pass in "console" as an argument, it will create a new instance and run it directly. Otherwise, it calls into the ServiceBase to run as a Windows service.

The ConsoleRun is stubbed out to give you a nice message that it is starting, then manually call the start event and wait for a line to be entered. When you hit ENTER, it will close the service and shut down. This is what enables us to take the generated executable, and call it, like:
HelloWorldService.exe console
and then debug interactively without having to install it as an actual service.

The OnStart and OnStop overrides do basic housekeeping for registering the types of the endpoints that will be active (this one process could host several endpoints, if you so desired) and shutting down when finished.

Of course, you'll need to add an app.config file and come up with your end point name. It can run on existing IIS ports, but must have a unique URL. I set mine up like this:


<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      <service name="HelloWorldService.HelloWorldService" behaviorConfiguration="HelloWorldServiceBehavior">
        <host>
          <baseAddresses>
            <add baseAddress="http://localhost:80/helloworld"/>
          </baseAddresses>
        </host>
        <endpoint address=""
                  binding="wsHttpBinding"
                  contract="HelloWorldService.IHelloWorldService"/>
        <endpoint address="mex"
                  binding="mexHttpBinding"
                  contract="IMetadataExchange"/>
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="HelloWorldServiceBehavior">
          <serviceMetadata httpGetEnabled="true"/>
          <serviceDebug includeExceptionDetailInFaults="False"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>

Once this is in place, you should be able to compile, browse to the directory it is in, and run the program with the "console" argument (no dashes or anything special). Once it is waiting for a keypress, go to a web browser and navigate to http://localhost/helloworld?wsdl and you should see the WSDL for your service. At this point you could hook it up to a test harness, use SoapUI, or about any other method for testing and start doing things with the service.

Of course, eventually the goal is to allow it to be installed as a Windows service. For that, add a reference to System.Configuration.Install. Add a new class and call it ProjectInstaller. Derive the class from Installer. The class will look like this:


[RunInstaller(true)]
public class ProjectInstaller : Installer
{
    const string DESCRIPTION = "Hello world service host.";
    const string DISPLAY_NAME = "Hello World Service";

    private ServiceProcessInstaller _process;
    
    private ServiceInstaller _service;

    public ProjectInstaller()
    {
        _process = new ServiceProcessInstaller();
        _process.Account = ServiceAccount.LocalSystem;
        _service = new ServiceInstaller();
        _service.ServiceName = HelloWorldService.NAME;
        _service.Description = DESCRIPTION;
        _service.DisplayName = DISPLAY_NAME; 
        Installers.Add(_process);
        Installers.Add(_service);
    }
}

Now you can navigate to the command line and use installutil.exe to install it as a bona fide Windows service.

I'm not including a demo project because this should be fairly straightforward and I've included 100% of the code in this post ... I bet you might not have known hosting a WCF service outside of an actual web project was so simple!

Jeremy Likness

I've been enjoying learning more about the Managed Extensibility Framework (MEF) and exploring various ways to integrate it with applications. After toying with MEF on Silverlight for awhile, I began to wonder about using it to export/import UI pieces or even define data elements in XAML. After a tweet to @gblock confirmed there was not native support, I set out to see what I could do. (If you're not familiar with MEF, take a look at my 10 minute walkthrough.)

The result is by no means ideal and is certainly a contrived "proof of concept" solution, but I believe it will help expose some of the custom extension points available with MEF and just how flexible it truly can be.

Download the Source

My goal was to minimize code behind for a common scenario of having pages with groups of widgets. Widgets will most likely be defined as user controls, but we've already seen plenty of examples there. I wanted to be able to define them as resources in pure XAML, no code behind, then import them into something like a StackPanel as child elements.

The Attachable View Model

The first thing I created was an attachable view model. It would get a list of FrameworkElement for binding to a control. To make it even more interesting, I wired in an attached property. This way I can simply attach the view model to a control and it will automatically pull in the parts and populate the children.

The initial shell looked like this:


public class ViewModel
{
    private static List<FrameworkElement> _uiParts = new List();
    
    [ImportMany("UIPart", AllowRecomposition = true)]
    public List<FrameworkElement> UIParts
    {
        get { return ViewModel._uiParts; }
        set { ViewModel._uiParts = value; }
    }

    public ViewModel()
    {
        var catalog = new AssemblyCatalog(Assembly.GetExecutingAssembly());
        var container = new CompositionContainer(catalog);
        container.ComposeParts(this);
    }

    static ViewModel()
    {
        new ViewModel();
    }

    public static readonly DependencyProperty ViewBinderProperty = DependencyProperty.RegisterAttached(
        "ViewBinder", typeof(bool), typeof(ViewModel), new PropertyMetadata(new PropertyChangedCallback(OnViewBound)));

    public static void OnViewBound(object sender, DependencyPropertyChangedEventArgs args)
    {
        // make sure we want this ...
        if (args.NewValue != null && args.NewValue.GetType().Equals(typeof(bool)) && (bool)args.NewValue)
        {
            Panel panel = sender as Panel;
            if (panel != null)
            {
                // iterate the parts
                foreach (FrameworkElement element in _uiParts)
                {
                    // clone it
                    FrameworkElement newElement = Clone(element);
                    
                    // give it a unique name
                    newElement.SetValue(FrameworkElement.NameProperty, Guid.NewGuid().ToString());
                    
                    // inject it
                    panel.Children.Add(Clone(newElement));
                }
            }
        }
    }

    public static bool GetViewBinder(DependencyObject obj)
    {
        return (bool)obj.GetValue(ViewBinderProperty);
    }

    public static void SetViewBinder(DependencyObject obj, bool value)
    {
        obj.SetValue(ViewBinderProperty, value);
    }
}

So far it feels pretty much like a standard class hosting a dependency property. You'll notice it's a bit strange, however, as the class itself is not static. This is because MEF is expecting an instance to compose the parts in. To facilitate that, I have an instance constructor that follows the general MEF pattern ... throw the catalog into the container and compose the parts. The "instance" getter and setter is really a facade that populates the static list of parts, in this case I'm just asking for any type of FrameworkElement. Obviously, those will have to come from somewhere else.

Because my intention is to use a resource dictionary, I must be able to share the elements. Silverlight won't let you take an element that is already the child of another element and then move it somewhere else. I have to assume I may reuse some of these elements as well (for example, this could be extended with a filter to choose the types of elements). So, instead of adding the elements directly to the parent, I am cloning them.

Thanks here goes to Justin Angel for his very functional clone method that I found here. I left it out of the code snippet above to keep it simple, but it is included in the source.

Now we need to tackle the task of exporting the framework elements. Ideally, I just want to put them into a resource dictionary, tag them somehow, and have the magic work. Fortunately, MEF gives us a nice ExportProvider we can derive from to do just that. There's an excellent article I started with by the "Code Junkie" you can access here.

It may have made more sense to split out the dependency properties and the provider to separate classes, but I figured, why not? So here is a custom export provider that also hosts some attached properties to facilitate exporting XAML:


public class XAMLProvider : ExportProvider
{
    private static readonly Dictionary<ExportDefinition, List<Export>> _exports = new Dictionary<ExportDefinition, List<Export>>();

    private static readonly XAMLProvider _provider = new XAMLProvider();

    public static DependencyProperty MEFExportProperty = DependencyProperty.RegisterAttached("MEFExport", typeof(string), typeof(XAMLProvider),
        new PropertyMetadata(new PropertyChangedCallback(OnMEFExport)));

    public static void OnMEFExport(object sender, DependencyPropertyChangedEventArgs args)
    {
        if (args.NewValue != null && !string.IsNullOrEmpty(args.NewValue.ToString()))
        {
            string contract = args.NewValue.ToString();
            _provider.AddExport(contract, sender);
        }
    }

    public static string GetMEFExport(DependencyObject obj)
    {
        return (obj).GetValue(MEFExportProperty).ToString();
    }

    public static void SetMEFExport(DependencyObject obj, string value)
    {
        obj.SetValue(MEFExportProperty, value); 
    }

    private static readonly object _sync = new object();

    public static XAMLProvider GetXAMLExportProvider()
    {
        return _provider;
    }

    public void AddExport(string contractName, object export)
    {
        lock (_sync)
        {
            var found =
                from e in _exports
                where string.Compare(e.Key.ContractName, contractName, StringComparison.OrdinalIgnoreCase) == 0
                select e;

            if (found.Count() == 0)
            {
                ExportDefinition definition =
                    new ExportDefinition(contractName, new Dictionary());

                _exports.Add(definition, new List<Export>());
            }

            Export wrapper =
                new Export(contractName, () => export);

            found.First().Value.Add(wrapper);
        }
    }

    protected override IEnumerable<Export> GetExportsCore(ImportDefinition definition, AtomicComposition atomicComposition)
    {
        var contractDefinition = definition as ContractBasedImportDefinition;
        IEnumerable<Export> retVal = Enumerable.Empty<Export>();

        if (contractDefinition != null)
        {
            string contractName =
                contractDefinition.ContractName;

            if (!string.IsNullOrEmpty(contractName))
            {
                var exports =
                    from e in _exports
                    where string.Compare(e.Key.ContractName, contractName, StringComparison.OrdinalIgnoreCase) == 0
                    select e.Value;

                if (exports.Count() > 0)
                {
                    retVal = exports.First();
                }
            }
        }

        return retVal; 
    }
}

The only override provided is to actually get the exports for a provided input definition. Everything else is left to us.

The first thing I did was create a dictionary. The key is the contract name (in MEF, the contract name is just a string ... if you use a type or an interface, then the fully qualified name becomes the string for the contract). The value is a list of all exports attached to that contract.

The dependency property allows me to attach "MEFExport" to any XAML object and give it a contract name. When this property is attached, it will look for the name in the dictionary and then either create a new entry or add the element to the existing list. It's as simple as that!

When the GetExportsCore is called, we are given an import definition. For a more complex example, we could look at attributes and other extensions. In this case, I'm simply extracting the contract name, finding the key in the dictionary and then sending off any exports that were loaded with the key.

Now I can add a resource dictionary and tag my elements for export. Mine looks like this:


<ResourceDictionary
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="clr-namespace:MEFExtension">
    <TextBlock FontSize="32" Text="This is a text block." x:Key="ui1" local:XAMLProvider.MEFExport="UIPart"/>
    <Rectangle Width="100" Height="100" Fill="Red" x:Key="ui2" local:XAMLProvider.MEFExport="UIPart"/>
    <TextBlock FontSize="16" Text="This won't get imported." x:Key="ui3"/>
    <Ellipse HorizontalAlignment="Left" Fill="Blue" Stroke="Black" Width="100" Height="50" x:Key="ui4" local:XAMLProvider.MEFExport="UIPart"/>
</ResourceDictionary> 

I threw in a dummy text block without tagging it to show that it won't get exported because the property is not attached. So now when that resource dictionary is pulled in, we can parse the XAML and export the elements. We need to let MEF know about our custom provider. Going back to my view model, I'll change the container creation to this:


var container = new CompositionContainer(catalog, XAMLProvider.GetXAMLExportProvider());
            

Notice I now passed in our custom export provider.

Now all of the elements are in place. The custom export provider knows how to scan XAML and load up elements for export, we've added a resource dictionary with some elements to export, and the view model is asking for imports and has its own attached property so that we can push the elements to any type of panel.

Last step: I go into my main page, pull in the resource dictionary and bind the view model:


<UserControl x:Class="MEFExtension.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"
    xmlns:local="clr-namespace:MEFExtension">
    <UserControl.Resources>
        <ResourceDictionary>
            <ResourceDictionary.MergedDictionaries>
                <ResourceDictionary Source="Resources.xaml"/>
            </ResourceDictionary.MergedDictionaries>
        </ResourceDictionary>
    </UserControl.Resources>
    <StackPanel Orientation="Vertical" Width="Auto" local:ViewModel.ViewBinder="true"/>
</UserControl>

So the resource dictionary will get pulled in. As the keys are processed, it will fire the attached properties and load them into exports. I gave them the "UIPart" contract. When the view model is attached, it will new an instance that fires the composition container for MEF. This will use the custom provider. Because we have the list of elements marked "UIPart", the exports will match and get loaded. The attach event will clone these objects and add them as children to the stack panel.

The result?

Silverlight MEF ExportProvider

There you have it, an example of extending the, ah, Managed Extensibility Framework, to support exporting using attached properties in XAML (I did this in Silverlight 3, so I had to add the reference to the System.ComponentModel.Composition from the download ... it is included in Silverlight 4).

Download the Source

Jeremy Likness

We have explored using dependency properties and attached properties to abstract behaviors and triggers. In my last article, TextBox Magic, I showed how to create a dependency property to enable a textbox filter that would prevent anything but digits. In this article, we'll take it a step further and turn it into a "true" behavior.

A "true" behavior inherits from Behavior. The first step is to add a reference to System.Windows.Interactivity. There are a number of nice things about using the behavior system that make them more flexible to use than basic dependency properties. First, the behaviors can integrate with Expression Blend. You can define a behavior, import it into the tool, and literally drag it onto a control to attach the behavior. Second, behaviors automatically provide overrides to tap into the attach/detatch events. Third, behaviors are typed to their target controls: you may have a generic behavior that targets FrameworkElement or a specific behavior that targets TextBox. Finally, we can decorate behaviors with attributes that are discovered by Intellisense and available when attaching the behavior.

We are going to create a filter behavior. The first step is to simply inherit from the base behavior class and then override the pertinent events:

public class TextBoxFilterBehavior : Behavior<TextBox>
{
   protected override void OnAttached()
   {
       AssociatedObject.KeyDown += _TextBoxFilterBehaviorKeyDown;
   }

   protected override void OnDetaching()
   {
       AssociatedObject.KeyDown -= _TextBoxFilterBehaviorKeyDown; 
   }
}

As you can see, we have a convenient place to hook into the KeyDown event and unhook at the end. We also have a nice, typed AssociatedObject to use and manipulate.

We'll extend our filter to handle alpha (alphanumeric and spaces), positive numeric digits, and regular numeric digits. For the regular numeric digits, we'll allow the subtract/minus sign only if it's the very first character in the text. The "helper" methods look like this:

private static readonly List _controlKeys = new List<Key>
                                                     {
                                                         Key.Back,
                                                         Key.CapsLock,
                                                         Key.Ctrl,
                                                         Key.Down,
                                                         Key.End,
                                                         Key.Enter,
                                                         Key.Escape,
                                                         Key.Home,
                                                         Key.Insert,
                                                         Key.Left,
                                                         Key.PageDown,
                                                         Key.PageUp,
                                                         Key.Right,
                                                         Key.Shift,
                                                         Key.Tab,
                                                         Key.Up
                                                     };

private static bool _IsDigit(Key key)
{
    bool shiftKey = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
    bool retVal;
    if (key >= Key.D0 && key <= Key.D9 && !shiftKey)
    {
        retVal = true;
    }
    else
    {
        retVal = key >= Key.NumPad0 && key <= Key.NumPad9;
    }
    return retVal;
}

static bool _HandleNumeric(string text, Key key)
{
    bool handled = true;
    
    // if empty, allow minus - only can be first character
    if (string.IsNullOrEmpty(text.Trim()) && key.Equals(Key.Subtract))
    {
        handled = false;
    }
    else if (_controlKeys.Contains(key) || _IsDigit(key))
    {
        handled = false;
    }

    return handled;
}

static bool _HandlePositiveNumeric(Key key)
{
    bool handled = true;

    if (_controlKeys.Contains(key) || _IsDigit(key))
    {
        handled = false;
    }

    return handled;
}

static bool _HandleAlpha(Key key)
{
    bool handled = true;

    if (_controlKeys.Contains(key) || _IsDigit(key) || key.Equals(Key.Space) ||
        (key >= Key.A && key <= Key.Z))
    {
        handled = false;
    }

    return handled;
}

public enum TextBoxFilterType
{
    AlphaFilter,
    PositiveNumericFilter,
    NumericFilter
}

public TextBoxFilterType FilterType { get; set; }

As you can see, the familiar list of "friendly" keys is carried over. There are some helper methods for our different types of filters, as well as an enumeration. The enumeration gives us the flexibility of determining which filter to use and then a property is exposed to set that enumeration.

The last step is to wire in the actual event:

void _TextBoxFilterBehaviorKeyDown(object sender, KeyEventArgs e)
{
    switch(FilterType)
    {
        case TextBoxFilterType.AlphaFilter:
            e.Handled = _HandleAlpha(e.Key);
            break;

        case TextBoxFilterType.NumericFilter:
            e.Handled = _HandleNumeric(AssociatedObject.Text, e.Key);
            break;

        case TextBoxFilterType.PositiveNumericFilter:
            e.Handled = _HandlePositiveNumeric(e.Key);
            break;
    }
}

As you can see, it's as simple as checking the enumeration, calling the helper function and modifying the handled property.

Now we can reference the project with our behavior and reference the System.Windows.Interactivity. In XAML, you attach the behavior like this:

<TextBox>
   <Interactivity:Interaction.Behaviors>
      <Behaviors:TextBoxFilterBehavior FilterType="AlphaFilter"/>
   </Interactivity:Interaction.Behaviors>
</TextBox>

As you can see, easy to add, easy to read quickly what the behavior does, and the added bonus is that you can manipulate these in Expression Blend.

Jeremy Likness

Edit 10/16/2009: Thanks to all who pointed out the bug in the detach event ... it's been fixed.

So far we've explored how to use dependency properties and attached properties to create reusable behaviors and triggers. I showed you recently how to refactor an attached property to use the Behavior base class instead. Today, we'll look at the TriggerAction that is also available in System.Windows.Interactivity (either as a part of Expression Blend, or available through the Blend SDK).

If you recall in TextBox Magic, I used an attached property to define an attribute that, when set to true, would bind to the TextChanged event and force data-binding to allow validation and binding without having to lose focus from the text box.

Because the action is tied to an event, it makes sense to refactor as a trigger action.

The first step is simply to build a class based on TriggerAction which requires adding a reference to System.Windows.Interactivity. Like the Behavior class, the TriggerAction can be strongly typed, so we will type it to the TextBox:

public class TextBoxBindingTrigger : TriggerAction<TextBox>
{
}

The method you must override is the Invoke method. This will be called when the action/event the trigger is bound to fires. If you recall from the previous example, we simply need to grab a reference to the binding and force it to update:

protected override void Invoke(object parameter)
{
    BindingExpression binding = AssociatedObject.GetBindingExpression(TextBox.TextProperty);
    if (binding != null)
    {
        binding.UpdateSource();
    }
}

That's it! We now have a trigger action that is ready to force the data binding. Now we just need to implement it with a text box and bind it to the TextChanged event. In Expression Blend, the new action appears in the Behaviors section under assets.

Behavior in Expression Blend

You can click on the trigger and drag it onto an appropriate UI element. Because we typed our trigger to TextBox, Blend will only allow you to drag it onto a TextBox. Once you've attached the trigger to a UI action, you can view the properties and set the appropriate event. In this case, we'll bind to the TextChanged event.

Trigger Properties in Expression Blend

Notice how the associated element defaults to the parent, but can be changed in Blend to point to any other TextBox available as well.

Of course, all of this can be done programmatically or through XAML as well. To add the trigger in XAML, simply reference both System.Windows.Interactivity as well as the namespace for your trigger. Then, you can simply add to the TextBox lik this:

...
<TextBox 
    Text="{Binding Name, Mode=TwoWay, NotifyOnValidationError=true, ValidatesOnExceptions=true}" 
    Grid.Row="0" Height="30" Grid.Column="0" Margin="5" Width="200">
 <i:Interaction.Triggers>
  <i:EventTrigger EventName="TextChanged">
   <local:TextBoxBindingTrigger/>
  </i:EventTrigger>
 </i:Interaction.Triggers>
</TextBox>

As you can see, this is a much more elegant way to create behaviors attached to events as it allows you to easily attach the trigger as well as define the event that the trigger is coupled with.

Jeremy Likness

The TextBox control is popular in Silverlight but comes with a few nuances. For example, the default behavior is that the data is not bound until the control loses focus! This can be awkward when you have a form with a disabled save button. The save button won't enable until the text box contains content, but it won't "know" about the content until the box loses focus, so the user is forced to tab from the last field before they can save.

I will cover two topics specific to the TextBox: the first is a behavior and trigger that resolve the issue with the "late data binding." The second is a filter behavior that allows you to control exactly what goes into the text box.

Let's get started! As you recall, the recipe for creating a new attached property is to declare the properties on a static class and register them as an attached property. We're going to start with the filter. As you know, the TextBox control itself takes any type of character input. A numeric field can be validated which prevents it from binding to the object, but why let the user type anything but a digit in the first place? Prevention is the best medicine, so why not filter the field?

We'll start with a class called TextBoxFilters to hold our attached properties specific to the text box. To filter the text box, we want to hook into the KeyDown event, check to see if it's a key we like, and set the event to "handled" if we don't want it (this prevents it from bubbling up and making it into the form). Of course, we have to be careful because we're not just checking for digits. Users must be able to navigate into and out of the field using TAB or fix their input using BACK.

The first part of the class is here. We create a convenient list of key presses that should always be allowed, then provide a method that tells us if it is a digit. Notice that we need to check the presence of the SHIFT key because Key.D1 becomes an exclamation mark when the SHIFT key is pressed.

public static class TextBoxFilters
{
    private static readonly List<Key> _controlKeys = new List<Key>
                                                            {
                                                                Key.Back,
                                                                Key.CapsLock,
                                                                Key.Ctrl,
                                                                Key.Down,
                                                                Key.End,
                                                                Key.Enter,
                                                                Key.Escape,
                                                                Key.Home,
                                                                Key.Insert,
                                                                Key.Left,
                                                                Key.PageDown,
                                                                Key.PageUp,
                                                                Key.Right,
                                                                Key.Shift,
                                                                Key.Tab,
                                                                Key.Up
                                                            };

    private static bool _IsDigit(Key key)
    {
        bool shiftKey = (Keyboard.Modifiers & ModifierKeys.Shift) != 0;
        bool retVal;
        if (key >= Key.D0 && key <= Key.D9 && !shiftKey)
        {
            retVal = true;
        }
        else
        {
            retVal = key >= Key.NumPad0 && key <= Key.NumPad9;
        }
        return retVal; 
    }
}

Next, we need to build our dependency properties. We'll provide a getter and setter and the registration. When the property is set, we'll check to see if the control is a TextBox. If it is, we hook into the KeyDown event and suppress it. The code looks like this:


public static bool GetIsPositiveNumericFilter(DependencyObject src)
{
    return (bool) src.GetValue(IsPositiveNumericFilterProperty);
}

public static void SetIsPositiveNumericFilter(DependencyObject src, bool value)
{
    src.SetValue(IsPositiveNumericFilterProperty, value);
}

public static DependencyProperty IsPositiveNumericFilterProperty = DependencyProperty.RegisterAttached(
    "IsPositiveNumericFilter", typeof (bool), typeof (TextBoxFilters),
    new PropertyMetadata(false, IsPositiveNumericFilterChanged));

public static void IsPositiveNumericFilterChanged(DependencyObject src, DependencyPropertyChangedEventArgs args)
{
    if (src != null && src is TextBox)
    {
        TextBox textBox = src as TextBox; 
        
        if ((bool)args.NewValue)
        {
            textBox.KeyDown += _TextBoxPositiveNumericKeyDown;
        }
    }
}

static void _TextBoxPositiveNumericKeyDown(object sender, KeyEventArgs e)
{
    bool handled = true;

    if (_controlKeys.Contains(e.Key) || _IsDigit(e.Key))
    {
        handled = false;
    }

    e.Handled = handled;
}

That's it ... now we have a handy attached behavior. If you include the namespace in your XAML and refer to it as Behaviors, you'll be able to attach the property to a text box like this:



<TextBox DataContext="{Binding MyNumericField}" Behaviors:TextBoxFilters.IsPositiveNumericFilter="True"/>

That's it - just attach the behavior, fire up your application, and try to put anything but a digit into your text box!

Now that we know how to attach that behavior, wouldn't it be nice to have some instant validation and databinding as well? This isn't difficult at all with dependency properties. All you need to do is hook into the event that is fired when the text changes, and force an update to the binding. The code for that behavior looks like this:

public static bool GetIsBoundOnChange(DependencyObject src)
{
    return (bool) src.GetValue(IsBoundOnChangeProperty);
}

public static void SetIsBoundOnChange(DependencyObject src, bool value)
{
    src.SetValue(IsBoundOnChangeProperty, value);
}

public static DependencyProperty IsBoundOnChangeProperty = DependencyProperty.RegisterAttached(
    "IsBoundOnChange", typeof(bool), typeof(TextBoxFilters),
    new PropertyMetadata(false, IsBoundOnChangeChanged));

public static void IsBoundOnChangeChanged(DependencyObject src, DependencyPropertyChangedEventArgs args)
 {
     if (src != null && src is TextBox)
     {
         TextBox textBox = src as TextBox;

         if ((bool)args.NewValue)
         {
             textBox.TextChanged += _TextBoxTextChanged;
         }
     }
 }

static void _TextBoxTextChanged(object sender, TextChangedEventArgs e)
 {
     if (sender is TextBox)
     {
         TextBox tb = sender as TextBox;
         BindingExpression binding = tb.GetBindingExpression(TextBox.TextProperty);
         if (binding != null)
         {
             binding.UpdateSource();
         }
     }
 }

As you can see, we hook into the text changed event, grab the binding and force it to update. Now you will have instant feedback. Of course, all validation rules are followed so if the binding causes a validation error, your validation will display instantly and the underlying objects will not be databound.

The new "super" text box that is filtered and binds as the text changes looks like this:


<TextBox DataContext="{Binding MyNumericField}" Behaviors:TextBoxFilters.IsPositiveNumericFilter="True"
   Behaviors:TextBoxfilters.IsBoundOnChange="True"/>

That's all there is too it ... keep your users honest by preventing them from typing something they don't need.

Jeremy Likness

One of the most powerful benefits of Silverlight is that it uses the DependencyProperty model. Using this model, you can create attached properties to describe reusable behaviors and attach those behaviors to certain elements.

An example of this is firing animations in the UI elements. One criticism of Silverlight has been the lack of support for the range of triggers that Windows Presentation Foundation (WPF) supports. The main "trigger" you can tap into is the Loaded event for a control. This makes it difficult to define triggers for events such as data binding and/or UI events.

It only takes a little bit of magic using the DependencyProperty system, however, to create those triggers yourself.

A behavior is a reusable "action" that can be attached to a control. A trigger is an event that causes something to happen. Imagine having a list that is bound to a list box. Your view model contains the list of top level entities. When a selection item is clicked on, a grid expands (using a Storyboard animation) that contains details for the selected item.

Using Silverlight's advanced databinding features, everything but the animation is straightforward. You can bind the ListBox directly to the list of objects:

...
<ListBox x:Name="ObjectListBox" ItemsSource="{Binding ObjectList}"
   DisplayMemberPath="Name"/>
...

The grid can then automatically databind to the selected object:

...
<Grid DataContext="{Binding ElementName=ObjectListBox,Path=SelectedItem}"/>
...

Now your UI will work like magic - provide your ObjectList, and then click to see the details "magically" appear in the grid. But how do we get the grid to explode? This is where I've seen a lot of attempts to do things like bind collections and triggers to the view model. While I understand the view model is a go-between data and the view, I still think knowing about animations in some cases is too much information for the view model.

I'm not really trying to drive anything from the data. I'm driving a UI behavior with a UI trigger, so why can't I keep all of this cleanly in the XAML, without involving a view model at all? As it turns out, I can.

To understand how to create this, we first need to understand the behavior and the trigger.

The behavior is to kick off a Storyboard. In our case, the storyboard will simply "explode" the grid using a scale transform:

<Grid.Resources>
    <Storyboard x:Name="GridExplode">
        <DoubleAnimation Storyboard.TargetName="TransformSetting" Storyboard.TargetProperty="ScaleX" 
   From="0" To="1.0" Duration="0:0:0.3"/>
        <DoubleAnimation Storyboard.TargetName="TransformSetting" Storyboard.TargetProperty="ScaleY" 
   From="0" To="1.0" Duration="0:0:0.3"/>
    </Storyboard>
</Grid.Resources>
<Grid.RenderTransform>
    <ScaleTransform x:Name="TransformSetting" ScaleX="1.0" ScaleY="1.0"/>
</Grid.RenderTransform>

Now we have a nice behavior, but short of the event trigger provided by Silverlight at load time, we have no easy way to fire it off. Our trigger is the SelectionChanged event on the ListBox. Normally, we would throw the event into the XAML:

...
<ListBox SelectionChanged="ObjectListBox_SelectionChanged"/>
...

Then go into our code behind and kick off the animation:

private void ObjectListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
   GridExplode.Begin();
}

So now that we know the behavior and the trigger, let's try a different way to accomplish it.

I'm going to create a host class for my storyboard triggers and call it, aptly, StoryboardTriggers. The class is static because it exists solely to help me manage my dependency properties. First, we'll want to keep a collection of storyboards that are participating in our new system. We will let the user assign a (hopefully globally unique) key to the Storyboard. This is different from the x:Name because it will be reused throughout the system.

public static class StoryboardTriggers
{
    private static readonly Dictionary<string, Storyboard> _storyboardCollection = new Dictionary<string, Storyboard>();
}

Two steps are required. First, we need to register the storyboard with our collection, so that it is available to manipulate. I like to go ahead and wire in the Completed event to stop the animation so that it can be reused.


public static string GetStoryboardKey(DependencyObject obj)
{
    return obj.GetValue(StoryboardKeyProperty).ToString();
}

public static void SetStoryboardKey(DependencyObject obj, string value)
{
    obj.SetValue(StoryboardKeyProperty, value);
}

public static readonly DependencyProperty StoryboardKeyProperty =
    DependencyProperty.RegisterAttached("StoryboardKey", typeof(string), typeof(StoryboardTriggers),
                                        new PropertyMetadata(null, StoryboardKeyChanged));

public static void StoryboardKeyChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    Storyboard storyboard = obj as Storyboard;
    if (storyboard != null)
    {
        if (args.NewValue != null)
        {
            string key = args.NewValue.ToString();
            if (!_storyboardCollection.ContainsKey(key))
            {
                _storyboardCollection.Add(key, storyboard);
                storyboard.Completed += _StoryboardCompleted;
            }
        }               
    }
}

static void _StoryboardCompleted(object sender, System.EventArgs e)
{
   ((Storyboard)sender).Stop();
}

This is the standard way to declare a new dependency property. The dependency property itself is registered and owned by our static class. Methods are provided to get and set the property. We also tap into the changed event (and we're assuming here that we'll only be attaching the property) and use that event to load the storyboard into our collection.

Now allowing a storyboard to participate in our trigger system is easy, we simply add a reference to the class (I'll call it Behaviors), and then attach the property. Our storyboard now looks like this:

...
<Storyboard x:Name="GridExplode" Behaviors:StoryboardTriggers.StoryboardKey="GridExplodeKey">
...

Note I've given it our "key" of GridExplodKey. Next, let's create a trigger! We want the selection change event to fire the grid. Instead of just writing it for our particular case, we can use the primitive Selector and make the trigger available to any control that exposes the SelectionChanged event. All we want to do is take one of those controls, and set a trigger to the storyboard we want to fire. We do this in our behavior class like this:

public static string GetStoryboardSelectionChangedTrigger(DependencyObject obj)
{
    return obj.GetValue(StoryboardSelectionChangedTriggerProperty).ToString();
}

public static void SetStoryboardSelectionChangedTrigger(DependencyObject obj, string value)
{
    obj.SetValue(StoryboardSelectionChangedTriggerProperty, value);
}

public static readonly DependencyProperty StoryboardSelectionChangedTriggerProperty =
    DependencyProperty.RegisterAttached("StoryboardSelectionChangedTrigger", typeof(string), typeof(StoryboardTriggers),
                                        new PropertyMetadata(null, StoryboardSelectionChangedTriggerChanged));

public static void StoryboardSelectionChangedTriggerChanged(DependencyObject obj, DependencyPropertyChangedEventArgs args)
{
    Selector selector = obj as Selector;
    if (selector != null)
    {
        if (args.NewValue != null)
        {
            selector.SelectionChanged += _SelectorSelectionChanged;
        }
    }
}

static void _SelectorSelectionChanged(object sender, SelectionChangedEventArgs e)
{
    string key = GetStoryboardSelectionChangedTrigger((DependencyObject) sender);
    if (_storyboardCollection.ContainsKey(key))
    {
        _storyboardCollection[key].Begin();
    }
}

That's it. When the property is set, we set a handler for the SelectionChanged event. When the selection changed event fires, we get the key from the dependency property, look it up in the master list, and, if it exists, kick off the animation. The property is attached like this:

...
<ListBox x:Name="ServiceList" Behaviors:StoryboardTriggers.StoryboardSelectionChangedTrigger="GridExplodeKey"/>

That's all there is to it! Now we have bound the trigger (selection changed) to the behavior (kick off the animation) and can leave the code-behind and view models completely out of the equation.

For a more full implementation of this, you would want to also handle the event of clearing or detaching the property and remove the event handler from the bound object. (Don't forget your data contract as well ... the methods for attaching, getting, setting, etc should check the parameters and types; I've left that out for brevity here.) You can create other triggers as well and attach those just as easily and even parse multiple values to allow multiple bindings. Once you start thinking in terms of triggers and behaviors within Silverlight, anything truly is possible.

Jeremy Likness

A common user interface component is the confirmation or message box, which is often presented as a dialog returns a boolean (OK/Cancel). There are a variety of ways to achieve this, but how can you decouple the implementation of the popup from the request itself? This is necessary, for example, for unit testing when you may not have a UI available. This article demonstrates one solution using Silverlight and the Composite Application Guidance library, also known as Prism.

The first piece we are going to build is a payload that allows us to deliver the popup message. The payload looks like this:

public class MessageBoxPayload
{
    public object DataContext { get; set; }

    public bool AllowCancel { get; set; }

    public string Title { get; set; }

    public string Message { get; set; }

    public Action<MessageBoxPayload> ResultHandler { get; set; }

    public bool Result { get; set; }

    private MessageBoxPayload()
    {            
    }

    public static MessageBoxPayload GeneratePayload(object dataContext, bool allowCancel, 
        string title, string message, Action<MessageBoxPayload> resultHandler)
    {
        MessageBoxPayload retVal = new PopupEntity {AllowCancel = allowCancel, Title = title, Message = message, 
            ResultHandler = resultHandler,
        DataContext = dataContext};
        return retVal; 
    }
}

Because we are implementing this completely decoupled, we cannot make any assumptions about state. Therefore, the payload carries a data context that can be passed back to the requestor. This is done using an Action of the payload type, allowing the requestor to provide a method to get called when the dialog closes.

Next, we'll define the event we use to request the message box. That is based on the event mechanism supplied by Prism:

public class MessageBoxEvent : CompositePresentationEvent<MessageBoxPayload>
{
}

Notice that we derive from the CompositePresentationEvent. This is a base class for all events that will participate in the event aggregator service. Now that we have our payload and our service defined, we can easily begin to pubish to the event. If you had a data grid with a delete button, the event would look something like this (for simplicity's sake I'm not using DelegateCommand):

private void Button_Delete_Click(object sender, System.Windows.RoutedEventArgs e)
{
    Button src = e.OriginalSource as Button;
    if (src != null)
    {
        _eventService.GetEvent<MessageBoxEvent>().Publish(
            MessageBoxPayload.GeneratePayLoad(src.DataContext, true, "Please Confirm", "Are you sure you wish to delete this item?",
                                      DeleteItem));
    }
}      

public void DeleteItem(MessageBoxPayload payload)
{
    if (payload.result) 
    {
       MyItem item = payload.DataContext as item;
       Delete(item);
    }
}

For unit tests, you can now simply build an object that subscribes to the delete event and returns the desired results.

As you can see, the delete click wraps the message into a payload and publishes the event. A delegate is provided to call back to "DeleteItem" with the result of the dialog. If the user confirmed, then the data context is used to pull the entity for the given row and the delete command is performed.

The _eventService is defined like this:

...
private readonly IEventAggregator _eventService;
...

Because IEventAggregator is supplied as a parameter in the constructor for the view, it is automatically wired in by the dependency injection framework. There are two steps required to get the event aggregator to your objects.

First, in your bootstrapper, you'll want to register a single instance:

protected override void ConfigureContainer()
{
    base.ConfigureContainer();

    // provide a reference to the event aggregator
    Container.RegisterInstance<IEventAggregator>(Container.Resolve<EventAggregator>());

}

Notice that I use "resolve" to get the instance. This is good practice when using a dependency injection/inversion of control framework. When you new your objects, you must select the appropriate constructor and inject the appropriate values. By calling Resolve you ask the container to read the signature of the constructors and provide implementations based on your current configuration and registrations.

The second step is to inject the service to the appropriate handler for the popup. Let's focus on implementing the actual popup. The easiest way to handle common infrastructure items is to create a common module. That module can contain elements that are shared between projects. First, we'll create a new child window and call it "Popup." The XAML looks like this (in my case, the project is Modules.Common and the Popup is in a subfolder called Views).

<controls:ChildWindow x:Class="Modules.Common.Views.Popup"
           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="Auto" Height="Auto" 
           Title="{Binding Title}">
    <Grid x:Name="LayoutRoot" Margin="2">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto" />
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <TextBlock TextWrapping="Wrap" Text="{Binding Message}" FontFamily="Arial" FontSize="12" TextAlignment="Center" Grid.Row="0"/>
        <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>

The main thing to note is the use of Auto to ensure the dialog resizes based on the content. Now for the code behind.

public partial class Popup
{   
    public Popup()
    {
        InitializeComponent();
    }

    public Popup(MessageBoxPayload payload)
    {
        InitializeComponent();
        DataContext = payload;
        CancelButton.Visibility = payload.AllowCancel ? Visibility.Visible : Visibility.Collapsed;
    }                

    private void OKButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        MessageBoxPayload result = (MessageBoxPayload) DataContext;
        result.Result = true; 
        result.ResultHandler(result);
    }

    private void CancelButton_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = false;
        MessageBoxPayload result = (MessageboxPayload)DataContext;
        result.Result = false;
        result.ResultHandler(result);
    }
}

The key here is that we have a constructor that takes in the payload and sets the data context, then sets the visibility of the cancel button. Then there are events bound to the buttons that will set the appropriate result then call the handler specified for the dialog close event.

One confusing topic here may be how to get the view into the application. If this is truly a decoupled module, how will it "know" about the regions you've defined? Furthermore, even if you iterated the region collection and injected it to the first one you found, you will find a goofy, empty popup window just hanging out. Not exactly what we want! In order to manage this popup, we'll use a controller.

The popup controller looks like this:

public class PopupController
{
    public PopupController(IEventAggregator eventService)
    {
        eventService.GetEvent<MessageBoxEvent>().Subscribe(PopupShow);
    }

    public void PopupShow(MessageBoxPayload payload)
    {
        Popup popupWindow = new Popup(payload);
        popupWindow.Show();          
    }
}

Now we can set up our module to invoke the controller.

public class CommonModule : IModule
{               
    private readonly IUnityContainer _container;

    public CommonModule(IUnityContainer container)
    {
        _container = container;
    }

    public void Initialize()
    {
        _container.RegisterInstance(_container.Resolve(typeof (PopupController)));         
    }
}

Notice we aren't registering with a region. Instead, we simply resolve a single instance of the controller. This will subscribe to the popup event. Because we use the container to resolve the controller, the container will automatically reference the EventAggregator and inject it into the constructor. Last but not least, this module simply needs to get registered with the module catalog:

protected override IModuleCatalog GetModuleCatalog()
{
    ModuleCatalog catalog = new ModuleCatalog();
    catalog.AddModule(typeof (MySpecificModule));
    catalog.AddModule(typeof (CommonModule)); 
    return catalog; 
}

Again, because we registered the EventAggregator earlier, it will pass the container along to the module and inject the aggregator into the controller. Now, when we publish the event, a nice child window will appear for us:

Silverlight popup

Of course, you can extend this to have the controller manage multiple windows, customize the button text or add nice images as well. This is just one of the many ways use of dependency injection and the event aggregator pattern can help the need (give me a response) from the implementation (show a popup) and provide an easy way to reuse components across applications.

Jeremy Likness

The observer pattern is well established and used. The typical scenario is to register to an class and then allow your Notify method to be called. This often involves keeping an internal list of observers and then iterating them to notify that something has changed. I had a situation recently that warranted a lighter weight approach that allows a many-to-many observation (multiple listeners, multiple objects to observe).

I was working with the Composite WPF/PRISM framework and had an interesting situation. One of my regions is implemented as a TabControl, so modules that register with the RegionManager inject their views into the tabs. This is a very powerful model because now I can add as many modules/views as I like and not worry about the implementation details of wiring up the tab control. I created a view interface IViewable to implement with my controls that exposes the name of the view along with a boolean indicating whether the view should be enabled (this allows me to restrict going to certain tabs if they depend on data from another tab).

The issue was figuring out the best way to handle the tab focused event. By default, the views are wired up and ready to go when you click the tab. I tried searching for a solution to allowing my view to know when it was "active" but didn't find much that was satisfactory. It could be I'm completely off on my approach because there is some pattern already existing, but I decided to go with something very lightweight ... even lighter than the observer pattern. I don't want to know the details of what the other views or modules are, I just want to know when I'm getting focus and that is controlled by my parent container (I also shouldn't know that my parent container is a TabControl - it could be any ItemsControl for that matter).

The pattern was quite simple, really. First, I created an interface:

public interface IObservableHelper 
{
   void Notify(object obj); 
   event EventHandler<EventArgs> Notified; 
}

The implementation was easy too:

public class ObservableHelper : IObservableHelper
{
   public void Notify(object obj) 
   {
      if (Notified != null) { Notified(obj, EventArgs.Empty); }
   }

   public event EventHandler<EventArgs> Notified;
}

See, very easy. I don't have to keep track of the objects observing because objects who want to know about this event simply register to the event. In my boot strapper class I make sure there is exactly one instance of the helper:

...
Container.RegisterInstance<IObservableHelper>(new ObservableHelper()); 
...

With the dependency injection, the helper can be injected simply by asking for it in the constructor. That means in my view, I can do this:

public MyView(IObservableHelper helper)
{
   helper.Notified += (obj,args) =>
   {
      if (obj == this) { DoSomething(); }
      else if (obj is ISomeInterface) { DoSomethingElse((ISomeInterface)obj); }
   }; 
}

// observe "me" 
public void DoSomething()
{
} 

// observe "ISomeInterface" 
public void DoSomethingElse(ISomeInterface someInterface)
{
}

I've just registered to, eh, observe "myself." That's OK ... as a view, what I really want to know is when I am activated. So in the shell, I simply tap into the selection changed event for the Tab Control. That will resolve IObservableHelper then call notify with the element that was selected. Notified will fire, I'll see its "me" and then call DoSomething. Very lightweight and decoupled ... and if there are other objects participating, I can interact with them as well!

Jeremy Likness

The Ref keyword is well known. It indicates that you are passing a reference, not a value, to a method. That means that if the method modifies the value, the changes will be apparent to the calling method as well.

Where I see a lot of confusion, however, is what happens when dealing with reference types. It is common to say that methods pass objects by reference, but that's not entirely true.

First, a pop quiz. Without actually running the code, what do you think this code snippet will produce?

using System;

namespace ByRef
{
    internal sealed class MyClass
    {
        public MyClass(int value)
        {
            Value = value;
        }

        public int Value { get; set; }
    }

    internal class Program
    {
        private static void _SwapByValue(MyClass myClass)
        {
            myClass = new MyClass(5);
        }
   
        private static void _SwapByRef(ref MyClass myClass)
        {
            myClass = new MyClass(5);
        }
        
        private static void Main(string[] args)
        {
            MyClass testclass = new MyClass(4);
            _SwapByValue(testclass);
            Console.WriteLine(testclass.Value);
           
            MyClass testclass2 = new MyClass(4);
            _SwapByRef(ref testclass2);
            Console.WriteLine(testclass2.Value);            

            Console.ReadLine();
        }
    }
}

We'll come back to that in a minute.

When you make a method call, all of the variables you pass are copied to the stack. This is the first place some people get confused. If I have an integer:

int x = 5;
CallMethod(x);

x is on my stack. A copy of the value of x ("5") is made and also placed on the stack. We now have two stack entries: "my x" and "the method's x."

But what about this?

MyClass myClass = new MyClass(5);
CallMethod(myClass);

The important thing to remember is that myClass is really a reference to the instance. So the first line gives us two allocations in memory: a block of heap that contains the class, and a local stack pointer to the class. So when we call the method, a copy is made just as in the value type example. In this case, it is a copy of the reference. So now I have my class in the heap, my local reference, and a copy of my local reference being passed to the method.

This is why the first case in the above example will print "4". All the method did was to change the reference on the method's stack to point to a new allocation in the heap - the new instance of MyClass. When the method returns, the copy is forgotten. The new instance (5) becomes orphaned, and is eventually garbage collected. The local reference still points to (4).

The second case is more interesting. As we mentioned, the ref keyword forces a reference, not a copy, to be passed. So this:

int x = 5;
MyMethod(ref x);

Skips making the copy. It simply gives the method access to the "5" value on the stack (some people mistakenly believe that the 5 is somehow boxed or unboxed, but that doesn't happen ... it simply isn't copied). If you change it, you change the same stack reference the calling program has, and therefore it will recognize the change.

What about with our object? This is where understanding the ref keyword is, well, key. Remember that when we new the (4) class, we have two important pieces: the class on the heap, and the pointer to the class (reference) on the stack. When we call the method with the ref keyword, it is not allowed to make a copy. Therefore, the method gains access to the same reference on the stack as the calling program. When it makes a new class (5), the stack reference is changed to point to this new instance. Now, the references point to (5) and (4) is orphaned and will be subject to garbage collection. This is why the second example shows "5" — the reference has been updated.

So, as you can see, objects are not "passed by reference" by default. Instead, when an reference type is passed in a parameter list, the reference is passed by value. This allows you to modify the object. If you want to change the reference, then you must ref it!

Jeremy Likness

Silverlight, with its powerful text and graphics manipulation capabilities and strong interaction with the scripting DOM, seems to be the perfect engine for a Captcha challenge.

See an Example Online

Download the Source (18.3KB)

Captcha is a challenge-response test used to determine to a degree of confidence that the end user is really human and not a bot. You see Captcha on things like forums, sign up forms, comment posts, and other places that may be succeptible to attacks by scripted bots. Usually, a Captcha involves playing a sound or displaying a distorted image that humans should be able to recognize but would be extremely hard for pattern-matching and/or optical character recognition (OCR) technology to decipher. Because the test is issued by a computer to test for a human, it is often referred to as a reverse-Turing test (a Turing test is designed by humans to test computers).

The key to Captcha is that it makes it difficult, if not impossible, for scripted software to determine the answer to the challenge. Asirra is an example of a Captcha challenge that displays random images of cats and dogs. The user is asked to identify only the cats by clicking on them. While easy for humans, this test is extremely difficult for computer algorithms.

As I was coding the other day, it occurred to me that Silverlight would be perfect for issuing Captcha challenges. It is very easy and straightforward to manipulate text and graphics to obscure the image, and furthermore, the output is NOT a simple bitmap that a robot could parse. Instead, it is an interactive plugin so for a script to recognize the image, it would have to have its own Silverlight engine and be able to scan and recognize what Silverlight renders.

I set out to produce a working example. I purposefully kept to the basics so those of you reading this who are interested have the opportunity to extend and add features.

The first step was to create a simple Captcha challenge class to use.

namespace SilverCaptcha.MVVM
{
    [ScriptableType]
    public class CaptchaViewModel
    {
        private const string CAPTCHA_KEY = "SilverCaptcha";

        private static readonly char[] _charArray = "ABCEFGHJKLMNPRSTUVWXYZ2346789".ToCharArray();

        public string CaptchaText { get; set; }

        public CaptchaViewModel()
        {
            char[] captcha = new char[8];

            Random random = new Random();

            for (int x = 0; x 

The class simply generates a random 8-digit sequence of characters. We supply a list of allowed values to avoid some of the common characters like the number one and letter "I" that could be easily mistaken for one or the other. The property CaptchaText exposes this value. The IsHuman method is decorated with the ScriptableMember tag. This makes it available to the Html DOM so that you can call it directly from JavaScript. To call it, you must register a "key" or handle to the object. This is done in the constructor through the RegisterScriptableObject call. We are giving it a handle in the JavaScript DOM of "SilverCaptcha." We'll see later how this is used.

Points of Extension

  • Add a method to "refresh" the challenge, i.e. generate a new one (hint: to do this, you'll also need to implement INotifyPropertyChanged)
  • Add parameters to control the challenge (length, use of alpha or numeric, etc)

Next, we'll need to show the challenge. Because I chose to use the Model-View-ViewModel pattern (MVVM) we won't need any code behind for the XAML. Instead, everything will be bound in the XAML itself. The XAML I came up with looks like this:

<UserControl x:Class="SilverCaptcha.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:MVVM="clr-namespace:SilverCaptcha.MVVM">
    <UserControl.Resources>
        <MVVM:CaptchaViewModel x:Key="CaptchaVM"/>
    </UserControl.Resources>    
    <Grid Width="100" Height="25" Margin="2" DataContext="{StaticResource CaptchaVM}">
        <Grid.Background>
            <LinearGradientBrush x:Name="CaptchaBackground" EndPoint="0.5,1" StartPoint="0.5,0">
                <GradientStop Color="LightBlue" Offset="1" />
                <GradientStop Color="LightSalmon" />
            </LinearGradientBrush>
        </Grid.Background>
        <TextBlock FontSize="14" Width="Auto" Height="Auto" 
                   HorizontalAlignment="Center" VerticalAlignment="Center" 
                   Text="{Binding CaptchaText}"
                   RenderTransformOrigin="0.5,0.5"> 
            <TextBlock.RenderTransform>
               <RotateTransform Angle="-5"/>              
            </TextBlock.RenderTransform>
            <TextBlock.Foreground>
                <LinearGradientBrush EndPoint="0.5,0" 
                    StartPoint="0.5,1">
                    <GradientStop Color="Black" Offset="1" />
                <GradientStop Color="Gray" />
                </LinearGradientBrush>
                                    
            </TextBlock.Foreground>
        </TextBlock>
    </Grid>
</UserControl>

This is fairly straightforward. By referring to CaptchaViewModel in the resources, an instance is created that can then be referenced using the key. I bind the class to the data context of the main grid using {StaticResource CaptchaVM}. The gradient is used to obscure the image somewhat. Because the class itself is bound to the grid, we can now simply bind the CaptchaText property to the text block. We also give that a slight gradient to make it more confusing to image scanning software, then rotate it against the background. That's all there is to it!

Points of Extension

  • Obviously, you could randomize or parameterize the angle of rotation and other attributes of the text
  • A more severe grid may help obscure the challenge but may also make it more difficult for human readers
  • Add a refresh button or icon to refresh the challenge for the user

Now, let's use it in a page. The page itself is fairly straightforward: we have a form with a table, and inside the table is a reference to the Silverlight XAP file, a text box for the user to enter their response to the challenge, and a button to click. This section looks like this:

<form id="_form1" runat="server" style="height:100%">
    <table><tr><td align="center">
    <div id="silverlightControlHost">
        <object id="silverlightControl" data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="110" height="30">
        ... etc, etc ...
     </object></div></td></tr><tr>
     <td align="center">Enter The Text You See Above:<br /><input type="text" maxlength="20" id="txtChallenge" /></td></tr><tr>
     <td align="center"><input type="button" onclick="validateCaptcha();return false;" value=" OK "/></td></tr></table>
    </form>

(Click here to see a live example)

The key here is that we've assigned the silverlight object an identifier of silverlightControl. If you use the Javascript or control method to load the silverlight, either way you just need a way to point to the object in the DOM for the Silverlight control.

The JavaScript function is then very straightforward. We simply call the method we exposed in the Silverlight class that will compare the response to the challenge. That code looks like this:

function validateCaptcha() {
    var silverlightCtrl = document.getElementById("silverlightControl");
    var challenge = document.getElementById("txtChallenge").value;
    var valid = silverlightCtrl.Content.SilverCaptcha.IsHuman(challenge);
    alert(valid ? "You are human!" : "You don't appear to be human, try again!");
}

This is what the final product looks like:

Captcha Challenge

As you can see, calling the Silverlight method is as simple as grabbing the control that hosts Silverlight, going into Content, then referencing the tag we gave it when we registered it in the Silverlight code. Then we simply call the method with the contents of the text box and it returns either true or false based on whether or not the response matches the challenge.

This is obviously a fast and basic example but it demonstrates just how flexible and powerful Silverlight can be to generate "mini-apps" or controls that you can embed in your existing HTML pages.

See an Example Online

Download the Source (18.3KB)

Jeremy Likness

Windows Workflow Foundation (WWF) is a powerful programming model and designer for workflow processes. Using workflow is easier than some may believe.

I wanted to share a quick post relative to some practices I've found useful for sequential workflows, specifically around Inversion of Control (IoC) and unit testing.

In our shop we have several complex algorithms that are great candidates for sequential workflow. By using sequential workflow, we can:

  • Easily visualize the overall layout and flow of the process
  • Test the architecture of the flow (i.e. do we get to this node or that node) without having to worry with or deal with the underlying implementation of nodes within the flow
  • Refactor complex code simply by dragging and dropping nodes in the designer
  • Setup unit tests to ensure the integrity of the workflow persists as other systems are refactored

If you aren't familiar with workflow, I'd suggest searching for a few tutorials or walkthroughs. This is one of those technologies that is probably easier to learn by building some test projects than it is simply reading about it. The scope of this article will be how to build your sequential workflows for unit tests.

Interfaces and Delegates In

The workflow model lets you declare public properties on the main workflow that are then available to all of the nodes within that workflow. When you instantiate the workflow, you can send in a collection of name-value pairs map to public properties. For example, if I have an interface declared on my workflow:

...
public IMyInterface MyInterfaceImplemented { get; set; }
...

Then I can pass to workflow an instance of that interface like this:

...
Dictionary<string, object> myParams = new Dictionary<string, object>
   {
      {"MyInterfaceImplemented", new MyInterfaceImplementation()}
   };
...
_runtime.CreateWorkflow(typeof (MyWorkflow), myParams);

I'll get to what _runtime is in a bit. My point is, however, that any type of business logic you follow within your workflow should be hidden behind an interface and/or delegate. If you are passing in concrete instances, you are missing out on the power of being able to unit test your workflow structure.

You may have noticed that the code blocks in a sequential workflow, unless encapsulated as a custom entity, are actually events triggered by the workflow engine. For example, I might insert a Code workflow activity called AnalyzeUser. In the code behind, this appears as:

private void AnalyzeUser_ExecuteCode(object sender, EventArgs e)
{
}

In some cases you might be calling a method or service on an existing interface. However, other cases may be simple snippets of code. In order to keep your workflow completely pluggable, consider using a delegate. For example, if the analyze user takes a user parameter and then sets a flag in the workflow based on the result, instead of this:

private void AnalyzeUser_ExecuteCode(object sender, EventArgs e)
{
   _isOver30 = User.Age > 30;            
}

Try this:

// declare a delegate to analyze the user
public delegate bool AnalyzeUserDelegate(User user); 

// declare a method to set the delegate
public AnalyzeUserDelegate AnalyzeUserMethod { get; set; }

private void AnalyzeUser_ExecuteCode(object sender, EventArgs e)
{
   _isOver30 = AnalyzeUserMethod(User); 
}

Note we've encapsulated the action that is required (set a flag by analyzing the user) but we've removed the dependency of a concrete implementation. Why would I want to do this? Perhaps I am testing the overall workflow structure and want to know when it reaches the call to the delegate. I'm not concerned about whether it sets the users age, only if the method is reached. I can easily test for that situation like this:

...
bool delegatedCalled = false;

AnalyzeUserDelegate testMethod = (user) =>
   {
      delegatedCalled = true;
      return true;
   };

myParams.Add("AnalyzeUserMethod", testMethod);
...
instance.Start(); // start the worfklow
Assert.IsTrue(delegateCalled, "The method was invoked."); 
...

This allows you to separate testing the logic/flow of the workflow from the implementation of the various nodes within the workflow.

Properties Out

We talked about how to get implementation into the workflow, now let's talk about what to get out. Even if your workflow does not "return" a value to the outside world, you should consider exposing some properties to indicate key milestones within the workflow. One of our workflows involves assigning an asset to a location. The workflow itself only needs to perform the actual assignment. There is no "output" other than the changes to the system itself. However, for testing purposes, we expose certain values such as the location assigned and a flag that indicates whether an assignment was successful. This allows us to test the outcome, like this:

...
public bool WasAssigned { get; set; }
...
instance.Start(); // start the workflow
Assert.IsTrue((bool)results["WasAssigned"]); 

That example is a simple test of whether or not a successful assignment took place.

Wiring the Tests

One thing I've noticed is that few people realize workflows are very easy to test. There are many ways to trigger a workflow (events, schedules, etc). The standard examples I've seen online involve launching the engine in potentially a different thread altogether. Fortunately, the engine is extensible and there is a service shipped with the runtime that allows you to run it in an almost-synchronous way.

The first thing to do is set up references to the run time and the service that allows for the immediate workflow execution:

...
private WorkflowRuntime _runtime; 
private ManualWorkflowSchedulerService _scheduler; 
...

In your test setup, you'll instantiate the runtime and add the manual service:

[TestInitialize]
public void TestInitialize()
{
   _scheduler = new ManualWorkflowSchedulerService(); 
   _runtime = new WorkflowRuntime(); 
   _runtime.AddService(_scheduler); 
}

Be sure to tear down the workflow after the test is run:

[TestCleanup]
public void TestCleanup()
{
    if (_runtime != null && _runtime.IsStarted)
    {
        _runtime.StopRuntime();
    }

    if (_runtime != null)
    {
        _runtime.Dispose();
    }
}

Now you can wire up your test. If you want to be able test the output results as I mentioned above, you need to bind to the WorkflowCompleted event:

...
Dictionary<string, object> results = null;
_runtime.WorkflowCompleted += delegate(object sender, WorkflowCompletedEventArgs wce) { results = wce.OutputParameters; };
...

This will take all public properties and dump them by name and value into the results variable for inspection. The next thing is simply to create an instance and run it, like this:

WorkflowInstance instance = _runtime.CreateWorkflow(typeof (MyWorkflow), myParams);
instance.Start();
ManualWorkflowSchedulerService schedulerService = _runtime.GetService<ManualWorkflowSchedulerService>();
schedulerService.RunWorkflow(instance.InstanceId);
Assert.IsNotNull(results);

The results test ensures the workflow successfully ran.

Now I can test my workflow structure using a mocking framework like Moq. Moq makes it easy to inject a test object and verify whether or not it was called. If I have an interface called IMyUserServices and I am expecting the workflow to call a method called ValidateUser, I would simply load it up like this:

Mock<IMyUserServices> myUserServices = new Mock<IMyUserServices>(); 
Dictionary<string, object> myParams = new Dictionary<string, object> 
   {
      { "MyUserServicesImplemented", myUserServices.Object }
   };
// set up the call to always return true
myUserServices.Setup(svc => svc.ValidateUser(It.IsAny<User>())).Returns(true); 
...
instance.Start();
...
// make sure we called it
myUserServices.Verify(svc => svc.ValidateUser(It.IsAny<User>()), Times.Once());
...

Obviously going through all of the features and functionality of mock frameworks is outside of the scope of this post, but I wanted to share how easy these tools make it to create powerful, granular tests. I am able to wire up the entire complex workflow and test that the flow works as expected before every writing a line of actual implementation. Then, it becomes simple to implement the code and write unit tests for each atomic piece of functionality. This then makes it easy to test and implement complex solutions by breaking them into simple parts.

Finally, I'll leave you with a little snippet of unit testing wisdom I recently learned. A stub is something you inject to make a test run. A mock is something you check the state of to validate your test. Often people refer to stubs as mocks, but if you aren't inspecting the stub for success, it's a stub. If you are checking it for something (state, output, exception) then it is a mock.

Jeremy Likness