App.config for WP7 applications

When developing applications it is always a good idea not to hardcode database connections, urls, server locations, etc... In .NET there's the Configuration stack that allows us to use the app.config xml file. Unfortunately this functionality doesn't exist in Silverlight as well as in the Windows Phone 7. However I always remember that there's an excellent set of Mobile Application Blocks that includes the Configuration block (I have been successfully using this block on all mobility projects I've ever been involved). It didn't take me too long to make port of this block's code to the WP7 platform. Most of the changes that I had to make where related to the usage of the non generic collections and the fact that we need to use the Application.GetResourceStream method instead of the file IO access. The best thing is that the usage of this block is very close to an existing .NET code which requires a few steps. First you'd need to create an implementation for your ConfigurationSection, ConfigurationElement, and ConfigurationElementCollection. Then you add app.config file to your project and make sure that it has the the Build Action set to "Content". The last step is to add the code that reads the values from this configuration file:

// Get section
ApplicationSettingsSection section  = (ApplicationSettingsSection)ConfigurationManager.GetSection("ApplicationSettings");

// Display values
this.textBlock1.Text = section.AppSettings["localServer"].Value;
this.textBlock2.Text = section.AppSettings["remoteServer"].Value;

You can download the sample client that includes implementation of the ApplicationSettingSection as well as the port of the Mobile Configuration here.

P.S. This port of the Mobile Configuration block should work just fine in desktop version of the Silverlight.

Comments (3)

  1. Nick says:

    Hey Alex, great post on using the Configuration block but it does make me wonder why you would go down that approach when you can simply create a strongly typed object that represents the configuration elements you want and add an instance of it to the App.xaml file in the Application.Resources section? (hopefully that makes sense, otherwise I might have to explain myself….)

  2. AlexYak says:

    You are right, but I think the whole purpose of the external configuration file is to decouple configuration from the application and allow changing settings without recompiling the whole app. Plus this implementation should allow an easier migration of the existing projects.

    Thanks… Alex

  3. In the end, the only way to deploy the app is to repackage it and send it to the AppHub. You'll never have an instance where a user can modify the app.config file, so it's pointless other than if you find it beneficial for your own development purposes.

Skip to main content