Architecting Silverlight LOB applications (Part 5) – Modules and UI composition

In this fifth post and the next ones I’m going to write about client development and how to create a modular and composite silverlight application. In this post I’ll focus on UI composition.

When building composite LOB silverlight apps you should be aware that modularity is an important requirement. As a developer it should be easier for you to mantain your code and add new features to your application without having to change the rest, plus your application’s XAP file doesn’t grow bigger. Every module is a separate XAP file, that can be downloaded on demand, depending on the user’s intent to use a certain functionallity.

Below is one possible architecture to achieve what we need.


Continue reading


Architecting Silverlight LOB applications (Part 4) – Metadata and localization

Specifying metadata for our entities is the easy part and here is a good place to start localizing our app.

First what we have to do is create a buddy class as described in the following example:

public partial class Customer
    internal class CustomerMetadata
        [Display(ResourceType = typeof(Metadata), Name = "MyApp_Customer_Number")]
        public int Number;

        [Display(ResourceType = typeof(Metadata), Name = "CommonProperties_Email")]
        public string Email;

        public EntityCollection<Order> Orders;
public partial class Employee
    internal class EmployeeMetadata
        [Display(ResourceType = typeof(Metadata), Name = "CommonProperties_Name")]
        [StringLength(128, ErrorMessageResourceType = typeof(Metadata), ErrorMessageResourceName = "CommonErrors_StringLength")]
        public string Name;

        [Display(ResourceType = typeof(Metadata), Name = "CommonProperties_Email")]
        public string Email;

        public Department Department;

The DisplayAttribute attribute is very useful, as it annotates your properties with information that can be consumed in various ways. For example, when using your entity in a Datagrid, the cell headers will automatically look up for DisplayAttributes and retrieve the localized string for that property. The same applies for labels in a Dataform and if you want to create your own UI framework, you can leverage this type of annotation to start localizing your app. Notice how I’ve reused some resource names for common properties like Email. The same could have been done for Number and Name, but that really depends on each case.

You can place validation rules on your properties as well using attributes like StringLength, apply regular expressions or even create your own custom validation rules. The great part about this is that those rules will be available in the client as well. The DomainService makes sure that before executing operations on entities all the validation rules are applied. Note that you can’t do all kinds of validation on your entities using metadata. Some validations may require connecting to a database, transactions, etc, and such information isn’t available in this type of validation context. I recommend that such validations are performed after DomainService’s ExecuteChangeSet is invoked and right before the PersistChangeSet method.

More on metadata specification can be found in the documentation or other resources on the web. I just want to focus on a different aspect that not many people tend to write about. That is sharing the Resources in the client and the server. The client project will not compile if the ResourceManager Metadata isn’t available. Since it is defined on the server, you should follow these steps in order to enable it on the client:

  • Add the resource files as a link to the client project
  • Change your client project’s default namespace to the same namespace that is defined in the server project that holds the resource files
  • Change the client project’s .csproj where it references the linked Designer.cs file and add these lines of code:

      <Compile Include=”..\..\..\Server\Data\MyApp.Data\Resources\Metadata.Designer.cs”>

            <AutoGen>True</AutoGen>      <Link>Resources\Metadata.Designer.cs</Link>




  • Make sure the resource files have the same relative path in the client project as in the server project. In this case, I’ve created a Resources folder in both projects.
  • Also make sure that the resource file has Public marked as its Access Modifier.

These steps are necessary because adding linked files for dependent files, like Medatata.resx / Metadata.Designer.cs won’t automatically mark them as dependent, so you need to do it manually.

Now you should be able to compile your application and start taking advantage of metadata in your entities.

To finish, I’d like to say that all the code is available at under trunk/2010/SL-MVVM-RIA. I’m sorry for the delay on this one.

Next posts will be covering client development.


Architecting Silverlight LOB applications (Part 3) – DomainServices and Repository

Hello again,

In the previous post I described an overview of an architecture that could be used when developing silverlight modular apps. In this post I’ll start with a simple business domain model and create a domain layer around that model.

In this example our app will be a web application for a company that sells products and that can be used by its customers to fulfill orders and its employees to process them. These orders have details which consist of products and quantities. Each product can have a product category. When a customer submits an order fulfillment, an employee of the company may process that order to prepare the items for shipping.

The company has a few departments, and each employee belongs to a department. This means that employees from the Sales department will be to process orders; employees from the Human Resources department will be able to recruit new employees; and employees from the Financial Department will be able to watch some charts and print reports with statistics of how sales are evolving as time goes by, sales reports, etc.

Continue reading

Architecting Silverlight LOB applications (Part 2) – Architecture overview

Continuing our series, I’d like to present an architecture that I’ve been working on and can be used in Silverlight LOB apps that are developed using DDD (Domain Driven Development) and have N-layers.

The following picture describes how an application can be layered into multiple Modules, all hosted within regions of a Shell. These modules can communicate with each other through well defined messages and contracts defined in the module Infrastructure layer. Furthermore, they retrieve and manipulate data objects through WCF Services that are suited for DDD (called WCF RIA Services). These data objects are often called entities and can represent your Domain Model and are persisted in a data store using Data Access Objects that abstract both the data store and the data access technology you’re using. WCF RIA Services provides ways for you to manipulate your entities in the client similarly as you would do in the server when it comes to querying, changing data and submitting changes.


Such application often relies on server-side infrastructure for authentication and authorization, logging and error management. At the client-side they rely on frameworks that help reduce, harmonize and reuse code in module development both at the presentation logic and at the presentation views. Some layers may have components that depend on components from other layers. In such cases, we reduce these dependencies with IoC containers or similar frameworks like MEF.

Developing in an N-layered architecture can be troublesome when you want to reuse code that has to be specified both at server-side and at client-side when it comes to validation or other business logic. WCF RIA Services relies on metadata that describes entities how entities are defined, validated and how they behave with each other. Although this technique is very effective, there are related problems that aren’t noticed until you actually hit them and I’ll try to identify and address some of them.

Notice the mapping layer between the Data entities and the Domain entities. This layer is “optional” and can be useful when you don’t want to expose your data entities as your domain model. This helps achieve persistence ignorance and also allows you to create simple and lightweight classes to transport data. For simplicity, I’m not going to use this layer in the upcoming posts, so my data entities will be my domain entities.

In the following posts I’ll be building an app that respects these layers and will evolve over time. I’ll also build a simple framework aimed for MVVM development to show how effective this pattern can be.

Never soon enough, but see you soon.

Architecting Silverlight LOB applications (Part 1) – Concepts and technologies

In this first part of the series I’ll focus on some open source projects in Microsoft’s Patterns & Practices and other technologies that are available and can help us achieve our goal.

First we have PRISM (Composite Application Guidance for WPF and Silverlight). PRISM is composed of a guidance and a set of libraries that are designed to help you more easily build modular WPF and Silverlight apps. It also has built-in components that let you take advantage of some known patterns like MVVM, Event Aggregator and Dependency Injection. There are others but I’ll focus on these three because I find them to be the most useful.


PRISM applies to client development. I think the best feature PRISM provides is the ability to specify your application modules (XAPs in Silverlight) as a catalog and load them on demand. We’ll explore this in detail in other parts of this series when we create a module catalog to be used within the application.

Dependency injection (a specific usage of the Inversion of Control concept) is a prime technique for building loosely coupled applications because it provides ways to handle dependencies between objects. It helps you build testable code because you can easily switch concrete implementations which your objects depend on. PRISM is built using this design principle and it uses the Unity container, which implements the DI technique. PRISM also lets you use other DI containers but I’ll focus on Unity since I haven’t enough experience with others.

This pattern can be applied in both client and server development.

I didn’t find a nice and simple figure about Dependency Injection so I’ll link to this post where I’ve used this technique in a WCF Service (OrderService) which used an IOrderRepository implemented by the OrderRepository class which had dependencies being injected in its constructor.

The MVVM pattern is becoming the alpha and the omega when building WPF and Silverlight apps. It helps you separate concerns when designing your presentation layer and if it is well thought you can create a great set of reusable code for your application and even reuse it for other applications.


With MVVM you basically think of your view as a set of classes and properties and not as a set of UI controls. This allows you to easily switch your UI while keeping the same logic that it is bound to, and at the same time enables testability. Plus it allows you to reuse a set of UI logic in lots of views with less effort. This pattern is applied to client development.

The Event Aggregator pattern allows you to build your app with an Event Driven Architecture where components communicate with each other in a decoupled manner. It provides a way to publish and subscribe to events without knowing who is subscribing or who is publishing. The only thing you need to know is the event you are publishing or subscribing and how to react to that event. Usually modules do not depend on each other and using events as contracts to communicate between them is a good approach. This pattern applies to client development.

Next we’ll focus on server development.

Client-server communication in Silverlight has been enforced and recommended to use web services. Since we are building LOB applications it makes sense to use services that are good to deal with data. WCF services sure are good but are they ideal? What’s the cost of maintaining a complete service layer that lets us expose CRUD operations on our data and also provides us the ability to do other queries (like get products by productType), or other business operations? How many times have we done this? And how many times have we done this for different applications? How about validation of the data on the server and client side? How about proxy generation? How about the amount of data sent to the wire just to change a DateTime value on the database?

We all know Visual Studio’s generated code is ugly as hell and maintaining client-side complete service agents can be troublesome, because you usually need to keep it synchronized with your service contract. In Silverlight it is slightly more complicated to share an assembly with service and data contracts than WPF, because of type incompatibilities. Also we usually like our client-side data contracts to implement INotifyPropertyChanged and use ObservableCollections so we take advantage of data binding but at the server we really do not care about this.

WCF RIA Services aims to solve all these problems and many others.. I’ll skip the “all the things RIA Services can do part”, and point you to the right place if you still don’t know. The most important features we’ll explore are query composition, data validation, change tracking, unit of work, among others.


I’ve been using RIA Services for the last 7 months and one thing I find very useful is that the way you communicate either with the server and with your model (at the client side) is through a very well defined API which makes it easy to create very generic code that can be used to create reusable viewmodels. This is especially useful when you have multiple persons working in the same project and you want to ensure that everyone will code the same way (I will definitely explore this in later posts).

WCF RIA Services current release is the RC2, it has a go live license, so we’re good to go.

This doesn’t mean you shouldn’t use WCF as well. There are cases where WCF RIA Services isn’t well suited to work for. For example, file uploading or downloading. In this situation it’s preferable that you create a WCF Service or an HttpHandler to deal with this particular case.

For our data layer the best options nowadays are still NHibernate (using Linq to NHibernate) or Entity Framework. Nevertheless, we should encapsulate our data access through repository objects and do not use our data access technology directly in our services. I’ve got a very simple post that talks exactly about this. In this case, we can use any or both. RIA Services generates code on the client based on reflection and other metadata that is applied in our server side entities. If you use Entity Framework with RIA Services it already has a specific metadata provider that is able to understand relationships between entities and generate them correctly in the client. If you wish to use NHibernate you will have to specify additional metadata in your entities. For simplicity I’ll use Entity Framework. There are other resources on the web that explains how to use NHibernate.

Last but not least, I’d like to talk about MEF. MEF stands for Managed Extensibility Framework, has been shipped with .NET 4 (SL4 also) and is designed to help us compose our apps in a decoupled way much easier than using an IoC container for dependency injection. You simply annotate your classes with Import/Export attributes and MEF will resolve dependencies between objects for you. Of course there’s more we can do. You can provide metadata when exporting an object and import only objects that follow some criteria. MEF can be used to download XAP’s when an Import must be satisfied and the exported object is in another XAP, which helps building modular apps. It is said that the new Prism version will use MEF for its modularity features, which makes it even more interesting.

In the next post I will start with a simple business scenario and follow a top-down approach by designing an architecture built upon these technologies. I haven’t had much time lately but I’m trying to catch up so see you soon!

Architecting Silverlight LOB applications

This post is an introduction to a series of posts that I will be doing about how we can architect an enterprise data-centric Silverlight application. While Silverlight is a powerful platform to create great interactive user experiences for Web, Desktop (and now) Mobile, it is also Microsoft’s best bet to create a multi-platform, cross-browser technology.

A lot of people think of Silverlight as just another Adobe Flash rival because of the RIA aspects both technologies offer and the strong multimedia support that Silverlight has. While this is true, we can get much more from Silverlight if we think of it as good technology for the software industry in Information Technologies. IT projects are all about manipulation, visualization and understanding data.

Silverlight, which is a subset of WPF (excellent to deal with data through data binding) and still a .NET application, when combined with today’s most popular patterns and some key technologies for software engineering, can be a very productive, straight-forward, reliable and successful technology to build this kind of applications, and at the same time, provide great UX.

In this series of posts I will try to cover key aspects when you are architecting an application that can start small, are meant to last for years and over time evolve into a bigger application due to new requirements and be developed by multiple teams without resulting in a big mess of code that no one ever wants to touch.

Such applications often are built using the following principles:

  • Separation of Concerns
    • The most important principle. Ability to divide and conquer by creating layers in your application that are meant to deal with a specific problem, task or functionality, thus reducing complexity. The rest of the principles are all based on this one.
  • Loosely coupling
    • Ability to create multiple components that can work together but do not depend on each other.
  • Flexibility
    • Ability to respond to future changes, either by completely switching the underlying technology or business needs.
  • Extensibility
    • Ability to create new functionality by extending or reusing existing one.
  • Modularity
    • Ability to create well defined (cohesion) independent business areas in your application that can be evolved separately, integrate with each other and even be deployed separately.
  • Testability
    • Ability to avoid/prevent unexpected bugs by changes or new functionality you make, by testing your application’s logic, behavior or dependencies.
  • Maintainable
    • Ability to quickly find the code you need to change, understand it and change it, even if the one who wrote it in the first place is not around anymore (happens frequently).
  • Reutilization
    • Ability to reduce code by creating components that will be reused by other components that require a specific functionality.
  • UI Independence
    • Ability to switch your presentation controls without breaking neither your presentation logic nor your application logic.
  • Localization
    • Ability to target multiple languages, thus increasing your range of customers.

I’m thinking in starting with an overall architecture, choose the right technologies, build a small application on top of it and then keep composing it. I’ll start with .NET 3.5 and later on move to .NET 4.

See you soon!

Silverlight for Windows Phone 7 and Symbian sooner than we think?

While MIX10 is taking place, it is expected that Microsoft anounces a Silverlight beta release along with developer tools for Symbian (running on Nokia S60 5th Edition platform, source) and also for Windows Phone 7 series.

I’ve been developing web app’s since I’ve started my career but I had the chance to develop some mobile app’s as well, and I gotta tell you, for me developing for mobile devices is very challenging and much more interesting than web app’s. 

I really enjoy .NET Compact Framework but when you want to do some cool UX stuff it’s a pain in the butt.

Last couple of years I’ve been working mostly with Silverlight/WPF and I’ve been waiting for a Silverlight release for Windows Mobile 7 (now called Windows Phone 7 series) for a long time.

I can’t wait until I start developing for mobile devices with Silverlight, and now being able to target Symbian devices as well it feels like the cherry on top of the cake.

On a side note, I’ll be attending Microsoft’s technology event in Portugal, Techdays 2010 on 20th,21st,22nd of April, and I’ll be most interested on Architecture, Web/UX, Mobility and Cloud sessions. I hope everyone has a chance to participate!