Over a million developers have joined DZone.

Silverlight Architecture Feedback

· Mobile Zone
Thanks to Devoteam Luxembourg, I am actually setting up a Silverlight architecture, but it was not my first practice... I have already setup Silverlight architectures over a service layer. In most cases, I found some great shortcuts, some tips about what can be done and what can't be done. My brainstorm results will be explained in this article.


Uses cases

For a few years, I have been practicing Silverlight in a business context. In each case clients ask us to develop a user interface with business logic and persistency. Most of the time, clients wanted a CRUD application with a nice user interface.  


Target

These applications had to manage complex data and, for each data type, must:

  • Have a read only view,
  • Have a write view,
  • Manage complex properties/navigation properties by adding or removing sub items,
  • Have a corporate view and an innovative user experience,

I have proposed approximately the same architecture, even with my experience feedback… Silverlight over SOA was for me the solution by design for many requirements.

  • Multi-User
  • Less deployment problems
  • Expose services/resources for others

Global architecture Silverlight  

Sample of my last project packages




The (L) icon says that files are "add as link" under the project. In this case, changing it in the first and real reference says that you change it where the file is linked.

Tools & Technologies

Through NuGet, I am using MVVM Light, Entity Framework 4 and also T4 code generation from Microsoft with a T4 editor.

In details

 
From database to classes
Based upon the database, I create an EDMX file that generates the persistency layer and the POCO files. These POCO files embed all the entity framework persistence layer. Also based upon the EDMX file, a T4 file can generate the DTO in MVVM Light format and the AutoMapper configuration.

The T4 generator is a fork of the Self Tracking Entity version. It generates one file per class for the DTO and one global file that defines the AutoMapper’s configuration.

In this configuration, changing the data formator and the data source allow developers to be more reactive. They have to adjust web services and views.

DTO choices allow developers to extend the generated pack by custom DTOs. For example in auto-completion features.

The generated MVVM DTO

This file will contain one MVVM property for each corresponding property in the given class (with RaisePropertyChange call for example).

The generated AutoMapper configuration

It will generate the configuration from POCO to DTO (full copy) and from DTO to POCO preventing copy of primary key, complex and navigation properties.

The data transfer

 
Data migration through layers
We will now describe how the data will evolve in the architecture.

The data is actually stored in the database. Through a LinQ request, the business layer will find the data and Entity Framework will fill a POCO. By default, the lazy loading is disabled. It will prevent loading the entire database with AutoMapper or serialization. Users must say which data is needed. Once the POCO is filled, AutoMapper can transfer data from it to a new DTO before sending it through WCF.

Silverlight will receive data and can directly bind it on views.

On the other hand, Silverlight can modify the principal data and send it back to the server. The business layer will receive a DTO. If it already exists, load it and write over thanks to AutoMapper. If it doesn’t exist, it will add data to the persistency layer.

Helped with a static method, it is possible to “merge lists” for hierarchical entities. You can find the script below and discover the target of the function. This is inspired from the stackoverflow thread solution exposed here.
public static void Reconcile(EntityCollection databaseList,
                                           ObservableCollection dtoList,
                                           Func keySelector,
                                           Func keySelectorDTO,
                                           Func databaseFinder) where T : class where TDTO : class
        {
            Dictionary databaseDict = databaseList.ToDictionary(key => keySelector(key));

            foreach (TDTO dtoObj in dtoList)
            {
                int key = keySelectorDTO(dtoObj);
                T databaseObj = null;

                if (databaseDict.TryGetValue(key, out databaseObj))
                {
                    databaseDict.Remove(key);
                }
                else
                {
                    T databaseObjFound = databaseFinder(key);
                    if (databaseObjFound != null)
                    {
                        databaseList.Add(databaseObjFound);
                    }
                }
            }

            foreach (T removed in databaseDict.Values)
            {
                databaseList.Remove(removed);
            }
        }
 

Validation

Validation can be setup by creating a partial class and adding the validation helped with FluentValidation. You can setup validation on the server side and add a link of the partial class to the client side. With this configuration, you can add client side only, server side only or both if you want.

The validation details can be found here
This article follows the previous one : Part 1

We will now detail much more validation integration in the generated context.
How validation is integrated
Here is a schema that summarize the validation integration.

  • The generated part (left side) is the MVVM DTO, processed from the edmx file. This file will be linked in the model in silverlight side. This part is absolutely not correlated with validation.
  • The other partial class (right side) is added by the user and can embed multiple pieces of information (extra properties, methods, ...) and, in this case, flag the class and say it can be validated.
  • The last part (below) is the validation definition. You can embed each rule in the constructor of the class.
If you link in the Silverlight model package these three classes, you will benefit from validation on the client side. This validation model is totally integrated by the Silverlight technology. Setting up the validation in the view by adding "ValidatesOnDataErrors=True". With this modification, all validation problems will be raised to the user (on update binding). The bonus is to add "ValidatesOnExceptions=True". You will now raise validations warnings on system exceptions (like conversion problem, setting a string on a float property...)

Binding sample
The last step of this article is exposing what i am generally using in Silverlight/WPF programs. Some of them are from other sources.
Package helpers view

 Behaviors

  • BindVisualStateBehavior : Link an enum property of your VM and, on changes, invoke a "change state" in the view. The main goal is to define a Laoding/Loaded state, an Error/NoError state, an Application state and allow user to orchestrate your silverlight application only by changing an enum value.
  • BackToStateBehavior : On a specific action, set an enum to a specified binded property.
  • KeyPressSelecterComboboxBehavior : On a user letter key press , select combobox item starting by the item.
  • NotNullCheckboxBehavior : When someone set null to a checkbox, it will automatically be modified to false. Fighting against bad database format :)
  • RadioButtonToValueBehavior : When a radio is checked, set the specified value to a linked property. Usefull to link radio button group to value.
  • SecurityBehavior : This behavior is linked to a list of "Role" and, if a specified role is not found in the list, it hides the associated object.
  • UpdateBindingOnTextChangedBehavior : On each key press, update the text binding.
  • ValueToVisibilityBehavior : Only show the associated object if a linked property is equal to a specified value.

Converters

  • BirthDateConverter : A simple converter to change a DateTime to a specified format.
  • VisibilityConveter (& Inverted version) : Convert a boolean to visibility
  • VisibilityFromDataConverter (& Inverted version) : Test if the data is null and transform the result to visibility.

The original source of this articles are :


My blog, Part 1 My blog, Part 2
Topics:

Opinions expressed by DZone contributors are their own.

The best of DZone straight to your inbox.

SEE AN EXAMPLE
Please provide a valid email address.

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.
Subscribe

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}