Sunday, August 9, 2009

using init parameters with silverlight

if you are writing highly configurable applications in silverlight we may want to use a lot of parameters that the user can set. Since there is no config file with silverlight because it runs on the client you can set these parameters in the web.config of the web application that launches your silverlight application.

First you need to add some setting in the web.config file of the web app that launches your silverlight

Here below I have a WFC service that can change for each user install. So I needed to configure the WCF URI that I will be using from Silverlight. In my web.config I added a simple Key value setting in Appsettings in the web.config file.







Secondly in the page load event of the Form that launches you Silverlight App you need to have this code. Reads the Web.config and then dynalically loads up silverlight init parameters.

This is the markup for the silverlight control in the ASPX page.
<asp:silverlight id="MySilverligtControl" runat="server" windowless="true" source="~/ClientBin/MySilverligtApp.SL.xap?v=1.00.00.09" minimumversion="2.0.31005.0" width="100%" height="100%">


protected void Page_Load(object sender, EventArgs e)
{
// required to load parameters to Silverlight. As silverlight runs on the client it has no config file
StringBuilder configSettings = new StringBuilder();
configSettings.AppendFormat("{0}={1}", "MyServiceURI",System.Configuration.ConfigurationSettings.AppSettings["MyServiceURI"].ToString());
configSettings.Append(",");
configSettings.AppendFormat("{0}={1}", "MyNextParameter", System.Configuration.ConfigurationSettings.AppSettings["MyNextparameter"].ToString());
MySilverligtControl.InitParameters = configSettings.ToString();
}

In silverlight app. in your app.xaml code behind in the Application_Startup event you add this piece of code.

private void Application_Startup(object sender, StartupEventArgs e)
{
// Load up Parameters from WEB.Config
Application.Current.Resources.Add("MyServiceURI", e.InitParams["MyServiceURI"]);
Application.Current.Resources.Add("MyNextParameter", e.InitParams["MyNextParameter"]);
}


that's it. you can now have parameters set in web.config and read by the silverlight application.

No comments: