Common sense lost with MVVM


I am a big fan of using MVVM in WPF applications, but am finding, increasingly,  that even seasoned developers frequently dispose of very good habits, in order to stay true to the pattern.

One such occurrence is is not using message boxes. A  cardinal sin in MVVM, is ensuring that message boxes are never used in View Models. The end result is that one starts to see code like this.

delete

If you don’t have a logging system for your exceptions then you should have, if you do then always ensure that you log the exception. During development, one instinctually starts to determine brittle code, and events where errors can occur and use try-catch blocks. The worst thing you can do here is nothing. It is better not to use the try-catch at all, and just let the application blow-up, because at least you know that there is a problem, and go about fixing it.

I really cannot sufficiently impress upon thee just how much of a bad practice this is, and the amount of time you or other developers that work on your project will spend trying to find obscure bugs that occur because you are swallowing exceptions, just because MVVM stipulates that message boxes should not be used, means they shouldn’t, they should!

Free WPF Ribbon with source code and MVVM samples


Finally after about 2 years as a CTP, Microsoft have released the WPF ribbon. Due to the delay, one can be certain that they were allowing their third party software vendors as much traction for users that needed a ribbon, but some brilliant open source versions including Fluent Ribbon Control Suite have been developed.

ribbon

The best thing about the release, is that the Office Fluent UI licensing is now no longer a requirement. This allows people to download the software straight away, without having to go through the cumbersome process of logging into the Office website, signing the licensing, then spending half a day trying to locate the installation because it was hidden in a way that made you think they don’t want anyone to use it.

The download for the ribbon is available here. Please ensure that you also take the time to install the source and samples if you want to build MVVM compliant applications with the ribbon (you should be doing this in WPF anyway) . The MSDN documentation is available here.

The installation notes say that this is not supported on XP, but on vista upwards but I have not tested this. If there are issues then you should be able to use another vendor.

After installing the MSI you should have the following template in Visual Studio

project

There is no information on the installation templates for the express editions, but I would hazard a guess as to them never being available, as building applications with a Ribbon is not something a learner ‘typically’ does. If you are using express, then you should be able to add the requisite .dll thus. If you look in my Tree View below in Visual Studio, you will find that there is a reference to RibbonControlsLibrary. This is located at; C:\Program Files (x86)\Microsoft Ribbon for WPF\v3.5.40729.1\RibbonControlsLibrary.dll

tree

Note:  If you installed the source and samples as well, a .zip file with both is available at the same location. Copy this, and unzip it in a location of your choosing

source

The code behind for my window has the following code, so inherit off RibbonWindow

ribboncode

Finally your XAML should be defined so, and you’re good to go!

xaml

WPF and Silverlight Timer


Users of Windows Forms will know that there are three timer objects you can use, namely the Windows Forms Timer, the System Timers Timer and finally the System Threading Timer, as the following example demonstrates;

Note: this tutorial is in both C# and Visual Basic, so look beneath the Visual Basic examples for the C# Version.

Visual Basic

Public Class Form1

 

    Dim timerCallBack As System.Threading.TimerCallback

 

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        ”Winforms Timer

        Dim wfTimer As System.Windows.Forms.Timer()

 

        ”Timers Timer

        Dim tTimer As System.Timers.Timer()

 

        ”Threading Timer

        timerCallBack = AddressOf PrintTime

        Dim thTimer As System.Threading.Timer = New System.Threading.Timer(Me.timerCallBack)

 

 

    End Sub

 

    Private Sub PrintTime(ByVal obj As System.Object)

        ”Print the time to screen

    End Sub

 

 

End Class

C#

using System.Windows.Forms;

 

namespace TimersExample

{

    public partial class Form1 : Form

    {

        System.Threading.TimerCallback timerCallBack;

 

        public Form1()

        {           

            InitializeComponent();

        }

        private void Form1_Load(object sender, System.EventArgs e)

        {

            // Winforms Timer

            System.Windows.Forms.Timer wfTimer = new Timer();

 

            //Timers Timer

            System.Timers.Timer tTimer = new System.Timers.Timer();

 

            //Threading Timer

            timerCallBack = new System.Threading.TimerCallback(PrintTime);

            System.Threading.Timer thTimer = new System.Threading.Timer(this.timerCallBack);

        }

        private void PrintTime(object obj)

        {

            //Print the time to screen

        }

 

    }

}

 

In both WPF and Silverlight there is a new timer (the fourth .NET framework timer) called the System.Windows.Threading.DispatcherTimer. To demonstrate how this works, look at the following simple code sample. In it, there is some XAML that declares a label, button and a button click and window loaded events (In Silverlight use the UserControl_Loaded event for the page instead of Window_Loaded).

 

<Window x:Class="WpfTimer.Window1"

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;

   Title="Window1" Height="300" Width="300" Loaded="Window_Loaded">

    <Grid>

 

        <StackPanel Orientation="Vertical">

        <Label Height="28" Width="70" Name="label1">Label</Label>

        <Button Height="23" Width="70" Name="button1" Click="button_Click">Button</Button>

 

        </StackPanel>

 

    </Grid>

</Window>

 

Note that in the Visual Basic XAML you have Window x:Class="Window1" at the top (in case you’re wondering why the XAML does not compile). In the code behind, you have the following code that instantiates a DispatcherTimer in the load event of the Window, and allows a user from starting and stopping the timer by toggling the button click event.

   

Visual Basic

Class Window1

    Dim timer As System.Windows.Threading.DispatcherTimer

    Public Event UpdateTime()

 

    Private Sub Window_Loaded(ByVal sender As Object, ByVal e As RoutedEventArgs)

        timer = New System.Windows.Threading.DispatcherTimer()

        timer.Interval = TimeSpan.FromSeconds(1)

        AddHandler timer.Tick, AddressOf timer_Tick

 

    End Sub

 

    Sub timer_Tick(ByVal sender As Object, ByVal e As EventArgs)

        Me.label1.Content = DateTime.Now.ToLongTimeString()

    End Sub

 

    Private Sub button1_Click(ByVal sender As Object, ByVal e As RoutedEventArgs)

        If Not Me.timer.IsEnabled Then

            Me.timer.Start()

            Me.button1.Content = "Stop"

        Else

            Me.timer.[Stop]()

            Me.button1.Content = "Start"

        End If

    End Sub

 

 

 

 

End Class

 

C#

using System;

using System.Windows;

 

namespace WpfTimer

{

    /// <summary>

    /// Interaction logic for Window1.xaml

    /// </summary>

    public partial class Window1 : Window

    {

        System.Windows.Threading.DispatcherTimer timer;

 

        public Window1()

        {

            InitializeComponent();         

        }

        private void Window_Loaded(object sender, RoutedEventArgs e)

        {

            timer = new System.Windows.Threading.DispatcherTimer();

            timer.Interval = TimeSpan.FromSeconds(1);

            timer.Tick += new EventHandler(timer_Tick);

        }

 

        void timer_Tick(object sender, EventArgs e)

        {

            this.label1.Content = DateTime.Now.ToLongTimeString();

        }

 

        private void button_Click(object sender, RoutedEventArgs e)

        {

            if (!this.timer.IsEnabled)

            {

                this.timer.Start();

                this.button1.Content = "Stop";

            }

            else

            {

                this.timer.Stop();

                this.button1.Content = "Start";

            }

        }

 

 

    }

}

 

DispatcherTimer

Free Training worth £5000


It’s not often that you find something that is too good to be true, but this is. Microsoft are offering free Windows Presentation Foundation training by two of their leading proponents on the technology Jaime Rodriguez and Karl Shiftlett.

The agenda for training will be

Day One:

  • Lap Around WPF
  • WPF Tools ( Blend, Visual Studio 2008)
  • Graphics Subsystem
  • Layout
  • WPF Fundamentals and new concepts
    • Application Model
    • Dependency Properties
    • Trees (logical & visual)
    • Events
    • Threading
    • Resources
  • Controls
  • Styling
  • Templating
  • Q&A with instructors at end of day
  • Day Two:
    • WPF integration with Win32 and Windows Forms
    • Data binding
    • Introduction to Model-View-ViewModel
    • Commanding in M-V-VM
    • Views, Navigation and Transitions
    • Data Validation
    • Error handling, Model dialogs, Logging
    • Unit Testing
    • MVVM & LOB tips and tricks
    • Q&A with the instructors

I have signed up for this training, and think that it is a seriously good offer, that you won’t find anywhere, especially seeing as the training will be coming from the “horses mouth” so to speak!

Building a Composite WPF and Silverlight Application with Prism – Part 4


Welcome to the final part in this four part series on building a WPF and Silverlight application with Prism. The previous parts are

Building a Composite WPF and Silverlight Application with Prism – Part 1

Building a Composite WPF and Silverlight Application with Prism – Part 2

Building a Composite WPF and Silverlight Application with Prism – Part 3

The main focus of this tutorial will be introducing communication between modules. Thus far, we have focussed on getting the Digg module operational. In this instalment we will add a search module, and demonstrate how this separate module can interact with another in a loosely coupled fashion.

This tutorial is in both C# and Visual Basic, but when creating projects in Visual Studio, the images I may use may be C# templates for example, but you should be able to do exactly the same in Visual Basic and vica-versa. It avoids the repetition of posting two images with “Open C# Silverlight Application” and “Open Visual Basic Application”, when the Visual Studio templates are the same – bar the language. I will however, post code samples in both languages

Adding the Search Module

Add a new Silverlight class library to the solution, and call this NewsAggregator.Search and delete the default class1 added to the project

SearchModule

Add references to the Prism libraries (in C# right click the References node in Solution Explorer and choose “Add Reference…” )

AddReferences

add a SearchModule class to this project that implements IModule and implement the interface.

Visual Basic

Imports Microsoft.Practices.Composite.Modularity

Public Class SearchModule

    Implements IModule

    Public Sub Initialize() Implements Microsoft.Practices.Composite.Modularity.IModule.Initialize

    End Sub

End Class

C#

using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using Microsoft.Practices.Composite.Modularity;

namespace NewsAggregator.Search

{

    public class SearchModule : IModule

    {

        #region IModule Members

        public void Initialize()

        {

            //throw new NotImplementedException();

        }

        #endregion

    }

}

Add a reference of the NewsAggregator.Search library to the NewsAggregator.Shell and add the SearchModule to the Bootstrapper. Note that this as in the previous example is setting a direct reference to the Shell. This is to hasten the tutorials, but typically you want to add this or any other module in a loosely coupled fashion was well.

Visual Basic

Imports Microsoft.Practices.Composite.UnityExtensions

Imports Microsoft.Practices.Composite.Modularity

Imports NewsAggregator.Digg

Imports NewsAggregator.Search

Public Class Bootstrapper

    Inherits UnityBootstrapper

    Protected Overrides Function CreateShell() As System.Windows.DependencyObject

        Dim shell As New Shell

        Application.Current.RootVisual = shell

        Return shell

    End Function

    Protected Overrides Function GetModuleCatalog() As Microsoft.Practices.Composite.Modularity.IModuleCatalog

        Dim catalog As New ModuleCatalog

        catalog.AddModule(GetType(DiggModule))

        catalog.AddModule(GetType(SearchModule))

        Return catalog

    End Function

End Class

C#

using System.Windows;

using Microsoft.Practices.Composite.UnityExtensions;

using Microsoft.Practices.Composite.Modularity;

using NewsAggregator.Digg;

using NewsAggregator.Search;

namespace NewsAggregator.Shell

{

    public class Bootstrapper : UnityBootstrapper

    {

        protected override DependencyObject CreateShell()

        {

            Shell shell = new Shell();

            Application.Current.RootVisual = shell;

            return shell;

        }

        protected override Microsoft.Practices.Composite.Modularity.IModuleCatalog GetModuleCatalog()

        {

            ModuleCatalog catalog = new ModuleCatalog();

            catalog.AddModule(typeof(DiggModule));

            catalog.AddModule(typeof(SearchModule));

            return catalog;

        }

    }

}

Implementing the Search Model View View Model

Adding the Model View

Add a UserControl to the NewsAggregator.Search library and call this SearchView

SearchView

In this UserControl add the following XAML

<UserControl x:Class=”NewsAggregator.Search.SearchView”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”&gt;

    <UserControl.Resources>

        <Style x:Key=”TitleBorder” TargetType=”Border”>

            <Setter Property=”CornerRadius” Value=”10″/>

            <Setter Property=”Background” Value=”#FFDEDEDE”/>

            <Setter Property=”Margin” Value=”0,0,5,0″/>

            <Setter Property=”Grid.Column” Value=”0″/>

        </Style>

        <Style x:Key=”TitleText” TargetType=”TextBlock”>

            <Setter Property=”FontSize” Value=”16″/>

            <Setter Property=”Foreground” Value=”#FF14517B”/>

            <Setter Property=”Margin” Value=”10,3,0,0″/>

        </Style>

        <Style x:Key=”SearchButton” TargetType=”Button”>

            <Setter Property=”Grid.Column” Value=”2″/>

        </Style>

    </UserControl.Resources>

    <Grid>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width=”*”/>

            <ColumnDefinition Width=”200″/>

            <ColumnDefinition Width=”100″/>

        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>

            <RowDefinition/>

        </Grid.RowDefinitions>

        <Border Style=”{StaticResource TitleBorder}”>

            <TextBlock Text=”NEWS SEARCH “ Style=”{StaticResource TitleText}” />

        </Border>

        <TextBox x:Name=”txtSearchTopic” Grid.Column=”1″ Padding=”1,3,1,1″ />     

        <Button Content=”Search” Style=”{StaticResource SearchButton}” />

    </Grid>

</UserControl>

which should result in the following user interface

SearchUI

Adding the View Model

When you click on search, normally you would be handle this by creating an event handler for the search button, but this is not easily testable. Implementing the MVVM pattern here will help with testing.

Add a new class library and call this SearchViewModel. In this library expose an ICommand with a private “setter” so this can be set in the constructor.

Note : Silverlight does not provide an commanding infrastructure here (but WPF does) so Prism has some commanding implementations that can be used. The easiest one to use is the Delegate command because we want to fire off a message on this ViewModel. In the constructor create a new SearchCommand that is a delegate command.Be cognisant that you have to pass in the type it will take (a search string in this case) and then point it to the method (the button click)

Now that the delegate command has been written, bind this method to the button, by adding binding in the XAML (again note that the commanding available in WPF is missing, but the Practices library has an implementation so include the namespace declaration at the top)

xmlns:Commands=”clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation”

Now add the binding to the search button

        <TextBox x:Name=”txtSearchTopic” Grid.Column=”1″ Padding=”1,3,1,1″ />     

        <Button Content=”Search” Style=”{StaticResource SearchButton}” Commands:Click.Command=”{Binding SearchCommand}” />

The SearchCommand binding is the one in the ViewModel that takes a search string as a parameter. In the XAML above you need to somehow pass whatever is entered in the TextBox into the command that is fired when the button is search button clicked. this is easily achieved in WPF but in Silverlight you can only bind to either the DataContext or static resources. To get this to work add a property called Title in the SearchViewModel, add and implement INotifyPropertyChanged as follows

Visual Basic

Imports Microsoft.Practices.Composite.Presentation.Commands

Imports System.ComponentModel

Public Class SearchViewModel

    Implements INotifyPropertyChanged

    Private _SearchCommand As ICommand

    Public Property SearchCommand() As ICommand

        Get

            Return _SearchCommand

        End Get

        Private Set(ByVal value As ICommand)

            _SearchCommand = value

        End Set

    End Property

    Public Sub New()

        Me.SearchCommand = New DelegateCommand(Of String)(AddressOf OnSearch)

    End Sub

    Private Sub OnSearch(ByVal title As String)

    End Sub

    Private _Title As String

    Public Property Title() As String

        Get

            Return Me._Title

        End Get

        Set(ByVal value As String)

            Me._Title = value

            OnPropertyChanged(“Title”)

        End Set

    End Property

#Region “INotifyPropertyChanged Members”

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

#End Region

#Region “INotifyPropertyChanged Members”

    Protected Sub OnPropertyChanged(ByVal propertyName As String)

        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))

    End Sub

#End Region

End Class

C#

using System.Windows.Input;

using Microsoft.Practices.Composite.Presentation.Commands;

using System.ComponentModel;

namespace NewsAggregator.Search

{

    public class SearchViewModel : INotifyPropertyChanged

    {

        public ICommand SearchCommand { get; private set; }

        public SearchViewModel()

        {

            this.SearchCommand = new DelegateCommand<string>(OnSearch);

        }

        private void OnSearch(string title)

        {

        }

        private string title;

        public string Title

        {

            get

            {

                return this.title;

            }

            set

            {

                this.title = value;

                OnPropertyChanged(“Title”);

            }

        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region INotifyPropertyChanged Members

        protected void OnPropertyChanged(string propertyName)

        {

            if (this.PropertyChanged != null)

            {

                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

        #endregion

    }

}

So a property has now been created that you can bind against. Add the following binding to the textbox, and ensure two way binding is used so all the changes are synchronised back into the model, and add the command parameter to the search button. the XAML in the SearchView should look like this

<UserControl x:Class=”NewsAggregator.Search.SearchView”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

   xmlns:Commands=”clr-namespace:Microsoft.Practices.Composite.Presentation.Commands;assembly=Microsoft.Practices.Composite.Presentation”>

    <UserControl.Resources>

        <Style x:Key=”TitleBorder” TargetType=”Border”>

            <Setter Property=”CornerRadius” Value=”10″/>

            <Setter Property=”Background” Value=”#FFDEDEDE”/>

            <Setter Property=”Margin” Value=”0,0,5,0″/>

            <Setter Property=”Grid.Column” Value=”0″/>

        </Style>

        <Style x:Key=”TitleText” TargetType=”TextBlock”>

            <Setter Property=”FontSize” Value=”16″/>

            <Setter Property=”Foreground” Value=”#FF14517B”/>

            <Setter Property=”Margin” Value=”10,3,0,0″/>

        </Style>

        <Style x:Key=”SearchButton” TargetType=”Button”>

            <Setter Property=”Grid.Column” Value=”2″/>

        </Style>

    </UserControl.Resources>

    <Grid>

        <Grid.ColumnDefinitions>

            <ColumnDefinition Width=”*”/>

            <ColumnDefinition Width=”200″/>

            <ColumnDefinition Width=”100″/>

        </Grid.ColumnDefinitions>

        <Grid.RowDefinitions>

            <RowDefinition/>

        </Grid.RowDefinitions>

        <Border Style=”{StaticResource TitleBorder}”>

            <TextBlock Text=”NEWS SEARCH “ Style=”{StaticResource TitleText}” />

        </Border>

        <TextBox x:Name=”txtSearchTopic” Grid.Column=”1″ Padding=”1,3,1,1″

                Text=”{Binding Path=Title, Mode=TwoWay}”/>

        <Button Content=”Search” Style=”{StaticResource SearchButton}”

               Commands:Click.Command=”{Binding SearchCommand}”

               Commands:Click.CommandParameter=”{Binding Path=Title}”/>

    </Grid>

</UserControl>

So what happens now is that when text is entered in the textbox it is synchronised back to the SearchViewModel and it is also bound to the search button.

Set the data context of the SearchView to the SearchViewModel

Visual Basic

Partial Public Class SearchView

    Inherits UserControl

    Public Sub New(ByVal viewModel As SearchViewModel)

        InitializeComponent()

        Me.DataContext = viewModel

    End Sub

End Class

C#

using System.Windows.Controls;

namespace NewsAggregator.Search

{

    public partial class SearchView : UserControl

    {

        public SearchView(SearchViewModel viewModel)

        {

            InitializeComponent();

            this.DataContext = viewModel;

        }

    }

}

Now ensure that this View shows up in the Region that has been created, by going to the SearchModule and using constructor injection again.

Visual Basic

Imports Microsoft.Practices.Composite.Modularity

Imports Microsoft.Practices.Composite.Regions

Public Class SearchModule

    Implements IModule

    Private _RegionManager As IRegionManager

    Public Sub New(ByVal regionManager As IRegionManager)

        Me._RegionManager = regionManager

    End Sub

    Public Sub Initialize() Implements Microsoft.Practices.Composite.Modularity.IModule.Initialize

        Me._RegionManager.RegisterViewWithRegion(“SearchRegion”, GetType(SearchView))

    End Sub

End Class

C#

using Microsoft.Practices.Composite.Modularity;

using Microsoft.Practices.Composite.Regions;

namespace NewsAggregator.Search

{

    public class SearchModule : IModule

    {

        private IRegionManager regionManager;

        public SearchModule(IRegionManager regionManager)

        {

            this.regionManager = regionManager;

        }

        #region IModule Members

        public void Initialize()

        {

            this.regionManager.RegisterViewWithRegion(“SearchRegion”, typeof(SearchView));

        }

        #endregion

    }

}

If you run the application you should find that the search module has been added

SearchModule

Decoupled Communication Mechanism

You will notice that the hard wired baseball query it still being used. To set up this decoupled communication two things are going to be required. In Prism there are quite a few ways that this can be achieved, but the EventAggregator will be used in this demo. This gives you access to a publish and subscribe mechanism where you can have multiple publishers for a topic and multiple subscribers as well.

Add a new Silverlight project (this is usually referred to as an infrastructure module) called NewsAggregator.Infrastructure and delete the default class1 that is added

Infrastructure

add references to the Patterns & Practices libraries

Libraries

add a class called SearchEvent that inherits from CompositePresentationEvent

Visual Basic

Imports Microsoft.Practices.Composite.Presentation.Events

Public Class SearchEvent

    Inherits CompositePresentationEvent(Of String)

End Class

C#

using Microsoft.Practices.Composite.Presentation.Events;

namespace NewsAggregator.Infrastructure

{

    public class SearchEvent : CompositePresentationEvent<string>

    {

    }

}

In the NewsAggregator.Search project, add a reference to the NewsAggregator.Infrastructure project

AddInfrastucture

in the constructor of the SearchViewModel add an event aggregator event to the constructor, and publish the “Title” in the OnSearch method

Visual Basic

Imports Microsoft.Practices.Composite.Presentation.Commands

Imports System.ComponentModel

Imports Microsoft.Practices.Composite.Events

Imports NewsAggregator.Infrastructure

Public Class SearchViewModel

    Implements INotifyPropertyChanged

    Private _SearchCommand As ICommand

    Public Property SearchCommand() As ICommand

        Get

            Return _SearchCommand

        End Get

        Private Set(ByVal value As ICommand)

            _SearchCommand = value

        End Set

    End Property

    Private _eventAggregator As IEventAggregator

    Public Sub New(ByVal eventAggregator As IEventAggregator)

        Me.SearchCommand = New DelegateCommand(Of String)(AddressOf OnSearch)

        Me._eventAggregator = eventAggregator

    End Sub

    Private Sub OnSearch(ByVal title As String)

        Me._eventAggregator.GetEvent(Of SearchEvent).Publish(title)

    End Sub

    Private _Title As String

    Public Property Title() As String

        Get

            Return Me._Title

        End Get

        Set(ByVal value As String)

            Me._Title = value

            OnPropertyChanged(“Title”)

        End Set

    End Property

#Region “INotifyPropertyChanged Members”

    Public Event PropertyChanged(ByVal sender As Object, ByVal e As System.ComponentModel.PropertyChangedEventArgs) Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged

#End Region

#Region “INotifyPropertyChanged Members”

    Protected Sub OnPropertyChanged(ByVal propertyName As String)

        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))

    End Sub

#End Region

End Class

C#

using System.Windows.Input;

using Microsoft.Practices.Composite.Presentation.Commands;

using System.ComponentModel;

using Microsoft.Practices.Composite.Events;

using NewsAggregator.Infrastructure;

namespace NewsAggregator.Search

{

    public class SearchViewModel : INotifyPropertyChanged

    {

        public ICommand SearchCommand { get; private set; }

        private IEventAggregator eventAggregator;

        public SearchViewModel(IEventAggregator eventAggregator)

        {

            this.SearchCommand = new DelegateCommand<string>(OnSearch);

            this.eventAggregator = eventAggregator;

        }

        private void OnSearch(string title)

        {

            this.eventAggregator.GetEvent<SearchEvent>().Publish(Title);

        }

        private string title;

        public string Title

        {

            get

            {

                return this.title;

            }

            set

            {

                this.title = value;

                OnPropertyChanged(“Title”);

            }

        }

        #region INotifyPropertyChanged Members

        public event PropertyChangedEventHandler PropertyChanged;

        #endregion

        #region INotifyPropertyChanged Members

        protected void OnPropertyChanged(string propertyName)

        {

            if (this.PropertyChanged != null)

            {

                this.PropertyChanged(this, new PropertyChangedEventArgs(propertyName));

            }

        }

        #endregion

    }

}

This is the first half of setting the event aggregation, now we need to configure the listening event.

Switch over to the NewsAggregator.Digg project and add a reference to the NewsAggregator.Infrastructure (in the same way you’ve just done this to the NewsAggregator.Search above)

In the DiggSearchResultsViewModel remove the previous dummy search data, and add an event aggregator event to the constructor, and subscribe to the the OnSearchEvent which is a local event just created to process the title.

 

Visual Basic

Imports System.Collections.ObjectModel

Imports Microsoft.Practices.Composite.Events

Imports NewsAggregator.Infrastructure

Public Class DiggSearchResultsViewModel

    Private _Stories As ObservableCollection(Of DiggStory)

    Private diggService As IDiggService

    Public Property Stories() As ObservableCollection(Of DiggStory)

        Get

            Return _Stories

        End Get

        Private Set(ByVal value As ObservableCollection(Of DiggStory))

            _Stories = value

        End Set

    End Property

    Public ReadOnly Property HeaderInfo() As String

        Get

            Return “Digg Search Results”

        End Get

    End Property

    Public Sub New(ByVal diggService As IDiggService, ByVal eventAggregator As IEventAggregator)

        Stories = New ObservableCollection(Of DiggStory)()

        Me.diggService = diggService

        eventAggregator.GetEvent(Of SearchEvent).Subscribe(AddressOf OnSearchEvent)

    End Sub

    Public Sub OnSearchEvent(ByVal title As String)

        Me.diggService.BeginSearch(title, AddressOf OnSearchComplete)

    End Sub

    Private Sub OnSearchComplete(ByVal newStories As IEnumerable(Of DiggStory))

        Me.Stories.Clear()

        For Each diggStory In newStories

            Me.Stories.Add(diggStory)

        Next

    End Sub

End Class

C#

using System.Collections.ObjectModel;

using System.Collections.Generic;

using Microsoft.Practices.Composite.Events;

using NewsAggregator.Infrastructure;

namespace NewsAggregator.Digg

{

    public class DiggSearchResultsViewModel

    {

        private IDiggService diggService;

        public DiggSearchResultsViewModel(IDiggService diggService, IEventAggregator eventAggregator)

        {

            Stories = new ObservableCollection<DiggStory>();

            this.diggService = diggService;

            eventAggregator.GetEvent<SearchEvent>().Subscribe(OnSearchEvent);

        }

        public void OnSearchEvent(string title)

        {

            this.diggService.BeginSearch(title, OnSearchComplete);

        }

        public string HeaderInfo

        {

            get { return “Digg Search Results”; }

        }

        private void OnSearchComplete(IEnumerable<DiggStory> newStories)

        {

            this.Stories.Clear();

            foreach (var diggStory in newStories)

            {

                this.Stories.Add(diggStory);

            }

        }

        public ObservableCollection<DiggStory> Stories

        {

            get;

            private set;

        }

    }

}

Important: Notice that the OnSearchEvent is a public method. This is because Prism does not keep a strong reference to that particular event, this help prevent problems with garbage collection, so it doesn’t prevent your ViewModel being garbage collected for example if the ViewModel is no longer in use. If you do chose to make this private you will need to remember to unsubscribe whenever your ViewModel is no longer in use.

If you run the application, and enter”baseball” you should find that the application can still search base. Try entering a “football” search and you should get football results

FootBallSearch

You should now be able to develop the Twitter client in exactly the same was and add that as a module to the module catalogue in the shell and have that just work.

The complete source code for the 4 part series is available here (Download the WPF Silverlight Prism Folder)

Building a Composite WPF and Silverlight Application with Prism – Part 3


Welcome to this four part series on building a WPF and Silverlight application with Prism. The previous parts are

Building a Composite WPF and Silverlight Application with Prism – Part 1

Building a Composite WPF and Silverlight Application with Prism – Part 2

In this third tutorial, we will create a Digg search view using the Model-View-View-Model (MVVM) pattern, create the Digg search service, and finally demonstrate how to use dependency injection to “inject” views into the View Models.

This tutorial is in both C# and Visual Basic, but when creating projects in Visual Studio, the images I may use may be C# templates for example, but you should be able to do exactly the same in Visual Basic and vica-versa. It avoids the repetition of posting two images with “Open C# Silverlight Application” and “Open Visual Basic Application”, when the Visual Studio templates are the same – bar the language. I will however, post code samples in both languages

Implementing the View using MVVM

The first thing to do is to separate the View from the View Model. We do this because

  1. View Models are far much more testable
  2. It works well with re-styling

Add another class called DiggSearchResultsViewModel. The View Model typically has all the properties that you want to bind to. Within this View Model we will have a DiggStory object, so add another class called DiggStory

Projects

In this DiggStory add the following properties

Visual Basic

Public Class DiggStory

    Public Class DiggStory

        Private _Id As Integer

        Public Property Id() As Integer

            Get

                Return _Id

            End Get

            Set(ByVal value As Integer)

                _Id = value

            End Set

        End Property

        Private _Title As String

        Public Property Title() As String

            Get

                Return _Title

            End Get

            Set(ByVal value As String)

                _Title = value

            End Set

        End Property

        Private _Description As String

        Public Property Description() As String

            Get

                Return _Description

            End Get

            Set(ByVal value As String)

                _Description = value

            End Set

        End Property

        Private _NumDiggs As Integer

        Public Property NumDiggs() As Integer

            Get

                Return _NumDiggs

            End Get

            Set(ByVal value As Integer)

                _NumDiggs = value

            End Set

        End Property

        Private _HrefLink As Uri

        Public Property HrefLink() As Uri

            Get

                Return _HrefLink

            End Get

            Set(ByVal value As Uri)

                _HrefLink = value

            End Set

        End Property

        Private _Thumbnail As String

        Public Property Thumbnail() As String

            Get

                Return _Thumbnail

            End Get

            Set(ByVal value As String)

                _Thumbnail = value

            End Set

        End Property

        Private _UserName As String

        Public Property UserName() As String

            Get

                Return _UserName

            End Get

            Set(ByVal value As String)

                _UserName = value

            End Set

        End Property

    End Class

End Class

C#

using System;

namespace NewsAggregator.Digg

{

    public class DiggStory

    {

        public int Id { get; set; }

        public string Title { get; set; }

        public string Description { get; set; }

        public int NumDiggs { get; set; }

        public Uri HrefLink { get; set; }

        public string Thumbnail { get; set; }

        public string UserName { get; set; }

    }

}

A list of these stories is now required, so in the DiggSearchResultsViewModel create the following collection, and add a dummy story in the constructor of the form (note we only need the title here). The ObvervableCollection provides a way to track changes make to the collection.

Visual Basic

Imports System.Collections.ObjectModel

Public Class DiggSearchResultsViewModel

    Public Sub New()

        Stories = New ObservableCollection(Of DiggStory)()

        Dim story As New DiggStory()

        story.Title = “I am here, Digg it”

        Stories.Add(story)

    End Sub

    Private _Stories As ObservableCollection(Of DiggStory)

    Public Property Stories() As ObservableCollection(Of DiggStory)

        Get

            Return _Stories

        End Get

        Private Set(ByVal value As ObservableCollection(Of DiggStory))

            _Stories = value

        End Set

    End Property

End Class

C#

using System.Collections.ObjectModel;

namespace NewsAggregator.Digg

{

    public class DiggSearchResultsViewModel

    {

        public DiggSearchResultsViewModel()

        {

            Stories = new ObservableCollection<DiggStory>();

            Stories.Add(new DiggStory(){Title = “I am here, Digg it”});

        }

        public ObservableCollection<DiggStory> Stories

        {

            get;

            private set;

        }

    }

}

Connecting the Model with the View Model

To connect these together we will use constructor injection again. In the DiggSearchResultsView controls constructor add the ViewModel and set the DataContext object of the control to the view model.

Visual Basic

Partial Public Class DiggSearchResultsView

    Inherits UserControl

    Public Sub New(ByVal viewModel As DiggSearchResultsViewModel)

        InitializeComponent()

        Me.DataContext = viewModel

    End Sub

End Class

C#

namespace NewsAggregator.Digg

{

    public partial class DiggSearchResultsView : UserControl

    {

        public DiggSearchResultsView(DiggSearchResultsViewModel viewModel)

        {

            InitializeComponent();

            this.DataContext = viewModel;

        }

    }

}

In the XAML for the control, delete the TextBlock with the message in it, and add a ListBox instead

<UserControl x:Class=”NewsAggregator.Digg.DiggSearchResultsView”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”&gt;

    <Grid x:Name=”LayoutRoot” Background=”White”>

        <ListBox Name=”storiesList” ItemsSource=”{Binding Stories}”></ListBox>

    </Grid>

</UserControl>

Click F5 to run the program and you should have the following

DiggStory

Add a DataTemplate to the ListBox to format the Stories (or story in this case). You will see that there is quite a bit of XAML, but most of it is to do with styling

<UserControl x:Class=”NewsAggregator.Digg.DiggSearchResultsView”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221; >

    <UserControl.Resources>

        <Style x:Key=”StoriesList” TargetType=”ListBox”>

            <Setter Property=”Margin” Value=”5″/>

            <Setter Property=”Grid.Row” Value=”1″/>

        </Style>

        <Style x:Key=”DiggPanel” TargetType=”StackPanel”>

            <Setter Property=”Margin” Value=”10″/>

            <Setter Property=”Width” Value=”55″/>

            <Setter Property=”Height” Value=”55″/>

            <Setter Property=”Background”>

                <Setter.Value>

                    <LinearGradientBrush EndPoint=”0.5,1″ StartPoint=”0.5,0″>

                        <GradientStop Color=”#FFFFF098″/>

                        <GradientStop Color=”#FFFFF9D4″ Offset=”1″/>

                    </LinearGradientBrush>

                </Setter.Value>

            </Setter>

        </Style>

        <Style x:Key=”NumDigsBlock” TargetType=”TextBlock”>

            <Setter Property=”HorizontalAlignment” Value=”Center”/>

            <Setter Property=”FontSize” Value=”18″/>

            <Setter Property=”FontWeight” Value=”Bold”/>

            <Setter Property=”Foreground” Value=”DarkSlateGray”/>

        </Style>

        <Style x:Key=”NumDigsSubBlock” TargetType=”TextBlock”>

            <Setter Property=”HorizontalAlignment” Value=”Center”/>

            <Setter Property=”FontSize” Value=”14″/>

            <Setter Property=”Foreground” Value=”DarkSlateGray”/>

        </Style>

        <Style x:Key=”ThumbNailPreview” TargetType=”Image”>

            <Setter Property=”Margin” Value=”7,7,5,5″/>

            <Setter Property=”Height” Value=”55″/>

        </Style>

        <Style x:Key=”TitleBlock” TargetType=”TextBlock”>

            <Setter Property=”FontSize” Value=”12″/>

            <Setter Property=”TextAlignment” Value=”Left”/>

            <Setter Property=”VerticalAlignment” Value=”Center”/>

        </Style>

    </UserControl.Resources>

    <Grid>

        <ListBox x:Name=”StoriesList” Style=”{StaticResource StoriesList}” ItemsSource=”{Binding Stories}”>

            <ListBox.ItemTemplate>

                <DataTemplate>

                    <StackPanel Orientation=”Horizontal”>

                        <!– Yellow Digg Panel with NumDiggs–>

                        <StackPanel Style=”{StaticResource DiggPanel}” >

                            <TextBlock Text=”{Binding NumDiggs}” Style=”{StaticResource NumDigsBlock}” />

                            <TextBlock Text=”diggs” Style=”{StaticResource NumDigsSubBlock}” />

                        </StackPanel>

                        <!– Story Thumbnail Preview –>

                        <Image Source=”{Binding ThumbNail}” Style=”{StaticResource ThumbNailPreview}” />

                        <!– Story Title–>

                        <TextBlock Text=”{Binding Title}” Margin=”5″ Style=”{StaticResource TitleBlock}”/>

                    </StackPanel>

                </DataTemplate>

            </ListBox.ItemTemplate>

        </ListBox>

    </Grid>

</UserControl>

If you F5 to run the program you should get

DiggClient

  Adding the Digg Service

First add an interface that will be a contract for the Digg service, call this IDiggService. This Interface will contain one method called BeginSearch that will do two things

  1. It will start the search using the query parameter
  2. It will provide a call-back mechanism for when the search is completed

This is because requests like web service calls in Silverlight must always be carried out asynchronously.

Visual Basic

Public Interface IDiggService

    Sub BeginSearch(ByVal query As String, ByVal SearchCompleteCallback As Action(Of IEnumerable(Of DiggStory)))

End Interface

C#

using System;

using System.Collections.Generic;

namespace NewsAggregator.Digg

{

    public interface IDiggService

    {

        void BeginSearch(string query, Action<IEnumerable<DiggStory>> SearchCompleteCallback);

    }

}

You can now either implement the Service or View, but I will start with the view first.

Implementing the View

In the constructor for the DiggSearchResultsViewModel add a reference to IDiggService. Here we will then perform a dummy query for “baseball”. When this query is complete it will return some stories (hopefully) pertaining to baseball. These then need to be added to a list in the OnSearchComplete method. The only thing you need to do to view the stories returned from the list is to add them to the Stories already defined.

Visual Basic

Imports System.Collections.ObjectModel

Public Class DiggSearchResultsViewModel

    Private _Stories As ObservableCollection(Of DiggStory)

    Private diggService As IDiggService

    Public Property Stories() As ObservableCollection(Of DiggStory)

        Get

            Return _Stories

        End Get

        Private Set(ByVal value As ObservableCollection(Of DiggStory))

            _Stories = value

        End Set

    End Property

    Public ReadOnly Property HeaderInfo() As String

        Get

            Return “Digg Search Results”

        End Get

    End Property

    Public Sub New(ByVal diggService As IDiggService)

        Stories = New ObservableCollection(Of DiggStory)()

        Dim dummyStory As New DiggStory()

        dummyStory.Title = “I am here, Digg it”

        Stories.Add(dummyStory)

        Me.diggService = diggService

        Me.diggService.BeginSearch(“baseball”, AddressOf OnSearchComplete)

    End Sub

    Private Sub OnSearchComplete(ByVal newStories As IEnumerable(Of DiggStory))

        Me.Stories.Clear()

        For Each diggStory In newStories

            Me.Stories.Add(diggStory)

        Next

    End Sub

End Class

C#

using System.Collections.ObjectModel;

using System.Collections.Generic;

namespace NewsAggregator.Digg

{

    public class DiggSearchResultsViewModel

    {

        private IDiggService diggService;

        public DiggSearchResultsViewModel(IDiggService diggService)

        {

            Stories = new ObservableCollection<DiggStory>();

            Stories.Add(new DiggStory(){Title = “I am here, Digg it”});

            this.diggService = diggService;

            this.diggService.BeginSearch(“baseball”, OnSearchComplete);

        }

        private void OnSearchComplete(IEnumerable<DiggStory> newStories)

        {

            this.Stories.Clear();

            foreach (var diggStory in newStories)

            {

                this.Stories.Add(diggStory);

            }

        }

        public ObservableCollection<DiggStory> Stories

        {

            get;

            private set;

        }

    }

}

Implementing the Service

In the Digg project add a reference to System.XML.Linq because I am calling a web service and am getting an XML document back (the RSS feed).

Add a new class called DiggService to the project that implements IDiggService

Visual Basic

Option Explicit On

Option Strict On

Imports System.Xml.Linq

Public Class DiggService

    Implements IDiggService

    Private searchCompleteCallback As Action(Of IEnumerable(Of DiggStory))

    Public Sub BeginSearch(ByVal query As String, ByVal SearchCompleteCallback As Action(Of IEnumerable(Of DiggStory))) Implements IDiggService.BeginSearch

        Me.searchCompleteCallback = SearchCompleteCallback

        ‘ Construct Digg REST URL

        Dim diggUrl As String = String.Format(http://services.digg.com/stories/topic/{0}?count=20&appkey=http%3A%2F%2Fscottgu.com”, query)

        ‘ Initiate Async Network call to Digg

        Dim diggService As New WebClient()

        AddHandler diggService.DownloadStringCompleted, AddressOf diggService_DownloadStringCompleted

        diggService.DownloadStringAsync(New Uri(diggUrl))

    End Sub

    Sub diggService_DownloadStringCompleted(ByVal sender As Object, ByVal e As DownloadStringCompletedEventArgs)

        searchCompleteCallback(BuildStories(e))

    End Sub

    Private Function BuildStories(ByVal e As DownloadStringCompletedEventArgs) As IEnumerable(Of DiggStory)

        If e.[Error] IsNot Nothing Then

            Return New List(Of DiggStory)(New DiggStory() {New DiggStory() With {.Title = e.[Error].Message}})

        End If

        Dim xmlStories As XDocument = XDocument.Parse(e.Result)

        Dim stories = From story In xmlStories.Descendants(“story”) _

                        Where story.Element(“thumbnail”) IsNot Nothing AndAlso _

                              Not story.<thumbnail>.Value.EndsWith(“.gif”) _

                        Select New DiggStory() With _

                        { _

                            .Id = CInt(story.@id), _

                            .Title = story.<title>.Value.Trim(), _

                            .Description = story.<description>.Value.Trim(), _

                            .ThumbNail = story.<thumbnail>.@src, _

                            .HrefLink = New Uri(story.@link), _

                            .NumDiggs = CInt(story.@diggs), _

                            .UserName = story.<user>.Value.Trim() _

                        }

        Return stories

    End Function

End Class

C#

using System;

using System.Net;

using System.Xml.Linq;

using System.Collections.Generic;

using System.Linq;

namespace NewsAggregator.Digg

{

    public class DiggService : IDiggService

    {

        public void BeginSearch(string query, Action<IEnumerable<DiggStory>> SearchCompleteCallback)

        {

            // Construct Digg REST URL

            string diggUrl = String.Format(http://services.digg.com/stories/topic/{0}?count=20&appkey=http%3A%2F%2Fscottgu.com”, query);

            // Initiate Async Network call to Digg

            WebClient diggService = new WebClient();

            diggService.DownloadStringCompleted += (sender, e) => SearchCompleteCallback(BuildStories(e));

            diggService.DownloadStringAsync(new Uri(diggUrl));

        }

        private IEnumerable<DiggStory> BuildStories(DownloadStringCompletedEventArgs e)

        {

            if (e.Error != null)

            {

                return new List<DiggStory> { new DiggStory() { Title = e.Error.Message } };

            }

            XDocument xmlStories = XDocument.Parse(e.Result);

            var stories = from story in xmlStories.Descendants(“story”)

                          where story.Element(“thumbnail”) != null &&

                                !story.Element(“thumbnail”).Attribute(“src”).Value.EndsWith(“.gif”)

                          select new DiggStory

                          {

                              Id = (int)story.Attribute(“id”),

                              Title = ((string)story.Element(“title”)).Trim(),

                              Description = ((string)story.Element(“description”)).Trim(),

                              ThumbNail = (string)story.Element(“thumbnail”).Attribute(“src”).Value,

                              HrefLink = new Uri((string)story.Attribute(“link”)),

                              NumDiggs = (int)story.Attribute(“diggs”),

                              UserName = (string)story.Element(“user”).Attribute(“name”).Value,

                          };

            return stories;

        }

    }

}

In the DiggModule register this search query in the UnityContainer. To acheive this, create a private IUnityContainer variable called container and add this to the constructor. You can then register this in the Initialize method. The ContainerControlledLifetimeManager class just indicates that the service should be a Singleton.

Visual Basic

Imports Microsoft.Practices.Composite.Modularity

Imports Microsoft.Practices.Composite.Regions

Imports Microsoft.Practices.Unity

Public Class DiggModule

    Implements IModule

    Private regionManager As IRegionManager

    Private container As IUnityContainer

    Public Sub New(ByVal regionManager As IRegionManager, ByVal container As IUnityContainer)

        Me.regionManager = regionManager

        Me.container = container

    End Sub

    Public Sub Initialize() Implements Microsoft.Practices.Composite.Modularity.IModule.Initialize

        Me.container.RegisterType(Of IDiggService, DiggService)(New ContainerControlledLifetimeManager())

        Me.regionManager.RegisterViewWithRegion(“ResultsRegion”, GetType(DiggSearchResultsView))

    End Sub

End Class

C#

using Microsoft.Practices.Composite.Modularity;

using Microsoft.Practices.Composite.Regions;

using Microsoft.Practices.Unity;

namespace NewsAggregator.Digg

{

    public class DiggModule : IModule

    {

        private IRegionManager regionManager;

        private IUnityContainer container;

        public DiggModule(IRegionManager regionManager, IUnityContainer container)

        {

            this.regionManager = regionManager;

            this.container = container;

        }

        #region IModule Members

        public void Initialize()

        {

            this.container.RegisterType<IDiggService, DiggService>(new ContainerControlledLifetimeManager());

            this.regionManager.RegisterViewWithRegion(“ResultsRegion”, typeof(DiggSearchResultsView));

        }

        #endregion

    }

}

If you run the project you should a view with live data

ConnectedToService

If you look carefully at the tab at the top of the shell you will see that there is not title for the shell so a way is needed to communicate title or header information back to the Shell

Header Information

There is a convention to follow when providing this information, and that is for the View Model to provide this information to the Shell Owner can look for this information. Add a new Property into the DiggSearchResultsViewModel called HeaderInfo.

Visual Basic

Imports System.Collections.ObjectModel

Public Class DiggSearchResultsViewModel

    Private _Stories As ObservableCollection(Of DiggStory)

    Private diggService As IDiggService

    Public Property Stories() As ObservableCollection(Of DiggStory)

        Get

            Return _Stories

        End Get

        Private Set(ByVal value As ObservableCollection(Of DiggStory))

            _Stories = value

        End Set

    End Property

    Public ReadOnly Property HeaderInfo() As String

        Get

            Return “Digg Search Results”

        End Get

    End Property

    Public Sub New(ByVal diggService As IDiggService)

        Stories = New ObservableCollection(Of DiggStory)()

        Dim story As New DiggStory()

        story.Title = “I am here, Digg it”

        Stories.Add(story)

        Me.diggService = diggService

        Me.diggService.BeginSearch(“baseball”, AddressOf OnSearchComplete)

    End Sub

    Private Sub OnSearchComplete(ByVal newStories As IEnumerable(Of DiggStory))

        Me.Stories.Clear()

        For Each diggStory In newStories

            Me.Stories.Add(diggStory)

        Next

    End Sub

End Class

C#

using System.Collections.ObjectModel;

using System.Collections.Generic;

namespace NewsAggregator.Digg

{

    public class DiggSearchResultsViewModel

    {

        private IDiggService diggService;

        public DiggSearchResultsViewModel(IDiggService diggService)

        {

            Stories = new ObservableCollection<DiggStory>();

            Stories.Add(new DiggStory(){Title = “I am here, Digg it”});

            this.diggService = diggService;

            this.diggService.BeginSearch(“baseball”, OnSearchComplete);

        }

        public string HeaderInfo

        {

            get { return “Digg Search Results”; }

        }

        private void OnSearchComplete(IEnumerable<DiggStory> newStories)

        {

            this.Stories.Clear();

            foreach (var diggStory in newStories)

            {

                this.Stories.Add(diggStory);

            }

        }

        public ObservableCollection<DiggStory> Stories

        {

            get;

            private set;

        }

    }

}

Open up the Shell.xaml and add the following markup in the tab regions section. Note in WPF this tab property is available to databind to directly, but this is not available in Silverlight.

<UserControl xmlns:basics=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls” x:Class=”NewsAggregator.Shell.Shell”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

      xmlns:Regions=”clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation”>

    <UserControl.Resources>

        <Style x:Key=”TopGrid” TargetType=”Grid”>

            <Setter Property=”Background” Value=”#FF5C7590″ />

        </Style>

    </UserControl.Resources>

    <Grid Style=”{StaticResource TopGrid}”>

        <Grid.RowDefinitions>

            <RowDefinition Height=”auto”/>

            <RowDefinition Height=”*”/>

        </Grid.RowDefinitions>

        <ContentControl Regions:RegionManager.RegionName=”SearchRegion” Grid.Row=”0″ Margin=”2″ />

        <basics:TabControl Regions:RegionManager.RegionName=”ResultsRegion” Grid.Row=”1″ Margin=”3″>

            <Regions:TabControlRegionAdapter.ItemContainerStyle>

                <Style TargetType=”basics:TabItem”>

                    <Setter Property=”HeaderTemplate”>

                        <Setter.Value>

                            <DataTemplate>

                                <TextBlock Text=”{Binding HeaderInfo}” />

                            </DataTemplate>

                        </Setter.Value>

                    </Setter>

                </Style>

            </Regions:TabControlRegionAdapter.ItemContainerStyle>

        </basics:TabControl>

    </Grid>

</UserControl>

If you run the program you should have

SearchResults

That wraps up this penultimate tutorial, in the fourth and final tutorial we will add a searchbox, and show how this can be added in a decoupled fashion.

The complete source code for the 4 part series is available here (Download the WPF Silverlight Prism Folder)

Building a Composite WPF and Silverlight Application with Prism – Part 2


In Building a Composite WPF and Silverlight Application with Prism – Part 1 I laid down the foundations of the composite application including

  • Configuring and connecting to Prism
  • Creating a Shell for the Silverlight application
  • Connecting that Shell using a Bootrapper class
  • Adding a Digg module and adding it to the ModuleCatalog

In this second tutorial in the series we will further develop the DiggModule by adding a View, what should be clear is that this architecture is applicable for your own custom application development needs. Prism ostensibly demonstrates the true power of WPF and Silverlight, in that it is a framework that can target both web and smart client applications, using the same modules and code.

This tutorial is in both C# and Visual Basic, but when creating projects in Visual Studio, the images I may use may be C# templates for example, but you should be able to do exactly the same in Visual Basic and vica-versa. It avoids the repetition of posting two images with “Open C# Silverlight Application” and “Open Visual Basic Application”, when the Visual Studio templates are the same – bar the language. I will however, post code samples in both languages

Open Shell.xaml and you should have the following standard XAML code

<UserControl x:Class=”NewsAggregator.Shell.Shell”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

   Width=”400″ Height=”300″>

    <Grid x:Name=”LayoutRoot” Background=”White”>

    </Grid>

</UserControl>

To restyle the shell, add the following markup

<UserControl xmlns:basics=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls” x:Class=”NewsAggregator.Shell.Shell”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

            Width=”300″ Height=”400″>

    <UserControl.Resources>

        <Style x:Key=”TopGrid” TargetType=”Grid”>

            <Setter Property=”Background” Value=”#FF5C7590″ />

        </Style>

    </UserControl.Resources>

    <Grid Style=”{StaticResource TopGrid}”>

        <Grid.RowDefinitions>

            <RowDefinition Height=”auto”/>

            <RowDefinition Height=”*”/>

        </Grid.RowDefinitions>   

    </Grid>

</UserControl>

Here the background colour is set, and a couple of grid rows are added. Now add a ContentControl whose purpose is to be a container for other controls. We will be adding a twitter client as well later on, so a tab control (you can drag it from the toolbox) is needed to switch between the Digg service and the Twitter on. Both controls are assigned to grid rows. Add the following below the end Grid.RowDefinitions tag

        <ContentControl Grid.Row=”0″ Margin=”2″ />

        <basics:TabControl Grid.Row=”1″ Margin=”3″/>

The following controls will act as containers, that any module can insert a view into i.e. The DiggModule and TwitterModule need to be added so these controls can show them. One approach, is for each module to communicate with the Shell directly, and know which control it needs to push things into, but that is tightly coupling the module to the shell.

Prism has a feature called a Region (you can think of a “Region” as a named place holder for where Views are going to be placed), and Modules can find that region by name, and push things into them. to access this in your XAML, you need to declare this namespace at the top

   xmlns:Regions=”clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation”

Which will allow you to add a Region to a control. In the following markup I have added a SearchRegion and a ResultsRegion so when the Shell is loaded Prism will find these regions and register them in a way that the modules will be able to find them. The following the the complete markup you should have in Shell.xaml

<UserControl xmlns:basics=”clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls” x:Class=”NewsAggregator.Shell.Shell”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml&#8221;

    xmlns:Regions=”clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation”>

    <UserControl.Resources>

        <Style x:Key=”TopGrid” TargetType=”Grid”>

            <Setter Property=”Background” Value=”#FF5C7590″ />

        </Style>

    </UserControl.Resources>

    <Grid Style=”{StaticResource TopGrid}”>

        <Grid.RowDefinitions>

            <RowDefinition Height=”auto”/>

            <RowDefinition Height=”*”/>

        </Grid.RowDefinitions>

        <ContentControl Regions:RegionManager.RegionName=”SearchRegion” Grid.Row=”0″ Margin=”2″ />

        <basics:TabControl Regions:RegionManager.RegionName=”ResultsRegion” Grid.Row=”1″ Margin=”3″>

        </basics:TabControl>

    </Grid>

</UserControl>

Now that some regions are available, create a View in the Digg module. to do this add a new Silverlight User Control called DiggSearchResultsView.xaml

DiggSearch

Add a textblock with some text in it (this is so it can be view in the shell) and delete the Width and Height properties

<UserControl x:Class=”NewsAggregator.Digg.DiggSearchResultsView”

   xmlns=”http://schemas.microsoft.com/winfx/2006/xaml/presentation&#8221;

   xmlns:x=”http://schemas.microsoft.com/winfx/2006/xaml”&gt;

    <Grid x:Name=”LayoutRoot” Background=”White”>

        <TextBlock>“Hello, I am here, Digg it””</TextBlock>

    </Grid>

</UserControl>

You should have

Hello

Now that this basic View is completed it now needs to be added to a Region. There are several ways to do this, including View Discovery or View Injection.

View Discovery

To get a hold of regions in Prism you need access to the Region Manager Service, and the easiest was to access it, is via it being injected in the constructor. In the DiggModule, add a constructor, and then add a IRegionManager to this. In the Initialize method, you can then indicate to the Region Manager, the name and type of View you wish to pass.

Visual Basic

Imports Microsoft.Practices.Composite.Modularity

Imports Microsoft.Practices.Composite.Regions

    Public Class DiggModule

        Implements IModule

        Private regionManager As IRegionManager

        Public Sub New(ByVal regionManager As IRegionManager)

            Me.regionManager = regionManager

        End Sub

    Public Sub Initialize() Implements Microsoft.Practices.Composite.Modularity.IModule.Initialize

        Me.regionManager.RegisterViewWithRegion(“ResultsRegion”, GetType(DiggSearchResultsView))

    End Sub

    End Class

 

C#

using Microsoft.Practices.Composite.Modularity;

using Microsoft.Practices.Composite.Regions;

namespace NewsAggregator.Digg

{

    public class DiggModule : IModule

    {

        private IRegionManager regionManager;

        public DiggModule(IRegionManager regionManager)

        {

            this.regionManager = regionManager;

        }

        #region IModule Members

        public void Initialize()

        {

            this.regionManager.RegisterViewWithRegion(“ResultsRegion”, typeof(DiggSearchResultsView));

        }

        #endregion

    }

}

If you run the program you should have the following

InternetExplorer

As you can see the view has shown up in the Region.

That wraps up this second tutorial. In the third tutorial, we will start to interact with data, and demonstrate the Model View View Model (MVVM) design pattern.

The complete source code for the 4 part series is available here (Download the WPF Silverlight Prism Folder)

Building a Composite WPF and Silverlight Application with Prism – Part 1


In this four part series based on Microsoft Patterns and Practices guidance, I am going to build a Composite Silverlight application using Prism. This tutorial is in both C# and Visual Basic, but when creating projects in Visual Studio, the images I may use may be C# templates for example, but you should be able to do exactly the same in Visual Basic and vica-versa. It avoids the repetition of posting two images with “Open C# Silverlight Application” and “Open Visual Basic Application”, when the Visual Studio templates are the same – bar the language. I will however, post code samples in both languages

Configuration

You will need the Silverlight development tools, and the Prism Libraries. For additional configuration information you can use the codeplex site.In the project you will need to reference the Prism Libraries, I downloaded the CompositeApplicationGuidance-Feb2009.exe from the link above, and extracted the files into a folder. You should now have the following files

Installation

Take the time to read the “Readme.txt”. You will also need to open the “Open Composite Application Library.bat” and build that project in Visual Studio. It is only after building the solution, that the requisite libraries become available in CompositeApplicationGuidance-Feb2009CALSilverlightComposite.UnityExtensionsBinDebug.

CAB Silverlight Demo

Create a new Silverlight application and call the Solution NewsAggregator and the project NewsAggregator.Shell

Shell

Create an ASP.NET Web Project

Website

In the Shell Project, delete the page.xaml and add the shell right clicking the project in solution explorer and choose Add a new item

AddUserControl

Add a Silverlight User Control  and call this Shell.xaml

ProperShell

Now you need to connect this application to Prism, and you do this typically using the “Bootstrapper”. To do this, create a new class called Bootstrapper and add it to the project, and inherit from UnityBootstrapper. UnityBootstrapper is available in the Prism libraries your require, so you will need to add references to them.

In C# right click the add a reference node and chose Add Reference

In Visual Basic double click your MyProject node in solution explorer and navigate to the references tab, and choose Add Reference. You should then navigate to the folder with the libraries (see configuration section above) and add the following five libraries

RequisiteLibraries

There are two things required by the bootstrapper, one of them is the Shell and the other is the ModuleCatalog

Visual Basic

Imports Microsoft.Practices.Composite.UnityExtensions

Imports Microsoft.Practices.Composite.Modularity

Public Class Bootstrapper

    Inherits UnityBootstrapper

    Protected Overrides Function CreateShell() As System.Windows.DependencyObject

        Return New Shell

    End Function

    Protected Overrides Function GetModuleCatalog() As Microsoft.Practices.Composite.Modularity.IModuleCatalog

        Return New ModuleCatalog

    End Function

End Class

C#

using System.Windows;

using Microsoft.Practices.Composite.UnityExtensions;

using Microsoft.Practices.Composite.Modularity;

namespace NewsAggregator.Shell

{

    public class Bootstrapper : UnityBootstrapper

    {

        protected override DependencyObject CreateShell()

        {

            return new Shell();

        }

        protected override Microsoft.Practices.Composite.Modularity.IModuleCatalog GetModuleCatalog()

        {

            return new ModuleCatalog();

        }

    }

}

For Silverlight applications you need to set the RootVisual, which is the starting control for a Silverlight application.

Visual Basic

    Protected Overrides Function CreateShell() As System.Windows.DependencyObject

        Dim shell As New Shell

        Application.Current.RootVisual = shell

        Return shell

    End Function

C#

       protected override DependencyObject CreateShell()

        {

            Shell shell = new Shell();

            Application.Current.RootVisual = shell;

            return shell;

        }

You then need to connect the Bootstrapper to the application, to do this, double click the App.xaml.cs or App.xaml.vb depending on your language and set the RootVisual in the Application Startup method thus

Visual Basic

    Private Sub Application_Startup(ByVal o As Object, ByVal e As StartupEventArgs) Handles Me.Startup

        Dim bootstrapper As New Bootstrapper

        bootstrapper.Run()

    End Sub

C#

      private void Application_Startup(object sender, StartupEventArgs e)

        {

            new Bootstrapper().Run();

        }

This will connect the application to Prism. Now everything is in place, we now can add a new module. Add a new Silverlight Class Library and call it NewsAggregator.Digg

DiggModule

Delete the default class1 that is added, and add references to the five Prism libraries (same libraries added to bootstrapper above).

add a new class to this project, and call it DiggModule and ensure it implements IModule

Visual Basic

Imports Microsoft.Practices.Composite.Modularity

Public Class DiggModule

    Implements IModule

    Public Sub Initialize() Implements Microsoft.Practices.Composite.Modularity.IModule.Initialize

    End Sub

End Class

C#

using Microsoft.Practices.Composite.Modularity;

namespace NewsAggregator.Digg

{

    public class DiggModule : IModule

    {

        #region IModule Members

        public void Initialize()

        {

            //throw new NotImplementedException();

        }

        #endregion

    }

}

Now that the module has been created, it needs to be added to the catalogue. This catalogue was created in the Bootstrapper, but that was just an empty catalogue. In the Shell project, add a reference to the Digg project, and set the method in the Bootstrapper

Visual Basic

    Protected Overrides Function GetModuleCatalog() As Microsoft.Practices.Composite.Modularity.IModuleCatalog

        Dim catalog As New ModuleCatalog

        catalog.AddModule(GetType(DiggModule))

        Return catalog

    End Function

C#

   protected override Microsoft.Practices.Composite.Modularity.IModuleCatalog GetModuleCatalog()

        {

            ModuleCatalog catalog = new ModuleCatalog();

            catalog.AddModule(typeof(DiggModule));

            return catalog;

        }

If you run the project you will get a message box asking if you want to enable debugging

Debugging

click OK, but remember that this option must be set to false in production websites, and you now have an empty project that has loaded the Digg module

EmptyProject

In lesson two we will focus on visual composition.

The complete source code for the 4 part series is available here (Download the WPF Silverlight Prism Folder)

WPF resource dictionaries


logo_big_web

One of the true powers of WPF is the ability to style or template all the controls you have in your application. In windows forms, this is obscenely difficult, and very time consuming.

For a Winforms application I have worked on, I elected the  free Krypton Toolkit. This is by far and away the best toolkit available, because it is intuitive and very easy to use. As time has passed more and more controls have been added to the free toolkit, but as is always the case, one always wants something that is not available, that ends up being on a ‘wishlist’.

This has always been the way with third party independent software vendors, where users request their most needed components. A good look at some third party Windows Presentation Foundation resource dictionaries from reuxables leaves one nothing short of gobsmacked! In Windows forms or Microsoft Foundation Classes it would have taken a very long time to achieve these designs (in C# or C++ code), yet a single individual has been able to create such jaw-dropping designs.

Presently, an area I’m not too happy about in WPF, is the structuring of the resource dictionaries, as it is liable to become very messy very quickly. Nikhil Kothari has run into this issue with Silverlight and I presume it will be remedied by the time .NET 4.0. is released.

Nevertheless, once you have the basics of WPF underneath your belt, it is possible to create applications of unprecedented quality and beauty with considerably less effort than years of yore. I literally want to ditch the winforms application I’m working on at present. That just how exciting WPF is to me now.

Free Silverlight DataGrids


One of the key controls in most applications is a datagrid. In smart client applications, you have always faced restrictions and difficulty when wanting to present data in a less ‘list style’ (using standard controls). Think of an employee table, with an image of the employee (see DevExpress example beneath).

There are commercial versions that improve things significantly, but they come at the expense of either taking a month or so out to figure how to use the control efficaciously or paying a developer to do this for you. Plus the expense of the suite of course, which usually appears vastly overpriced, but it takes genius and time to create these features with C/C++ or .NET and Windows Forms, hence the hefty price tag.

WPF and Silverlight offer  the ability to style and template controls, pretty much however you like. ASP.NET has several controls that handle this scenario in Visual Studio.

VSData

If you’re in Windows Forms you’re limited to the inflexible DataGridView or third party controls. If you are in ASP.NET and don’t know of Matt Berseth’s blog you need to correct this alarming lack of good education and check it (blog) out. There are some peaches and absolute nuggets euphemistically speaking. Matt has some technically accomplished posts, and pretty much everything he writes about is excellent. I cannot stress enough the kind of hoops you’d need to jump through to create a datagrid that looked and functioned like the super-duper listview control in ASP.NET and Matt’s example.

Scott Morrison is the new program manager for the Silverlight datagrid, and has some introductory tutorials on using this ubiquitous control. I can’t help thinking that if Microsoft had got this right with WPF and had the same availability of controls for WPF, uptake would have been far swifter. Nevertheless, we are where we are now, and some great features are already being added.

DevExpress have also announced a free datagrid that is beautiful. You can view an online demo here.

Speaking as a not quite ‘hardened’ Windows Forms developer, the sooner performance issues are sorted in WPF/Silverlight in the forthcoming Visual Studio 2008 and .NET 3.5 service pack, one begins to find it increasingly difficult, latching onto previous technologies, for the sake of reasons I have hitherto promulgated in this blog (check the windows forms category).