Composite Application Library (Prism) for CAB developers guidance released

August 22nd, 2008 by dpoza

Today we published the Composite Application Library for Composite UI Application Block developers guidance at Codeplex.
You can find the PDF in the CAL Getting Started page under theĀ  section “Interested in Migrating from the Composite Application Block (CAB)?”.

This guidance will help those CAB developers that want to migrate their applications to the Composite Application Library and those who want to give it a try.

The guidance states the main reasons to migrate to the Composite Application Library for WPF and compares both libraries. This will help you to better understand how the concepts in CAB map to CAL.

The guidance includes code comparison, figures and comments. For example, the following figure compares the equivalent elements between the WPFQuickstart solution shipped with the Composite UI Application Block in the Smart Client Software Factory and the WPFQuickstart solution rewritten to use the Composite Application Library.

image

It also includes an interesting appendix which shows how to emulate WorkItems in CAL, using controllers with scoped containers.

We are looking forward to have feedback from your side on this guide in order to improve it before publishing it on MSDN.

I hope it helps,

Diego

Posted in .NET Framework 3.5, Composite Application Guidance for WPF, Composite Applications, WPF | No Comments »

Getting Started with the Composite Application Guidance for WPF

August 13th, 2008 by dpoza
 

Continuing with my previous post. Now I will be describing some of the Composite Application Library (Prism) concepts in more detail.
The following sections will describe how to create an application using the library and some of its key features.

How to create a new application that uses the Composite Application Library

To create an application that uses the Composite Application Library, you just have to create a new WPF Application project.

image

After that create a folder where you will put the Composite Application Library assemblies and add references to them.

You will use the recently created project as a Shell project. Typically, in a composite application, the Shell project provides an UI extensibility point where the views that compose the application will be shown.

You can see the XAML markup of a basic Shell window, containing an empty control defined as the main region, in the following snippet.

image

Bootstrapper

In an application that uses the Composite Application Library, you use a bootstrapper class to initialize the application. Having a bootstrapper gives you more control of how the Composite Application Library components are wired up to your application.

Typically, the bootstrapper initializes the container used for dependency injection, registers infrastructure services and region adapters, creates and shows the shell window, and loads modules.

The Composite Application Library comes with a default abstract UnityBootstrapper class that handles this initialization using the Unity container. Typically, you use this base class to create a derived bootstrapper class for your application.

The Composite Application Library allows you to choose the Dependency Injection container that your application will use because it is unaware of the container. The library brings out-of-the-box support for the Unity container; however, one of the architectural principles of the Composite Application guidance is Extensibility, therefore the container, as other library pieces, can be easily replaced.

If you are using a container other than Unity, you should write your own container-specific bootstrapper.

The bootstrapper’s CreateShell method must be overridden because it is declared as an abstract method in the base class.

You can see the typical implementation of the CreateShell Method in the following snippet:

image

Working with Modules

A module is a logical unit in your application and represents a set of related concerns. Modules created with Composite Application Library are defined in such a way that they can be discovered and loaded by the application at run time. Modules do not reference each other but they communicate with each other in a loosely coupled way.

A module initializer class should implements the IModule interface. This interface contains a single Initialize method that is called during the module’s initialization process.

In the Initialize method of your module initializer class, you implement logic to initialize the module. For example, you can register views and services or add views to regions.

Module loading is the process of loading modules into the application and initializing them. Modules are listed by the module enumerator service. The module enumerator creates a collection of metadata about those modules that can be consumed by the module loader service. After that, the module loader service loads the modules, instantiates the module initializer classes of each module, and invokes the Initialize method on them.

Types of Module Loading

You can load modules in several ways provided by the library, but you can also provide your own custom implementation.

The following are types of module loading supported out-of-the-box by the Composite Application Library:

  • Static module loading. When you statically load a module, the shell contains a reference to the module’s assembly. Static module loading provides less decoupling of the shell with modules than dynamic module loading. However, in cases where decoupling modules from the shell is not a requirement, loading modules statically can reduce code complexity, simplify the application deployment, improve startup performance, and simplify debugging compared to dynamic loading.
  • Dynamic module loading. When you dynamically load a module, the shell does not contain a reference to the module’s assembly; instead, modules are dynamically discovered at run time when the application starts. By doing this, the shell is decoupled from the modules. This implies that you can add, update, or remove modules from your application without recompiling the Shell project. There are two dynamic module loading provided by the library:
    • Directory lookup: This approach allows you to configure the modules using attributes in code and does not require a configuration file.
    • Configuration: This approach allows you to specify the modules in the application configuration file and does not require you to use attributes in code.

The following table shows the bootstrapper’s GetModuleEnumerator method configured to use each type of module loading.

Static Module Loading

image

Dynamic Module Loading - Directory Lookup

image

Dynamic Module Loading - Configuration

image

When modules are configured to be loaded using the ConfigurationModuleEnumerator, you have to add the corresponding section to the app.config file and configure that section.

image

Views and Regions

A region is a mechanism that developers can use to expose to the application’s WPF container control as components that encapsulate a particular visual way of displaying views (typically, views are user controls). Regions can be accessed in a decoupled way by their name and support adding or removing views dynamically at run time.

Because the library is designed to be extensible, it does not enforce you to use a specific view pattern. Therefore, you can use the pattern that suits your application better. See the “Separated Presentation” section in the library documentation for more information.

The following controls are supported out-of-the.box to be exposed as regions:

·         ContentControl and derived controls

·         ItemsControl and derived controls

·         Controls derived from Selector

Region Manager

The region manager service is responsible for maintaining a collection of regions and creating new regions for controls. Typically, you interact directly with this service to locate regions in a decoupled way through their name and add views to those regions. By default, the UnityBootstrapper base class registers an instance of this service in the application container. This means that you can obtain a reference to the region manager service in the application by using dependency injection.

Commands

Commands handle UI actions in a decoupled way. The Composite Application Library provides two command types.

Delegate Commands

The DelegateCommand allows you to delegate the commanding logic instead of requiring a handler in the code behind. It uses a delegate as the method of invoking a target handling method.

Additionally, because it accepts delegates, it removes the need for creating a new command type that implements ICommand for every instance where you need commanding. Also, it does not rely on control focus or the element tree as the RoutedCommand does, which can reduce headaches in composite applications, where pieces of the UI are pushed from different modules.

In the case of the Order module from the Commanding QuickStart had a Save Order command that was bound to a Button control in the UI. This is a simplified version of the code:

image

And from the view in XAML:

image

Composite Commands

The CompositeCommand is a command that has multiple child commands.

In the Commanding QuickStart, the Order module is using a CompositeCommand command to implement the Save All Orders functionality from the toolbar, where all the individual Save Order commands are called at a single button click.

Event Aggregator

The Event Aggregator service enables loosely coupled communications between components in your application. This service implements the publish/subscribe pattern, where the publishers do not send their messages to specific receivers, instead they publish to the service and subscribers receive only messages that are of their interest.

The real work of connecting publishers and subscribers is done by the CompositeWpfEvent class. This class maintains the list of subscribers and handles event dispatching to the subscribers.

The CompositeWpfEvent class is a generic class that requires the payload type to be defined as the generic type. This helps enforce, at compile time, that publishers and subscribers provide the correct methods for successful event connection.

Subscribing to an Event

Subscribers can enlist with an event using one of the CompositeWpfEvent available Subscribe method overloads. There are a number of options for subscribing to CompositeWpfEvents. The following code shows an example of event subscription.

image

Publishing an Event

Publishers raise an event by retrieving the event from the EventAggregator and simply calling the Publish method. As it can be seen in the following snippet.

image

Summary

This post is a pretty long one, but hopefully helps you realize the advantages of composite applications when developing enterprise-level applications between different teams. It is intended to provide a reasonably broad look at the Composite Application Library and all its features, and to show how easy it is to start developing applications with it.

While many of the concepts were redesigned from the Composite UI Application Block (CAB), the Patterns & Practices team has done an excellent job by incorporating customer and user’s feedback in the development of the library, thus, creating a simpler, more lightweight, less invasive and extensible library.

Therefore if you want to create a composite application taking advantage of WPF capabilities or upgrade an existing WPF application to a composite application, you definitely should take a look at the Composite Application Library.

If you want to learn more about the Composite Application Guidance, I strongly recommend giving the documentation a try, because it is very exhaustive and easy to read.

I hope you find it useful,

Diego

Posted in .NET Framework 3.5, Composite Application Guidance for WPF, Composite Applications, Visual Studio 2008, WPF | No Comments »

First experience with LINQ

January 21st, 2008 by dpoza

I’m finishing my second week at Southworks and I’m so happy about it, I met awesome people, but above all things, nice and easy-going partners.

During this time I’ve been reading so much about Software Development and new technologies shipped with Visual Studio 2008, like LINQ & MVC Framework.

I decided to write my first blog post about LINQ, my experiences & thoughts. I’ve been reading about it for some weeks, but I have just had the opportunity to try it.

“LINQ to SQL” is an ORM (Object – Relational Mapping) that comes with VS 2008, it maps a relational database to .NET classes, so you can easily query and perform DML operations on the database just by using the generated classes which represents the DB objects. LINQ automatically generates the SQL and persists the changes you made.

Visual Studio 2008 ships with a LINQ to SQL Designer, which greatly simplifies the task of modeling your DB, you can just drag and drop the DB objects you want from the Server Explorer to the designer, and they will be mapped including relationships among them, which are represented by arrows. You can obviously make custom changes to the model if you want.

LINQ1

Fig. 1 – LINQ to SQL Designer – A simple Northwind model

DataContext Class

Once you save your model, VS will generate .NET classes representing the entities and relationships in it, and also a custom DataContext Class will be generated.

This class will provide us the interaction between the model and the real DB objects. It will have properties representing every modeled table, and also methods will be created for every SP added to the designer.

Knowing this, we can see some query examples.

Examples (C# Syntax)

  •  Select

LINQ2

Fig. 2 – Selecting products in "Condiments" category

You can notice a few things from this code:

First to use LINQ generated classes we have to instantiate a new DataContext class.

Second, as we are selecting several products we have to store the query result in a Generic Collection of Products, or we can simply store it in the new VS2008 “var” type which infers the correct type.

Third, LINQ syntax is very similar to regular SQL, but also having OOP advantages.

Fourth, we query about the category name being equal to “Condiments”, if you remember the model, this is stored in a Category table, and related to Products table by CategoryID, so using standard SQL, will require joining both tables to obtain the same result, but with LINQ this is done in a simple and natural way.

  • Insert

LINQ3

Fig. 3 – Inserting a new category and two new products within it

This code is self-explanatory; you create objects and set the properties you want.

Then, you have to add the products to the new category using the Add method, after that add the new category in the Categories table, using the InsertOnSubmit method passing the category object as a parameter.

Finally you persist changes with DataContext’s method, SubmitChanges.

  • Delete

LINQ4

Fig. 4 – Deleting all products in a category

To delete the products we’ve inserted before, we will first query the DB, and store the results into a variable, note we used the new var type, so the compiler will infer that result is a collection of Products, then we call the DeleteAllOnSubmit method passing result as a parameter. This method will put all products in result in a pending delete state. Finally we commit deletion, using SubmitChanges method.

  • Update

LINQ5

Fig. 5 – Updating a single product 

Update is very intuitive. You can update a product, first by retrieving it from the database, and then modifying its properties, finally as the previous cases, you have to commit the changes with SubmitChanges();

For product’s retrieval we used a method called Single, which retrieves one and only one product that meets the given conditions and fails if the query returns more than one.

If you noticed we used a different syntax in this query, it is called Lambda expression, I’ll try to explain this a little more on a next post. But its objective is to simplify even further LINQ syntax.

Note: The syntax used is the one of Visual Studio RTM version, some methods had other names in VS betas, and because of this the syntax in older post of external blogs may vary.

Conclusion

As you have seen, LINQ is a powerful technology that will greatly simplify your work with DB. You have ORM capabilities shipped with Visual Studio 2008. You design your DB model, which is easy, and then it is even easier to query and perform DML operations on the DB. LINQ’s generated SQL statements are very efficient, and you can see the generated SQL of a statement in debug mode.

With LINQ you can build simple applications easily, saving you a lot of written code, but it is also useful for complex scenarios.

I hope you liked LINQ and want to give it a try, so I recommend you to pay a visit to Scott Guthrie’s awesome blog for more information and tutorials.

Posted in .NET Framework 3.5, LINQ, Visual Studio 2008 | No Comments »