WPf and Prism Tab Region Adapter, Part 02.

10 Comments | Jul 04, 2010

As we saw in the previous post, it’s pretty complicate to create a custom design in WPF to override the default style of the TabControl, but it’s pretty simple to extend the behavior of it.

As a senior dev, I usually don’t like to: 1) touch what is already working, 2) reinvent the wheel just to write the same code twice. For that there is the refactoring process, at most!

So, let’s start by the requirement we had in the previous post, we need to emulate the VS IDE in our applications, that’s it! We also saw that Prism has the RegionAdapter, so now we just need a cool control. Well there is the Avalon Dock project that is open source, really well done, flexible and ready for WPF 4. So let’s use it for our purposes. The final result should be something like this:

image

Avalon dock is crazy powerful and allows you to build a complete system of docking and modal windows into your WPF application. But before doing that you need to write a custom region adapter for it!

So, this is the basic concept of a custom Region Adapter in Prism. You create you custom adapter class by inheriting from RegionAdapterBase<T> in the following way:

Region adapter for Avalon Dock
  1. public sealed class AvalonRegionAdapter : RegionAdapterBase<DocumentPane>
  2. {
  3.     public AvalonRegionAdapter(IRegionBehaviorFactory factory)
  4.         : base(factory)
  5.     {
  6.  
  7.     }

 

Avalon dock has a lot of future, and you should create a Region adapter able to attach any type of dock view. In my case I will use only the Tab region adapter that is called DocumentPane. Now the RegionAdapterBase requires that you implement three methods:

Create region
  1. protected override IRegion CreateRegion()
  2. {
  3.     return new AllActiveRegion();
  4. }

 

The create region which specify what base adapter you want to use. In this case we want to handle any type of view added to this adapter, like an ItemsContainer or a TabControl.

Adapt
  1. protected override void Adapt(IRegion region, DocumentPane regionTarget)
  2. {
  3.     region.Views.CollectionChanged += delegate(Object sender, NotifyCollectionChangedEventArgs e)
  4.     {
  5.         OnViewsCollectionChanged(sender, e, region, regionTarget);
  6.     };
  7. }

Then we override the adapt method. This method is called once so in my case, because I have a DocumentPane I will then listen for the event Views.CollectionChanged. In this way I know every time if a view has been added or removed from the region.

Code Snippet
  1. private void OnViewsCollectionChanged(object sender, NotifyCollectionChangedEventArgs e, IRegion region, DocumentPane regionTarget)
  2. {
  3.     if (e.Action == NotifyCollectionChangedAction.Add)
  4.     {
  5.         //Add content panes for each associated view.
  6.         foreach (object item in e.NewItems)
  7.         {
  8.             UIElement view = item as UIElement;
  9.  
  10.             if (view != null)
  11.             {
  12.                 DockableContent newContentPane = new DockableContent();
  13.                 newContentPane.Content = item;
  14.                 //if associated view has metadata then apply it.
  15.                 newContentPane.Title = view.GetType().ToString();
  16.                 //When contentPane is closed remove the associated region
  17.                 newContentPane.Closed += (contentPaneSender, args) =>
  18.                 {
  19.  
  20.                 };
  21.                 regionTarget.Items.Add(newContentPane);
  22.                 newContentPane.Activate();
  23.             }
  24.         }
  25.     }
  26.     else
  27.     {
  28.         if (e.Action == NotifyCollectionChangedAction.Remove)
  29.         {
  30.  
  31.         }
  32.     }
  33. }

Now, here there are two major steps. First we want to know if the item has been added or removed from the collection. If it’s added we create a new DockableContent and we set the Content to our view. Then we need to set a couple of properties like Title and name. In my case I am just adding the view, we will see later how to implement our TabModel property. What we can do then is to attach a listener to the close event of this tab. Why? Because when avalon will close a dock document we need also to destroy the corresponding view.

Then the second part is when the regionAdapter has a request of closing a view. We want to destroy the corresponding tab control.

Now go back a little bit and change the code in this way:

Code Snippet
  1. TabViewModel viewModel = ((UserControl)view).DataContext as TabViewModel;
  2. if (view != null)
  3. {
  4.     DockableContent newContentPane = new DockableContent();
  5.     newContentPane.Content = item;
  6.     if (viewModel != null)
  7.     {
  8.         Image img = new Image();
  9.         img.Source = new BitmapImage(new Uri(@"Resources/Alerts.png", UriKind.Relative));
  10.         newContentPane.Title = viewModel.TabModel.Title;
  11.         newContentPane.IsCloseable = viewModel.TabModel.CanClose;
  12.         newContentPane.Icon = img.Source;
  13.     }

It’s a little bit dirty but what we are trying to do here is to cast the View.DataContext to a type TabViewModel. It it’s the right type, as NET won’t throw an exception but simply returns an empty instance … we will populate the tab controls with our info.

The final result is this one:

SNAGHTML388d63e

The first can’t be closed and the second one can be, also we added a special icon to the context menu. More than that, this is still a WPF controls where you can apply your custom style. That’s it!

Ops, this is the new code in the MainView, of course:

XAML Avalon Dock adapter
  1. <ad:DockingManager Grid.Column="1" Grid.Row="1" >
  2.     <ad:DocumentPane cal:RegionManager.RegionName="TabRegion" Name="TabRegion">
  3.         <ad:DockableContent Title="Some title">
  4.  
  5.         </ad:DockableContent>
  6.     </ad:DocumentPane>
  7. </ad:DockingManager>

Final Note: As you can see building a custom region adapter is easy but you must know the control behind that, the one that will act as a region adapter. When you know that part you can play as you want. For example I have a region adapter for the ToolBar so every time you load a view, I pass the corresponding Toolbar to the main toolbar region. Same for the ribbon and for the Outlook bar.

Prism and WPF. Custom Tab region adapter. Part 01.

One Comment | Jul 04, 2010

The second part of this tutorial is here. Enjoy!

One thing that I really hate when I started working on Prism was the fact that the developers didn’t provide a nice tab region adapter. Well, the items adapter provided in Prism fits perfectly with the tab control, but if you use it “as is” it pretty sucks.

I am pretty sure that as soon as you will release your first Prism “Visual Studio style” Prism application your manager will ask you for a cook tab like the one below:

image

This is an add-in of VS2010. As you can see it allows you to: 1) close the current active tab, 2) identify the tabs that have changes with a red dot, 3) use different colors in order to identify the active tab and the different types of files opened.

Another cool tab system, also present in VS 2010 is the one that splits the XAML code from the designer IDE, look here:

image

I simply love this style of a non–squared tab, it remembers me Chrome browser.

How Prism region adapter works?

First of all let’s have a look on how we create a new tab in a tab region adapter, using the default Prism settings. What you usually do is to add a view to a region and that’s it … The code below shows you how to define a tab region adapter and then how to add a new tab on it. Pretty straightforward.

First of all we initialize the bootstrapper in the Shell project.

The Shell bootstrapper
  1. protected override System.Windows.DependencyObject CreateShell()
  2. {
  3.     var shell = Container.Resolve<MainWindow>();
  4.     shell.Show();
  5.     return shell;
  6. }
  7.  
  8. protected override IModuleCatalog GetModuleCatalog()
  9. {
  10.     var catalog = new ModuleCatalog()
  11.         .AddModule(typeof(TabModule));
  12.     return catalog;
  13. }

 

Then we prepare the Shell XAML Window to include the regions we need.

Shell XAML Window
  1. <ItemsControl Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2"
  2.               cal:RegionManager.RegionName="HeaderRegion" Name="HeaderRegion">
  3.     
  4. </ItemsControl>
  5. <TabControl Grid.Row="1" Grid.Column="1"
  6.             cal:RegionManager.RegionName="TabRegion" Name="TabRegion">
  7.     
  8. </TabControl>

And then, in the module, we just assign each view to the specific region in the shell.

Module initialization
  1. public sealed class TabModule : IModule
  2. {
  3.     private IRegionManager regionManager = null;
  4.  
  5.     public TabModule(IRegionManager regionManager)
  6.     {
  7.         this.regionManager = regionManager;
  8.     }
  9.  
  10.     public void Initialize()
  11.     {
  12.         regionManager
  13.             .AddToRegion("TabRegion", new FirstView())
  14.             .AddToRegion("TabRegion", new SecondView());
  15.     }
  16. }

And this is the ugly result you get …

image

As you can see the tab doesn’t know how to render the tab item because we didn’t specify any style.

Now in order to fix this there are two simple solutions. The first one is to create a custom region adapter and override the method on adding a region and provide all the info you need to the region adapter. This is cool especially if you are using third party controls. The second way is the Raf’s way, as I don’t use at all third party controls for the simple reason that as a blogger, I don’t have money … [:)]

Everything starts with the Dependency Property.

XAML is cool especially because it allows you to extend it as much as you want, so why don’t we start to consider its powerful engine before going mad adopting strange solutions?? So let’s build a simple .dll project that will be our “model” for the TabItem style. This model represents our properties to say that: 1) A view has a title, 2) A View can be or cannot be closed, 3) A view has changes that must be saved.

Model for a tab item
  1. public sealed class TabModel : DependencyObject
  2. {
  3.     public string Title
  4.     {
  5.         get { return (string)GetValue(TitleProperty); }
  6.         set { SetValue(TitleProperty, value); }
  7.     }
  8.  
  9.     // Using a DependencyProperty as the backing store for Title.  This enables animation, styling, binding, etc...
  10.     public static readonly DependencyProperty TitleProperty =
  11.         DependencyProperty.Register("Title", typeof(string), typeof(TabModel));
  12.  
  13.     public bool CanClose
  14.     {
  15.         get { return (bool)GetValue(CanCloseProperty); }
  16.         set { SetValue(CanCloseProperty, value); }
  17.     }
  18.  
  19.     // Using a DependencyProperty as the backing store for CanClose.  This enables animation, styling, binding, etc...
  20.     public static readonly DependencyProperty CanCloseProperty =
  21.         DependencyProperty.Register("CanClose", typeof(bool), typeof(TabModel));
  22.  
  23.     public bool IsModified
  24.     {
  25.         get { return (bool)GetValue(IsModifiedProperty); }
  26.         set { SetValue(IsModifiedProperty, value); }
  27.     }
  28.  
  29.     // Using a DependencyProperty as the backing store for IsModified.  This enables animation, styling, binding, etc...
  30.     public static readonly DependencyProperty IsModifiedProperty =
  31.         DependencyProperty.Register("IsModified", typeof(bool), typeof(TabModel));
  32.  
  33. }

Now we need just to create a ViewModel which represents a View rendered in a tab control. Of course you should have the entire infrastructure of your ViewModel toolkit but in this sample we don’t really need it! This is the code:

image

Now that everything is in place we need two more pieces of code. The first is a ViewModel for each view which implements also the TabItem model, the code below is just for the FirstView:

Concrete ViewModel for TabItem
  1. public sealed class FirstViewModel : TabViewModel
  2. {
  3.     public FirstViewModel()
  4.     {
  5.         this.TabModel = new TabModel
  6.         {
  7.             Title = "First View.",
  8.             CanClose = true,
  9.             IsModified = false
  10.         };
  11.     }
  12. }

And the very easy xaml:

FirstView vm binding
  1.          xmlns:vm="clr-namespace:PrismCustomModule.ViewModels"
  2.          mc:Ignorable="d"
  3.          d:DesignHeight="300" d:DesignWidth="300">
  4. <UserControl.DataContext>
  5.     <vm:FirstViewModel />
  6. </UserControl.DataContext>

Customize the TabItem using styles.

The first step is very easy, just go in the Shell project and add a Resource dictionary that will be then referenced in the Shell Window. Create a custom style for the tab container and specify how to bind the header text with the TabItem model we created previously:

Dictionary
  1. <ResourceDictionary xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
  2.                     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
  3.     <Style TargetType="{x:Type TabItem}" x:Key="HeaderStyle">
  4.         <Setter Property="Header"
  5.                 Value="{Binding RelativeSource={RelativeSource Self},
  6.                     Path=Content.DataContext.TabModel.Title}" />
  7.     </Style>
  8. </ResourceDictionary>

 

So far so good, now we just customize the TabContainer in the shell and that’s the final result:

Code Snippet
  1. <TabControl Grid.Row="1" Grid.Column="1"
  2.             cal:RegionManager.RegionName="TabRegion" Name="TabRegion"
  3.             ItemContainerStyle="{StaticResource HeaderStyle}">
  4.     
  5. </TabControl>

 

image

Pretty good and because the TabItem model is a property that raises changes in the ViewModel, we can communicate with the user changing this property “on fly” when the tab is open. We can also use it to activate a specific tab, adding a behavior to the tab style and more. But the tab header still sucks, and a lot! I mean I really don’t like it. So here we come with Blend 4 and Design 4.

There are a lot of tutorials on the web about Blend and Design. I came out with a final result pretty minimal but functional, this one using this tutorial: http://stackoverflow.com/questions/561931/how-to-create-trapezoid-tabs-in-wpf-tab-control

Another interesting project is AvalonDock on Codeplex. They just resemble the VS2010 style just using XAML code. This is the link for the style they used for the tab header http://avalondock.codeplex.com/SourceControl/changeset/view/60974#1218433 and this is the result:

image

Next time I will show you how to add a custom behavior to the tab in order to broadcast with prism the closing event, so that prism can kill the corresponding view …

[;)] Stay tuned!

How to write fluent interface with C# and Lambda.

2 Comments | Jun 26, 2010

Last week I had a nice discussion in the office about “how to write fluent interface” and I have found a couple of articles over the internet about that. As usual I disagree with some of them and, as usual, my friend Mauro Servienti (MVP C#) has a nice article about it, unfortunately in Italian. He just gave me the startup input.

If you think about the Fluent Interface, it is just a trick that you use with C# in order to cheat the intellisense of Visual Studio and in order to create a nice style for your code. Of course there is a specific way to write fluent interface.

Let’s make a short sample. The classic Person class and the factory pattern.

We have a class which represents the Person Entity and has some common properties.

image

Very easy. Now, in a normal world you would have something like this, in order to create a new instance of a class person.

First way, the classis way:

Classic Person Factory
  1. public class PersonFactory
  2. {
  3.     public static Person CreatePerson(string firstName, string middleName, string lastName)
  4.     {
  5.         var person = new Person
  6.         {
  7.             FirstName = firstName,
  8.             MiddleName = middleName,
  9.             LastName = lastName
  10.         };
  11.         return person;
  12.     }
  13. }

This code is classic and very verbose. If you want to use it the syntax would be something like this:

Create Person
  1. var person = PersonFactory.CreatePerson("Raffaele", string.Empty, "Garofalo");

 

Now, if we want to add an address to this person we need an additional like of code like this one, and of course a new factory for the class person or a new method in the person factory … whatever …

Create Address
  1. var address = PersonFactory.CreateAddress("1st Lane", "Main Road", "Hamilton", "Bermuda", "HM10");
  2. person.Addresses.Add(address);

 

First of all, here we have a big problem. All the parameters are strings. So, if we don’t explain in a proper verbose way each parameter, the developer that will use our factory won’t be able to know what to write in each parameter. Second thing, if we don’t use C# 4 we have to specify each parameter value anyway … Finally we are avoiding a nice readability in our code.

The first step for a fluent interface.

I saw a lot of code around the web but a lot of people forget about the name of this technique … The name is Fluent Interface so this means that probably we should add some interfaces in our code in order to have a good result. Well VS 2010 is able to create an interface from a class just with a couple of clicks … And this is the final result:

image

Now we need to translate each method in a Fluent method. Let’s start with the class person. What I am doing is an interface for my Factory and two methods, one for the Factory initialization, where we initialize a new instance of the class person and one to finalize it, where we will return the current instance of that class. Of course we need also the methods to add some values to the person properties. Look at the UML:

image

At here is the code:

IPersonFactory
  1. public interface IPersonFactory
  2. {
  3.     IPersonFactory Initialize();
  4.     IPersonFactory AddFirstName(string firstName);
  5.     IPersonFactory AddLastName(string lastName);
  6.     IPersonFactory AddMiddleName(string middleName);
  7.     IPerson Create();
  8. }

 

And this is the implementation:

PersonFactory
  1. public class PersonFactory : IPersonFactory
  2. {
  3.  
  4.     private IPerson person = null;
  5.  
  6.     public IPersonFactory Initialize()
  7.     {
  8.         person = new Person();
  9.         return this;
  10.     }
  11.  
  12.     public IPersonFactory AddFirstName(string firstName)
  13.     {
  14.         person.FirstName = firstName;
  15.         return this;
  16.     }
  17.  
  18.     public IPersonFactory AddLastName(string lastName)
  19.     {
  20.         person.LastName = lastName;
  21.         return this;
  22.     }
  23.  
  24.     public IPersonFactory AddMiddleName(string middleName)
  25.     {
  26.         person.MiddleName = middleName;
  27.         return this;
  28.     }
  29.  
  30.     public IPerson Create()
  31.     {
  32.         return person;
  33.     }
  34. }

 

So now we start to have a FluentInterface capability in our code.

Code Snippet
  1. var person = new PersonFactory()
  2.                 .Initialize()
  3.                 .AddFirstName("Raffaele")
  4.                 // we can skip this line now ...
  5.                 .AddMiddleName(string.Empty)
  6.                 .AddLastName("Garofalo")
  7.                 .Create();

 

Very well done but we still have a problem here. We are not giving a constraint to the developer that will use our fluent syntax. Let’s say that we are working with a retarded colleague, nobody can prohibit him to write something like this:

Wrong Person
  1. var wrongPerson = new PersonFactory().Create();

 

In this case he will get a nice NullReferenceException because if he doesn’t call the method Initialize the factory won’t create a new instance of the class person … So how can we add a constraint to our interface? Very simple, we need 3 interfaces and not only one anymore. We need IInitFactory, IPersonFactory and ICreateFactory.

Let’s see the code:

IPersonFactory
  1. public interface IPersonFactory
  2. {
  3.     IPersonFactory AddFirstName(string firstName);
  4.     IPersonFactory AddLastName(string lastName);
  5.     IPersonFactory AddMiddleName(string middleName);
  6.     IPerson Create();
  7. }

 

The IPersonFactory now will not be in charge anymore of creating a new instance of the class person, it will just be in charge of working with it. We will use dependency injection to inject a new instance. Let’s the concrete implementation of this factory:

Person Factory refactored
  1. public class PersonFactory : IPersonFactory
  2. {
  3.  
  4.     private IPerson person = null;
  5.  
  6.     public PersonFactory(IPerson person)
  7.     {
  8.         this.person = person;
  9.     }
  10.  
  11.     public IPersonFactory AddFirstName(string firstName)
  12.     {
  13.         this.person.FirstName = firstName;
  14.         return this;
  15.     }
  16.  
  17.     public IPersonFactory AddLastName(string lastName)
  18.     {
  19.         this.person.LastName = lastName;
  20.         return this;
  21.     }
  22.  
  23.     public IPersonFactory AddMiddleName(string middleName)
  24.     {
  25.         this.person.MiddleName = middleName;
  26.         return this;
  27.     }
  28.  
  29.     public IPerson Create()
  30.     {
  31.         return this.person;
  32.     }
  33. }

 

Now we need an orchestrator. Somebody that will be visible outside and will be in charge of giving to the fluent syntax a static flavor (we want to avoid the new Factory() syntax …) and that will return a PersonFactory ready to work …

Person Fluent Factory
  1. public static class PersonFluentFactory
  2. {
  3.     public static IPersonFactory Init()
  4.     {
  5.         return new PersonFactory(new Person());
  6.     }
  7. }

 

And now Visual Studio will follow our rules …

Parallels Picture

Parallels Picture 1

Final Step, Lamba expression for a cool syntax.

Ok this is cool and it works like we want but … it is really time consuming. We want a fluent interface and that’s fine but if you a domain with 100 entities and more or less 100 factories, can you imagine the pain in the neck in order to adopt this pattern all over?? Well this is the reason you should study more in depth C#!! If you didn’t know, there is a cool syntax future in C# called Lambda Expressions. If you don’t know what I am talking about, have a look here.

First of all we need a generic interface for our factory with only two methods, one to add a value to a property and one to return the current instance of the entity created by the factory.

IGenericFactory
  1. public interface IGenericFactory<T>
  2. {
  3.     IGenericFactory<T> AddPropertyValue(Expression<Func<T, object>> property, object value);
  4.     T Create();
  5. }

Then following the same logic of the previous steps we need a concrete implementation but using generics and lambda expressions (I really love this part).

Generic Factory &lt;T&gt;
  1. public class GenericFactory<T> : IGenericFactory<T>
  2. {
  3.     T entity;
  4.  
  5.     public GenericFactory(T entity)
  6.     {
  7.         this.entity = entity;
  8.     }
  9.  
  10.     public IGenericFactory<T> AddPropertyValue(Expression<Func<T, object>> property, object value)
  11.     {
  12.         PropertyInfo propertyInfo = null;
  13.         if (property.Body is MemberExpression)
  14.         {
  15.             propertyInfo = (property.Body as MemberExpression).Member as PropertyInfo;
  16.         }
  17.         else
  18.         {
  19.             propertyInfo = (((UnaryExpression)property.Body).Operand as MemberExpression).Member as PropertyInfo;
  20.         }
  21.         propertyInfo.SetValue(entity, value, null);
  22.  
  23.         return this;
  24.     }
  25.  
  26.     public T Create()
  27.     {
  28.         return this.entity;
  29.     }

And the Fluent Factory, now generic, in this way:

Code Snippet
  1. public static class GenericFluentFactory<T>
  2. {
  3.     public static IGenericFactory<T> Init(T entity)
  4.     {
  5.         return new GenericFactory<T>(entity);
  6.     }
  7. }

 

The final syntax will be this one:

Code Snippet
  1. var person = GenericFluentFactory<Person>
  2.     .Init(new Person())
  3.     .AddPropertyValue(x => x.FirstName, "Raffaele")
  4.     .AddPropertyValue(x => x.LastName, "Garofalo")
  5.     .Create();

 

Ta da!! One generic factory with syntax constraints to create as many entities as you want! And the smart developer that is working with you won’t be able to complain at all.

Final notes.

We can make this code better by:

  • Adding a custom type reflected by the property we are using, so you won’t be able to add an integer value to a property of type string and so on …
  • Remove that ugly .Init(new Person()) using an IoC engine or a new constraint to our class, of course in this case you must provide classes with at least 1 parameters less constructor.

That’s it! Have fun!

WebHost4Life, the worst Hosting Service.

9 Comments | Jun 18, 2010

Oh, I am so glad that after 15 days of troubles and problems I am finally able to post again from my blog.

An this is just one of the new important news! But let’s start to shame on WebHost4Life.

I want to let you know that I am the owner of this domain, starting from the far 2003 and I had various Hosts in these years but I never had such a kind of problem.

Around January 2010 the crappy WebHost4Life started the tedious migration under the new Control Panel but this is not the true. They started to migrate manually user by user. I tried to post this migration until 15 days ago but then, when I renewed my subscription with them I started to have problems over problems.

First, the domain Raffaeu.com totally disappeared from my control panel, at that point I was not able anymore to receive e-mails, to host my blog and more … After 10 open tickets and a lot of money spent in calling them, I decided to block my payment with Paypal and open a formal claim.

You know what happened after that? They simply wiped everything. My files, my account, my e-mails and my SQL server. The only way to get back these files, that are mine, was to pay them an upfront of 143 USD.

After that they simply putted online again an old version of my blog and a mess in the database. All the emails are gone! I am sure about that because I use Subtext 2.2 and the version they restored was the 1.9. I did the migration to the version 2 more than 6 months ago ….

Now everything is fine for the simple reason that I moved to a new provider. Now I am using Discountasp.net and it’s pretty cool. In less than 1 day they contacted the registrar, changed my DSN and made everything working. I have also a cool IMAP provider for my mail accounts.

I am trying now to open a formal claim with all the other users that had the same problem I had as WebHost4Life doesn’t deserve to be a web host for the crap they are doing all around.

What I can suggest to you, if you are under them is to look for a new host and try to postpone the migration to the new platform as far as you can. Also remember to backup everything as it seems that they are totally incompetent …

There is still plenty of work to do. I lost most of my screenshots and files so you will find some problems reading my articles but I have a lot of backups so don’t worry, I will replace everything in few weeks.

Stay tuned as we are going back to talk about WPF and Prism again in few days. I have plenty of posts to share with you.

Big changes on my blog.

2 Comments | Apr 02, 2010

Hi everybody, I am writing this post to let you know that I am still alive and there are big changes coming in blog, soon. With soon I mean, probably, a couple of weeks.

The new version of Subtext, my blog engine, may be out soon and it will include many futures. The best one will be a search index engine, it should be Lucene.NET. In the meantime I am going to update my blog to the current available version, 2.1.2.

The second news is that my personal blog skin it’s pretty close to be ready. I worked hard on it and I can’t say anything yet but it will have an extensive use of the new JQuery application framework plus a nice search capability. More than that it will allow me to display better my posts and my tutorials. More space for the code and more space for the comments. I will also introduce a stronger captcha comment validation due to the huge amount of spam that I am receiving everyday on my blog.

I am also preparing a new section on my blog skin where you will be able to view the tutorials by category. Smile

I got a lot of emails in the last month about the Prism Tutorial project, about the future of Entity Framework and also about an easy way for searching articles on my blog. Stay tuned guys, I am really working hard on it and you will have a nice surprise soon!

I want just to share with a preview of the amazing layout I came out for my new blog skin:

mockup

Update:

This is the final skin, in few days it will be ready for SubText.

BlogSkinV1.png

VMWare Fusion 3 or Parallels 5? My two cents.

Add Comment | Apr 02, 2010

It has been a month now since my last post. Unfortunately I have been very busy in the office and more than that I also lost my old PC.

Now, I bought a nice MacBookPro 13” with an SD disk and I can’t complain at all about performances and robustness of my new laptop.

As many of you already know, I am a Windows Developer, or better, I use .NET as my primary development tool. As you can understand this requirement doesn’t fit at all with my new Laptop, a Steve Jobs’ “PC”.

Also I want to let you know that I didn’t have any intention to buy an MBP and use Windows on it, it doesn’t make any sense. Also I am not afraid saying that Snow Leopard is an awesome operating system, really well done. So for these reasons here we come with the virtualization solution I have tried in the latest month.

There are two major software for virtualize Windows on a MAC. The first is VMWare Fusion 3, a product of the famous software house specialized in virtualization, VMWare; the second is Parallels Desktop for MAC.

I tried both software for the evaluation period and I want to be honest, after I tried parallels (it was the second one) I pointed my choice to it without any reserve.

But let’s just review what you can do with Fusion and what you can do with Parallels.

Comparison.

The first thing that everyone of you will notice is the price. Pretty cheap for what the software does and pretty close one to the other one. VMWare Fusion is sold now for 79 USD without assistance or subscription and 99 with 12 months subscription. Parallels is sold for 79 USD and you can add 6 USD if you want to be able to get the software download available for 12 months.

Trial version. Both trials are full for 30 days is Fusion and for 15 is Parallels. The big difference is that for Fusion you need to register an account on their web site and I got an answer from then with the serial key, only the next day. With parallels you get everything you need in the same time you download the trial. Very quick.

Windows Installation. For both system I did a full customized installation in a new expandable virtual disk. Here there is nothing to say more than Parallels was much faster. Maybe 10 minutes to get Windows 7 ready to go? Fusion spent more time … and then you need to install this and that. With parallels my machine was ready to go after the installation.

Modality. If you ever worked in the past with another VMWare product, you know that they provide 2 way to integrate the guest system with the host. You can use the VM Player or you can use Unity. With Unity you will have the active program running in windows, integrated into your MAC OS. And here we come with the huge difference. Parallels has 5 different ways to integrate windows inside your MAC. The best is the crystal mode. Here is a small summary of the parallels display futures:

  • New! MacLook Theme — Transform Windows applications by making them look like native Mac applications
  • New! Crystal Mode — Pull the shades on Windows altogether. Access Windows and Mac apps from the Mac Dock
  • Coherence — Run Windows and Mac apps side-by-side as if both operating systems have melted together into one.
  • Window — Choose to run your Virtual Machine as a separate window alongside your Mac apps.
  • Modality — View all your Virtual Machines and programs running in transparent windows working in Mac OS X.
    Full Screen — Don’t give up the familiarity of Windows. Replace your Mac desktop with Windows 7, Vista, or XP

Visual Studio 2010. I tried different approaches with both systems but if you try to use Windows Aero on Fusion running VS, the system is slow and also the screen has a strange refresh. I also enabled the 3D acceleration but nothing changed. With Parallels I am doing this: VS2010 + Windows Live Writer + Photoshop CS4 on MAC + iTunes on MAC in the same time and I can’t complain at all. Look at this screenshot:

parallels.png

Shared spaces. If you use the integration on Fusion “Unity” or one of the various integration in Parallels you can share the data from Win to MAC OS. This is pretty cool especially if you are working with Live Writer on Windows and Photoshop on MAC. Unfortunately if you plan to share a VS Solution, due to permissions problems and wrong setup, with Fusion it can be a pain in the neck.
I can’t complain at all about Parallels, I can simply copy something from my MAC desktop and paste it directly inside Live Writer or vice-versa.

I don’t know what you think about having a MAC OS and working on VS 2010 but now that I am working on a MAC, thanks to Parallels, I won’t move anymore back to a PC, trust me!

Technorati Tags: ,

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

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