Silverlight

New DimeCast: Introduction to WP7

DimeCasts.net just published my latest screen-cast titled: “Hello World, I am Win Phone 7″

I cover the basic of a File –> New Windows 7 Phone Application and talk about the emulator for a few minutes.

Enjoy.

Watch the Screen-Cast

Note: I do not cover installing the tools, Peter Henry does a great job of outlining what is necessary on his blog. Thanks Peter!

Using Prisms (CompositeWPF) EventAggregator

Event Aggregator – What is it?

The event aggregator in Prism is an implementation of the Event Aggregator pattern.

Fowler explains the Event Aggregator pattern as follows: 

Channel events from multiple objects into a single object to simplify registration for clients.

Microsoft also has a link for this pattern as well, its located here. Here’s what they have to say [snippet]:

The EventAggregator service is primarily a container for events that allow decoupling of publishers and subscribers so they can evolve independently. This decoupling is useful in modularized applications because new modules can be added that respond to events defined by the shell or, more likely, other modules.

At a high level it is decoupling the need to bubble events up through the system. Imaging you had a system that was layered like this:

image

 

Lets say that the “Services” layer needs needs to send off an event that some data has changed. One way to do this would be to bubble the event to the parent layer and then let that layer bubble the event up again. For example, lets say that the Service layer changed the Customer and it wants to let any interested parties know (as it should) through an event. So it sends a “CustomerChanged” event notification. Since the only object who is watching the Service layer is the Model layer, the model layer will grab the event and then re-publish it again (bubbling it up) the object graph). Eventually we need the event to get to the view, a grid, list, form or whatever the customer info is represented in. Graphically, it would look like this:

 

image

 

As you can tell, its a royal pain to do this. Imagine the amount of code you have to write. You’ve to write a ton of plumbing just to bubble the event from the service to the model to the view model to the view, and vice versa.

This is where an event aggregator  comes in. The event aggregator sits beside the layers, kind of like this:

 

 image

 

The event aggregator is an event broker, a simple level of indirection. In a basic Observer pattern methodology the observer would have to keep track of all of the event subscribers and so forth. By utilizing an event aggregator we can push this responsibility off to the event aggregator to handle the subscription and publishing of the event for us.

When to use it

Its best to use the event aggregator when you have many objects which are potential event sources. In the example above, we used the service layer as the publisher of the event, but any other layer could have changed that object as well and any interested party should be notified (such as the UI, or db layer).

 

The Event Aggregator in code

When we want to use an event aggregator we must create an “event” that we can subscribe to and publish. This event is a class that inherits from the abstract generic class CompositePresentationEvent<T>  (Change this to the new item). The type that is utilized to fulfill the generic need is the payload of the event. Therefore when an event gets fired, the event that is published to subscribers has a payload. This payload is what the subscribers are interested in.

The code for a composite class is:

public class CustomerAddedEvent : CompositePresentationEvent<Customer>
{

}

The customer Added Event gets all of its functionality from the generic CompositePresentationEvent. This event is published from a publisher (some layer in the system via the Event Aggregator) and then subscribers subscribe via the Event Aggregator.

Here’s a High Level Diagram of how it works.

EventAggregator

 

Code In Action

This code would be located in the presentation layer. We want to know when a customer added event occurs so we can update the UI.

public MockProgramAdminController(IEventAggregator eventAggregator)
{
    this.eventAggregator = eventAggregator;

    //
    // Watch for these events.
    //
    eventAggregator.GetEvent<ProgramEditEvent>().Subscribe(HandleCustomerAdded);
}

public void HandleCustomerAdded(Customer customer)
{
    // Update the view ...
}

 

The above subscribes to an event. When the event is fired, the “HandleCustomerAdded” method is invoked.

 

Now we want to be able to publish an event when something in the system changes. This code would normally be lower in the layer stack, such as in the Service or DB layer. Once the customer is added we will have a domain object and we need to notify all the subscribers that a new customer has been added. . Here’s how we do that. (again, this is in another class that has had an EventAggregator injected via constructor injection as well).

public void UpdateCustomer()
{
    // ... Code to add a customer to your system ..
    Customer cust = new Customer();
    cust.Save(); 

    //
    // Publish the change to the customer
    //
    eventAggregator.GetEvent<CustomerAddedEvent>().Publish(customer);
}

 

Once the publish takes place, all of the the subscribers will be notified with the customer object that was added. Now the subscribers can react to system events without having to resort to bubbling up the events.

 

I hope this helps you understand the event aggregator a bit more! Good luck!

Prism Drop 8 Breaking Changes

The Prism team dropped another version of Prism last Friday at the usual spot: www.codeplex.com/compositewpf . This is Drop 8 of their product.

Breaking Change #1 – Cannot Find CompositeWpfEvent

However, there is not note of a breaking change in this drop that is not noted in the release notes.

The type “CompositeWpfEvent” has now been changed to “CompositePresentationEvent”. I had to hunt around in reflector for a few minutes to find what they had they had changed it to. Update your composite events to inherit from that new class name and you’ll be good to go.

Example:

Pre Drop 8:

public class CustomerAddedEvent : CompositeWpfEvent<Customer>
{

}

 

Post Drop 8:

public class CustomerAddedEvent : CompositePresentationEvent<Customer>
{

}

 

Breaking Change #2 = ModuleCatalog.Groups.Add Not Found

Here’s what the previous code looks like:

var catalog = new ModuleCatalog();
catalog.Groups.Add(
	new ModuleInfoGroup {InitializationMode = InitializationMode.WhenAvailable}
		.AddModule(typeof(MyTestModule).FullName, typeof (MyTestModule)));
return catalog;

 

here’s what it looks like now:

var catalog = new ModuleCatalog();
catalog.AddModule(typeof (MyTestModule), InitializationMode.WhenAvailable);
return catalog;

They changed the catalog so that the Modules and Groups return an Enumerable of the modules or groups. You cannot “Add” to an Enumerable return value. You can only get the enumerator on it and iterate through it (and then do some other stuff etc).

Debugging Silverlight Tip

If you’re doing any kind of Silverlight work you’re bound to get “Error on page” in Internet Explorer. Here’s what I’m talking about.

You fire up your app in the browser window and BLAM. Screen is empty and you get the “Error in page” error. Double click the error and you get an Internet Explorer JS Error Window. Here it is in all its glory:

 image

 

How Do I Catch The Exception in Code?

The exception IS happening in code you’re just not catching un-handled exceptions.

To turn them on, go to Debug –> Exceptions:

image

You’ll get the window below. Check the “Common Language Runtime Exceptions” checkbox and click OK.

image

 

You will not get exceptions bubbled up to the Dev Environment. Here’s what it looks like in action  (with the same error as the “blank screen” above).

image

 

Click “Break” and break into the area where the code barfed on you, and then clean up the mess you’ve created (on accident of course – who creates un-handled exceptions for fun anyway). :)

 

Enjoy.

XamlParserException – AG_E_PARSER_BAD_TYPE

Ohhhhh the dreaded XamlParserException. The exception message is not to helpful at all.

In my instance I was working with Silverlight. Namely working with the Prism  V2 Drop #5 from the Composite WPF team. Get the latest and read up the project here. I was loading the TreeView control into my view (Xaml) and when the app fired up the project would bomb with this exception and the message was VERY informative *sarcasm*.

AG_E_PARSER_BAD_TYPE

Hmm… Ok. Sure. Sounds good.

I have my projects laid out like so.

image

 

The Prism Shell (Top) loads different modules at runtime. Module A has a view (View 1) which has a tree view. Therefore, Module A (which is a Silverlight App itself) references the Microsoft.Windows.Controls library which contains the new controls for Silverlight (download them here). When this was getting compiled and referenced at runtime, the Microsoft.Windows.Controls dll was not in the Shell project, therefore it would blow up when it tried to parse the Xaml. Giving me the lovelly and dreaded XamlParserException.

The Fix

Simple. Add a reference to the Microsoft.Windows.Controls dll in the main Prism App. Then…. BLAMMO… the control toolkit works as expected.