Getting Ramped for Silverlight 4

Here is a quick walk through of setting up your Silverlight 4 development environment.  The first assumed step is that you have Visual Studio 2010 already installed and any appropriate patches.  Then download the following in order and install each.

Once each of these are installed jump into Visual Studio 2010.  Start a new Silverlight 4 Project by going to File -> New -> Project -> and select the Silverlight Project Templates.  Here you’ll see a new list of projects that are specific to the above listed downloads.

  • Silverlight Business Application
  • WCF RIA Service Class Library
  • Silverlight Unit Test Application

One way to confirm (and what I am going to display here in this entry) Silverlight 4 is installed ok is to select the Silverlight Application Template and start a new project.

On the next screen you will see some of the standard options.  I always go with the ASP.NET MVC Option and with these new installations I am going to select Silverlight 4 (should be selected already) from the drop down and check the Enable WCF RIA Services check box.

I also, for good measure, always create a unit test project for the ASP.NET MVC Project that will host the Silverlight Application Project.  When all is setup, the Solutions Explorer should look like what is shown below.

Add the following code to the XAML of the MainPage.xaml of the Silverlight Project.

[sourcecode language="html"]
<UserControl x:Class="Silverlight4.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400">
    <Grid x:Name="LayoutRoot" Background="White">
        <TextBlock x:Name="textBlockTest" Text="Hello World!" />
    </Grid>
</UserControl>
[/sourcecode]

Now execute the project, if all runs well you have installed Silverlight 4 successfully.

Bam!  Silverlight 4 ready to go!  I will have more on Silverlight 4 very soon, as I will be starting a project (personal) and blogging it as I work through it.  Also, if you run into any issues I would like to read about them, so please comment.  I had a few issues and also had some design time rendering issues in the VS 2010 IDE when I installed these bits at first.

HighBall Part Duex (#4) Patterns

Navigation of Highball Series Part #1 | Part #2 | Part #3 | Part #4

Here in part #4 I want to cover the final wire up I did to get the initial screens to show.  The other primary focus of this blog entry is to cover some of the architectural patterns behind what I have so far.  We haven’t touched upon testing this yet, primarily because I’m stepping through wiring both Silverlight & WPF with these libraries for the first time.  I’ve done the WPF before, but not both.  Soon enough, I’ll get back to good standard practice and get some tests done first.  But for now, here’s the low down on wiring up Silverlight and the architectural patterns so far.

Architectural Patterns & Ideas

Dependency Injection

This is one of interesting parts of the application, at least to me.  For many the dependency injection is endlessly confusing, but it comes in immensely helpful in getting things loosely coupled and all wired up.  Because even when you decouple things, they do have to get wired up again – it’s just the how that’s important.  Below is an example of a presenter in the schedule module that uses constructor based dependency injection.  Dig it?  I’ll have another follow up entry in the future about what and how Dependency Injection works, along with the respective Dependency Inversion, Inversion of Control, and all those other patterns.  For now, just now that this is how the view gets registered with the region that is responsible for displaying it when the application runs.

[sourcecode language=”csharp”]
public class ScheduleViewAllPresenter : IModule
{
private readonly IRegionViewRegistry regionViewRegistry;

public ScheduleViewAllPresenter(IRegionViewRegistry registry)
{
regionViewRegistry = registry;
}

public void Initialize()
{
regionViewRegistry.RegisterViewWithRegion("HighBallMainRegion", typeof(ScheduleViewAllView));
}
}
[/sourcecode]

In the code snippet above you’ll see in the initialize method that the view that is injected is registered to the particular region that it will be displayed in.  In the shell the view will be displayed in the region as shown below.

[sourcecode language=”xml”]

[/sourcecode]

Composite Modules

I’ve added a single module to the solution so far.  This module has two views & their respective presenters, which I’ll cover in the section below.  The module is simply a project, loosely coupled, that will provide a view and the presentation logic for that view to be injected into the shell upon some application logic.

The module itself isn’t so much a pattern but more an architectural piece of the application.  As I move forward on this project I’ll add more modules to the solution as functionality is needed.  Each module will have an isolated, or mostly isolated, business use.  The first example that I have is the HighBall.Interface.Modules.ScheduleModule.  I’ll be adding more, probably along these lines;  mileage tracking, vehicle inventory, driver check-in, driver route choice, etc.  Each having a particular part of functionality that will primarily be isolated to itself.

When the CAL is used within a development team the modules would most likely be split off to individual pairs in the case of Agile, or even entire teams.  In Agile parlance each module would be a number of user stories, or in the most simple form, a single user story.

View & Presenter, with no Model yet.

The view and presenter are where you get to see the Model View Presenter (MVP) first start to appear.  Eventually as I move forward there will be the model, and more elaboration on the view and presenter.  For now all we have is the view, which is just the xaml markup and the presenter which is responsible for registering the view in the registry, and initializing the view with a region that it would be displayed in.  As you can see above in the Dependency Injection example the presenter is very thin at this point.

So that summarizes the cut off point for my first basic release of HighBall.  Check out the code release, rant at me about deficiencies, and if you have any additional ideas or other elaborations you’d like to see please do comment.

Currently I’m researching how to put TDD into effect to build the presenters, views, and other composite pieces of this application.  My next entry will have several examples of unit tests that aren’t currently included in this release.  Until then, happy hacking (or coding).

HighBall Part Duex (#3) Wiring Up Silverlight

Navigation of Highball Series Part #1 | Part #2 | Part #3 | Part #4

In this part I’ll be covering wiring up Silverlight with an appropriate module similarly to what part #1 and part #2 covered for WPF.  What I want to show in this entry is basically the differences of each module and the difference in the startup shell.  The differences are however very minimal, which leaves me curious about abstracting some of this and removing the code duplication, or maybe I should say xaml duplication.

One of the things I did after the first two parts of this series is to add some more projects that I would need once wired up and ready to continue with other parts of the project.  First I added the respective test projects, the other Silverlight Module projects etc.

This brings me to one of the differences between the WPF and Silverlight Interfaces.  For the modules that will be used in the Silverlight Project you?ll need to add Silverlight Class Library Project as shown to the left.  The Silverlight Class Library Template adds various assemblies and other references that are needed for these modules to be used in Silverlight Applications.

At this time I added a project to match each of the WPF Modules I had added previously.  I created four, then basically created the exact same presenters and views for the Silverlight Module.  After all of this I ended up with the following solution explorer view ? check the image to the right.

The second differences is in the shells and boot strappers.

In the WPF application the shell has the following simple code to kick off of the shell.  I used ReSharper to remove the unnecessary assemblies and other references.

[sourcecode language=”csharp”]
using System.Windows;

namespace HighBall.Interface.Wpf
{
public partial class App : Application
{
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
var bootstrapper = new HighBallBootStrapper();
bootstrapper.Run();
}
}
}
[/sourcecode]

What I ended up with was simple an OnStartup method overriding the Application Class method.  In this method is simply the base class call, instantiation, and the Run method to kick off the boot strapper.  This is very different then the slew of code needed for the Silverlight application bootstrapper startup.  Now keep in mind that most of this code is generated when you create the Silverlight Application.

[sourcecode language=”csharp”]
using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Browser;

namespace HighBall.Interface.Silverlight
{
public partial class App : Application
{
public App()
{
Startup += Application_Startup;
Exit += Application_Exit;
UnhandledException += Application_UnhandledException;

InitializeComponent();
}

private void Application_Startup(object sender, StartupEventArgs e)
{
var bootstrapper = new HighBallBootStrapper();
bootstrapper.Run();
}

private void Application_Exit(object sender, EventArgs e)
{
}

private void Application_UnhandledException(object sender, ApplicationUnhandledExceptionEventArgs e)
{
if (!Debugger.IsAttached)
{
e.Handled = true;
Deployment.Current.Dispatcher.BeginInvoke(delegate { ReportErrorToDOM(e); });
}
}

private void ReportErrorToDOM(ApplicationUnhandledExceptionEventArgs e)
{
try
{
string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;
errorMsg = errorMsg.Replace(‘"’, ‘\”).Replace("\r\n", @"\n");

HtmlPage.Window.Eval("throw new Error(\"Unhandled Error in Silverlight 2 Application " + errorMsg +
"\");");
}
catch (Exception)
{
}
}
}
}
[/sourcecode]

The only method that is really altered is the Application_Startup method.  Simply instantiate the boot strapper and call run.

Now that we have that take a look at the boot strappers themselves.  They each have some respective differences.  The WPF bootstrapper looks like this:

[sourcecode language=”csharp”]
using System.Windows;
using HighBall.Interface.Modules.Schedule;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.UnityExtensions;

namespace HighBall.Interface.Wpf
{
internal class HighBallBootStrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
var shell = new HighBallShell();
return shell;
}

protected override IModuleCatalog GetModuleCatalog()
{
var catalog = new ModuleCatalog();
catalog.AddModule(typeof(ScheduleAddPresenter));
return catalog;
}
}
}
[/sourcecode]

The Silverlight bootstrapper is below:

[sourcecode language=”csharp”]
using System.Windows;
using HighBall.Interface.Modules.Schedule.Silverlight;
using Microsoft.Practices.Composite.Modularity;
using Microsoft.Practices.Composite.UnityExtensions;

namespace HighBall.Interface.Silverlight
{
public class HighBallBootStrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
var shell = Container.Resolve();
Application.Current.RootVisual = shell;
return shell;
}

protected override IModuleCatalog GetModuleCatalog()
{
var catalog = new ModuleCatalog();
catalog.AddModule(typeof(ScheduleAddPresenter));
return catalog;
}
}
}
[/sourcecode]

The one difference as one can see is the Silverlight Application sets the Application.Current.RootVisual to the application shell.  Again, one of those places that just screams code duplication.  That?s it.

In my next entry I’m going to do a real quick wrap up and then post the code for what I?ve worked through so far.

HighBall Part Duex (#01)

Navigation of Highball Series Part #1 | Part #2 | Part #3 | Part #4

I’m working through this next part of my HighBall Project, which I’ll be blogging regularly, using TDD and UI/X First Development.  In other words, to give some context, I’m building out a UI first, then I’ll start from the back end and build together using primarily TDD style development.  I’ll admit, I’m a bit unsure of how to go about building out the UI with a TDD style process.  But hopefully by the end of this little application building exercise I’ll have it figured out.

My basic user stories so far is as follows.

  1. As a manager I want to create a schedule for a particular route.
  2. As a manager I want to delete an old schedule for a particular route.
  3. As a manager I want to view all of the schedules for all routes.
  4. As a manager I want to view the history of all past schedules for all routes.
  5. The driver needs to select a route and view the route schedule.

Basically we have the simple CRUD operations for a schedule tracking system.  I’ll elaborate more as I work through this project.

For the first step I created the follow UI pieces in Silverlight & WPF, one for web and one for desktop.  Eventually I might even toss in the ASP.NET MVC for a non-Silverlight web version.  But for now the first step is to mock up the screens as the manager & drivers would view them.

Mocking Up the Screens

I created the create screen first to figure out how I would do this.  Keep in mind I’m going at this almost completely blind, as I’m not even sure what the actual architecture might be.  I’m merely giving both of these approaches a shot at the same time.  One last note, I’ll be using TriMet, NJ Transit, and Sound Transit as my sources of example data, so if it seems familiar, it is.

The first view module that I built was the add route schedule screen.  Upon completion of the basic screen I was amazed at how similar the xaml was for the Silverlight and the WPF.  With this level of similarity I’m thinking there will be many more ways to refactor the xaml itself.  Maybe even create a xaml view generator?  At this point, the goal is to get the view modules created, so back to work.  Here is my first module below.  So far the WPF and Silverlight screen are exactly the same.

[sourcecode language=”xml”]
<UserControl x:Class="HighBall.Interface.Wpf.ScheduleAdd"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot;
Foreground="White" Background="Black">
<Grid x:Name="LayoutRoot" Background="Black">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="25"></RowDefinition>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<TextBlock Margin="5,5,5,5" x:Name="textRoutes">Routes:</TextBlock>
<ListBox Margin="5,5,5,5" Grid.Column="0" Grid.Row="1" HorizontalAlignment="Stretch" VerticalAlignment="Stretch">
<ListBoxItem x:Name="routeOne" Content="WES Commuter Rail"></ListBoxItem>
<ListBoxItem x:Name="routeTwo" Content="9 Powell"></ListBoxItem>
<ListBoxItem x:Name="routeThree" Content="72 Killingsworth/82nd Ave"></ListBoxItem>
<ListBoxItem x:Name="routeFour" Content="590 Tacoma/Seattle"></ListBoxItem>
<ListBoxItem x:Name="routeFive" Content="Sounder Commuter Rail"></ListBoxItem>
<ListBoxItem x:Name="routeSix" Content="The Newark Light Rail Orange Line"></ListBoxItem>
<ListBoxItem x:Name="routeSeven" Content="The Newark Light Rail Blue Line"></ListBoxItem>
<ListBoxItem x:Name="routeEight" Content="The River Line"></ListBoxItem>
</ListBox>
<TextBlock x:Name="routeName" Margin="0,5,5,5" Grid.Column="1" Grid.Row="0" >Add New Schedule</TextBlock>
<StackPanel Grid.Column="1" Grid.Row="1" >
<TextBlock x:Name="frequencyIdentifier" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">Frequency Identifier</TextBlock>
<TextBox x:Name="textFrequencyIdentifier" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<TextBlock x:Name="startLocation" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">Start Location</TextBlock>
<TextBox x:Name="textStartLocation" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<TextBlock x:Name="startTime" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">Start Time</TextBlock>
<TextBox x:Name="textStartTime" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<TextBlock x:Name="endLocation" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">End Location</TextBlock>
<TextBox x:Name="textEndLocation" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<TextBlock x:Name="endTime" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" HorizontalAlignment="Left" VerticalAlignment="Top">End Time</TextBlock>
<TextBox x:Name="textEndTime" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<TextBlock x:Name="scheduleStarts" Margin="0,5,5,0" Grid.Column="0" HorizontalAlignment="Left" VerticalAlignment="Top">Schedule Starts</TextBlock>
<TextBox x:Name="textScheduleStarts" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<TextBlock x:Name="scheduleEnds" Margin="0,5,5,0" Grid.Column="1" HorizontalAlignment="Left" VerticalAlignment="Top">Schedule Ends</TextBlock>
<TextBox x:Name="textScheduleEnds" Margin="0,5,5,0" Grid.Column="1" Grid.Row="1" Height="23" HorizontalAlignment="Stretch" VerticalAlignment="Top" Text=""></TextBox>
<Button x:Name="buttonAddNewSchedule" Margin="10,10" Grid.Column="1" Grid.Row="1" Height="Auto" Width="Auto" HorizontalAlignment="Right" VerticalAlignment="Top" Content="Add Schedule"></Button>
</StackPanel>
</Grid>
</UserControl>[/sourcecode]

The next screen I built was the view all module.  Since I would most likely reuse this screen, or at least a large part of it, for the delete screen it would be best not to get the cart before the horse.

[sourcecode language=”xml”]
<UserControl x:Class="HighBall.Interface.Silverlight.ScheduleViewAll"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation&quot;
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml&quot; >
<Grid x:Name="LayoutRoot" Background="White">
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition></RowDefinition>
</Grid.RowDefinitions>
<ListBox x:Name="listSchedules">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal">
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="260" Text="{Binding Path=FrequencyIdenfitier}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="210" Text="{Binding Path=Route}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="100" Text="{Binding Path=StartLocation}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="100" Text="{Binding Path=EndLocation}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="140" Text="{Binding Path=ScheduleStarts}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="140" Text="{Binding Path=ScheduleEnds}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="80" Text="{Binding Path=StartTime}"/>
<TextBlock Width="Auto" Height="Auto" Padding="5" MinWidth="80" Text="{Binding Path=EndTime}"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</Grid>
</UserControl>
[/sourcecode]

To test out what it would look like I added the following class and code just for an example.

[sourcecode language=”csharp”]
using System;
using System.Collections.Generic;
using System.Windows.Controls;
namespace HighBall.Interface.Silverlight
{
public partial class ScheduleViewAll : UserControl
{
public ScheduleViewAll()
{
InitializeComponent();
var schedules = LoadTestViewData();
listSchedules.ItemsSource = schedules;
}
private static List<RouteSchedule> LoadTestViewData()
{
var schedules =
new List<RouteSchedule>
{
new RouteSchedule
{
Route = "WES Commuter Rail",
EndLocation = "Beaverton",
EndTime = DateTime.Now.AddHours(-5),
FrequencyIdenfitier = Guid.NewGuid().ToString(),
ScheduleEnds = DateTime.Now.AddDays(185),
ScheduleStarts = DateTime.Now.AddDays(5),
StartLocation = "Wilsonville",
StartTime = DateTime.Now.AddHours(10)
},
new RouteSchedule
{
Route = "WES Commuter Rail",
EndLocation = "Wilsonville",
EndTime = DateTime.Now.AddHours(-5),
FrequencyIdenfitier = Guid.NewGuid().ToString(),
ScheduleEnds = DateTime.Now.AddDays(185),
ScheduleStarts = DateTime.Now.AddDays(5),
StartLocation = "Beaverton",
StartTime = DateTime.Now.AddHours(10)
},
new RouteSchedule
{
Route = "WES Commuter Rail",
EndLocation = "Beaverton",
EndTime = DateTime.Now.AddHours(-5.5),
FrequencyIdenfitier = Guid.NewGuid().ToString(),
ScheduleEnds = DateTime.Now.AddDays(185),
ScheduleStarts = DateTime.Now.AddDays(5),
StartLocation = "Wilsonville",
StartTime = DateTime.Now.AddHours(9.5)
},
new RouteSchedule
{
Route = "WES Commuter Rail",
EndLocation = "Wilsonville",
EndTime = DateTime.Now.AddHours(-5.5),
FrequencyIdenfitier = Guid.NewGuid().ToString(),
ScheduleEnds = DateTime.Now.AddDays(185),
ScheduleStarts = DateTime.Now.AddDays(5),
StartLocation = "Beaverton",
StartTime = DateTime.Now.AddHours(9.5)
},
new RouteSchedule
{
Route = "590 Tacoma/Seattle",
EndLocation = "Seattle",
EndTime = DateTime.Now.AddHours(-5),
FrequencyIdenfitier = Guid.NewGuid().ToString(),
ScheduleEnds = DateTime.Now.AddDays(185),
ScheduleStarts = DateTime.Now.AddDays(5),
StartLocation = "Tacoma",
StartTime = DateTime.Now.AddHours(10)
}
};
return schedules;
}
}
public class RouteSchedule
{
public string Route { get; set; }
public string FrequencyIdenfitier { get; set; }
public string StartLocation { get; set; }
public string EndLocation { get; set; }
public DateTime StartTime { get; set; }
public DateTime EndTime { get; set; }
public DateTime ScheduleStarts { get; set; }
public DateTime ScheduleEnds { get; set; }
}
}
[/sourcecode]

While trying to get this to work in the Silverlight screen I ran into the dreaded “AG_E_INVALID_ARGUMENT” exception.  This is some type of xaml parsing issue, which I jumped right out to Google to try and figure out.  The link above eventually led me to this entry on the silverlight forums.  Even after digging through all of these ancient (in Silverlight terms) fixes, I still had the error.  At this point I threw up my hands and recreated the entire screen.  Once I did that, it worked.  However, the Silverlight xaml screen stopped color coding the xaml correctly and shaded out ALL of the ListBox.ItemTemplate xaml between the tags.  I don’t know what is wrong with this but it is extremely annoying.

StringFormat is another thing that works in WPF but not in Silverlight.  I started to use them to format the date time bound fields.  Since there is this disparity, I just left that as is.  I’ll eventually get back to cleaning up data a bit later.

At this point I needed to wire these together for the customer (which at this point is me, but I’m following Agile Practice).  I didn’t want to get too many UI modules done and then realize I had to change significant parts.  In my next entry I’ll cover working with the Composite Application Library (used to be the Composite Application Block, but that’s evil) to get two builds, one for Silverlight and one for WPF.

Other bits of Information relating to user stories, UI/X, TDD, and other topics.