Page view counter

Silverlight Tips of the Day - Blog by Mike Snow

Game Programming with Silverlight

Silverlight Tip of the Day #84 – How to Dynamically Load a Control from a DLL

If you have a large game or application it might be wise to break it up into smaller components (DLL’s) that can be downloaded to the client from the server as needed. This way your customers are not stuck waiting for a large download to complete when they first connect to your application on the web.

In this tip I will show you how to package Silverlight controls into a DLL and place them on your web server. Then, I will show you how to have the client download the DLL, create and instance of the Silverlight control from the DLL and then to add the control to your Silverlight application.

Step 1. Create a Silverlight Component DLL.

To start, create a new Silverlight Class library. This can be done through the menu in VS: File | New->Project. In Project Types expand the Visual C# node and choose Silverlight. From the Templates pane on the right of this dialog choose Silverlight Class Library. Give the project a name (such as “Mage”) and click OK on the dialog when ready.

In the Solution Explorer right click on your Class node and choose Add->New Item. This will bring up the Add New Item dialog. Select Silverlight User Control, give it a name (such as “Mage.xaml”) and click OK when ready.

Add whatever content you want to this control. For my demo purposes I have simply added an image of a mage character.

<UserControl x:Class="Mage.Mage"
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation 
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml 
    Width="96" Height="96">
    <Canvas>
        <Image Source="mage.png"></Image>
    </Canvas>
</UserControl>

Ctrl+Shift+B to build the project. This will put your component in a DLL in your bin folder such as bin\Mage.dll.

Step 2. Create a Silverlight Application.

Now that you have your Silverlight component built and ready to go it’s time to create a Silverlight application that will load and display the component. Create a Silverlight application by selecting in the menu File->New Project and choosing Silverlight Application this time instead of Silverlight Class Library. Give the project a name (such as MyGame) and click OK when ready.

Copy the Silverlight component DLL that you built earlier (such as Mage.dll) to your Web site folder (such as MyGame\MyGame.Web).

Step 3. Download and Display the Silverlight Control

The following code below shows you how to load and display the Silverlight control. Few things to note:

  1. Add a using statement to reference System.Reflection since they component we are creating is declared as an Assembly object.
  2. Use the WebClient component to open a asynchronous read of the DLL.
  3. Make certain you point to the absolute path of your DLL. An absolute path uses the full URL.
  4. Once the download is complete the assembly is loaded and an instance of the control is created.
  5. Finally the control is added to the root level of the application.

The result, a nice little mage is rendered:

image

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Reflection;
 
namespace MyGame
{
    public partial class Page : UserControl
    {
        private Assembly _mageComponent;
 
        public Page()
        {
            InitializeComponent();
 
            LoadMageComponent();
        }
 
        private void LoadMageComponent()
        {
            WebClient downloader = new WebClient();
            downloader.OpenReadCompleted += new OpenReadCompletedEventHandler(downloader_OpenReadCompleted);
 
            string component = "Mage.dll";
            string absoluteUri = System.Windows.Application.Current.Host.Source.AbsoluteUri;
            string path = absoluteUri.Substring(0, absoluteUri.IndexOf("ClientBin")) + component;
 
            downloader.OpenReadAsync(new Uri(path, UriKind.Absolute));
        }
 
        void downloader_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
        {
            AssemblyPart assemblyPart = new AssemblyPart();
            _mageComponent = assemblyPart.Load(e.Result);
            UserControl control = (UserControl)_mageComponent.CreateInstance("Mage.Mage");
            LayoutRoot.Children.Add(control);
        }
    }
}

Thank you,
--Mike Snow

 Subscribe in a reader

Comments

Microsoft Weblogs said:

If you have a large game or application it might be wise to break it up into smaller components that

# January 21, 2009 6:42 PM

Silverlight Travel » Dynamically Load a Control from a DLL said:

Pingback from  Silverlight Travel &raquo; Dynamically Load a Control from a DLL

# January 22, 2009 12:48 AM

samcov said:

Did you have to add it to the root, or was that just your desired position?

# January 22, 2009 5:00 AM

samcov said:

Another Question.

How would you pass initilization parameters to the control?  The only solution I can think of is to execute a known method via reflection, or once added to the tree, get a reference, and then call some init method.

What do you think?

# January 22, 2009 5:21 AM

Silverlight Tips of the Day - Blog by Mike Snow said:

In Tip of the Day #84 I discussed the importance of being able to load controls from server side components

# January 22, 2009 7:51 PM

mike.snow said:

Samcov- You can add it anywhere. As for the parameters, i'll look into it. :)

# January 22, 2009 7:52 PM

DotNetShoutout said:

Thank you for submitting this cool story - Trackback from DotNetShoutout

# January 22, 2009 11:40 PM

Community Blogs said:

In this issue: Russell Greenspan, Andrej Tozon, Patrick Keating, Timmy Kokke, csharpsean, John Stockton

# January 23, 2009 1:46 AM

Silverlight Travel » How to Load External Images in Silverlight said:

Pingback from  Silverlight Travel &raquo; How to Load External Images in Silverlight

# January 23, 2009 4:25 AM

Silverlight Tips of the Day - Blog by Mike Snow said:

The purpose of this post is to create an outline summary all the blogs from my Silverlight Tips of the

# January 23, 2009 7:21 PM

Programming with Silverlight, WPF & .NET » Tip of The Day #84 - #89 How to …. said:

Pingback from  Programming with Silverlight, WPF &amp; .NET &raquo; Tip of The Day #84 - #89 How to &#8230;.

# January 29, 2009 2:26 AM

Visual Web Developer Team Blog said:

Most Recent Posts: Tip #93 - Reading XML with Silverlight Tip #92 - How to Load Images from a Stream

# February 10, 2009 6:25 PM

mliebster said:

Is it possible to strongly type these dynamic loaded dlls?

We've got a fairly complicated LOB to put together and it would be handy to break it into separate projects.

Strongly typing it would be handy so that we could make method calls into them.

Or do we just need to rely on reflection?

# April 10, 2009 8:12 PM

mike.snow said:

I would think so but honestly I haven't tried yet. This might be a good question to post on the Silverlight forums at silverlight.net.

If I can find time though I will try to test it out :)

--Mike

# April 13, 2009 11:25 AM

misschoudhary said:

While execution i got this error how to solve?

An exception occurred during the operation, making the result invalid.  Check InnerException for exception details.

# April 27, 2009 3:24 AM

Astuce Silverlight : comment charger dynamiquement un contr??le depuis une DLL - #S027 | Coded Style said:

Pingback from  Astuce Silverlight : comment charger dynamiquement un contr??le depuis une DLL - #S027 | Coded Style

# May 6, 2009 7:11 PM

Astuce Silverlight : comment charger dynamiquement un contr??le depuis une DLL - #S027 | Coded Style said:

Pingback from  Astuce Silverlight : comment charger dynamiquement un contr??le depuis une DLL - #S027 | Coded Style

# May 6, 2009 7:11 PM