Even a chimp can write code

Monday, March 10, 2008

How to pass initialization params to a Silverlight 2 app

This is something of an FAQ on our internal discussion lists, so I figured it merited a post.

Step 1: Declare the initParams param on the Silverlight plug-in and pass in a comma-delimited set of key-value pair tokens. For e.g. "key1=value1,key2=value2,key3=value3".

<object type="application/x-silverlight"
        width
="100%" height="100%">

  <param name="source"
         value
="ClientBin/SLInitParams.xap"/>

<!-- startPage key can have values Page1 or Page2 -->

  <param name="initParams"
         value
="startPage=Page1" />

</object>

For best results, the key and value tokens in the initParams string must be restricted to alphanumeric values. There currently isn't support for escaping equality signs or commas, for instance, should they exist in the key or value part of the token.

Step 2: In the Application's Startup event handler, extract the initialization parameters via StartupEventArgs.InitParams property. You'll get an IDictionary<string, string>.

// Contents of App.xaml.cs

private void Application_Startup(object sender,
                                   StartupEventArgs
e)

{
    string startPage = e.InitParams["startPage"];
    if (startPage != null && startPage.Equals("Page1"))

    {
       // Load Page1
       this.RootVisual = new Page();
    }
    else
    {
       // Load Page2
       this.RootVisual = new AlternatePage();
    }
}

Simple, huh? I have a sample project on how to pass initialization params to a Silverlight 2 app, and conditionally show UI, up on my sky drive.

Labels:

Email this | Bookmark this

13 Comments:

  • Ashis, that was a great blog. With your deep knowledge in SL2, you should write more blogs.

    Thanks!
    ..Ben

    By Anonymous Anonymous, at March 10, 2008 at 7:53 PM  

  • Hi Ashis,
    Thanks for this.
    Suppose I need the initparams in my page.cs. Is there any way to get to the initparams from there or do you have to create a constructor that passes the initparams to the page?

    By Blogger Rob, at March 11, 2008 at 1:20 AM  

  • Rob, from my understanding, is that, this is done BEFORE the SL is even loaded which is at ASP page (parent container) level to pass the parameters to the SL Page.

    Hope I didn't mislead you!
    ..Ben

    By Anonymous Anonymous, at March 11, 2008 at 7:32 AM  

  • Very helpful and very needed/important.

    By Anonymous Anonymous, at March 11, 2008 at 11:33 AM  

  • Rob: You can create a custom property on the application type and assign it the value of the initParams, if you want to use it in a Page class elsewhere in the app. Since this is a simple workaround, and to minimize any disparities between the WPF and Silverlight application models, this isn't already done by default in Silverlight.

    By Blogger Ashish Shetty, at March 11, 2008 at 4:42 PM  

  • Is there a similar method to pass parameters if I'm using the Asp.Net Silverlight server control?

    By Anonymous Anonymous, at March 23, 2008 at 9:25 PM  

  • If you're using the asp:silverlight control, you can use the same approach. The property is called InitParameters.

    By Blogger Ashish Shetty, at April 15, 2008 at 10:25 PM  

  • Here's an example step by step:

    1. The Silverlight control:
    In the Default.Aspx page, I have the following Silverlight control:

    < asp:Silverlight ID = "slvTest01" runat="server" Source="~/ClientBin/Silverlight04App.xap" MinimumVersion="2.0.30523" Width="100%" Height="800" />

    2. Assign parameteres through code:
    In the “Page_Load” for this host page (Default.Aspx), two Key-Value pairs are being assigned through “InitParameters”:

    slvTest01.InitParameters = "TheValue1=something,TheValue2=321";

    3. Define properties for the Silverlight control:
    Inside “Page.xaml.cs”, two properties are defined:

    #region The Properties
    public String TheValue1 {get;set;}
    public String TheValue2 {get;set;}
    #endregion The Properties

    4. Read InitParams:
    In the “App.xaml.cs” file, inside the “Application_Startup” event, read the values from InitParams, and assign them to the properties previously defined:

    private void Application_Startup( object sender, StartupEventArgs argTheEventData )
    {
    Page pagTheSilverlightControl;
    IDictionary<String, String> dicTheParameters ;

    //Obtain parameters:
    dicTheParameters = argTheEventData.InitParams;

    //Create instance:
    pagTheSilverlightControl = new Page();

    //Assign parameters:
    if ( dicTheParameters.ContainsKey( "TheValue1" ) )
    {
    pagTheSilverlightControl.TheValue1 = dicTheParameters[ "TheValue1" ];
    }
    if ( dicTheParameters.ContainsKey( "TheValue2" ) )
    {
    pagTheSilverlightControl.TheValue2 = dicTheParameters[ "TheValue2" ];
    }
    }

    IMPORTANT: Notice that the “Application_Startup” event is in “App.xaml.cs” and not in “Page.xaml.cs” (or however you call your control)

    5. Use values sent
    Inside “Page.xaml.cs” use the values according to your needs. For example:

    lblTheTitle.Content = this.TheValue2;

    To send “special” characters:
    Values being sent through “InitParameters” are not automatically escaped so, if you directly send an “=” or a “,” as a value, it won’t work. You need to “escape” them yourself. For example, to send a connection string, you could do something like this:

    1. Assign parameters:
    In the “Page_Load” for the host page, assign and escape the connection string with something like this:

    slvTest01.InitParameters = String.Format( "cnnNorthwind={0}", ConfigurationManager.ConnectionStrings[ "cnnNorthwind" ].ConnectionString.Replace( "=", "&eq;" ) );


    4. Read InitParams:
    In the “App.xaml.cs” file, inside the “Application_Startup” event, read and unescape the values from InitParams:

    private void Application_Startup( object sender, StartupEventArgs argTheEventData )
    {
    Page pagTheSilverlightControl;
    IDictionary<String, String> dicTheParameters ;

    //Obtain parameters:
    dicTheParameters = argTheEventData.InitParams;

    //Create instance:
    pagTheSilverlightControl = new Page();

    //Assign parameters:
    if ( dicTheParameters.ContainsKey( "cnnNorthwind" ) )
    {
    pagTheSilverlightControl.TheConnectionString = dicTheParameters[ "cnnNorthwind" ].Replace( "&eq;", "=" );
    }
    }

    By Blogger Jelgab, at August 27, 2008 at 1:47 PM  

  • Commas and equal signs can be passed by using Server.UrlEncode(myParam) on the asp code behind, and HttpUtility.UrlDecode(myParam) in silverlight.

    By Anonymous Anonymous, at February 9, 2009 at 3:02 AM  

  • hi ashish,
    thanx for the gr8 blog.

    In my project i used hidden fields on my corresponding aspx page which holds silverlight object.Those value are set in the code behind throgh db call.Is there any advantage or benefit of doing it the way u have shown above? if yes then could u explain it little?
    thanx for ur time

    By Anonymous Anonymous, at March 25, 2009 at 3:08 AM  

  • Where do you define the param name as in the following code?

    param name="source" value="ClientBin/SLInitParams.xap"

    I would have thought this would go in the xaml control but it will not accept this.

    By Anonymous Anonymous, at June 24, 2009 at 3:49 AM  

  • Is it just me or does your code from skydrive gives a KeyNotFound Exception right off the bat?

    By Anonymous Anonymous, at December 7, 2009 at 1:22 AM  

  • Nice & simple and too the point

    You ROck :-)

    By Anonymous Anonymous, at June 9, 2011 at 5:49 PM  

Post a Comment | Home | Inference: my personal blog