Wednesday, December 4, 2013

Read web.config from a Silverlight Application

When developing silverlight applications sometimes we are facing this situation where we need to read some values from web applications’ web.config file. This is how you can accomplish such a need.

I have added a key “MyKeyForSilverlightApp” under appsettings section in the web.config file.
<appSettings>
    <add key="MyKeyForSilverlightApp" value="Hello Silverlight"/>
</appSettings>
In my aspx page which hosts the silverlight xap file, I am passing another key “MyKeyForSilverlightApp” as init params. This keys’ value is set by reading the web.config file.
<div id="silverlightControlHost">
    <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
        <param name="source" value="ClientBin/ReadWebConfigSilverlightApp.xap" />
        <param name="onError" value="onSilverlightError" />
        <param name="background" value="white" />
        <param name="minRuntimeVersion" value="5.0.61118.0" />
        <param name="autoUpgrade" value="true" />
        <param name="initParams" value="MyKeyForSilverlightApp=<%= ConfigurationManager.AppSettings["MyKeyForSilverlightApp"] %>" />
        <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=5.0.61118.0" style="text-decoration: none">
            <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style: none" />
        </a>
    </object>
    <iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px; border: 0px"></iframe>
</div>
Now inside my Silverlight applications App.xaml.cs file, I can access the init params.
private void Application_Startup(object sender, StartupEventArgs e)
{
   string valueFromWebConfig = e.InitParams["MyKeyForSilverlightApp"];
   this.RootVisual = new MainPage();
}

I have uploaded a sample to my SkyDrive.


Happy Coding.

Regards,
Jaliya