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

4 Comments | Feb 13, 2010

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:

2 Years of blog.raffaeu.com.

One Comment | Feb 07, 2010

Today it’s 2 years that I have opened my blog in English and it’s two years that I moved to Bermuda web site.

I should do some considerations about it but it’s not the right time for me so I will try to be as less negative as I can.

Job and career.

I moved here 2 years ago as a Senior Software Developer working for a public Company as the IT Manager. In this company I was in charge of the entire (small) IT department. Unfortunately, after the Market Crisis of the 2009 I was ‘convinced’ to look for another job.

Actually I am working as a ‘real software architect’ for a pretty cool company also in the re-insurance business. In this company I am using all my knowledge (design architectures, .NET, latest technologies like WCF, WPF, WF) and I have also the luckiness to have the opportunity to mentor my colleagues with a weekly workshop. Trust me, for a community addicted like me it’s a huge satisfaction!

I got some new Microsoft Certifications and I am working hard to gain the complete set of MCPD certifications too.

Moving to Bermuda web site.

Bermuda web site is a small Island in the Atlantic Ocean. The size is around 50Kmq and the population size is around 60,000 people, more or less.

After the ‘first year honeymoon’ the life starts to be really hard here.

Honestly, is not an easy place for a lot of reasons, especially for someone like me that is coming from one of the nicest place in the North of Italy, the Lake Maggiore and that likes a lot mountain activities like skiing and walking in the forest. What I miss in order of importance are:

  • Friends, friendship in Italy is very different than in any other country, trust me! Smile
  • Food, also if me and my wife are decent cook, we still miss a lot of our traditional food here.
  • The environment. I miss the mountain, the snow, the lake and the quite winter we have in my town. I miss Milan and the shopping and I also miss the Switzerland where I spent the last 7 years.
  • NET Communities. Nothing like that in Bermuda web site, I also tried to open a workgroup a year ago but it seems to be a mission impossible.

Life is crazy expensive, just to give you a small idea, a normal rent is around 3, 4K a month and a decent dinner in a decent restaurant is around 150, 200 USD for two person.

Fortunately, I have here all my family (my wife, my sweetie dog and my cat) so I feel comfortable and for now I still don’t have the need to come back home; I also found some nice Italians friends that help me in the daily complains ... Smile

Personal.

When I moved here two years ago I started an awesome sport called ‘Kite surfing’. Unfortunately, last year, I had a bad accident in Brazil, when I was on holiday with my wife, and I had a hernia surgery. After that I stopped to kite also because my wife won’t allow me to do that anymore. Wink

The plan for this year is pretty ambitious but I won’t mention anything yet. I am just planning to write a lot, articles, online tutorials, book and more. Of course everything will be related to .NET 4.

My blog has now a small but really interesting average of 150 feed readers and an average of 200 visits per day with at least 1 daily feedback. Trust me, it’s a huge satisfaction especially when your readers send you e-mail for business requests. Laughing

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

2 Comments | Feb 07, 2010

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

UI Patterns tutorials. MVP, MVVM and Composite app with WPF.

2 Comments | Jan 31, 2010

I got a lot of e-mails from my readers (I am very happy for that) where they claim the fact that It’s pretty hard to follow my tutorials because the actual version of SubText (my blog engine) doesn’t allow any search.

Unfortunately until the new version of SubText will be released, and I know it will include a search engine, there is no way to help you.

For this reason I am writing this post, that I will keep up to date constantly, with a list of available tutorials regarding the UI patterns.

Please forgive me if I forget some of them.

Model-View-ViewModel tutorials and articles:

Model View presenter:

Composite UI Applications with WPF and Prism:

I want also to let you know that I am writing to complete guides for the web UI patterns. The first one will be “Building business validation with ASP.NET 4 and

Workflow foundation 4” and “Complete guide to ASP.NET MVC 2.0”. These two guides will be published on HTML.it, an Italian community for web developers. I am not sure I will be able to translate them also in English on my blog.

Tags:

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

3 Comments | Jan 02, 2010

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

The Model View Presenter pattern with .NET.

6 Comments | Dec 30, 2009

I had a request from one of my blog’s reader (Bastien) that I can’t skip. Last week he asked me to write a short article on how to implement the Model View Presenter with Windows form. So let’s skip for a while my series of articles about Prism and let’s see what is the MVP and how it should be implemented.

The Model View Presenter pattern.

The definition of the model view presenter pattern can be found in many web site, let’s use the classic definition provided by MSDN. (This is an interesting article that explains the MVP).

Model-view-presenter (MVP) is a user interface design pattern engineered to facilitate automated unit testing and improve the separation of concerns in presentation logic.
1) The model is an interface defining the data to be displayed or otherwise acted upon in the user interface.
2) The view is an interface that displays data (the model) and routes user commands (events) to the presenter to act upon that data.
3) The presenter acts upon the model and the view. It retrieves data from repositories (the model), persists it, and formats it for display in the view.

There are two different types of MVP implementation: the MVP passing view and the MVP supervising controller. The main difference from these two types of UI patterns is that in the passive view, the view doesn’t know anything about the model and the presenter is in charge of “advise the view” that something happened. In the second implementation, the view knows the model for the basic binding and the presenter is used only when the view requires complex UI manipulation.

image

Personally I completely disagree with the second approach, because the layers are not really recyclable, and a change in the model constraint the developer to change also the view … Frown

The sample model.

As I usually do, you will find a sample application at the end of this article. So let’s start building a very simple fake model that will be the “famous” Customer-> Orders.
First of all we need a new Visual Studio solution and we need to structure our application into 3 layers. Of course I am going to create just one project with 3 folders but usually you should have 3 different .dll (UI, Presenter, DAL, Model …) maybe more than 3. tongue-out

image

As you can see from the model we have our classic DomainObject class, abstract, that represents a domain object, so in my case I want to know for each object, its unique id and if it’s valid.

Then we have a Customer, that can have one or more address, a List of Order and for each Order a list of Order Items.

The view and the windows forms.

Using the Windows form approach, our view is what we are showing to the user. So in this case our view will be a Windows form. We have 2 views, one is an overview of all the available customers, and the second one is specific to an order.

All available Customers.

image

All available Order for a specific Customer.

image

Now we need to create a generic implementation of the relation View-Model-Presenter and try to recycle some code. This is my idea: we will have a base view that will expose the view name and a couple of methods, then each view will inherits the base one. In this case the view will expose directly the domain entity, but this should not be done in production, I would suggest to use the DTO.

image The implementation of the Generic View.

Under the folder views, we need to create a new interface, IBaseView:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: 
  6: namespace ModelViewPresenter.View {
  7:     public interface IBaseView {
  8:         string Name { get; set; }
  9:     }
 10: }

Now we can start to implement the CustomersView that will represent the information we have in the Customer window:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using ModelViewPresenter.Model;
  6: 
  7: namespace ModelViewPresenter.View {
  8:     public interface ICustomersView : IBaseView {
  9:         Customer SelectedCustomer { get; }
 10:         IList<Customer> Customers { get; set; }
 11: 
 12:         string FirstName { set; }
 13:         string LastName { set; }
 14:         string BirthDate { set; }
 15:         string Address { set; }
 16:     }
 17: }

In this view we have two different types of information. First of all we have an IList of Customer that will represent our data source for the main grid, and a single instance of type Customer that will represent the selected Customer in the grid.

Then we have some basic data type information that we will use to render the current selected Customer in the grid. These information will be filled by the presenter. Unfortunately in my case the view knows the model but you can avoid that using a Dto.

A fake repository.

Of course we usually have a DAL that read the data from the Db and translate these information into a collection of entities, or better, inside our Domain Model. For this application I have created a simple repository structure just to show you how I implement the MVP pattern using generics.

The base repository:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: 
  6: namespace ModelViewPresenter.Model {
  7:     public interface IBaseRepository {
  8:         void Initialize();
  9:     }
 10: }

And then the concrete implementation for our views:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: 
  6: namespace ModelViewPresenter.Model {
  7:     public sealed class CustomersRepository : IBaseRepository {
  8: 
  9:         private IList<Customer> customers;
 10:         
 11:         #region IBaseRepository Members
 12: 
 13:         public void Initialize() {
 14:             customers = new List<Customer>();
 15:         }
 16: 
 17:         #endregion
 18: 
 19:         public IList<Customer> GetCustomers() {
 20:             customers.Add(
 21:             ... ...
 22: 
 23:             return customers;
 24:         }
 25: 
 26:         private void AddAddressToCustomer(Customer customer) {
 27:             ... ...
 28:         }
 29: 
 30:         private void AddOrdersToTheCustomer(Customer customer) {
 31:             ... ...
 32:         }
 33:     }
 34: }
 35: 

My code doesn’t do anything special. It just creates a fake collection of customers and will add 2 orders with some order items for each one.

Use some glue and put all together, the presenter.

Now it’s time to play with a generic presenter that won’t know the view and or the repository. My idea is to do something like this:

  1: using System;
  2: using System.Collections.Generic;
  3: using System.Linq;
  4: using System.Text;
  5: using ModelViewPresenter.View;
  6: using ModelViewPresenter.Model;
  7: 
  8: namespace ModelViewPresenter.Presenter {
  9:     public abstract class BasePresenter<TView, TRepository> 
 10:            where TView : IBaseView 
 11:            where TRepository : IBaseRepository {
 12:         
 13:         protected TView view;
 14:         protected TRepository repository;
 15: 
 16:         public virtual void InitializeView() { }
 17: 
 18:         public virtual void UpdateView(object model) { }
 19:     }
 20: }

First of all we have to declare a generic view and a generic repository. In this way we will pass our concrete view and repository when we will create a new instance of the presenter. Then I have added to simple virtual methods. The first one will “prepare” the view, so we can call it in the load method of the form, or better, in his constructor. UpdateView will receive the selected “instance”  and will update the view.

Let’s try to imagine how the CustomersPresenter should be implemented following this approach:

We declare the class

  1: public sealed class CustomersPresenter : 
  2:      BasePresenter<ICustomersView, CustomersRepository> {
  3: 

The we implement the 2 constructors:

  1: public CustomersPresenter(ICustomersView view) {
  2:  repository = new CustomersRepository();
  3:  repository.Initialize();
  4:  this.view = view;
  5: }
  6: 
  7: public CustomersPresenter(ICustomersView view, CustomersRepository repository) {
  8:  this.view = view;
  9:  this.repository = repository;
 10:  repository.Initialize();
 11: }
 12: 

And then we start to write the code that will override the default methods of our presenter:

  1: public override void InitializeView() {
  2:     base.InitializeView();
  3:     this.view.Name = "All available Customers View.";
  4:     this.view.Customers = repository.GetCustomers();
  5: }
  6: 

and

  1: public override void UpdateView(object model) {
  2:     base.UpdateView(model);
  3:     var selected = model as Customer;
  4:     if (selected != null) {
  5:         this.view.FirstName = selected.FirstName;
  6:         this.view.LastName = selected.LastName;
  7:         this.view.BirthDate = selected.BirthDate.ToShortDateString();
  8:         this.view.Address = selected.FirstAddress;
  9:     }
 10: }
 11: 

When a customer is selected:

  1: public void SelectionChanged() {
  2:     UpdateView(this.view.SelectedCustomer);
  3: }
  4: 

Finally we need to bind all this code in our form, that will “implement” the view and will “know” the presenter. Let’s see.

Bind the view and the presenter to the corresponding windows form.

We have previously created a windows form with some controls and a gridview that will show the available customers. Now, first of all, we implement the view in the form:

  1:     public partial class CustomersView : Form, ICustomersView {
  2: 
  3:         #region ICustomersView Members
  4: 
  5:         public string FirstName 
  6:         {
  7:             set {
  8:                 txtFisrtName.Text = value;
  9:             }
 10:         }
 11: 
 12:         public string LastName {
 13:             set {
 14:                 txtLastName.Text = value;
 15:             }
 16:         }
 17: 
 18:         public string BirthDate {
 19:             set {
 20:                 txtDateBirth.Text = value;
 21:             }
 22:         }
 23: 
 24:         public string Address {
 25:             set {
 26:                 txtAddress.Text = value;
 27:             }
 28:         }
 29: 
 30:         public Customer SelectedCustomer {
 31:             get {
 32:                 if (grdCustomers.SelectedRows.Count > 0) {
 33:                     return (Customer)grdCustomers.SelectedRows[0].DataBoundItem;
 34:                 }
 35:                 return null;
 36:             }
 37:         }
 38: 
 39:         public IList<Customer> Customers {
 40:             get {
 41:                 return (IList<Customer>)grdCustomers.DataSource;
 42:             }
 43:             set {
 44:                 grdCustomers.AutoGenerateColumns = false;
 45:                 grdCustomers.DataSource = value;
 46:             }
 47:         }
 48: 
 49:         #endregion

And now we can assign the presenter to this view in the following way:

  1: protected CustomersPresenter presenter;
  2: 
  3: public CustomersView() {
  4:    InitializeComponent();
  5:    presenter = new CustomersPresenter(this);
  6:    presenter.InitializeView();
  7: }
  8: 

Now, whatever will happen in the form, the corresponding event will call a method in the presenter. In this way we are sure that the form (view) will know only the presenter. Remember that in order to satisfy this prerequisite, you should have a Dto that represents the information you want to show in the view, and not a reference to domain model.

Select a customer:

  1: private void grdCustomers_SelectionChanged(object sender, EventArgs e) {
  2:    presenter.SelectionChanged();
  3: }
  4: 

And show the corresponding orders, a method handled by the presenter that will open a new orders view and show the corresponding orders:

  1: private void grdCustomers_DoubleClick(object sender, EventArgs e) {
  2:     presenter.LoadOrders();
  3: }
  4: 

Conclusions and source code.

The source code of this article is available on my sky drive at this address. The solution is complete so you will find more code, the implementation of the navigator pattern, useful to navigate through the views, and the complete design of the windows form.

This is the address: Raffaeu Visual Studio Sky drive

Remember that you should never share your domain entities inside the view, leave them in the presenter and try to use the Dto and a framework like AutoMapper to do the rest.

This code is trivial just to show you how to implement the MVP using generics, from my point of view. It can be implemented in a better way and it can also be refactored.
I will appreciate if you have suggestions and feedbacks.

If you need another example, like how to use the MVC, or how to implement validation in MVVM, please write me an e-mail, and I will try to satisfy your request.

For now I will continue my series using WPF, Prism and WCF. So stay tuned and Happy new year!

Tags:

Books review: Scrum techniques.

Add Comment | Dec 30, 2009

Today it seems to be, for me, the day of the books review. The reason is because I am at home, for the Christmas holiday, and my wife is working. tongue-out This means “I have time to read my tech books and write some posts on my blog”.

What is scrum?

The scrum is an agile methodology used in software development. This is the description provided on Wikipedia:

“Scrum is an iterative incremental framework for managing complex work (such as new product development) commonly used with agile software development. Although the word is not an acronym, some companies implementing the process have been known to spell it with capital letters as SCRUM. This may be due to one of Ken Schwaber’s early papers, which capitalized SCRUM in the title.[1]

Although Scrum was intended for management of software development projects, it can be used to run software maintenance teams, or as a general project/program management approach.”

There are a lot of resources over the network and I can’t explain what is scrum and how it should be implemented in one post, for sure! But I have found a couple of really interesting books that you should read if you plan to adopt this technique in your IT Department.

Agile Software Development with Scrum.

Prentice Hall – Ken Schwaber and Mike Beedle (45.99 USD)

image

Thanks to my boss, I had in my hands this book that is the first book written by Ken Schwaber, the author and founder of the Scrum technique.

The book is easy to read and distill both, practice and theory on how the Scrum methodology should be used and implemented.

A must to have for a software architect and for a project manager.

Agile Project Management with Scrum.

Microsoft – Ken Schwaber (39.99 USD)

image

This is the second book written by Ken Schwaber and in my opinion is another must to have! It is pretty clear, if you have already read the previous book, that in this book Ken will share all his experience in mentoring Scrum.

Easy to read and very well done, with samples and pictures (flowcharts) that will guide you through the process of learning and applying the Scrum technique in your daily routine.

Additional resources.

I am not going to enumerate the thousands of blogs and web sites that talk about Scrum but I have a friend of mine, that is not living anymore in Italy, that is a great Scrum master and has a blog where he talks only about Scrum, you can have a look at his blog here: Luca Minudel.

Tags:

Book Review: Architecting application for the enterprise.

4 Comments | Dec 30, 2009

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.

2 Comments | Nov 08, 2009

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/PrismTutorialSmile

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.

2 Comments | Nov 08, 2009

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: