Appearance in CoDe Magazine

If you haven’t already taken a look at the Nov / Dec 2008 issue of CoDe magazine I would highly recommend it 😉 On my last gig at Magenic I had the pleasure of working for Rocky Lhotka, Sergey Barskiy and Nermin Dibek on CSLA Light. Along the way we managed to crank out an article for CoDe Magazine related to the work we were doing. Here is a link to the article online, Using CSLA .NET for Silverlight to Build Line-of-Business Applications.

I got a copy of this magazine at the last Twin Cities Code Camp and didn’t even know that I was a co-author of one of the articles in it! It wasn’t until the following monday that a coworker of mine pointed out to me that I was in the magazine and he only knew because he recognized my picture. That was pretty funny.

Now that I’m famous if anyone wants me to autograph their copy of CoDe magazine just let me know!

Silverlight and Interoperability

I read something interesting on Scott Guthries blog about the release of Silverlight 2:

Interoperability

Today we are also announcing that Microsoft is partnering with Soyatec to sponsor additional tools for developing Silverlight applications using the cross platform Eclipse development platform.  Click here to learn more about this and download the free Silverlight Eclipse plugin.  Click here for a step-by-step tutorial that walks-through how to use their Eclipse tools today to build a Silverlight 2 application.

We are also announcing today that we are releasing the Silverlight XAML vocabulary and schema under the Open Specification Promise (OSP), which enables anyone to create products that read and write XAML for Silverlight.

This is a bit surprising but a good move I think. Scott Guthrie and the ASP team have also been creating the ASP MVC framework under an open source license so it shouldn’t be too much of a shock to see the focus on interoperability with Silverlight. I do like this trend though, I feel like it’s important to focus on interoperability and support open source as much as possible.

CSLA Light PropertyStatus control in Action

I have been working on CSLA Light for a while now and one of the coolest things I’ve gotten to work on is the “PropertyStatus” control. It turns out that creating controls for Silverlight is a huge pain in the neck but I think this one turned out pretty well actually.

So what the property status control does is that once bound to a CSLA business object it will hook into PropertyChanged events and display the properties IsBusy status and various broken rules. It will also disable / make read-only another control based on the authorization rules specified in the object. All in all it’s pretty useful.

I put together a quick little video demonstrating the effects. The second half of the video I have logged in under “Guest” credentials to show how it works with authorization.

Unit Testing Asynchronous Code in Silverlight

My current job is a very enjoyable one. I have the pleasure of working for Rocky Lhotka on CSLA 3.6 and CSLA Light, more specifically CSLA Light but the two definitely bleed together.

CSLA Light is a project where we are trying to create a version of CSLA that will run on Silverlight. If you’re interested in hearing more details about this you should check out Rocky’s blog since it is the most up to date authority on CSLA development progress.

One of the problems we ran into right away was the ability to unit test our Silverlight code. Unit testing on Silverlight presents a number of limitations that are not present in a standard .net application. We initially tried using the unit test framework provided by Microsoft but found it impossible to test anything with a WCF service call in it due to threading.

To help illustrate the problem consider the following test:

[TestClass]

public class TestExample

{

    [TestMethod]

    public void Example()

    {

        ManualResetEvent mre = new ManualResetEvent(false);

        BackgroundWorker worker = new BackgroundWorker();

        worker.DoWork += (o, e) =>

        {

            // Do some processing…

        };

        worker.RunWorkerCompleted += (o, e) =>

        {

            mre.Set();

        };

        worker.RunWorkerAsync();

 

        mre.WaitOne();

    }

}

This test simulates a unit of work that is performed asynchronously. If you run this test in Silverlight what will happen? Also, suppose in your DoWork method there is bug and an Exception is thrown, what will happen? I’ll get back to this in a moment.

One of the features of CSLA is something called the “Data Portal” which is a concept that has been preserved in CSLA Light with only some slight differences, primarily all network calls in Silverlight must be done asynchronously. The Data Portal is the mechanism your CSLA business objects must use to transfer data across network separated application tiers. In CSLA 3.6 an asynchronous Data Portal has been created to provide parity with Silverlight, not to mention the fact that it’s just plain cool.

One interesting thing to know about Silverlight is that whenever you use WCF to make a network call it will dispatch that call onto the UI thread. I believe this is actually a limition of the browser rather than Silverlight itself, it must be piggy backing on top of the browser XmlHttpRequest functionality and therefore suffers from the same limitations.

This is a major problem for the Silverlight MSTest framework! Since your test is running on the UI thread if your test tries to make a WCF call it will need to be dispatched to the UI to work and you will end up with a deadlock. The above test will not work in Silverlight because we have used a ManualResetEvent to hold the UI thread since it too will dispatch to the UI thread.

So to respond to this we came up with a light weight unit testing framework that will allow you to easily test asynchronous code in Silverlight and to accompany NUnit or MSTest in .NET. The project is on Codeplex and it is called Unit Driven. It is designed to allow you to easily test asynchronous code in both Silverlight and .NET. In fact, in CSLA the test code we are writing is identical for both CSLA and CSLA Light despite the various differences in the environments. Here is an example of how you would write the previous test to address all of the questions I posed using Unit Driven:

[TestClass]

public class TestExample : TestBase

{

    [TestMethod]

    public void Example()

    {

        UnitTestContext context = GetContext();

        BackgroundWorker worker = new BackgroundWorker();

        worker.DoWork += (o, e) =>

        {

            // Do some processing…

        };

        worker.RunWorkerCompleted += (o, e) =>

        {

        };

        worker.RunWorkerAsync();

 

        context.Complete();

    }

}

The subtle differences in this approach are simply that you’re using the UnitTestContext object to block the thread, or not, for you depending on the framework your test is running in as well as having an AsyncAsserter to manage getting exceptions back to the test thread for you.

In the first example you would end up in a deadlock in Silverlight and if your DoWork method threw an exception in either framework it would be interpreted as an unhandled exception and would cause your test to hang. With UnitDriven we are able to manage this easily by using an Assert.Try( … )

[TestMethod]

[ExpectedException(typeof(InvalidOperationException))]

public void ExpectedExceptionExample()

{

    UnitTestContext context = GetContext();

    BackgroundWorker worker = new BackgroundWorker();

    worker.RunWorkerCompleted += (o, e) =>

    {

        // catches exception here and passes to the context.

        context.Assert.Try(() =>

        {

            throw new InvalidOperationException();

        });

        context.Assert.Fail();

    };

    worker.RunWorkerAsync();

 

    // When the context is triggered it will find the

    // exception and re-throw it in .NET

    // and simply pass it back in Silverlight.

    context.Complete();

}

For some working examples check out our AsyncTests.cs on codeplex.

Happy Testing!

Thinking Async 1 – Asynchronous Data Access in Silverlight

I have created a simple example of how you can do asynchronous business objects in a Silverlight application using a WCF service reference. This example is very simple and is not as fully abstracted as it could be but I am simply focusing on the aspects of retrieving data asynchronously and putting them into your business objects for now.

Download this examples source.

The first key is in the factory method, let’s see an example.

public static ExampleCollection FetchAll()

{

    ExampleServiceSoapClient client = new ExampleServiceSoapClient();

    client.FetchAllCompleted += (sender, e) =>

    {

        ExampleCollection collection = e.UserState as ExampleCollection;

        collection.Load(e.Result);

    };

 

    ExampleCollection examples = new ExampleCollection();

    client.FetchAllAsync(examples);

    return examples;

}

 

In the example factory above we are attaching an event handler to the FetchAllCompleted handler of our WCF service client. This would normally be abstracted out into a Data Access Provider layer but for the sake of simplicity we are doing it using an inline lambda expression.

Next we are creating a new, empty, collection then calling FetchAllAsync then passing back the example collection to the caller. At this point the collection will actually be empty and at some time in the future the asynchronous call will complete and begin adding objects to the collection. This is important because for data binding we need the object we wish to be bound to immediately but we don’t necessarily need its data.

In order to notify the caller that we have added objects to our collection asynchronously we will need our collection to implement INotifyCollectionChanged. For non-collection objects you will need to implement INotifyPropertyChanged. The easiest way to do this for collections is to simply inherit from ObservableCollection<T>.

Here is a simple example of how you might implement a your asynchronous business object collection

public class ExampleCollection : ObservableCollection<Example>

{

    private void Load(ExampleInfo[] exampleInfo)

    {

        foreach (ExampleInfo info in exampleInfo)

        {

            this.Add(new Example(info));

        }

    }

 

    public static ExampleCollection FetchAll() …

}

 

Here is an example of a non-collection business object

public class Example : INotifyPropertyChanged

{

    public Example(ExampleInfo exampleInfo)

    {

        Load(exampleInfo);

    }

 

    private Example() { }

 

    private int _id;

    private string _name;

 

    public int ID

    {

        get { return _id; }

        private set

        {

            _id = value;

            OnPropertyChanged(“ID”);

        }

    }

 

    public string Name

    {

        get { return _name; }

        set

        {

            _name = value;

            OnPropertyChanged(“Name”);

        }

    }

              

    private void Load(ExampleInfo exampleInfo)

    {

        ID = exampleInfo.ID;

        Name = exampleInfo.Name;

    }

 

    public event PropertyChangedEventHandler PropertyChanged;

    protected void OnPropertyChanged(string propertyName)

    {

        if (PropertyChanged != null)

            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

    }

 

    public static Example Fetch(int id)

    {

        ExampleServiceSoapClient client = new ExampleServiceSoapClient();

        client.FetchCompleted += (sender, e) =>

        {

            Example example = e.UserState as Example;

            example.Load(e.Result);

        };

 

        Example ex = new Example();

        client.FetchAsync(id, ex);

        return ex;

    }

}

 

Remember, you just have to think in async!