Archive

Posts Tagged ‘Prism’

Carolina Code Camp 2011

May 15, 2011 1 comment

I had a great time speaking at the Carolina Code Camp 2011. We had an awesome turnout. Thanks to all who helped make it a success. I look forward to the next one!

As promised, here are the slides from the presentations I made:

Silverlight Dashboards

Taking a look at Caliburn.Micro

Taking a look at Prism 4.0

Thanks again for coming out….

Advertisements

I am speaking at Carolina CodeCamp 2011

I am going to be doing three presentations at the Carolina CodeCamp 2011. The three topics include Silverlight Dashboards, Taking a look at Caliburn.Micro, and Taking a look at Prism 4.

Hope to see you all there.

Implementing View First using a ViewModelLocator

May 17, 2010 3 comments

A while back I did a post on a way to use dependency injection (DI) to handle View first approach to your MVVM development. Today, I am going to be talking about another approach that is Blend friendly if you are wanting to go View first and still have your VieModel created with dependencies. For this example, I am going to use a simple data entry screen that will be composed of DataEntryView and corresponding DataEntryViewModel.

Before we get started, I want to show you the most common approach for implementing the View first in Xaml:

<UserControl 
    x:Class="CodeCamp2010.Calc.Views.DataEntryView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:CodeCamp2010.Calc"
    >
    <UserControl.DataContext>
        <l:DataEntryViewModel />
    </UserControl.DataContext>
    <Grid x:Name="LayoutRoot">
        ...
    </Grid>
</UserControl>

Here is a sample of the ViewModel:

public class DataEntryViewModel
{

    #region ctor
    public DataEntryViewModel()
    {
    }
    #endregion

    Property Bindings...

};

If you only need to use your default constructor of the ViewModel, this is a quick and easy way to wire you View and ViewModel together. This does have its limitations since it will only work with the default constructor.

Now let’s examine how we would go about facilitating dependency injection in the ViewModel. I will be using Unity as my container since I am using Prism. I will also be use the ServiceLocator from Prism. Let’s look at what it takes to register these two objects in Unity.

public class CalcModule : IModule
{
    private IUnityContainer _container;
    private IRegionManager _regionManager;
    private IEventAggregator _eventAggregator;

    #region ctor
    public CalcModule(IUnityContainer container, IRegionManager regionManager, IEventAggregator eventAggregator)
    {
        _container = container;
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;
    }
    #endregion

    public void Initialize()
    {
        _container.RegisterType<DataEntryView>();
        _container.RegisterType<DataEntryViewModel>();       

        _regionManager.RegisterViewWithRegion("MainRegion", typeof(DataEntryView));
    }
};

In Prism, every separate module or assembly that you create needs to have a class that implements IModule. This interface requires a single Initialize() method. It is in this method that I am registering and also requesting the view to be displayed.

Now let’s look at the DataEntryView:

<UserControl 
    x:Class="CodeCamp2010.Calc.Views.DataEntryView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:l="clr-namespace:CodeCamp2010.Calc"
    >
    <UserControl.Resources>
        <l:ViewModelLocator x:Key="ViewModelLocator" />
    </UserControl.Resources>
    <UserControl.DataContext>
        <Binding Path="DataEntryViewModel" Source="{StaticResource ViewModelLocator}" />
    </UserControl.DataContext>
    <Grid x:Name="LayoutRoot">
        ...
    </Grid>
</UserControl>

We see that we have a new entry compared to the previous view example. We now have a UserControl.Resources entry and it is providing a ViewModelLocator resource. We then see how the DataContext uses this new Resource and requests the DataEntryViewModel as its path.

Let’s now look at the ViewModelLocator class:

public class ViewModelLocator
{
    private IUnityContainer _container;
    private IUnityContainer Container
    {
        get
        {
            if (_container == null)
                _container = ServiceLocator.Current.GetInstance<IUnityContainer>();
            return _container;
        }
    }

    public DataEntryViewModel DataEntryViewModel
    {
        get
        {
            return Container.Resolve<DataEntryViewModel>();
        }
    }
};

This class is very simple. It basically is your one-stop shopping for all of your ViewModels that need to be referenced by your Views in your module. It uses the ServiceLocator to get an instance of IUnityContainer. Then it simple uses the Container to resolve for the corresponding type that you need.

Finally, here is an exmple of the DataEntryViewModel with an overloaded constructor:

public class DataEntryViewModel
{
    private IUnityContainer _container;
    private IRegionManager _regionManager;
    private IEventAggregator _eventAggregator;

    #region ctor
    public DataEntryViewModel(IUnityContainer container, 
        IRegionManager regionManager, 
        IEventAggregator eventAggregator)
    {
        _container = container;
        _regionManager = regionManager;
        _eventAggregator = eventAggregator;
    }
    #endregion

    Property Bindings...

};

Hopefully, this gives you an idea as to another alternative to implementing your View first approach and still using the power of dependency injection.

Categories: English Tags: , , ,

Loading your catalog.xaml dynamically in Silverlight

May 7, 2010 1 comment

When developing Silverlight applications in Prism it is sometimes nice to have the ability to have your catalog.xaml be a little bit more dynamic than the standard examples you see in the Prism guidance. I will show you an example that allow you to load your catalog.xaml file dynamically and thus giving you the ability to save in a database, IsolatedStorage, etc.

Lets first take a look at what a sample catalog.xaml file would look like:

<m:ModuleCatalog  
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:sys="clr-namespace:System;assembly=mscorlib"
    xmlns:m="clr-namespace:Microsoft.Practices.Composite.Modularity;assembly=Microsoft.Practices.Composite">

    <m:ModuleInfo ModuleName="Security"
                  ModuleType="Security.SecurityModule, Security, Version=1.0.0.0"
                  InitializationMode="OnDemand"
                  Ref="Security.xap"/>
    <m:ModuleInfo ModuleName="Logging"
                  ModuleType="Logging.LoggingModule, Logging, Version=1.0.0.0"
                  InitializationMode="OnDemand"
                  Ref="Logging.xap"/>
</m:ModuleCatalog>

Typically this file is located in the main Silverlight application with a build action of ‘Content’. If we wanted to be able to modify this, we would have to make a change, build it, and then publish it to our hosting website.

Let’s look at our Bootstrapper.cs file that we use to configure Prism. We will be looking at the GetModuleCatalog method:

protected override IModuleCatalog GetModuleCatalog()
{
    var catalog = ModuleCatalog.CreateFromXaml(new 
        Uri("catalog.xaml", UriKind.Relative));
    return catalog;
}

The interface IModuleCatalog lives in the Microsoft.Practices.Composite.Modularity namespace.

Now lets see how we can change our code so that we can load the catalog dynamically. The following code shows a simple implementation for this:

protected override IModuleCatalog GetModuleCatalog()
{
    var modules = @"<m:ModuleCatalog  " +
        "xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"" + 
        "xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"" +
        "xmlns:sys=\"clr-namespace:System;assembly=mscorlib\"" +
        "xmlns:m=\"clr-namespace:Microsoft.Practices.Composite.Modularity;assembly=Microsoft.Practices.Composite\">" +
        "<m:ModuleInfo ModuleName=\"Security\"" +
            "ModuleType=\"Security.SecurityModule, Security, Version=1.0.0.0\"" +
            "InitializationMode=\"OnDemand\"" +
            "Ref=\"Security.xap\"/>" +
        "<m:ModuleInfo ModuleName=\"Logging\"" +
            "ModuleType=\"Logging.LoggingModule, Logging, Version=1.0.0.0\"" +
            "InitializationMode=\"OnDemand\"" +
            "Ref=\"Logging.xap\"/>";

    var xamlStream = new MemoryStream();
    Byte[] bytes = Encoding.UTF8.GetBytes(modules);
    xamlStream.Write(bytes, 0, bytes.Length);
    xamlStream.Position = 0;
    var catalog = ModuleCatalog.CreateFromXaml(xamlStream);
    xamlStream.Close();
    return catalog;
}

For demonstration purposes, I am showing you the catalog string inline in the method. In production, you would have a WCF service that would return a string containing the catalog information and you would just need to get a stream from it.

This gives you a lot of flexibility for third vendors or just adding new logic to your own applications. You could now deploy your .xap files and then update a database or serverside configuration file that keeps track of the catalog information. You could make this be part of your startup sequence in your application and turn on or off certain modules based on your licensing or some other metric.

Hope this helps….

Categories: English Tags: ,

Silverlight 4 Business Applications

February 27, 2010 Leave a comment

Over then next months, I will be posting about putting together an architecture for line of business applications.  First, I would like to break down the many components that would comprise building enterprise level applications.

Let’s first talk about cross-cutting concerns at a very high level:

  • Security – this would include authentication and authorization.  We will discuss permissions based authorization in order to support more than just screen level authorization but break it down to screen part and individual control level security.
    • Logging – this will provide global logging in a centralized manner.  Our goal will be to facilitate a flexible logging infrastructure without impacting any of modules that desire to log.  We should be able to change out the logging implementation whether it be a flat file, database, or rest service.
  • Exception Handling – this will provide a common means for receiving exceptions and notifying users of issues.  We will provide a mechanism to report exceptions and then allow for the developer to decide whether the end user should see the exception or just silently log to through the logging service.
  • Messaging – this service will be used throughout the other cross-cutting concerns.  It main purpose is to allow other modules to broadcast messages(events) without the need to have references to the other various modules.

We will go into each of these global services in more detail as dedicated posts.  Next we will take a look at one approach as to building a shell and module infrastructure to support the development of modular applications.  These posts will go into detail using both Prism and MEF (Managed Extensible Framework).

Stay tuned for more.

Which comes first? Chicken or the Egg?

October 17, 2009 Leave a comment

A common question I have been seeing in the blogosphere when dealing with dependency injection (DI) is which comes first?  The View or the ViewModel.

I have seen several approaches where the ViewModel receives a View via a constructor parameter.  I have also seen another approach with the ViewModel receiving a View via Property injection.  This limits how much support you get from Blend.

I have seen the approach where a View creates a ViewModel as a static resource and then the DataContext of the View is set to the key of the resource.  I have seen the locator approach where you have a class that acts as the ViewModel service locator and then returns the correct ViewModel depending on your scenario.  This actually comes in handy if you want to have Blend support.

The one concern I have with both of these goes to the heart of the question and that is who is going to write and maintain all of this ceremonious scaffolding?  I believe that neither the View nor the ViewModel should be concerned with hooking each other up.  I am currently using Prism developing Silverlight applications but the approach I am going to provide would work for either Silverlight or WPF.

Here goes….What I offer is that the true responsibility of hooking the View with the ViewModel or vice versus belongs to the dependency injection container.  It should be the container who decides what to do and how to proceed.  I am introducing a little convention to get this accomplished but I think you will find this to be an eloquent solution for shops that are more focused on maintenance and reusability.

What I have created is an extension method attached to the Unity container.

As you can see from above, I resolve the View and ViewModel from the Container first.  Then I check by convention if there is a property named “View” on the ViewModel.  If I find it, then I set the property with the value of the newly resolved View.  Likewise, I check the View to see if it is a FrameworkElement and if it is, then I set the DataContext with the value of the ViewModel.

There you have it!  I am sure that you can think of many other conventions or ways that you could make this work for your development shop.

Thanks for reading and stay tuned for more….