UPDATE: Thanks to everyone who voted! It looks like I'll be presenting on Syncing Audio, Video and Animations in Silverlight Applications at MIX10.
MIX10 is right around the corner which should be a lot of fun especially if you’re interested in Web and Rich Internet Application (RIA) development. If you’re not into development then the conference is held in Las Vegas so you can still have a good time while seeing a bunch of us software developer types hang out and get all “giddy” over technology.
I submitted a few sessions this time around and could use some help getting votes for the sessions since the votes will carry a lot of weight I hear. I know…probably cheesy to say “go vote for my sessions”…it’d be much cooler if I could say “go vote for my sessions and you’ll get an XBox 360 or PS3” but I don’t think my wife would be onboard with that one. In fact, I’m pretty sure I’d be looking for a new home at that point.
So, without any good incentive other than getting a chance to vote, if you have a minute please go and vote for any of the sessions below (or other sessions that interest you as long as they’re presented by Dan Wahlin) whether you’re planning to go to MIX10 or not. I’ll definitely owe you one. And, do me a favor and have your friends vote too! Just tell them that the check’s in the mail. :-)
Tales from the Trenches: Building a Real-World Silverlight Line of Business Application (Vote Here)
Silverlight provides a great deal of functionality that can be used to build robust Line of Business (LOB) applications for companies. In this session Silverlight MVP Dan Wahlin will discuss lessons learned while building a real-world enterprise Silverlight LOB application. Topics covered include best practices for coding and architecture, communicating between components and layers, data access dos and don'ts, error logging, gracefully applying animations and other media effects into an application, plus more. If you're interested in hearing real-world insight and tips and tricks that can help you save time building your LOB applications then plan on attending this event.
Getting Started with the MVVM Pattern in Silverlight Applications (Vote Here)
If you're already building Silverlight applications or interested in getting started with Silverlight you may wonder what best practices and architecture patterns should be used. In this session Silverlight MVP Dan Wahlin will break-down the MVVM pattern in easy to understand terms and demonstrate the benefits it offers for Silverlight applications. Key concepts found in the MVVM pattern will be discussed as well as other important technologies such as commanding and event buses. Code samples shown will demonstrate each concept along the way so that you understand how the different pieces fit together. If you're interested in learning best practices and seeing how to write more modular and loosely coupled Silverlight application code this session is for you!
Increase Ajax Developer Productivity with ASP.NET Ajax Client Templates (Vote Here)
Although Ajax provides end users with a rich and interactive application experience, it can be challenging for developers that retrieve data from services since all of the data binding normally done on the server-side is now done on the client-side. As a result, a lot of custom JavaScript and HTML has to be written. In this session Dan Wahlin will demonstrate how the new client templates feature in ASP.NET Ajax Library can simplify the process and significantly increase your productivity. Learn how to work with client-side data views, define templates, create data converters, work with template parameters, two-way bindings, plus more.
Leverage ASP.NET MVC 2 Ajax Features (Vote Here)
The ASP.NET MVC framework provides a lot of functionality that can be used to build efficient web applications. In this session, Dan Wahlin will dive into the Ajax functionality built into theASP.NET MVC framework and demonstrate how it can be used to enhance the end user experience. Learn how to leverage Ajax forms, JsonResult objects combined with REST calls, integrate jQuery into your applications, use client-side templates from the ASP.NET Ajax Library, plus more.
Syncing Audio, Video and Animations in Silverlight Applications (Vote Here)
Silverlight provides a robust framework for integrating audio, video and animations into applications but how do you keep them all in-sync? In this session Silverlight MVP Dan Wahlin will discuss an animation project created for a Fortune 500 company and demonstrate tips and tricks that can be used to keep various assets synced so that audio and video clips can be started at specific times as a storyboard plays. Topics covered include working with timers, segregating large storyboards into user controls, defining sync points using XML, generating markers using Expression Encoder, integrating closed captioning into an application, plus more.
Integrating WCF RIA Services into the MVVM Pattern in Silverlight Applications (Vote Here)
WCF RIA Services provides a flexible yet simple way to integrate distributed data and data rules into your applications while minimizing the complexity associated with asynchronous calls. In this session Silverlight MVP Dan Wahlin will demonstrate how WCF RIA Services can be used along with the MVVM pattern to access and bind data in applications. Topics covered include WCF RIA Services features as well as how ViewModel and Service Agent classes can leverage RIA Services to simplify the data binding process. Integrating built-in and custom data validation rules into an application will also be discussed along with best practices for using WCF RIA Services within applications that follow the MVVM pattern.
Print Silverlight 3 or higher screens and generate PDF documents with SmartPrint for Silverlight.
![SmartPrintSmallBox[1] SmartPrintSmallBox[1]](http://weblogs.asp.net/blogs/dwahlin/SmartPrintSmallBox1_69A19AE7.png)

Posted by dwahlin |
Wed, 06 Jan 2010 04:54:00 GMT |
Comments (5)
The subject of Dependency Injection (DI) and Inversion of Control (IoC) containers has received a lot of attention over the last few years. Building applications that are loosely coupled has become more and more popular (and for good reason) especially in applications that have a lot of dependencies that could break over time or need to handle the addition of new modules seamlessly. From a personal standpoint I fall somewhere in the middle of the overall DI argument. I definitely feel that DI has its place and personally use the general pattern in applications but also feel that some use DI in ways that seem to make applications overly complex and more difficult to maintain in the future. My opinion on the subject really doesn’t matter here though since this post is about using an IoC container framework in Silverlight applications.
I’ll walk through a simple example from an existing application that my company is working on and demonstrate how using a dependency injection pattern can help minimize code and simplify changes down the road. If you’re new to the concept of DI and IoC containers I’d recommend reading Martin Fowler’s post on the subject. He provides a good introduction to constructor, setter and interface injection. If I had to sum up DI and the purpose of IoC Containers in a single sentence here’s what I’d say:
Minimize hard coded class names when creating object instances and let IoC containers dynamically look-up types and “inject” them into your application at runtime.
Before jumping into using Autofac in Silverlight let’s take a quick look at the type of problem an IoC container can solve. The following code shows a ViewModel class (see my post of using the MVVM pattern with Silverlight if you’d like more information on what a ViewModel is) that has two constructors:
public class JobChangeOrdersViewModel : JobMaterialsViewModelBase
{
public JobChangeOrdersViewModel() : this(new ServiceProxy()) { }
public JobChangeOrdersViewModel(IServiceProxy proxy) : base(proxy)
{
if (!this.IsDesignTime)
{
//Communicate with another ViewModel (JobManagementViewModel) to get current JobID by using events
JobManagementEventBus.JobReturned += JobManagementEventBus_JobReturned;
JobManagementEventBus.OnJobRequested(this, EventArgs.Empty);
JobManagementEventBus.JobMaterialsUploading += JobMaterialsUploading;
WireCommands();
GetChangeOrders();
}
}
}
Notice that the first constructor forwards a new ServiceProxy object instance to the second constructor which accepts an IServiceProxy type. XAML views (Silverlight pages or user controls) call this first constructor to create a ViewModel instance and access data. While there’s nothing wrong with this code, if I need to change the type of service proxy object used I’d have to change the new ServiceProxy() line of code. Since Visual Studio provides nice search and replace functionality it’s really easy to do that across multiple files. However, a better solution would be to define the type of service proxy object to use in one place so it’s easy to locate and easy to change and then “inject” it into the application at runtime. I use the same two constructor signatures across many ViewModel classes so this centralized-code approach is definitely preferred. Let’s look at how Autofac can be used to avoid hard coding the new ServiceProxy() call.
Getting Started with AutoFac in Silverlight
There are several different IoC containers that can be used with Silverlight such as Unity (included with the Prism framework), Ninject, Caliburn and MEF (an extensibility framework that can act like an IoC container). I’ve always liked Autofac mainly because it’s very easy to use and a project I’ve followed for awhile. Autofac can be used in ASP.NET, Windows Forms, WPF (or any .NET application) and Silverlight applications so it’s very flexible. A specific Autofac download for Silverlight 3 (or higher) is available from http://code.google.com/p/autofac/downloads/list.
To get started place the Autofac.dll assembly in your project’s bin folder and add a reference to it using Add Reference. Once that’s done you can create a ContainerBuilder object instance (located in the Autofac.Builder namespace) and use it to build a Container that can resolve specific types against interfaces (more on this later). For the code shown above this means that I can associate the ServiceProxy class with the IServiceProxy interface so that anytime I need to supply an object of type IServiceProxy an instance of ServiceProxy will be created and passed behind the scenes. I created the following class named IoCContainer to handle creating the ContainerBuilder and Container:
public static class IoCContainer
{
public static IContainer BaseContainer { get; private set; }
public static void Build()
{
if (BaseContainer == null)
{
var builder = new ContainerBuilder();
builder.Register<ServiceProxy>().As<IServiceProxy>();
BaseContainer = builder.Build();
}
}
public static TService Resolve<TService>()
{
return BaseContainer.Resolve<TService>();
}
}
The Build method handles creating the ContainerBuilder which is used to associate classes with interfaces. In this case I associate ServiceProxy with IServiceProxy using the Register<TService>() method. This is a simple example (simple on purpose) but keep in mind that an application can register many associations between types and interfaces as needed. More advanced associations can also be registered using Autofac including passing parameters to a resolved object’s constructor. See the Autofac wiki documentation for additional details. Once the type is registered the ContainerBuilder object’s own Build() method is called which returns an IContainer type (a Container object that can be used to resolve an interface with an object instance). The Resolve<TService>() method added into the IoCContainer class wraps a call to the Container object’s Resolve<TService>() method. It’s added purely for convenience to save a little code.
In the App.xaml.cs file’s Application_Startup event handler I add the following code which calls the IoCContainer class’s static Build() method:
private void Application_Startup(object sender, StartupEventArgs e)
{
IoCContainer.Build();
ProcessInitParams(e.InitParams);
this.RootVisual = new MainPage();
}
Once that’s done the Autofac container can be used to resolve interfaces. An example of using the IoCContainer class and Autofac classes to create the ServiceProxy object shown earlier in a ViewModel class is shown next:
public class JobChangeOrdersViewModel : JobMaterialsViewModelBase
{
public JobChangeOrdersViewModel() : this(IoCContainer.Resolve<IServiceProxy>()) { }
public JobChangeOrdersViewModel(IServiceProxy proxy) : base(proxy)
{
if (!this.IsDesignTime)
{
//Communicate with another ViewModel (JobManagementViewModel) to get current Job
JobManagementEventBus.JobReturned += JobManagementEventBus_JobReturned;
JobManagementEventBus.OnJobRequested(this, EventArgs.Empty);
JobManagementEventBus.JobMaterialsUploading += JobMaterialsUploading;
WireCommands();
GetChangeOrders();
}
}
}
You can see that the new ServiceProxy() code originally in the first constructor has been replaced with the IoCContainer code instead. If a different class needs to be used instead of ServiceProxy then a change can be made in the IoCContainer class’s Build() method and all calls that need to resolve the IServiceProxy interface will automatically be updated throughout the application (which is obviously a good thing as far as maintenance goes).
There’s much more than can be done with Autofac - this post has only scratched the surface. However, you should have a better understanding of how Autofac (or any compatible IoC container for that matter) can be used in a Silverlight application to keep code loosely coupled.
Print Silverlight 3 or higher screens and generate PDF documents with SmartPrint for Silverlight.


Posted by dwahlin |
Sun, 03 Jan 2010 08:31:21 GMT |
Comments (4)
With the increasing popularity of Silverlight as an application development framework the discussion of patterns has grown louder and louder. Fortunately the majority of developers building Silverlight applications have agreed on a pattern that fits well in the Silverlight world called Model-View-ViewModel (MVVM). The MVVM pattern allows applications to be divided up into separate layers that provide multiple benefits ranging from better code re-use to enhanced testing capabilities. This post will explain key concepts found in the MVVM pattern and attempt to present them in a way that is easy to understand. I’ll show some code along the way to demonstrate how the MVVM pattern can be used and provide a few alternatives when it comes to binding data. The code shown later in the post can be downloaded here.
Getting Started with the MVVM Pattern
The MVVM pattern defines three key parts including the Model, the View and the ViewModel. The following image shows a slide from a Silverlight course we offer that sums up the role of each part of the MVVM pattern in a concise way:

Looking through the description of each part you can see that the Model represents the business domain which includes the model classes used (Customer, Order, etc.), data access code and business rules. In general you can think of the Model as representing the entities that live on the server as well as the objects that are responsible for interacting with the data store your application uses and filling entities with data. While some people feel that the Model represents only the model classes (classes like Customer, Order, etc.) used in the application I personally think of it more broadly and include data access code and business rules in the Model definition. Silverlight applications will call into the Model code through services written using WCF, ASMX, REST or even custom solutions.
The View in MVVM represents the Silverlight screens that you build. This includes the XAML files and the code-beside files that are responsible for showing data to end users. The View's responsibilities include displaying data and collecting data from end users. A given View isn't responsible for retrieving data, performing any business rules or validating data.
The ViewModel acts as the middle-man between the View and the Model. It's responsible for aggregating and storing data that will be bound to a View. For example, a ViewModel may contain a List<State> property and a List<Person> property that may be bound to two ComboBox controls in a View. The ViewModel will retrieve the values held by these two properties from the Model. By using a ViewModel the View doesn't have to worry about retrieving data and knows nothing about where data comes from.
Additional players may be added into the Model-View-ViewModel mix to help segregate code even further. For example, I normally create a service agent class that is responsible for making calls from Silverlight to remote services. The service agent is responsible for initiating the service call, capturing the data that's returned and forwarding the data back to the ViewModel. By doing this the ViewModel classes can delegate data gathering responsibilities to the service agent. A given service agent can also be re-used across multiple ViewModel classes as needed. The following image shows how the service agent can be integrated into the MVVM pattern:

When developers first start building Silverlight applications they typically add all of the code for the application into the XAML's code-beside file (MainPage.xaml.cs for example). Although this approach certainly works, by following the MVVM pattern you can take advantage of several inherent benefits including better code re-use, simplified maintenance, more modular code and enhanced testing support. I'll focus on the overall benefits achieved by building applications that are based on the MVVM pattern throughout the rest of this article.
The Model
There are many different ways that the Model can be created including using Microsoft's Entity Framework or LINQ to SQL technologies, nHibernate, PLINQO, SubSonic, custom solutions and more. The technology chosen is generally unique to a given company's development policies so I'm not going to go into a discussion of the pros and cons of each technology here. What's important is that one or more classes used by a Silverlight application are "modeled" using tools or by writing code by hand. This involves defining all of the properties that each class will expose. A simple example of a Model class is shown next:
public class Person
{
public string FirstName { get;set;}
public string LastName { get;set; }
public int Age { get; set; }
}
Once the Model classes are in place they'll need to be populated with data from a data store which can be done by writing custom code or using ORM frameworks that handle mapping query results to object instances. Services will also need to be written to expose one or more of the Model classes used in a Silverlight application which can be done using WCF, ASMX or even custom REST services.
The View and ViewModel Classes
Once the Model is ready to go the View and ViewModel classes can be created. As mentioned earlier, a View represents a Silverlight screen that end users interact with which includes the XAML file and the associated code-beside file. Rather than adding all of the code to call the Model and retrieve data directly into the View's code-beside file, the View will rely on a ViewModel class to retrieve data and then bind to the properties of the ViewModel.
ViewModel classes should implement an interface that's available in Silverlight called INotifyPropertyChanged which defines a single event named PropertyChanged. This event is used to notify different Silverlight bindings that data has changed for one or more properties so that controls can be updated automatically. Although INotifyPropertyChanged can be implemented directly on a ViewModel class, your application may have multiple ViewModel classes in it and writing the same code over and over tends to get old. Creating a base ViewModel class that handles implementing INotifyPropertyChanged is useful to minimize code and allow more re-use to occur in applications. The following code shows a class named ViewModelBase that implements the INotifyPropertyChanged interface. The class also provides an OnNotifyPropertyChanged method that can be used to raise the PropertyChanged event.
public class ViewModelBase : INotifyPropertyChanged
{
protected void OnNotifyPropertyChanged(string p)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(p));
}
}
public bool IsDesignTime
{
get
{
return (Application.Current == null) || (Application.Current.GetType() == typeof(Application));
}
}
#region INotifyPropertyChanged Members
public event PropertyChangedEventHandler PropertyChanged;
#endregion
}
A ViewModel class can derive from ViewModelBase and automatically take advantage of the INotifyPropertyChanged interface. An example of a ViewModel class named PeopleViewModel that derives from the ViewModelBase class and defines several properties and methods is shown next:
public class PeopleViewModel : ViewModelBase
{
IServiceAgent _ServiceAgent;
Person _Person;
ObservableCollection<Person> _People;
public PeopleViewModel() : this(new ServiceAgent()) {}
public PeopleViewModel(IServiceAgent serviceAgent)
{
if (!IsDesignTime)
{
_ServiceAgent = serviceAgent;
GetPeople();
}
}
#region Properties
public Person Person
{
get
{
return _Person;
}
set
{
if (_Person != value)
{
_Person = value;
OnNotifyPropertyChanged("Person");
}
}
}
public ObservableCollection<Person> People {
get
{
return _People;
}
set
{
if (_People != value)
{
_People = value;
OnNotifyPropertyChanged("People");
}
}
}
#endregion
public void GetPeople()
{
_ServiceAgent.GetPeople((s,e) => this.People = e.Result);
}
public void UpdatePerson()
{
_ServiceAgent.UpdatePerson(this.Person, (s, e) =>
{
PeopleEventBus.OnOperationCompleted(this, new OperationCompletedEventArgs { OperationStatus = e.Result });
});
}
}
Looking through the code you'll see that PeopleViewModel defines two fields, two properties and two methods. Each property raises the PropertyChanged event as the set block is called by calling the OnNotifyPropertyChanged method defined in ViewModelBase. This notifies any controls bound to the properties that the values have changed which allows them to update the data they display automatically.
Looking at the first constructor in PeopleViewModel you'll see that it forwards the call to a secondary constructor that accepts a parameter of type IServiceAgent. Why have two constructors? This approach allows testing frameworks to pass in different types of service agents to the ViewModel when running tests. When the ViewModel is called at runtime the parameterless constructor will be called and an instance of a ServiceAgent class (shown next) will be passed as the IServiceAgent parameter. From there, once the service agent object is passed into the ViewModel's constructor a call to a method named GetPeople is made which invokes a method on the service agent and passes a callback delegate. The WCF service is then called by the service agent and the results are assigned to the People property.
public interface IServiceAgent
{
void GetPeople(EventHandler<GetPeopleCompletedEventArgs> callback);
void UpdatePerson(Person p, EventHandler<UpdatePersonCompletedEventArgs> callback);
}
public class ServiceAgent : IServiceAgent
{
public void GetPeople(EventHandler<GetPeopleCompletedEventArgs> callback)
{
PeopleServiceClient proxy = new PeopleServiceClient();
proxy.GetPeopleCompleted += callback;
proxy.GetPeopleAsync();
}
public void UpdatePerson(Person p, EventHandler<UpdatePersonCompletedEventArgs> callback)
{
PeopleServiceClient proxy = new PeopleServiceClient();
proxy.UpdatePersonCompleted += callback;
proxy.UpdatePersonAsync(p);
}
}
Binding a ViewModel to a View
Now that the ViewModel class is defined it can be bound to a View. This can be done declaratively in XAML or imperatively through code in the View's code-beside file. Imperative (or code-based) binding is typically accomplished by assigning a ViewModel instance to the layout root's DataContext property as shown next:
this.LayoutRoot.DataContext = new PeopleViewModel();
An example of declaratively binding a ViewModel (which is my personal preference) to a View is shown next:
<UserControl x:Class="ViewModelExample.MainPage"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:converter="clr-namespace:ViewModelExample"
xmlns:viewModel="clr-namespace:ViewModelExample.ViewModel"
mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480">
<UserControl.Resources>
<viewModel:PeopleViewModel x:Key="ViewModel" />
</UserControl.Resources>
<Grid x:Name="LayoutRoot" DataContext="{Binding Source={StaticResource ViewModel}}">
</Grid>
</UserControl>
The ViewModel namespace is first referenced using an XML namespace prefix of "viewModel". The ViewModel is then defined in the UserControl's Resources section and given a key of "ViewModel" (note that any name can be chosen for the key). The key is important since it's used to hook the ViewModel to the DataContext of the layout root using the {Binding Source={StaticResource ViewModel}} syntax. The declarative binding will cause a new PeopleViewModel instance to be created at runtime which is then bound to the layout root's DataContext. Child controls of the layout root can then bind to properties on the ViewModel. An example of binding a ListBox to the ViewModel's People property and a StackPanel to the Person property is shown next:
<StackPanel Margin="20">
<TextBlock Text="Binding Controls to a ViewModel" Margin="20,0,0,0" FontWeight="Bold" FontSize="12" />
<ListBox x:Name="lbPeople" Margin="0,10,0,0" Height="250" Width="300" HorizontalAlignment="Left"
ItemsSource="{Binding People}" ScrollViewer.HorizontalScrollBarVisibility="Hidden"
SelectedItem="{Binding Person, Mode=TwoWay}">
<ListBox.ItemTemplate>
<DataTemplate>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
<ColumnDefinition Width="100" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Margin="10" Text="{Binding FirstName}" />
<TextBlock Grid.Column="1" Margin="10" Text="{Binding LastName}" />
<TextBlock Grid.Column="2" Margin="10" Text="{Binding Age}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<StackPanel DataContext="{Binding Person}">
<TextBlock Text="First Name" Margin="0,10,0,0" />
<TextBox Text="{Binding FirstName,Mode=TwoWay}" Width="100" Height="25" HorizontalAlignment="Left"/>
<TextBlock Text="Last Name" />
<TextBox Text="{Binding LastName,Mode=TwoWay}" Width="100" Height="25" HorizontalAlignment="Left"/>
<TextBlock Text="Age" />
<TextBox Text="{Binding Age,Mode=TwoWay}" Width="100" Height="25" HorizontalAlignment="Left"/>
</StackPanel>
<Button Margin="0,10,0,0" Click="Button_Click" Content="Submit" Height="20" Width="100" HorizontalAlignment="Left" />
</StackPanel>
The MVVM pattern provides a flexible way to work with data that encourages code re-use and simplifies maintenance. There's much more that can be discussed with regard to the MVVM pattern in Silverlight such as event buses, commanding and dependency injection but I hope this post helps jumpstart the process of architecting and developing Silverlight applications. If you have specific Silverlight development concepts you'd like to see covered in future posts tweet me at @DanWahlin or add a comment below.

Posted by dwahlin |
Wed, 09 Dec 2009 07:30:06 GMT |
Comments (23)