Read Web.config AppSettings from Silverlight application

Some time ago I ran into the following scenario: “After the page loads read the cookie file to determine the default language. If there is no cookie read the AppSettings in the Web.config file and load this language”

It sounded pretty straight-forward, something like this:

var defaultLanguage =
ConfigurationManager.AppSettings["defaultLanguage"];

But not so fast! Because of Silverlight being a client side application we can’t access it directly but have to bee a little smarter about it.

In order to achive this you have to do the following things:

1. Define the value in Web.config

<appSettings>
<add key="defaultLanguage" value="English"/>
</appSettings>

2. Load the value into the aspx page

<object data="data:application/x-silverlight-2,"
type="application/x-silverlight-2"
width="100%" height="100%">
<param name="initParams" defaultLanguage=<%= ConfigurationManager.AppSettings["defaultLanguage"] %>"/>
</object>

3. Get the value in Silverlight

// App.xaml.cs file
public static string defaultLanguage;
private void Application_Startup(object sender,
StartupEventArgs e)
{
 defaultLanguage = e.InitParams["defaultLanguage"];
}

//Somewhere else in your code
var defaultLanguage = App.defaultLanguage;

Hope this might help someone out in the future.

Happy coding :)

Book challenge, week 12

Book challenge, week 11