Category: WCF

Castle WCF Facility

In the previous post we saw how to provide Inversion of Control capabilities to a WCF service. That’s pretty cool but unfortunately it requires a big refactoring if you plan to apply the Dependency Inversion pattern on an existing WCF project.

Today we will see an interesting alternative provided by Castle project. If you are not aware of Castle, you can have a look at the community web site here. Castle provides a set of tools for NET, Active Record, Dynamic Proxy, Windsor and a set of facilities that you can easily plug into your code.

The demo project

Before starting to have  a look at Castle Wcf Facility we need a new WCF project and a WCF web site to host our service. The idea is to create an empty service and host it, then we will refactor the project to include Castle Windsor and WCF facility.

Let’s start by creating an IIS web site, a DNS redirect and a folder for our IIS web site. The final result will be like the following one:

image

Now we need to create the new project in Visual Studio. I have created a solution that contains 2 projects:

  • Empty WCF Service Library named “Service.Contracts
  • Empty WCF Service Library named “Service.Implementations
    • reference the project “Service.Contracts

And this would be the final result of this step:

image

We have just implemented the correct way of creating a WCF service implementation and a WCF service contract. The Client will have a reference to the contract assembly in order to be able to work with the service implementation, without the need of using a Proxy. This concept is outside the fact that I will use an ioc container, it’s just a lot easier than adding a “web service reference” in visual studio and carry tons of useless proxy classes in your project.

Hosting WCF service

The final step is to host this WCF Service inside an IIS ASP.NET or ASP.NET MVC website. I have create a new “web site application” and from the options I choose “WCF service application”. Then I select my local IIS for the development path, but this is up to you.

image

Now Visual Studio will ask you if you want to override the current web site or use the existing content. If you choose the second option you will have to provide also web.config configuration and initial setup, so I kindly suggest the first option.

If everything went ok you should be able to visit the default service created by Visual Studio at this url: http://staging.service.local/Service.svc.

Now we need to change the content and the name of the .svc file, but before we need to add a reference for Contracts and Implementations from the solution explorer!

[sourcecode language='php' ]
<%@ ServiceHost 
    Language="C#" Debug="true" 
    Service="Service.Implementations.ServiceImplementation" %>
[/sourcecode]

We need to reference the Implementation because we don’t have a factory yet able to translate the IServiceContract into a ServiceImplementation class. So the next step is to install in our solution the WCF castle facility nuget package.

image

Add WCF facility

So far we didn’t need any external tool because we have an empty service created by default by Visual Studio with a dummy code, or probably during the tutorial you have already changed your service to so something more interesting. The next step is to add a facility in order to be able to change the default factory used by IIS to create an instance of our service.

The first step is to add a new global.asax file if you don’t have one already and plug the Windsor container inside the Application_Start event.
This is my global.asax file:

[sourcecode language='php' ]
<%@ Application Language="C#" Inherits="ServiceApplication" %>
[/sourcecode]

Now, in the code behind file we want to create an instance of a new Windsor Container during the Application_Start event:

[sourcecode language='csharp' ]
public class ServiceApplication : HttpApplication
{
    public static WindsorContainer Container { get; set; }

    protected void Application_Start()
    {
        BuildContainer();
    }
}
[/sourcecode]

And this is the code to initialize a new container. In this code we need to pay attention in the way we specify the server name, because WCF facility uses the service attribute value to search inside the Windsor container. So, this is the code to register the service:

[sourcecode language='csharp' ]
private void BuildContainer()
{
    Container = new WindsorContainer();
    Container.Kernel.AddFacility<WcfFacility>();
    Container.Kernel.Register(Component.For<IServiceContract>()
                                        .ImplementedBy<ServiceImplementation>()
                                        .Named("ServiceContract"));
}
[/sourcecode]

And this is the change we need to apply to the Service.svc file:

[sourcecode language='php' ]
<%@ ServiceHost 
    Language="C#" Debug="true" 
    Service="ServiceContract"
    Factory="Castle.Facilities.WcfIntegration.DefaultServiceHostFactory, Castle.Facilities.WcfIntegration" %>
[/sourcecode]

Now your service is ready to use dependency injection under the power of Castle Windsor.

Add a dependency to a WCF service using Windsor

Simple example, I have a service that requires an ILogger injected in it. I need to change the code for my service to allow injection and then I need to register the logger in the global.asax file during the Windsor container activation process.

[sourcecode language='csharp' ]
public class ServiceImplementation : IServiceContract
{
    private readonly ILogger logger;

    public ServiceImplementation(ILogger logger)
    {
        this.logger = logger;
    }

    public string GetData(int value)
    {
        this.logger.Trace("Method started!");
        return string.Format("You entered: {0}", value);
    }
}
[/sourcecode]

And this how we change the registration in the container:

[sourcecode language='csharp' ]
Container.Kernel.Register(
    // register the logger
    Component.For<ILogger>()
        .ImplementedBy<TraceLogger>(),
    // register the service
    Component.For<IServiceContract>()
        .ImplementedBy<ServiceImplementation>()
        .Named("ServiceContract"));
[/sourcecode]

The source code is available here:

http://sdrv.ms/16BLYoI

WCF and dependency inversion using Castle Windsor

When you start to work with TDD and other Agile practices the first thing you try to apply almost everywhere in your code is the Dependency Inversion pattern because you want to invert the logic of your dependencies to make your code more testable and maintainable.

In order to accomplish this result I am using Castle Windsor, while before 2013 I was working with Microsoft Unity. I am not going to jump into the conversation “Which Inversion of Control container is better?” because it really depends on what you need to do. For years I was more than satisfied with Unity but recently I started to create complex bootstrappers for my applications and I found Windsor more flexible, that’s it! Nerd smile

How does WCF create a service instance?

First of all, in order to apply dependency inversion inside WCF we need to understand how WCF works and how it creates new service instance. I found this article on MSDN very helpful during my researches: Extending WCF.

So, this is the final result I want to obtain:

image

When you create a new service in WCF, you can specify the factory that will be in charge of creating the service instance.

This is the code you should use to specify the factory:

   1: <%@ ServiceHost Language="C#"

   2:     Factory="Raf.DependencyInjectionHostFactory"

   3:     Service="Raf.MyService" %>

Now, the factory should start a new instance of our service, or better, should use the ioc container to resolve an instance of that service.

Second step is to create a custom host that will add a new behaviour to our service, the behaviour will call the service locator (I know it’s an anti-pattern …) to inject the dependencies. In my case, Castle Windsor.

Factory

   1: public class DependencyInjectionHostFactory : ServiceHostFactory

   2: {

   3:     protected override ServiceHost CreateServiceHost(Type serviceType, Uri[] baseAddresses)

   4:     {

   5:         // method called when we hit a request to http:// ... youservice.svc

   6:         return new DependencyInjectionHost(serviceType, baseAddresses);

   7:     }

   8: }

Host

   1: public class DependencyInjectionHost : ServiceHost

   2: {

   3:     // omit

   4:     // ...

   5:     protected override void OnOpening()

   6:     {

   7:         // attach the behavior

   8:         Description.Behaviors.Add(new DependencyInjectionServiceBehavior());

   9:         base.OnOpening();

  10:     }

  11: }

Service behavior

   1: public class DependencyInjectionServiceBehavior : IServiceBehavior

   2: {

   3:     #region IServiceBehavior Members

   4:

   5:     public void Validate(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

   6:     {

   7:     }

   8:

   9:     public void AddBindingParameters(

  10:         ServiceDescription serviceDescription,

  11:         ServiceHostBase serviceHostBase,

  12:         Collection<ServiceEndpoint> endpoints,

  13:         BindingParameterCollection bindingParameters)

  14:     {

  15:     }

  16:

  17:

  18:     public void ApplyDispatchBehavior(ServiceDescription serviceDescription, ServiceHostBase serviceHostBase)

  19:     {

  20:         foreach (ChannelDispatcherBase cdb in serviceHostBase.ChannelDispatchers)

  21:         {

  22:             var cd = cdb as ChannelDispatcher;

  23:             if (cd != null)

  24:             {

  25:                 foreach (EndpointDispatcher ed in cd.Endpoints)

  26:                 {

  27:                     ed.DispatchRuntime.InstanceProvider =

  28:                         new DependencyInjectionInstanceProvider(serviceDescription.ServiceType);

  29:                 }

  30:             }

  31:         }

  32:     }

  33:

  34:     #endregion

  35: }

So, the instance provider is able to retrieve a registration for our service using the service locator:

   1: public class DependencyInjectionInstanceProvider : IInstanceProvider

   2: {

   3:     private readonly Type serviceType;

   4:

   5:     public DependencyInjectionInstanceProvider(Type serviceType)

   6:     {

   7:         this.serviceType = serviceType;

   8:     }

   9:

  10:     public object GetInstance(InstanceContext instanceContext, Message message)

  11:     {

  12:         IServiceLocator serviceLocator = ServiceLocator.Current;

  13:

  14:         return serviceLocator.GetInstance(serviceType);

  15:     }

  16:

  17:     public void ReleaseInstance(InstanceContext instanceContext, object instance)

  18:     {

  19:         // if you container allows you to destroy instance

  20:         // you can destroy your service instance here

  21:     }

  22:

  23:     #endregion

  24: }

That’s it. Of course my container needs to know what is my service registration, and with Windsor I have two options:

   1: // option one, register the interface

   2: Component

   3:     .For<IWriteService>()

   4:     .ImplementedBy<WriteService>()

   5:

   6: // option two register the class

   7: Component

   8:     .For<WriteService>()

   9:     .ImplementedBy<WriteService>()

And of course you need to change the markup of your .svc file depending on how you want to resolve the service, with the interface or with the  class type.

Dependency Injection

Now, let’s assume that my service needs an IUnitOfWork contract, how should we do that?

First of all we need to register both types in our container, and with Windsor one of the possible options is this one:

   1: Component.For<IUnitOfWork>()

   2:             .ImplementedBy<UnitOfWork>(),

   3: Component

   4:     .For<ICommandService>()

   5:     .ImplementedBy<CommandService>(),

And my command service is constructed in this way:

   1: public class CommandService : ICommandService

   2: {

   3:     private readonly IUnitOfWork unitOfWork;

   4:

   5:     public CommandService(IUnitOfWork unitOfWork)

   6:     {

   7:         this.unitOfWork = unitOfWork;

   8:     }

   9: }

Note for purist of CQRS: I know that a command service should get a command dispatcher injected but for this blog post I guess it would not make things clear enough, so a unit of work or an IRepository would make more sense.

TDD a WCF service, is it possible?

Right now I am working on a CQRS project, and I am using WCF as my web service technology. In this project I decided to challenge myself and make a full TDD project. The first big problem I found was to simulate a real web server, because I didn’t want to hit a production or QA environment to run my tests.
Second I didn’t want to write any integration test at all, so I had to figure out how to create an in-Process test to run my WCF methods.

Why in-process test? When you write a unit test, you should test a single functionality, and in order to make the test atomic, it should run in-process. It should not involve third party tiers like a database or IIS, otherwise the test won’t be in-process anymore, so it will became an Integration test.

The first idea I came out was to fake the behaviour of IIS, and in order to accomplish this I could easily work with a mock framework like Typemock and mock out the entire IIS infrastructure.

Is this what I really want? Not at all. I don’t want and I don’t need to fake the behaviour of IIS, I need an instance of it because my WCF services are using custom factories and custom behaviours and I need to be sure they are acting in the right way.

So I have created two different type of tests. The first one is pure Unit Test, where I verify the command behaviours:

   1: [TestMethod]

   2: public void AddUsersCommandHandler_ValidCommand_WillPersist()

   3: {

   4:     // arrange

   5:     AddUsersCommand expectedCommand = new AddUsersCommand { UsersStream = expectedStream };

   6:     // service with mocked unit of work

   7:     IServiceCommandHandler<AddUsersCommand> handler = new AddUsersCommandHandler(mockUnit.Object);

   8:  

   9:     // act

  10:     handler.Handle(expectedCommand);

  11:  

  12:     // assertions against the command behaviour

  13:     mockUnit

  14:         .Verify(x => x.BeginTransaction(), Times.Once());

  15:     mockUnit

  16:         .Verify(x => x.Save(It.IsAny<User>()));

  17:     mockUnit

  18:         .Verify(x => x.CommitTransaction(), Times.Once());

  19: }

The second one is the (in)famous integration test, where you call the WCF service and test the overall process. Unfortunately for the second step I couldn’t find anything really TDD so I had to figure out by myself a different solution.

IIS Express

Yesterday I spent some time googling around for a solution while I found a nice post from Scott Gu about IIS express. With IIS express we have an in-process IIS server that we can startup or shutdown at any time during the lifecycle of our tests. It provides almost all the functionalities provided by IIS and it also trigger the Application_Start event, something not very well handled by Cassini …

So, first of all I had to figure out how to bootstrap my unit tests to run over a different IIS than the one configured in the web.config.

Piece of cake, first of all I need something that allows me to bootstrap IIS express before my unit test harness starts:

   1: [ClassInitialize]

   2: public static void ClassInitialize(TestContext context)

   3: {

   4:     // create a process for IIS express

   5:     issProcess = new Thread(IssUtility.StartIisExpress) 

   6:                  { 

   7:                     IsBackground = true 

   8:                  };

   9:     // start it

  10:     issProcess.Start();

  11:     // create a new channel factory using the generated URL

  12:     factory = new ChannelFactory<IDomainWriteService>(

  13:        new BasicHttpBinding(), 

  14:        new EndpointAddress("http://localhost:5555/services/DomainWriteService.svc"));

  15: }

Then I need another utility to kill everything when my test harness is done:

   1: [ClassCleanup]

   2: public static void ClassCleanup()

   3: {

   4:     // close the WCF factory

   5:     factory.Close();

   6:     // shutdown IIS express

   7:     IssUtility.TearDownIis();

   8:     issProcess.Abort();

   9: }

At this point I can write any test in the following format:

   1: [TestMethod]

   2: public void ChannelFactory_ReceiveValidCommand_WillExecute()

   3: {

   4:     var expectedCommand = BuildAddUsersCommand();

   5:     service.AddUsers(expectedCommand);

   6: }

I found this technique very useful because we work with TFS on Azure so my Build environment cannot be polluted at all with any third party components or by installing the WCF service under test in the build machine.

In the same way I found very quick to bootstrap IIS express for my tests, honestly they are faster than running on my local IIS 8.

IIS Express utility class

Below is the code I use to initialize IIS express, feel free to use it in your tests and let me know if you come up with a better solution than this one.

   1: namespace xxx

   2: {

   3:     using System.Diagnostics;

   4:  

   5:     public class IssUtility

   6:     {

   7:         private static Process iisProcess;

   8:         

   9:         // Start IIS on port 5555

  10:         public static void StartIisExpress()

  11:         {

  12:             var startInfo = new ProcessStartInfo

  13:                 {

  14:                     WindowStyle = ProcessWindowStyle.Normal,

  15:                     ErrorDialog = true,

  16:                     LoadUserProfile = true,

  17:                     CreateNoWindow = false,

  18:                     UseShellExecute = false,

  19:                     Arguments =

  20:                         string.Format("/path:\"{0}\" /port:{1}",

  21:                                         @"your WCF dev path", 5555)

  22:                 };

  23:  

  24:             var programfiles = string.IsNullOrEmpty(startInfo.EnvironmentVariables["programfiles"])

  25:                                     ? startInfo.EnvironmentVariables["programfiles(x86)"]

  26:                                     : startInfo.EnvironmentVariables["programfiles"];

  27:  

  28:             startInfo.FileName = programfiles + "\\IIS Express\\iisexpress.exe";

  29:  

  30:             try

  31:             {

  32:                 iisProcess = new Process {StartInfo = startInfo};

  33:  

  34:                 iisProcess.Start();

  35:                 iisProcess.WaitForExit();

  36:             }

  37:             catch

  38:             {

  39:                 iisProcess.CloseMainWindow();

  40:                 iisProcess.Dispose();

  41:             }

  42:         }

  43:  

  44:         // kill everything

  45:         public static void TearDownIis()

  46:         {

  47:             iisProcess.CloseMainWindow();

  48:             iisProcess.Dispose();

  49:         }

  50:     }

  51: }

Enjoy!

Build enterprise applications with WPF, WCF, EF and Prism. Tutorial 09.

Today we will see the modularity concept of Prism. Probably the best part of it, as it will allow us to build a real plug-and-play application where the main Shell won’t know anything about the modules.

Discover and load the module.

What does it mean? As we saw in the previous article, we have declared a reference in our Shell for the hello world module. In this way we force the Shell to be compiled including in the shell project a reference to the Hello World module. Fine, but what happen if we want to replace this module with a new version? We need to change the reference in the project and recompile it … Pretty ugly for a modular application doesn’t it?

The basic concept in Prism is that we can discover on fly the available modules and load them … This is the workflow process of discovering and loading a module in Prism.

 prism module

There are different ways to load a module. As we saw in the previous article, the easiest way is to add a direct reference to the module in the Shell and load it in the bootstrapper:

  1: ModuleCatalog catalog = new ModuleCatalog()
  2:    .AddModule(typeof(HelloWorldModule.HelloWorldModule));

The second way is to add the module reference in the app.config and REMOVE the code in the bootstrapper. In this way we won’t need to recompile the module each time we will run the application in Visual Studio and we won’t need a direct reference to it. Let’s see the code below. I have a added an app.config file in my shell project:

  1: <?xml version="1.0" encoding="utf-8" ?>
  2: <configuration>
  3:   <configSections>
  4:     <section name="modules"
  5:              type="Microsoft.Practices.Composite.Modularity.ModulesConfigurationSection, Microsoft.Practices.Composite"/>
  6:   </configSections>
  7:   <modules>
  8:     <module 
  9:       assemblyFile="Modules/HelloWorldModule.dll" 
 10:       moduleType="HelloWorldModule.HelloWorldModule, HelloWorldModule" 
 11:       moduleName="HelloWorldModule"/>
 12:   </modules>
 13: </configuration>

I am using the composite section in the app.config file to load a specific module. Now, in order to make this ‘runnable’ we need to:

  • remove the reference in the Shell project
  • clean-up the code in the bootstrapper that loads the module

The shell project will use this code now to load the Module catalog:

  1: ModuleCatalog catalog = new ConfigurationModuleCatalog();

As you can see we are telling to Prism to look in the app.config and load the modules available there. In order to make the module available in the modules folder inside the bin folder of the shell you can play with MSBuild or a post-event action in VS. I copied this code from MSDN and added to the post event build action in the HelloWorldModule project properties:

  1: xcopy "$(TargetDir)*.*" 
  2: "$(SolutionDir)Shell\bin\$(ConfigurationName)\Modules\" /Y

Pretty cool! We can now work with our modules without breaking any change in the Shell project, and trust me, when you work on a team, this happens every day …

Additional configuration options.

Of course the game is not done yet. We have a lot of options that we can configure in the app config in order to load modules on fly and to add dependencies from other modules. For example, let’s say that Outlook can’t open a view if the ribbon is not loaded, but the ribbon is on another module … Wink

Load on demand

We can specify, for example, that we want to load on demand (by request) a specific module that we don’t know. Pretty cool as this is how should work a real modular application. In order to do this we don’t need anything more that this tag in the app.config:

  1: <module 
  2:    assemblyFile="Modules/HelloWorld.dll" 
  3:    moduleType="HelloWorld, HelloWorld" 
  4:    moduleName="HelloWorld" 
  5:    InitializeMode="OnDemand"/>

Now that we setup the module to load “onDemand” the module won’t be load in memory until we will instruct Prism to do that. This is a real plug and play concept, because without any dependencies we can load on demand part of our UI during the program execution. In Windows Form this can’t simply be done!

  1: moduleManager.LoadModule("HelloWorld");

There you go, in a simple call from any view we can ask for a specific module. The initialize method of the module will be call and our UI will receive the ‘default’ view of that module, injected in the shell or in another module … there are no limitations at all.

Now we are ready to build the first cool module of our app, the main Ribbon bar.

Tags:

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

Update: source code and documentation are now available on CodePlex at this address: http://prismtutorial.codeplex.com/

Today we will build the skeleton of our application using the latest version of Prism, available in this section of MSDN: Prism February 2009. One of the reasons that I didn’t write anything concrete until now is the fact that I knew that the new version of Prism was coming this month. Smile

The classic Hello World application.

As for every tutorial, is always better to start with the classic Hello World in order to understand, step by step, how Prism structures the various part of the UI.

Let’s open our VS Solution (remember that if you download the solution from my CodePlex repository the solution will contains already the entire code of each article) and let’s add a new project of type WPF application. I called Prism.Shell because this one will be our shell that will contain the bootstrapper.

Note about references.

In order to add the assemblies that I will mention in this and in the next tutorials you must download the latest version of Prism V2 and build the solutions so you will have all the assemblies you need. This is the structure of my Prism Framework:

image_thumb6

For practice I have already compiled all the required assemblies and added them to a solution folder in VS. This is what I have and what I reference in my projects:

image_thumb14

Finally, remember also that you can open each Prism component and re-compile it, add new future and suggest new capabilities to the Microsoft team. They will appreciate for sure! Smile

So … coming back to our project this is what we need in our Shell:

References:

  1. Microsoft.Composite
    This is the core of the composite framework
  2. Microsoft.Composite.Presentation
    This assembly contains the components that target Prism for WPF
  3. Microsoft.Composite.UnityExtension
    It’s a utility assembly for unity IoC container

The Shell XAML container.

Let’s add a new Windows Component from WPF template and the name will be Shell.xaml. Below the code I have added to the window in order to show 3 different regions.

1: <Window x:Class=“Shell.Shell”

2: xmlns=“http://schemas.microsoft.com/winfx/2006/xaml/presentation”

3: xmlns:x=“http://schemas.microsoft.com/winfx/2006/xaml”

4: Title=“Hello World with Regions” Height=“500” Width=“500”>

5: <DockPanel>

6: <ItemsControl x:Name=“HeaderRegion” DockPanel.Dock=“Top” Height=“50”>

7:

8: </ItemsControl>

9: <ItemsControl x:Name=“LeftRegion” Width=“100” DockPanel.Dock=“Left”>

10:

11: </ItemsControl>

12: <ItemsControl x:Name=“MainRegion” DockPanel.Dock=“Bottom”>

13:

14: </ItemsControl>

15: </DockPanel>

16: </Window>

We have added 3 ItemsControl inside a DockPanel in order to design a simple Outlook style layout with an header, a main container and a left navigation menu.

Now we need to extend this control using the attached properties in order to use the Prism region adapters. This is the code we must include in the xaml declaration:

1: xmlns:cal=”http://www.codeplex.com/CompositeWPF”

Now we are ready to change our xaml code in this way:

1: <ItemsControl

2: x:Name=“HeaderRegion”

3: cal:RegionManager.RegionName=“HeaderRegion”

4: …

5: <ItemsControl

6: x:Name=“LeftRegion”

7: cal:RegionManager.RegionName=“LeftRegion”

8: …

9: <ItemsControl

10: x:Name=“MainRegion”

11: cal:RegionManager.RegionName=“MainRegion”

12: …

We said to Prism: “Hey when you load the Shell assign to each ItemsControl the corresponding Region using the attached property regionManager.RegionName”.

The bootstrapper.

The bootstrapper is nothing more than the entry point of our application. He is in charge to resolve and charge the modules and assign them to the corresponding view for the initial setup. So we need to create a new class in our Shell project and call it Bootstrapper.cs. This is the code we need for our initial setup:

1: protected override IModuleCatalog GetModuleCatalog() {

2: ModuleCatalog catalog = new ModuleCatalog();

3: return catalog;

4: }

This method should return an instance of the modules catalog used inside the application. What is the module catalog? The catalog contains all the modules we will use in our application. As we don’t have any module right now, this method returns an empty catalog. We will see in the future that we can load modules in the catalog also during the application execution.

1: protected override DependencyObject CreateShell() {

2: Shell shell = new Shell();

3: shell.Show();

4: return shell;

5: }

The create shell method, is only creating a new instance of the main window, called Shell and showing it to the user. Let’s say that this is the first entry point.

Now we need to modify the app.xaml in order to startup our application using the Boostrapper. First of all remove this row from the xaml code:

1: StartupUri=”Window1.xaml“>

We don’t want anymore that the application will start using this window but we want to use the boostrapper.

Now we need to modify the app.xaml.cs in this way:

1: protected override void OnStartup(StartupEventArgs e) {

2: base.OnStartup(e);

3: Bootstrapper bootstrapper = new Bootstrapper();

4: bootstrapper.Run();

5: }

As you can see, starting from now our application will request to the bootstrapper to load the first window and we won’t have any more dependency to the related main window.

You should be able to press F5 and run this part of the tutorial without any problem.

Add custom content to the regions.

Until now we wrote the code to startup our prism application but we still need to create at least 3 views, in order to load some content to the corresponding regions.

We need for this a new “module” that in VS is nothing more than a Class Library Project. We need the following references in order to be able to use WPF and the composite framework in our assembly:

image_thumb22

The first thing that every module will have is a “module class” that will implement the IModule contract from the composite framework. It’s pretty easy because this contract exposes only 1 method “void Initialize()”. The basic structure of the module class is something like this:

1: public sealed class HelloWorldModule : IModule {

2:

3: private readonly IRegionManager regionManager;

4:

5: public void Initialize() {

6:

7: }

8:

9: public HelloWorldModule(IRegionManager regionManager) {

10: this.regionManager = regionManager;

11: }

12: }

13:

So we have declared a private IRegionManager that will represent the main region manager instantiated by the bootstrapper. As soon as the bootstrapper will load it will inject the region manager inside our module. Than we have created a constructor with dependency injection, this mean that as soon as the module will be declared it will receive a specific RegionManager class. Finally we have implemented the IRegionManager Initialize() method that will be used to register the views to the corresponding regions.

Now let’s go back to the shell application. We need now to add a “project reference” to the new module we have created. After that we need to add this line of code inside the Bootstrapper class:

1: protected override IModuleCatalog GetModuleCatalog() {

2: ModuleCatalog catalog = new ModuleCatalog()

3: .AddModule(typeof(HelloWorldModule.HelloWorldModule));

4: return catalog;

5: }

We said to the boostrapper that as soon as it will load it will need to add to the module catalog a new module, our HelloWorldModule class. If we try to run the app now it will run successfully but nothing will change in the UI because we still need to create the views.

What I want to show is the power of loading different views in different regions, so for this reason I am rendering a special textblock with some fancy shadows. This is the code and the final result:

image_thumb31

1: <Border

2: Margin=“20”

3: Padding=“10”

4: BorderThickness=“3”

5: CornerRadius=“15”

6: Background=“White”

7: BorderBrush=“SteelBlue”>

8: <Border.Effect>

9: <DropShadowEffect Color=“Gray”/>

10: </Border.Effect>

11: </Border>

12: <Border

13: Margin=“20”

14: Padding=“10”

15: BorderThickness=“3”

16: CornerRadius=“15”>

17: <TextBlock

18: Text=“A custom header.”

19: FontSize=“24”

20: TextWrapping=“Wrap”

21: Foreground=“DarkSlateBlue”

22: HorizontalAlignment=“Center”

23: VerticalAlignment=“Center”/>

24: </Border>

Now, we need to add to our module 3 views using this effect in order to have this final result in our project:

image_thumb40

Now, in the module class we need to tell to Prism where each view should be loaded in the shell region manager. The ‘declarative way’ do to that it’s pretty simple:

1: public void Initialize() {

2: regionManager

3: .RegisterViewWithRegion(“HeaderRegion“, typeof(Views.HeaderView));

4: regionManager

5: .RegisterViewWithRegion(“LeftRegion“, typeof(Views.LeftView));

6: regionManager

7: .RegisterViewWithRegion(“MainRegion“, typeof(Views.MainView));

8: }

So for each view I assign the view to a corresponding region. The region name is the one we used in the attached property of the ItemsControl in the shell view.

Now if you press F5 this will be your final result:

image_thumb43

Conclusions.

This is the ‘primordial’ way to use Prism and to load 3 different views in 3 different regions. The next time we will see how many way Prism offers to load a module and the corresponding view, dynamically.

Tags: WPF Prism Composite application

Build enterprise application with WPF, Prism and WCF. Tutorial 07.

Update: source code and documentation are now available on CodePlex at this address: http://prismtutorial.codeplex.com/

Design of a Rich Interface using WPF.

WPF is a very powerful language and allows you to do everything you want. The only problem is that Microsoft didn’t release yet a rich toolkit with all the controls we need and the XAML is not easy to learn.

Before starting to build a UI, usually, I follow these 3 fundamental steps.

1. Main layout of my application (MDI, Tab, Ribbon …)

2. Style of my application (Custom, Office style, Vista style)

3. Resources available for free (Icons, themes, controls)

After I have everything in my hands I can start to design the UI and match all the pieces of the puzzle. For example I can build the main environment (shell) and then create the single components (search control, navigation bar and so on).

Sketch the UI with Microsoft Blend.

At this address, you can find an evaluation version of Microsoft Blend, a nice product for WPF designer that fully integrates with Visual Studio 2008/2010. Inside this amazing product, there a tool called Sketchflow designer. You saw this tool in action in my previous post or at the MIX09.

Why we should use a sketchflow designer instead of designing directly the UI? Because when you build an enterprise application that will be used by  hundreds of users, it’s fundamental to reflect the UI to what the users want. If they already know the Office 2007 UI and the ribbon concept, it won’t be difficult for them to move inside your new WPF application. If they work with a MDI application, you will need to think about it and redesign your idea of RIA. Remember that the user is the person that will use, buy, advertise you product. It’s the most important part of your software development process. So try to satisfy it before your ego … Wink

Anyway, I will leave you the pleasure of discovering the Sketchflow world. Here I just want to show you how our application will be designed and why.
First of all the application will be divided in 3 main regions: the ribbon, the navigation and the content region. Like outlook 2007.

The layout will be something like this one:

 New Picture (15)

As you can see, we will have 3 principal regions, plus a couple of additional components, like a status bar and a search context bar.

 New Picture (15)

Get the controls you need for free.

Before buying thousands of dollars of UI controls, I usually step into Codeplex or Codeproject and I search what I am looking for. If I don’t find anything, well I start to consider to use a different approach … Smile
You will wondering why I don’t use something cool like Telerick, for example. What I don’t like about the third party controls, especially when you pay them, is the fact that you don’t give you access to the source code, and you have to pay thousands of dollars for a datagrid. Also XAML is so powerful that after you will handle it, you won’t need any third party control. Trust me!

Anyway, this is the list of controls that we will need for our application:

1. A Ribbon

2. An Outlook style navigation bar

3. A tabbed “MDI” container.

About the ribbon, finally Microsoft has released a full license to use and work with the Microsoft Office 2007 Ribbon using XAML. In order to use it you must sign and agree to the license at this address: Codeplex Office 2007 WPF Ribbon project.

About the Outlook navigation bar there are 2 good choices for free. The first one is the article on CodeProject that explains you, in a step by step tutorial, how to build an outlook 2007 navigation bar starting with a tabbed control. Very cool.

If you are lazy, there is also this set of free controls, that I use, available on CodePlex. Composite Application Contribution. Very well done and useful if you plan to work with Prism.

Then we need a Tabbed MDI container. We have already one in WPF that we can try to customize, and this is what we will do in the next articles. Otherwise you can use the one provided in the Composite WPF Contribution or there is this good article that explains how to fully customize a tabbed control.

Then we can also have the need of using a grid, right? Well if you really think you need one, you can use the XCeed data grid, for free, otherwise you can move to the WPF control toolkit or the WPF contribution, two nice open source projects that deliver some nice and useful controls.

Ready to go?

Now, from the next article we will start to build our application’s skeleton, so let’s try to be ready with everything you’ll need.

Download all these controls and add a reference into your Visual Studio Toolbox. Then agree and download the Office 2007 Ribbon project for WPF. Download the latest version of Prism and install also the Enterprise Library 4.1, required to use Prism.

Also, if you have time, try to have a look at this series of articles and web cast about WPF fundamentals. In this way you will better understand my steps.

Enjoy this tutorial and stay tuned for the next one!

Tags: WCF Prism WPF Composite application

Book Review: Architecting application for the enterprise.

Good morning everybody, first of all I want to apologize for my absence in December. I am really sorry but I was ‘trying’ to deliver a component in my office and I was so busy and tired that I didn’t have time for the blog.

Let’s start this ‘holiday’ posts with an interesting review of a software architecture book written by two friends of mine: Andrea Salatarello and Dino Esposito.

image

The title is: Microsoft .NET: Architecting Applications for the Enterprise (PRO-Developer) (Paperback) available at Amazon.com for 29.69 USD.

Chapters and sections.

The book is divided in 2 main sections: Principles and Design of the system.
The principles section talks about the architect and the architectures in software development. The design of the system talks about how the application should be architected and developed.

The first part has these chapters:

  • Architects and architecture today
  • UML essentials
  • Design principles and patterns

And the second one has the following:

  • The business layer
  • The service layer
  • The Data access layer
  • The presentation layer

Description and overall.

This is the description provided on the back of the book and I completely agree with it.

“Make the right architectural decision up front – and improve the quality and reliability of your results. … you will learn how to apply the patterns and the techniques that help control project complexity …”

I am 100% satisfy of this book as I already use these patterns and approaches  explained in depth in the book.

It’s a must to have for senior developers and software architects. You can’t miss it!!
First of all, this is the first book I have read where is explained in depth what is a Software Architect and why his role it’s fundamental in the development of a complex application. Second, it explains in depth the different approaches you may use for the various layer of an application, starting from the DBMS ending with the UI.

I wish any developer that works or will work with me, will read this book as it gives you a complete overview on how an application should be developed and when a particular layer should or should not be used.

There is also a complete open source project (NSK) on codeplex where you can see all the patterns and methodologies explained in this book. Of course, opening the Visual Studio solution and try to understand everything is not easy as it is using this awesome book.

I am really satisfy and happy! Thanks Andrea and Dino for your effort!

Tags:

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 {
  3: 
  4:  [OperationContract]
  5:  IList<CustomerDto> GetCustomers();
  6: 
  7:  [OperationContract]
  8:  IList<CustomerDto> GetFilteredCustomers(string searchCriteria);
  9: 
 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 “System.data.entity” 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: }
 12: 
 13: 

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: }
  9: 

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 http://raffaeu.com/service/Customer.svc 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 web.app, click on the .svc file, and select Browse.

You should get this result:

image

Considerations.

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.

Tags:

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: http://prismtutorial.codeplex.com/

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.

image

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.

myImage

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;
  2: 
  3: namespace PrismTutorial.WCF {
  4: 
  5:     [DataContract]
  6:     public class CustomerDto {
  7:         [DataMember]
  8:         public int Id { get; set; }
  9:         [DataMember]
 10:         public string FullName { get; set; }
 11:     }
 12: }
 13: 

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;
  3: 
  4: namespace PrismTutorial.WCF {
  5: 
  6:     [ServiceContract]
  7:     interface ICustomerService {
  8:     
  9:         [OperationContract]
 10:         void AddCustomer(CustomerDto customer);
 11:         
 12:         [OperationContract]
 13:         void DeleteCustomer(CustomerDto customer);
 14:         
 15:         [OperationContract]
 16:         IList<CustomerDto> GetCustomers();
 17:     
 18:     }
 19: }
 20: 

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;
  6: 
  7: namespace PrismTutorial.WCF {
  8:     [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
  9:     public class CustomerService : ICustomerService {
 10: 
 11:         IList<CustomerDto> Customers = new List<CustomerDto>();
 12: 
 13:         #region ICustomerService Members
 14: 
 15:         public void AddCustomer(CustomerDto customer) {
 16:             Customers.Add(customer);
 17:         }
 18: 
 19:         public void DeleteCustomer(CustomerDto customer) {
 20:             Customers.Remove(customer);
 21:         }
 22: 
 23:         public IList<CustomerDto> GetCustomers() {
 24:             return Customers;
 25:         }
 26: 
 27:         #endregion
 28:     }
 29: }
 30: 

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: }
  6: 

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.

Considerations.

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!

Tags:

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

Service Oriented Application.

Introduction.

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:

image 

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.

image 

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

image

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!

Tags: