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.
    <add key="MyKeyForSilverlightApp" value="Hello Silverlight"/>
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="" style="text-decoration: none">
            <img src="" alt="Get Microsoft Silverlight" style="border-style: none" />
    <iframe id="_sl_historyFrame" style="visibility: hidden; height: 0px; width: 0px; border: 0px"></iframe>
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.


1 comment:

  1. Thank you for blogging this! It was exactly what I needed.