How to supply startup parameters to Silverlight applications using InitParams

Lets talk about how you can pass some start up parameters to your silverlight application. In this post I will talk about how you can do it with ASP.Net Silverligh control. The control allows passing start up parameters through InitParamaters property. You can specify the parameters as commans separated key-value pair string. So you can pass values as described below.

    
    InitParameters="key1=value1,key2=value"
    

So a simple definition of asp:Silverlight may look like the snippet below. You can see that it is specifying two initial parameters k1 and k2 with value. And if you put a break point in Application_Startup event of your silverlight application, you can see two parameters as show in image.


<asp:Silverlight ID="Xaml1" runat="server" 
    Source="~/ClientBin/InitParamsMgr.xap" 
    MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
    InitParameters="k1=v1,k2=v2" />

This look all well and good. Problem comes when you have one or more values that have commas embedded in it. If you pass those value as such, framework is going to treat occurance of comma as separator and going to present you with parameters that are not parameters. Look at the code snippet below where value for k2 key has comma in it. And look at the screen shot showing how the parameters look like in debugger in application.


<asp:Silverlight ID="Xaml1" runat="server" 
    Source="~/ClientBin/InitParamsMgr.xap" 
    MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
    InitParameters="k1=v1,k2=v2,vx" />

Clearly you can see that application thinks that there are 3 parameters. Somebody suggested how about repalcing comma in the value with some special character. Then I was like, what if that special character is part of value as well. I was looking for a solution that is generic and would not require any custom parsing in silverlight application. So I came up with solution of replacing comma with URL encoded value %2C. And then in application I can use Uri.UnescapeDataString to decode the value. So now the mark up looks as follows and in snapshots you can see that application treats two values correctly.


<asp:Silverlight ID="Xaml1" runat="server" 
    Source="~/ClientBin/InitParamsMgr.xap" 
    MinimumVersion="2.0.31005.0" Width="100%" Height="100%"
    InitParameters="k1=v1,k2=v2%2cvx" />


private void Application_Startup(object sender, StartupEventArgs e)
{
 if (e.InitParams.Count != 0)
 {
  string k2val = e.InitParams["k2"];
  k2val = Uri.UnescapeDataString(k2val);
 }
 this.RootVisual = new Page();
}


Here is the list of URL encodings for special characters.

  • Space  %20
  • "  %22
  • #  %23
  • %  %25
  • &  %26
  • (  %28
  • )  %29
  • +  %2B
  • ,  %2C
  • /  %2F
  • :  %3A
  • ;  %3B
  • <  %3C
  • =  %3D
  • >  %3E
  • ?  %3F
  • @  %40
  • \  %5C
  • |  %7C

Search

Social

Weather

-1.1 °C / 30.1 °F

weather conditions Snow

Monthly Posts

Blog Tags