Month: November 2009

Build enterprise application with WPF, WCF, Entity Framework and Prism. Tutorial 06.

Configure your Customer lookup and run it on IIS 7.0

In the previous article we saw how to use WCF (a basic approach) and what we should keep in consideration if we want to use SOA as our repository.

Now we need to:

  1. Change the WCF service to point to a real database
  2. Test the service
  3. Build a web site to host our service
  4. Host the web site on IIS 7.0
  5. The the final result

Change the Customer service to reflect our database.

First of all let’s open the ServiceLibrary project and change the ICustomerService interface to reflect this:

  1: [ServiceContract]
  2: interface ICustomerService {
  4:  [OperationContract]
  5:  IList<CustomerDto> GetCustomers();
  7:  [OperationContract]
  8:  IList<CustomerDto> GetFilteredCustomers(string searchCriteria);
 10: }

For our menu we need two methods. The first one will retrieve all the available customers, in alphabetical order; the second one will filter this results, in order to show us only the customers that match our search criteria.

The concrete implementation of this contract will consequently change in this way:

  1: List<CustomerDto> Customers = new List<CustomerDto>();
  2: IRepository customerRepository = 
  3:    new Repository(new ADVConnection());

Of course, in order to declare our Repository we need to add a reference to the DataLayer project in our WCF service. We need also to reference the entity framework .dll “” and we need also to add the connectionString section in the app.config of our WCF service, otherwise when we will instantiate a new database session (new ADVConnection()) the Visual Studio will throw an error “configuration not found … ”. This happens because the WCF is the final layers so you can use in .NET just one config file in the final layer (UI).

Now, what we want to do, is to populate the list of customer, in our service library, with the customers available in the database. Because our service is a singleton, we will do that when the first user will call the service:

  1: public CustomerService() {
  2:     var result = from c in customerRepository.GetAll<Customer>() orderby c.FirstName, c.LastName select c;
  3:     foreach (var customer in result) {
  4:         Customers.Add(
  5:             new CustomerDto() { 
  6:                 Id = customer.CustomerID, 
  7:                 FullName = customer.FirstName + " " + customer.LastName
  8:             }
  9:         );
 10:     }
 11: }

Now, this piece of code is pretty easy and ugly. We should use something like AutoMapper to populate on fly our DTO but I want to show you  exactly what happens behind the scene.

We takes all the available customers from the database and one by one, we fill up the Dto with the resultset.

A niece solution here would be also to use an extension method and do something like “from c in customers select c.ToDto()” that may returns a IList<CustomerDto>. Wink

The two methods will change consequently in this way:

  1: public IList<CustomerDto> GetCustomers() {
  2:     return Customers;
  3: }

And the filtered version will change in this way:

  1: public IList<CustomerDto> GetFilteredCustomers(string searchCriteria) {
  2:  return Customers.FindAll(
  3:   delegate(CustomerDto c) { 
  4:    return c.FullName.ToLower()
  5:     .Contains(searchCriteria.ToLower()); 
  6:   }
  7:  );
  8: }

We just said to the List “Hey, looks inside the items and whether the items lower case contains this word, keep it”. Using this approach will allow us to keep clean the in memory list of customers and retrieve only the customers that match the criteria.

Test the environment.

Now if we press F5 our project will compile but when we will try to call the GetCustomers, we will receive this error:

imageVisual Studio is pretty nasty in this, because whatever you will say in the app.config, it will use a different app.config “on fly” when you test your service. So in the service windows, click on the app.config under the customer service and change it in this way:

imageBy default WCF doesn’t allow to carry out more than  few bytes on our messages, but because we are retrieving a list of 800 entities … we should increase this parameter.

Remember that everything has a cost in resources and it is not a good practice to send and receive a lot of megabytes of message content.
Consider using pagination and other tricks.

Now we need to expose this service on a web site. Why? Because when we will develop the UI we will add a reference to an host web site service, like and not to a dev address like http://localhost:9080/PrismTutorial… Smile

Create a host web site and install it on IIS 7.

We need to add a new web site application on our solution, but it has to be a WCF Service web site solution, like the picture below:

imageDelete all the content except the service.svc file and the web.config.

First add a new reference to our project ServiceLibrary.

Then add the connection string to the web.config file.

Finally, change the service.svc to customer.svc and change the HTML code in this way:

  1: <%@ 
  2:    ServiceHost Language="C#" 
  3:    Debug="true" 
  4:    Service="PrismTutorial.ServiceLibrary.CustomerService" 
  5: %>

Cool, now let’s modify the web.config of our WCF web site and we are done.

imageI just said to the new endpoint to point to our .dll service library and to expose the contract IServiceContract. The same step we did previously to the service library layer.

If you now press F5 you can see the process running under ASP.NET. Of course we need to install it on IIS in order to have a common address for our future services. Because the web site points to our project, every time we will change the WCF library this will automatically change in the web service. Of course when we will create new contracts we will need to define new endpoint in both layers.

Note: if you have, like me, Windows 7 and you want to follow this step, you need to install and configure IIS 7 and WCF for IIS. You can do that by following this simple and useful post.

Open IIS 7 and install the new application by creating a new application that will point to our project:

image If everything is ok, you will be able to browse the folder of this, click on the .svc file, and select Browse.

You should get this result:



This tutorial shows how to create and host a WCF service using Visual Studio and IIS 7. Starting from the next tutorial I will not show you anymore this part as you can use this article as a reference.

We will create new services and contracts and we will call them asynchronously inside WPF UI.

I use this approach to get the data on my applications as I can manage better the points of failure of my applications and keep the code separated and clean. If something change on the customer service I can simply add a new method and all the previous versions of my software will continue to work. If my WCF service crashes I can change the web app to point to a different .dll and everything will continue to work.

Stay tuned as from the next time we will start to build the UI. We will talk about Prism, regions IoC and more.


Build enterprise application with WPF, WCF, Entity Framework and Prism. Tutorial 05.

Update: source code and documentation are now available on CodePlex at this address:

Starting with WCF.

Today we will see how WCF works and what are the best practices we should use in order to keep our application safe and maintainable.

WCF startup.

I assume that you know already what is WCF and what’s the difference between WCF and the old Web Service technology. If you don’t, this is a nice overview of WCF, and this is a nice overview of the differences from these 2 technologies.

The big difference from using a normal data access layer and a SOA service is in the architecture. We must keep in consideration, always, that we are working with a message service and that all the information are serialized and passed through the network. This point it’s really important because the most common error I saw using WCF is to serialize directly the entities in the domain model …

Let’s keep as an example our Customer entity.


We have a lot of information in this graph and I am pretty sure that we will use those information only when we will look at the details of each customer, so it completely doesn’t make any sense to carry all these information with us for all the time.

Let’s have a break and let’s see what will be the final result of our application using a sketch. (I use Microsoft Expression Blend sketch available for trial here). The style is modified by me to reflect Balsamiq, another Sketch flow design software.


What we will do, when the navigation bar will be open to the Customer section, we will load a list of Customers, but we need only the Id and a FullName that will represent the customer. Then if the user will click on a customer, we will load an additional view with all the details. To accomplish this data transformation we will use a Dto (Data transfer object)

“The Data Transfer Object “DTO”, is a simple serializable object used to transfer data across multiple layers of an application. The fields contained in the DTO are usually primitive types such as strings, boolean, etc. Other DTOs may be contained or aggregated in the DTO.”

directly inside WCF. In this way we will have a light version of our customer entity that will be carried over the network.

Customer Dto.

Let’s create a new WCF project in our solution and add a new class. The class will be a serialized light version of our Customer entity.

  1: using System.Runtime.Serialization;
  3: namespace PrismTutorial.WCF {
  5:     [DataContract]
  6:     public class CustomerDto {
  7:         [DataMember]
  8:         public int Id { get; set; }
  9:         [DataMember]
 10:         public string FullName { get; set; }
 11:     }
 12: }

First of all, the DataContract attribute. This attribute identifies the entity CustomerDto as serializable. Through the attribute DataMember we are saying that both the Id and the FullName properties will be serialized.

In order to use this Dto, we need a service contract that will allows us to do some simple operations with the Dto. The service contract will expose the operations that we will allow to the end user.

Let’s add a new interface on our WCF project that will look in this way:

  1: using System.Collections.Generic;
  2: using System.ServiceModel;
  4: namespace PrismTutorial.WCF {
  6:     [ServiceContract]
  7:     interface ICustomerService {
  9:         [OperationContract]
 10:         void AddCustomer(CustomerDto customer);
 12:         [OperationContract]
 13:         void DeleteCustomer(CustomerDto customer);
 15:         [OperationContract]
 16:         IList<CustomerDto> GetCustomers();
 18:     }
 19: }

The two attributes that we use now are ServiceContract and OperationContract. The first one will identify the Interface as a WCF contract. Using this attribute we are going to say to WCF: “Hey this is the contract that I want to expose, so let’s look inside and see if there is anything useful for you”.

The second attribute is identifying our method as visible to the contract. Of course we can have also some methods that we want to include in the service but that we don’t want to expose to the public.

After that we need to implement in a concrete class our contract and implement the operations. This is just an example so we will have an internal IList of Dto and we will use the operations just to interact with the list exposed by the service.

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Web;
  5: using System.ServiceModel;
  7: namespace PrismTutorial.WCF {
  8:     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  9:     public class CustomerService : ICustomerService {
 11:         IList<CustomerDto> Customers = new List<CustomerDto>();
 13:         #region ICustomerService Members
 15:         public void AddCustomer(CustomerDto customer) {
 16:             Customers.Add(customer);
 17:         }
 19:         public void DeleteCustomer(CustomerDto customer) {
 20:             Customers.Remove(customer);
 21:         }
 23:         public IList<CustomerDto> GetCustomers() {
 24:             return Customers;
 25:         }
 27:         #endregion
 28:     }
 29: }

The only notable thing here is the attribute ServiceBehavior that explains how our service will be created.  In this case we said that the first call will activate the service, so it’s like using a SingleTon pattern. Of course the service behavior attribute has a lot of options.

We can also use this code in order to be sure that our entity will be correctly removed. Change the intenal IList to a List<T> and change the DeleteCustomer method in this way:

  1: public void DeleteCustomer(CustomerDto customer) {
  2:    Customers.Remove(Customers.Find(
  3:       c => c.Id.Equals(customer.Id))
  4:    );
  5: }

Configure the service.

Now that we have our basic service we have to build the solution CTRL+SHIFT+B and then right click on the app.config and select Configure. We will see a window like this one:

imageFirst of all click on service one and point to the compile .dll in order to have the service to Customer Service and not Service1.

Now select the endpoint in the service node and again, change it to point to our .dll and select the ICustomerService.

Now if you press F5 and set the WCF as the startup project, you will be prompt by this windows that is the default test window of Visual Studio 2008 for WCF.

imageBy clicking on a method you will be prompted by a default view that allows us to interact with the service in testing mode.

You can test it by using the addCustomer a couple of times and then the GetCustomers. You will find in the message the customers you previously added.


In this post we saw how WCF works so now we can do our considerations and create the service for each entity or view, it depends on how you want to structure your software. Of course we should do something better like sending a response message each time we do an operation, or get back the changed list of customers each time we do a CRUD operation.

The are also other considerations using WCF and attributes that we didn’t see this time. This will be part of the next tutorial.

Finally, I want to give you some tips using WCF that I have found in the pattern and practices on MSDN web site.

Enjoy this tutorial and stay tuned for the next one!


Build enterprise application with WPF, WCF, Entity Framework and Prism. Tutorial 04.

Service Oriented Application.


The first problems I always encounter when I design a scalable, multi-tier application are:

  • Work on a disconnected environment but be able to work with the data previously downloaded.
  • Keep always the data up to date, notify the users when the data changes.
  • Threading and UI performances, do not provide frozen screen when the user requests the data.
  • Synchronization from the database and the disconnected environment.

Those are common problems of a complex software and can be solved using a SOA service solution and WPF for the UI. Of course WPF and WCF by themselves cannot help us without a strong and well designed solution.

The idea of having a SOA service for the communication will give us the ability to design something like this:


Where we will have 1 or more databases, remotely stored somewhere; a distributed SOA service that will allow our software to operate with the remote data, and maybe to have also some security concerns; the final Client application that will be build using some techniques, in order to use the full power of this kind of solution.

Of course this sketch is fancy and cool but it doesn’t give us anything more than a .PNG file that we can present to the CTO or to the customer! What you have to do in order to transform the sketch in a real solution, it’s complex and hard.

Consideration when working with SOA Services.

The first consideration we have to do, if we decide to leave the DAL on a remote web service, and work with a completely disconnected environment, is the data synchronization and the data concurrency.

Let’s make a very simple self explanatory workflow.


We have the order 10-AED-2020 and is opened remotely by 3 employees in the same time. Everyone makes a change to the row, and then they all try to save the changes. What will happen? … a mess … Wink

Usually, what I do, is to “virtually” lock the record so when someone else try to open the row, the UI notifies that the row is already opened by someone else. Then when the “someone else” save or close the row, we notify the changes to everybody.

The second problem can be called routing messaging approach.
Also for this problem I have drawn a simple workflow. (Sorry guys but I love Visio!) tongue-out


The process is described below:

  1. The Vendor requests for a new order
  2. The software submit the request to the service and wait
  3. The service creates the order
  4. The service gives back to the client the new order created

As you can see we can have two different type of message: a single way message (the request) and a request and response message (create order), that has a delay time.

Of course there are many others considerations but for now this is enough for what we are going to do.

Some interesting articles.

Before writing XML or C# code I wish you will have the time to read those articles that I have found really interesting, especially if you had never step into an n-tier application.

MSDN – Build service oriented app

The Entity Framework In Layered Architectures

Patterns for Flexible WCF services

In the next tutorial we will write the code to exposes our entities through WCF, but of course we will not expose directly them but an “alias”. I will show the differences from using a DTO or something else.

Stay tuned!


Build enterprise application with WPF, WCF, Entity Framework and Prism. Tutorial 03.

Update: source code and documentation are now available on CodePlex at this address:

Value and business validation with Enterprise Library 4.1 and Entity Framework.

In this article I will show you how to validate a domain using the enterprise library 4.1 over the Entity Framework.

First of all I want to talk about the validation and the thousands of implementations you can find over the web. In my opinion there are 2 different types of validation. The value validation and the business validation.

What’s the difference? The first, the value validation should validate an entity against it’s value content. For example, the entity order should have a validation of type NotNull inside it’s Id field, or a LengthValidation inside it’s order number, in order to reflect the corresponding field in the database table. In this way we will execute a value validation in our domain model, before sending the data to the Data Access Layer.

The second validation is the business validation and it can be accomplished with a lot of different ways. The most common is the hard coded way that personally, I don’t really like it. What’s a business validation? Let’s say we have an order entity and we have a rule that says “if the total order is grater than 1,000 $ apply 10% of discount”. This is a business rule that force our entity to change its value after some business considerations.

Available validation framework for NET.

I use for my value validation the Enterprise Library Validation block and I have found it really useful. The only problem is that this framework forces you to use the decorator pattern, so we hard code our entity with the value validation rules. This approach is fine, but only if related to the values. You can also include the value validation in a separate XML file, and this is the solution we will use later.

Another interesting framework is the Validation Framework project on Codeplex, that similar to the EL, uses decorator and generics to validate our entities.

Very powerful but with an high learning curve is the powerful SPRING.NET framework, that inside its application blocks has a space also for the validation. What I really like about SPRING.NET is the fact that you will not hard code anything because the entire validation is in a separate XML file. But remember that the learning curve is pretty complex because SPRING.NET is a full IoC tool, so everything is under the concept of be “Injected”.

Finally, my friend Simone Chiaretta, suggested me this open source framework: Fluent Validation, that has a nice procedural implementation:

  1: using FluentValidation;
  3: public class CustomerValidator: AbstractValidator<Customer> {
  4:   public CustomerValidator() {
  5:     RuleFor(customer => customer.Surname).NotEmpty();
  6:     RuleFor(customer => customer.Forename).NotEmpty().WithMessage("Please specify a first name");
  7:     RuleFor(customer => customer.Company).NotNull();
  8:     RuleFor(customer => customer.Discount).NotEqual(0).When(customer => customer.HasDiscount);
  9:     RuleFor(customer => customer.Address).Length(20, 250);
 10:     RuleFor(customer => customer.Postcode).Must(BeAValidPostcode).WithMessage("Please specify a valid postcode");
 11:   }
 13:   private bool BeAValidPostcode(string postcode) {
 14:     // custom postcode validating logic goes here
 15:   }
 16: }
 18: Customer customer = new Customer();
 19: CustomerValidator validator = new CustomerValidator();
 20: ValidationResult results = validator.Validate(customer);
 22: bool validationSucceeded = results.IsValid;
 23: IList<ValidationFailure> failures = results.Errors;

The only real business validator framework for NET that I know and that I use in production is IBM iLOG for NET a real powerful engine for business validation that keeps separate your domain model from the business rules. It’s cool and probably it needs just 10 articles only in order to describe it, so you can have a look at the official web site. This is a simple screenshot of how it works:


Enterprise Library Validation with Entity Framework.

The first problem we have using this framework is the way we can apply the decorator pattern on it. Why? Because in Visual Studio the EF model is built through a DSL tool called Entity Framework designer. So each time we change the model, our validation decorations are lost through the way …

So let’s add a reference to the enterprise library validation block in our project and let’s try to understand how we can use them in a productive way.


The first approach is to overwrite with the partial attribute our domain entity is a way like this one:

  1: public partial class Customer {
  3:     public bool IsValid { get { return Validate(); } }
  5:     private bool Validate() {
  6:         //validation implementation
  7:         return true;
  8:     }
  9: }

and then validate the entity inside the Validate method. Of course because we cannot use the partial attribute for a property we need to find a different way to grab our validation attributes. From XML?

Good so first of all we need a basic validation class that will validate every single entity using the generics. This solution is the only affordable because the entity generated with EF inherits already from EntityObject class.

  1: public static class EntityValidator<T> {
  3:     public static Dictionary<string,string> ValidationErrors { get; set; }
  5:     public static bool Validate<T>(T entity) {
  6:         ValidationResults results = Validation.ValidateFromConfiguration<T>(entity);
  7:         if (results.IsValid) {
  8:             return true;
  9:         } else {
 10:             foreach (var error in results) {
 11:                 ValidationErrors.Add(error.Key, error.Message);
 12:             }
 13:             return false;
 14:         }
 15:     }
 17: }

Now we can do the validation in this way from the repository, for example:

  1: public int Add<T>(T entity) {
  2:     ADVConnection context = GetObjectContext();
  3:     if (EntityValidator<T>.Validate(entity)) {
  4:         context.AddObject(typeof(T).Name, entity);
  5:         int result = context.SaveChanges();
  6:         ReleaseObjectContextIfNotReused();
  7:         return result;
  8:     }
  9:     return -1;
 10: }

An then we can handle that return –1 in a way that we prefer, maybe we can catch it in the “presenter” and interact with the UI. We just need to keep alive the validation errors generated by the method Validate<T>.

Entity Framework mapping file.

The Entity Framework works similar to NHibernate, so for each business object we have a mapping file. If you open the .edmx file with a right click->open with-> XML editor, you will get an XML representation of your model, similar to this file:

  1: <EntityType Name="Customer">
  2:   <Key>
  3:     <PropertyRef Name="CustomerID" />
  4:   </Key>
  5:   <Property Name="CustomerID" Type="int" Nullable="false" StoreGeneratedPattern="Identity" />
  6:   <Property Name="NameStyle" Type="bit" Nullable="false" />
  7:   <Property Name="Title" Type="nvarchar" MaxLength="8" />
  8:   <Property Name="FirstName" Type="nvarchar" Nullable="false" MaxLength="50" />
  9:   <Property Name="MiddleName" Type="nvarchar" MaxLength="50" />
 10:   <Property Name="LastName" Type="nvarchar" Nullable="false" MaxLength="50" />

As you can see, we have already all the rules in place, so we do not need to declare anything. For example, the EF already knows that the Title field should be at most, 8 characters long and can be null. Unfortunately, with the version 3 of EF those rules cannot be connected to the Enterprise Library, easily.

How we can handle this in our static validator using generics?

Close you Visual Studio solution, and navigate to your Enterprise Library installation folder.

Open the .exe called EntLibConfig.exe. The first screenshot you will se is something like this:


Click on the file menu and open the app.config file in the layer PrismTutorial.DataLayer.App.Config  and you will load the configuration file inside this tool.

Now, click on the root of your application and select new validation application block. The result should something like this:


Now we can create a Rule, or a Rule Set and then we can load our domain model and associate those rules with every entity.

In order to load the domain model, choose new Type, in the type window, select the PrismTutorial.DataLayer.DomainModel.dll using this button:


At this point you can use the search filter of this window to load one entity per time. I started with the Customer entity. The final result is this one:


Finally, right click on the customer and select new rule set and give it a name. In this rule set we will contain all the rules associated with this entity.

Now, on the ruleset node, choose select members and here it’s the magic!!


Finally, you will have now the node Customer showing for every loaded field, an additional node. From here you can select any field and add a new validator. You can include the message template, the type of validation and so on …

This is my final result:


If you open Visual Studio, you will find the app.config file changed. Of course you cannot change the app.config file when the solution is open because in my case, I work under source control and the app.config is locked.

  1:   <configSections>
  2:     <section name="validation" type="Microsoft.Practices.EnterpriseLibrary.Validation.Configuration.ValidationSettings, Microsoft.Practices.EnterpriseLibrary.Validation, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  3:     <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
  4:   </configSections>

And the Customer validation rules.

  1:     <type defaultRuleset="CustomerValidation" assemblyName="PrismTutorial.DataLayer, Version=, Culture=neutral, PublicKeyToken=d5210384f83ebb19"
  2:       name="PrismTutorial.DataLayer.Customer">
  3:       <ruleset name="CustomerValidation">
  4:         <properties>
  5:           <property name="CustomerID" />
  6:           <property name="NameStyle" />
  7:           <property name="Title" />
  8:           <property name="FirstName" />
  9:           <property name="MiddleName" />
 10:           <property name="LastName" />
 11:           <property name="Suffix" />
 12:           <property name="CompanyName">
 13:             <validator negated="false" messageTemplate="Company name cannot be null."
 14:               messageTemplateResourceName="" messageTemplateResourceType=""
 15:               tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.NotNullValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
 16:               name="Not Null Validator" />
 17:             <validator lowerBound="0" lowerBoundType="Ignore" upperBound="100"
 18:               upperBoundType="Inclusive" negated="false" messageTemplate="Company Name cannot be long more than 100 characters."
 19:               messageTemplateResourceName="" messageTemplateResourceType=""
 20:               tag="" type="Microsoft.Practices.EnterpriseLibrary.Validation.Validators.StringLengthValidator, Microsoft.Practices.EnterpriseLibrary.Validation, Version=, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
 21:               name="String Length Validator" />

Finally I just want to remember you that you can integrate this editor inside Visual Studio 2008 SP1.

Note: With Visual Studio 2010 and the Entity Framework 4.0, this problem is going to be deprecated because the EF 4 allows us to build POCO object like in NHibernate, so we can then use the decorator pattern or any other type of validation pattern.