Tuesday, November 17, 2009

Dynamic Module Loading with Silverlight Navigation using Prism

I started a project to update my personal website using Silverlight. The goal is to use Prism/Composite Application Guidance to build out a nice site that demonstrates some Silverlight capabilities and make the source code available as a reference. One of the first pieces I chose to tackle was ensuring I could facilitate deep linking using Silverlight navigation and still take advantage of dynamic module loading using the Prism framework.

The initial research I did was not promising. Most sites claimed that Prism broke the Silverlight navigation, while others had partial solutions that didn't really cut it for me. Mapping a separate view in the main module to have a named region for every dynamically loaded module seems to be overkill. So, I set out to see for myself if it could be done. The answer, of course, is yes!

While the project is a simple pair of pages, I've built in a few more advanced pieces of functionality to extend its richness as a reference project. In addition to dynamic loading the module for the "biography" page, I've trimmed the size of the XAP files, sprinkled in a little search engine optimization, and used the visual state manager to handle some animations to boot.

You can download the full source code by clicking here. For a working demo, click here. You can use a sniffer or proxy like Fiddler 2 to confirm for yourself that the Biography module doesn't load until you click that tab, BUT you can also navigate directly:

I do apologize in advance for the vanity built into the project ... it is a project with the goal of replacing my biography website so it made since to name it after, well, me.

The first step in creating a deep linking navigation website is to go ahead and create a Silverlight Navigation Application. I called mine JeremyLikness.Main and it gave me JeremyLikness.Web to host it. Go ahead and trash everything in the views folder but the error window (I like that functionality, some might find it annoying), leave the App pieces alone but rename the main page to Shell.xaml.

Here's when things start to get interesting. First, I've seen a lot of implementations that want the pure "my module gets added magically" functionality, so they do things like inject the link to the module when the module itself gets loaded, etc. This is all great but then they also stuff a view in the main application that maps one-to-one with the module, give a new named region per module, and leave me scratching my head wondering, "What did we gain?" To me, the main portion of my app is a single region that can have multiple modules inject their views into it, so that's how I approached this project.

I'm going to be a bit more pragmatic and go ahead and map my links in the main shell because I'm assuming right now the shell is like the overall "controller" and is aware of the other modules. It should, however, be very easy and minimal overhead for me to add a new module later on. I'm not going to worry about the modules injecting the links because then I have to load the module before I can show the link, and that defeats the purpose of dynamically loading the modules. Ideally, your browser doesn't fetch that extra 100K of XAP download if you don't care about reading my biography!

I end up keeping the generated code for the links (I'll go back and rearrange and style it later ... getting it functioning for me comes before making it pretty). I'm starting with two links, so that section looks like this:


 <Border x:Name="LinksBorder" Style="{StaticResource LinksBorderStyle}">
                <StackPanel x:Name="LinksStackPanel" Style="{StaticResource LinksStackPanelStyle}">

                    <HyperlinkButton x:Name="homeLink" Style="{StaticResource LinkStyle}" 
                                     NavigateUri="/Home" TargetName="ContentFrame" Content="Home"/>
          
                    <Rectangle x:Name="Divider1" Style="{StaticResource DividerStyle}"/>
     
                    <HyperlinkButton x:Name="Link2" Style="{StaticResource LinkStyle}" 
                                     NavigateUri="/Bio" TargetName="ContentFrame" Content="Bio"/>
                </StackPanel>
            </Border>

Not bad. Now we're going to start butchering the generated template, so bear with me.

Dynamic Modules

Setting up modules to be dynamic is fairly straightforward. While there are many ways to approach this, the method I used has two key features:

  1. I'm using a XAML configuration for the module, not programmatic, and
  2. to add the module in a way that Prism can dynamically load it, I add it as a Silverlight Application, not a Class Library

That's it! We're going to work a bit backwards and live without the project compiling for a bit until we get all of the pieces put into place. I know I'm going to have a Home and a Bio module. For the sake of simplicity and this example, I'm doing one view per module, but you could obviously do more. You'll see why this makes it easy for me in a minute. First, let's set up the XAML that will describe the modules.

Right click on the main project (the one with your shell) and add a new Resources File. Name it ModuleCatalog.xaml. Blow away everything in there and instead put in the Prism notation for a module, like this:


<m:ModuleCatalog xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
                 xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
                 xmlns:sys="clr-namespace:System;assembly=mscorlib"
                 xmlns:m="clr-namespace:Microsoft.Practices.Composite.Modularity;assembly=Microsoft.Practices.Composite">
    <m:ModuleInfoGroup Ref="JeremyLikness.ModuleHome.xap" InitializationMode="WhenAvailable">
        <m:ModuleInfo ModuleName="JeremyLikness.ModuleHome.InitModule"
                      ModuleType="JeremyLikness.ModuleHome.InitModule, JeremyLikness.ModuleHome, Version=1.0.0.0"/>
    </m:ModuleInfoGroup>
    <m:ModuleInfoGroup Ref="JeremyLikness.ModuleBio.xap" InitializationMode="OnDemand">
        <m:ModuleInfo ModuleName="JeremyLikness.ModuleBio.InitModule"
                      ModuleType="JeremyLikness.ModuleBio.InitModule, JeremyLikness.ModuleBio, Version=1.0.0.0"/>
    </m:ModuleInfoGroup>
</m:ModuleCatalog>
                 

I've purposefully set the home page to load when available and the bio to load on demand to show the difference between the methods ... I could just as easily load both modules on demand. This simply points to the class that defines the module, and the assembly to find it in. Prism will assume it's available for download in the same directly as the hosted XAP and kindly pull down the XAP when it's needed for us.

We're now referring to some modules we don't have yet. At this point, you could go ahead and create the shells for the applications. In order for the project to be set up correctly for dynamic loading, instead of adding a Silverlight Class Library, you're going to add a new Silverlight Application. Pick the same web page to host it but don't bother with the generation of a test page as it will load into the same test page we used for the main. I called my projects JeremyLikness.ModuleBio and JeremyLikness.ModuleHome.

Once the projects are created, blow away the all of the generated XAML files. You won't need the App object because this will be hosted in our main application. I simply added the references needed for Prism, then created a Views folder and added a Home.xaml in my home project and a Bio.xaml in my bio project. These are UserControl types, not pages. In the root, I created InitModule classes for both projects (note that I referenced this in the ModuleCatalog.xaml). The code looks almost identical - here is the bio:


namespace JeremyLikness.ModuleBio
{
    public class InitModule : IModule
    {
        private IRegionManager _regionManager;

        public InitModule(IRegionManager regionManager)
        {
            _regionManager = regionManager;
        }

        #region IModule Members

        public void Initialize()
        {
            _regionManager.RegisterViewWithRegion("ModuleRegion", typeof(Bio));
        }

        #endregion
    }
}

Simple: reference the region manager in the constructor. The Prism will use Unity to resolve the reference and inject it. On the Initialize method, we register our view with the region. The home project will register to the same region, but with typeof(Home) home instead.

Now we've got the catalog and the modules, what's next?

Bootstrapping

We need to tell the Prism framework how to "get started." This means a bootstrapper. Back to JeremyLikness.Main, I add a class called Bootstrapper and base it on UnityBootstrapper. I need to create the shell and set it as the root visual:


protected override DependencyObject CreateShell()
{
    Shell shell = Container.Resolve<Shell>();
    Application.Current.RootVisual = shell;
    return shell;
}

I also need to supply a module catalog. For this, I'll point to the XAML file we created earlier:


protected override Microsoft.Practices.Composite.Modularity.IModuleCatalog GetModuleCatalog()
{
    return Microsoft.Practices.Composite.Modularity.ModuleCatalog.CreateFromXaml(
        new Uri("JeremyLikness.Main;component/ModuleCatalog.xaml", UriKind.Relative));
}

You can see I'm telling it to look to the XAML to create the catalog, then specifying the path to it. The last thing I need to do is go into the App.cs code behind and change the application start up to just run the boot strapper:


private void Application_Startup(object sender, StartupEventArgs e)
{
   new Bootstrapper().Run();
}

Adapting to the Region

Prism works with defined regions that can host views. There are a number of different ways those regions can be implemented. I would ask that you refer to the Prism documentation for this, but basically something like a ContentControl can have a single view active at any given time, while something like a ItemsContentControl can hold multiple views. One source of confusion is what "active" really means. Active views doesn't necessarily mean "visible" or "hidden." I had two challenges for this application: the first was how to host the view, and the second was how to manage the visibility of the views. Ideally, something would hold all of the views as they are selected, then simply make them visible or invisible as they are selected/deselected.

We'll tackle visibility in a minute. ContentControl wasn't an option because it only holds one view at a time. The problem with ItemsControl was related to layout. As each view is injected, it takes up space in the container (this is the same whether it's a items control or a stack panel, etc). Even when I'd collapse the visibility of a control, the original space would still cause the other controls (views) to be shifted, which was not the effect I wanted. I needed something like a Grid where I could stack the views one on top of the other.

Fortunately, making your own type of region is easy. After reading John Papa's excellent post, I made a PrismExtensions folder and built my GridRegionAdapter to allow Prism to use a grid as a container. You can read his article to understand the how/why and see how the adapter is constructer. I had to revisit the boot strapper and tell Prism how to map the adapter to the grid:


protected override RegionAdapterMappings ConfigureRegionAdapterMappings() 
{ 
    RegionAdapterMappings mappings = base.ConfigureRegionAdapterMappings(); 
    mappings.RegisterMapping(typeof(Grid), Container.Resolve()); 
    return mappings; 
}

Now I was ready to give the solution a go!

The Problem with Navigation

The first iteration I tried was to declare a single page with the region adapter to process the requests. In my Views folder in the main project, I created a Silverlight Page (Page, not UserControl) and called it Module.xaml. The XAML for the module looked like this:


<navigation:Page x:Class="JeremyLikness.Main.Views.Module" 
           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"
           xmlns:cal="clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation"
           xmlns:navigation="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Navigation"
           xmlns:local="clr-namespace:JeremyLikness.Main.Views"
                 d:DesignWidth="640" d:DesignHeight="480"
           Title="Module Page">
    <Grid x:Name="MainGrid" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" cal:RegionManager.RegionName="ModuleRegion">
    </Grid>
</navigation:Page>
      

Going back to the main shell, I mapped all requests to the module, like this:


<Border x:Name="ContentBorder" Style="{StaticResource ContentBorderStyle}">

    <navigation:Frame x:Name="ContentFrame" Style="{StaticResource ContentFrameStyle}" 
                      Source="/Home" Navigated="ContentFrame_Navigated" NavigationFailed="ContentFrame_NavigationFailed">
        <navigation:Frame.UriMapper>
          <uriMapper:UriMapper>
            <uriMapper:UriMapping Uri="" MappedUri="/Views/Module.xaml"/>
            <uriMapper:UriMapping Uri="/{pageName}" MappedUri="/Views/Module.xaml"/>
          </uriMapper:UriMapper>
        </navigation:Frame.UriMapper>
    </navigation:Frame>
</Border>

As you can see, pretty much every request is handled by the Module page. In the code behind, I had to work a little bit of magic to ensure the appropriate module would be loaded. First, I added a reference to the module manager:


public partial class Shell : UserControl
{
    private IModuleManager _moduleManager;

    public Shell(IModuleManager moduleManager)
    {
        _moduleManager = moduleManager;
        InitializeComponent();
    }

    private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
    {
    
        string module = e.Uri.ToString().Substring(1);
        string moduleName = string.Format("JeremyLikness.Module{0}.InitModule", module); 
       
        _moduleManager.LoadModule(moduleName);

...

}

The key here was getting the reference to the module manager, then calling the module load on the request. The module manager is smart enough to know when a module has already been loaded, so I didn't have to worry about that. The idea here is that when I request the "bio" tab, the string manipulation maps it to JeremyLikness.ModuleBio.InitModule, then calls the manager. The manager checks to see if it is loaded. If not, it will download the required XAP file and initialize the module. The module would then register the view with the region and it would magically appear!

There were two problems that arose immediately. The first issue was visibility: the different pages were stacking on each other. I'd load the application and see the home page, then click on the bio tab and watch the bio appear overlaid on top of the home page. Definitely not the right solution! We'll address visibility in a minute.

The second was a little more disturbing. The pages were behaving a little strangely so I fired up the debugger and found something disturbing: every time I would navigate to a link, the navigation framework would generate a new instance of the Module.xaml. This, in turn, would create new instances of the views. Just a few clicks of the tab and suddenly I had lots of instances hanging out that I just didn't need.

The solution for this was to create a static view that would live between navigation requests and hold the views as they are stacked in place. The first step was to build the container for the views. Under the Views folder, I created ViewContainer.xaml. The XAML contained the region mapping:


<UserControl x:Class="JeremyLikness.Main.Views.ViewContainer"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
    xmlns:cal="clr-namespace:Microsoft.Practices.Composite.Presentation.Regions;assembly=Microsoft.Practices.Composite.Presentation"
   >
    <Grid x:Name="LayoutRoot" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"
          cal:RegionManager.RegionName="ModuleRegion">
       </Grid>
</UserControl>

The code behind implemented the singleton pattern:


public partial class ViewContainer : UserControl
{
    private static readonly ViewContainer _viewContainer = new ViewContainer();

    private ViewContainer()
    {
        InitializeComponent();
    }

    public static ViewContainer GetViewContainer()
    {
        if (_viewContainer.Parent != null)
        {
            Grid grid = _viewContainer.Parent as Grid;
            grid.Children.Remove(_viewContainer); 
        }

        return _viewContainer;
    }
}

Note that an element can only have one parent, and cannot be added as a child to another element. The GetViewContainer method first detaches the view from its previous parent before returning the instance so that the consumer of the method can use the orphaned view. I removed the region reference from the Module.xaml and added this to the code behind:


public Module()
{
    InitializeComponent();
    MainGrid.Children.Add(ViewContainer.GetViewContainer()); 
}

Now the navigation will still create a new instance of Module every time we navigate, but the module will simply reuse the same container for the views. This ensures that the views persist once they are added and don't have to be reloaded or recreated.

Next, I needed to manage showing and hiding the views so they don't remain stacked on top of each other.

Managing Visibility

To manage the views, I decided to create a service that the views will register to. The service is called when navigation takes place, and then calls back to the views to manage their visibility.

First, I created a new project that would be common across other projects. This was named, ironically, JeremyLikness.Common. First was an interface that the views could use. They provide a name for themselves as well as a method to call to either show or hide. This offloads the need for the view manager to understand how to show or hide a view ... since the view is a UserControl, it should have a pretty good idea.


public interface IPrismView
{
    void Show();

    void Hide();

    string ViewName { get; }
}

Next, I added a reference to the common project in both modules and implemented IPrismView. This is what the Bio.xaml.cs looked like:


#region IPrismView Members

public void Show()
{
    this.Visibility = Visibility.Visible; 
}

public void Hide()
{
    this.Visibility = Visibility.Collapsed;
}

public string ViewName
{
    get { return "Bio"; }
}

#endregion

Now I can create my view manager. In the same common project, I created a class called ActivationManager (continuing the Prism concept of "activating" a view although it is probably misnamed in retrospect). ActivationManager contains a collection of views. It allows a view to register with it, then exposes a method called SwapToView that iterates the views and calls their Show or Hide methods. It looks like this:


public class ActivationManager
{
    List<WeakReference> _views = new List<WeakReference>();

    public void Register(IPrismView view)
    {
        _views.Add(new WeakReference(view));
        view.Show();
    }

    public void SwapToView(string viewName)
    {
        foreach (WeakReference weakRef in _views)
        {
            if (weakRef.Target != null)
            {
                IPrismView view = (IPrismView)weakRef.Target;
                
                if (view != null)
                {
                    if (view.ViewName.Equals(viewName))
                    {
                        view.Show();
                    }
                    else
                    {
                        view.Hide();
                    }
                }
            }
        }
    }
}

Now we need to wire the activation manager in. We only need one copy, so in the boot strapper in the main project, I set up the instance:


protected override DependencyObject CreateShell()
{
    Container.RegisterInstance<ActivationManager>(
        Container.Resolve<ActivationManager>());
    Shell shell = Container.Resolve<Shell>();
    Application.Current.RootVisual = shell;
    return shell;
}

Notice I did this before creating the shell. There is a reason: we need the shell to coordinate the views. The shell has a method that fires when the navigation changes. If you recall, we used this method to tell the module manager to load the appropriate module. Now we'll need to pass in the activation manager and ask it to activate the views. These are the changes to the Shell code-behind:


private ActivationManager _activationManager;

public Shell(IModuleManager moduleManager, ActivationManager activationManager)
{
    _moduleManager = moduleManager;
    _activationManager = activationManager;
    InitializeComponent();
}

private void ContentFrame_Navigated(object sender, NavigationEventArgs e)
{

    string module = e.Uri.ToString().Substring(1);
    string moduleName = string.Format("JeremyLikness.Module{0}.InitModule", module); 
   
    _moduleManager.LoadModule(moduleName);

    _activationManager.SwapToView(module); 

    foreach (UIElement child in LinksStackPanel.Children)
    {
        HyperlinkButton hb = child as HyperlinkButton;
        if (hb != null && hb.NavigateUri != null)
        {
            if (hb.NavigateUri.ToString().Equals(e.Uri.ToString()))
            {
                VisualStateManager.GoToState(hb, "ActiveLink", true);
            }
            else
            {
                VisualStateManager.GoToState(hb, "InactiveLink", true);
            }
        }
    }
}

The last step is to take each module and pass the activation manager into the constructor so the view can register itself. This could probably be moved back into the module initialization (i.e. when the view is injected into the region) and perhaps even something extended on the framework to handle it. However, this works for now, using Bio.xaml.cs as our example:


public Bio(ActivationManager activationManager) : this()
{
    activationManager.Register(this);
}

Notice that I use this() to ensure it calls the default parameterless constructor to InitializeComponent etc etc.

At this point, I claimed victory. After compiling and publishing the project, I was able to navigate between the home and bio tabs, and watch the bio module loaded dynamically when I navigated to the tab. The views swapped in and out nicely. If you were reading this for dynamic module loading ... there it is!

To round out the example, I wanted to show two more things. First, I wanted to take the idea of Show and Hide a step further, and second, I don't believe navigation or deep linking makes sense to discuss unless we also cover search engine optimization.

Visual State Manager

The visual state manager is the key to managing visual states on controls (seems like it was well-named, huh?). I have to thank Justin Angel for pointing this out to me when I was doing a lot of behaviors and triggers for animations that truly belonged in the VSM instead. Really, when we're swapping our views, we are changing the state of the view ("show me" or "hide me"). If we do this programmatically, then we're stuck with the attributes we set. However, if we do this through the VSM, then all of the the transition becomes customizable through the designer and in Expression Blend, so our designers can then tinker with the transitions without touching the code behind.

To demonstrate this, I decided to take both views and give them a ShowState and a HideState. To show the power of the Visual State Manager, I created two different transitions: the home page will explode in using a scale transform, while the biography page will fade in using an opacity animation.

Because there are a million examples that show how to add custom view states using Blend, I decided to document the code behind approach. The main container in our views is a grid, so that's what we're going to manipulate. I want the view to hide immediately, but when it goes to show, it should have a nice animation. This is what the Bio.xaml ends up looking like:


<Grid x:Name="LayoutRoot" Background="White">
        <VisualStateManager.VisualStateGroups>
            <VisualStateGroup x:Name="VisualStates">
                <VisualState x:Name="ShowState">
                    <Storyboard>
                        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:01.0000000" Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Opacity)">
                            <EasingDoubleKeyFrame KeyTime="00:00:01" Value="1"/>
                        </DoubleAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:01.0000000" Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Visibility)">
                            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                                <DiscreteObjectKeyFrame.Value>
                                    <Visibility>Visible</Visibility>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
                <VisualState x:Name="HideState">
                    <Storyboard>
                        <DoubleAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:00.0000100" Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Opacity)">
                            <EasingDoubleKeyFrame KeyTime="00:00:00" Value="0"/>
                        </DoubleAnimationUsingKeyFrames>
                        <ObjectAnimationUsingKeyFrames BeginTime="00:00:00" Duration="00:00:01.0000100" Storyboard.TargetName="LayoutRoot" Storyboard.TargetProperty="(UIElement.Visibility)">
                            <DiscreteObjectKeyFrame KeyTime="00:00:00">
                                <DiscreteObjectKeyFrame.Value>
                                    <Visibility>Collapsed</Visibility>
                                </DiscreteObjectKeyFrame.Value>
                            </DiscreteObjectKeyFrame>
                        </ObjectAnimationUsingKeyFrames>
                    </Storyboard>
                </VisualState>
            </VisualStateGroup>
        </VisualStateManager.VisualStateGroups>
        <TextBlock>This is my bio. It tells people about me and my background.</TextBlock>
    </Grid>

So there are a few things going on here. First, we define a "group" of visual states that I call, sure enough, VisualStates. I am defining two states: a HideState and a ShowState. The hide state has an animation with a zero duration and simply sets the Opacity to 0. The show state animates for a second (you'd normally make this faster, but it helps demonstrate my point) and fades in. While many people are used to the color and double animations, did you know there existed an object animation as well? This allows you to manipulate almost any property on your target control using the visual state. In this case, I won't even have to set the Visibility property in my code behind - I simply define the value in the view state! Notice in the ShowState that the property is set immediately so it becomes visible in time for the animation to fire and fade it in.

So now we simply go to the code-behind for our control and set the state. The VSM expects a control when you set the state, but it will traverse the hierarchy and find the state you specify. So while we set the state on our control, it will use the state definitions that are contained within the grid object. We also make sure we set a default state in the constructor. In this case, it will be hidden because the activation manager will call show when it is registered. This is what our new code-behind looks like:


public partial class Bio : UserControl, IPrismView
{
    public Bio()
    {
        InitializeComponent();
        VisualStateManager.GoToState(this, "HideState", false);
    }

    public Bio(ActivationManager activationManager) : this()
    {
        activationManager.Register(this);
    }

    #region IPrismView Members

    public void Show()
    {
        VisualStateManager.GoToState(this, "ShowState", true);
    }

    public void Hide()
    {
        VisualStateManager.GoToState(this, "HideState", true);
    }

    public string ViewName
    {
        get { return "Bio"; }
    }

    #endregion
}

As you can see, we simply move to a new state and leave it up to the designer to add any fancy animations or other transitions when that happens.

Getting Along with Search Engines

The final piece here is to get along with search engines. Deep linking is nice if you just want to add it to your favorites and jump right in, but doesn't really do much for search engines when they are scanning the page. The search enginges need to have some points like a page title and description to properly index your pages.

In the common project, I created a class called SEOHelper to contain my title, description, and keywords. It exposes a method called PageUpdate that then parses these values into the HTML page. Let's take a look at the class:


public class SEOHelper
{
    private const string TEMPLATE = "metatags = document.getElementsByTagName(\"meta\");"
        + "for (x=0;x<metatags.length;x++) {{"
        + "var name = metatags[x].getAttribute(\"name\");"
        + "if (name == '{0}'){{"
        + "var content = metatags[x].getAttribute(\"content\");" 
        + "metatags[x].setAttribute('{0}','{1}');break;}}}}";

    private List<string> _keywords = new List<string>();

    public string Title { get; set; }

    public string Description { get; set; }

    public void AddKeyword(string keyword)
    {
        _keywords.Add(keyword);
    }

    public void UpdatePage()
    {
        HtmlPage.Document.SetProperty("title", Title);

        string titleSet = string.Format(TEMPLATE, "title", Title);
        HtmlPage.Window.Eval(titleSet);

        string descriptionSet = string.Format(TEMPLATE, "description", Description);
        HtmlPage.Window.Eval(descriptionSet);

        if (_keywords.Count > 0)
        {
            StringBuilder keywordList = new StringBuilder();
            bool first = true;
            foreach (string keyword in _keywords)
            {
                keywordList.Append(keyword);
                if (first)
                {
                    first = false;
                }
                else
                {
                    keywordList.Append(",");
                }
            }
            string keywordSet = string.Format(TEMPLATE, "keywords", keywordList);
            HtmlPage.Window.Eval(keywordSet);
        }
    }
}

I'm not a big fan of burying JavaScript inside of C# classes, so I included it here only to help keep the solution in one place. Ordinarily I'd have some methods defined in a .js file that this would link to.

Setting the title is a call into the document object. Setting the meta tags is a little more convuluted. You could create the tags but in this example, I'm stubbing out empty title, description, and keywords meta-tags, then finding them and updating the content attribute. The TEMPLATE contains the code to iterate the tags, then update the content attribute. The PageUpdate method simply updates the meta tag name and content then asks the page to evaluate the javascript.

Now we just place the object inside of the appropriate view and call it when the view becomes visible. Here is the new Home.xaml.cs:


public partial class Home : UserControl, IPrismView
{
    SEOHelper _helper = new SEOHelper { Title = "Home Page", Description="Home page for the website." }; 

    public Home()
    {
        InitializeComponent();
        VisualStateManager.GoToState(this, "HideState", false);
        _helper.AddKeyword("Home");
        _helper.AddKeyword("SEO"); 
    }

    public Home(ActivationManager activationManager)
        : this()
    {
        activationManager.Register(this);
    }

    #region IPrismView Members

    public void Show()
    {
        VisualStateManager.GoToState(this, "ShowState", true);
        _helper.UpdatePage();
    }

    public void Hide()
    {
        VisualStateManager.GoToState(this, "HideState", true);
    }

    public string ViewName
    {
        get { return "Home"; }
    }

    #endregion
}

As you can see, the helper takes in the settings for the page, then whenever the view is shown (the Show) method, the helper is called to update the page. For testing, this could be abstracted even further to a ISEOHelper to avoid trying to actually access the html page when its not needed.

Important Note: as pointed out by Alexey Zakharov in the comments, most search engines won't be able to fire up the Silverlight plug-in and run the XAP to even affect the page to "see" the meta data. To be able to truly have it all indexed, you'll still either need to have a separate page per link (which isn't too efficient with XAP files loading) or have a JavaScript stub independent of the Silverlight plugin that updates this information ... the search engines DO understand javascript for the most part. Thanks for that and I'll probably blog a post about it later, unless I suddenly start seeing my content show up on Google links.

Trimming the XAP Size

Last but not least is trimming the XAP size. I put most of my references in the main XAP file, so they aren't needed in the modules. By going to the project properties, I can check "Reduce XAP size by using appliciation library caching." This will create a new ZIP file that contains some of the referenced controls on my modules when they build, and not include them in the main XAP. Fortunately, these are already loaded by the main XAP, so there is nothing more to do when the XAP is loaded.

There it is ... I know this was a long blog post for what, in the end, is a simple page with two tabs. However, I hope this has proven that you can combine Prism with Silverlight Navigation and use dynamic module loading will keeping your pages search engine friendly. The VSM piece might have made sense in a separate post but I also wanted to get a good example out there that shows how to wire it in when you're not making a custom control or using Blend. Enjoy!

Download the source

View the demo

Jeremy Likness