Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Configure Silverlight 3 Applications using the Web.config File from ASP.NET

0.00/5 (No votes)
6 Jan 2010 2  
This article introduces a method to configure Silverlight 3 applications using the Web.config file from ASP.NET.

Introduction

This article introduces a method to configure Silverlight 3 applications using the Web.config file from ASP.NET.

Background

Rich Internet Applications or RIAs are attracting more and more attention in the IT field with the advent of XML Web Services and, more recently, WCF technologies. Three major competing technologies represent the advancement of the RIA technology. They are Adobe Flex, JAVA Applet, and Silverlight. Being available everywhere on every computer, Adobe clearly has its advantages. JAVA applet is no longer as popular, but its glorious past and its crystal clear JAVA programming environment should be an indication of its future revival. Silverlight comes later compared with the other two, but the beautiful .NET programming environment and the tight integration with WCF makes it an ideal platform to develop serious IT applications. We should expect to see the three technologies co-exist for a long time in the future. In this article, we will be focusing on Silverlight and introducing a method to configure Silverlight applications using the Web.config file from the ASP.NET host web application.

One of my recent Silverlight projects needs to communicate with a WCF service to transfer some business data with the database server. The server administrator asked me if I could let him change the Web.config file of the hosting ASP.NET application to specify the address of the WCF service. He has been very familiar with supporting ASP.NET applications using IIS, and it has been a standard practice to use the Web.config file to configure applications hosted by IIS. By studying the way that a Silverlight application is embedded in an ASP.NET page and the "InitParams" parameter of Silverlight applications, I found a method. The following is a step by step introduction of this method by using a simple example Visual Studio solution.

The example code was developed using Visual Studio 2008 and Silverlight 3.

Create a Silverlight Application in Visual Studio 2008

To create a Silverlight application, you need to have a version of the Silverlight Toolkit installed on your computer. The version that I used for this example is Silverlight 3. After installing the toolkit, you can open Visual Studio 2008 and create a Silverlight application and name it "SilverlightConfigurationDemo". When the Wizard asks if you want to create a host web application, choose "Yes" and change the default name for this web application to "SilverlightConfigurationDemoWeb". Follow the rest of the instructions from Visual Studio. The Solution Explorer looks like the following when we finish creating the Silverlight application:

Solution Explorer

Visual Studio creates two projects. One is the Silverlight application and the other is the host ASP.NET web application. The web application is the default startup project. Both projects are added to a Visual Studio solution called "SilverlightConfigurationDemo", which is the same name as the Silverlight application project. The above picture shows the two projects in the Solution Explorer.

In the hosting ASP.NET web application project, you will notice two files created by Visual Studio. They are "SilverlightConfigurationDemoTestPage.aspx" and "SilverlightConfigurationDemoTestPage.html". Visual Studio has already created the required HTML, styles, and JavaScript to host the Silverlight application in the two files. In fact, we can use any web page to host the Silverlight application. In this article, we will be using "Default.aspx", as you will see later.

Add the Configuration Information to the Web.config File

For demonstration purposes, we will add the following to the Web.config file:

<appSettings>
 <add key="ApplicationName" value="Silverlight Configuration Demonstration"/>
 <add key="WCFEndPointAddress" value="http://localhost/HelloService/MyService" />
 <add key="AnotherWCFEndPointAddress" 
  value="http://localhost/AnotherService/MyanotherService"/>
 <add key="Author" value="Song Li"/>
 <add key="Version" value="1.0.0.0"/>
 <add key="DeploymentTime" value="01/01/2010"/>
 <add key="CopyRight" value="The Code Project Open License (CPOL)"/>
 <add key="OtherSilverlightApplicationInfo" 
  value="Whatever needed to send to Silverlight application @ deployment time"/>
</appSettings>

This XML block needs to be added immediately inside the "<configuration>" tag in the Web.config file.

Host the Silverlight Application in Default.aspx and Pass the Configurations to the Silverlight Object

In order to host the Silverlight application in the "Default.aspx" file, we change the "Default.aspx" code like the following:

<%@ Page Language="C#" 
    AutoEventWireup="true" CodeBehind="Default.aspx.cs" 
    Inherits="SilverlightConfigurationDemoWeb.Default" %>
    
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
    <title>Silverlight Configuration Demonstration</title>
    
    <!-- Link the Microsoft generated style -->
    <link href="Styles/SilverlightDefault.css" 
       rel="stylesheet" type="text/css" />
    
    <!-- Link the Microsoft generated JAVA scripts -->
    <script src="JS/Silverlight.js" type="text/javascript"></script>
    <script src="JS/SilverlightDefault.js" type="text/javascript"></script>
</head>
 
<body>
    <form id="frmMain" runat="server">
    <div>
        <object data="data:application/x-silverlight-2,"
            type="application/x-silverlight-2"
            width="100%" height="100%">
    <param name="source" value="ClientBin/SilverlightConfigurationDemo.xap"/>
    <param name="onError" value="onSilverlightError" />
    <param name="background" value="white" />
    <param name="minRuntimeVersion" value="3.0.40624.0" />
    <param name="autoUpgrade" value="true" />
    
    <!-- This is ASP.NET code behind accessible object to add the configuration -->
    <asp:Literal ID="ParamInitParams" runat="server"></asp:Literal>
    
    <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" 
          style="text-decoration:none">
          
      <img src="http://go.microsoft.com/fwlink/?LinkId=108181" 
        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>
    </form>
</body>
</html>

You will notice that the code in the "Default.aspx" file is very similar to the code generated by Visual Studio in the "SilverlightConfigurationDemoTestPage.aspx" file. Due to browser compatibility issues mentioned by Microsoft, I did not want to make significant changes from the code generated by Visual Studio. The only change that I made was to wrap the CSS styles and the JavaScript code that Visual Studio created in-line into different files. I then linked them in the "Default.aspx" to make the code clean.

One thing to mention is the ASP.NET Literal object "ParamInitParams" inserted inside the "<object>" tag that represents the Silverlight application in the ASP.NET page. This is the place where we will transfer the configuration information to the Silverlight object. The configuration information will be written by the C# code in the "Default.aspx.cs" file to this Literal object, as follows:

using System;
using System.Web;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
using System.Web.UI;
using System.Web.UI.WebControls;
 
namespace SilverlightConfigurationDemoWeb
{
    public partial class Default : System.Web.UI.Page
    {
        private void SaveSilverlightDeploymentSettings(Literal litSettings)
        {
            NameValueCollection appSettings = ConfigurationManager.AppSettings;
 
            StringBuilder SB = new StringBuilder();
            SB.Append("<param name=\"InitParams\" value=\"");
 
            int SettingCount = appSettings.Count;
            for (int Idex = 0; Idex < SettingCount; Idex ++)
            {
                SB.Append(appSettings.GetKey(Idex));
                SB.Append("=");
                SB.Append(appSettings[Idex]);
                SB.Append(",");
            }
            SB.Remove(SB.Length - 1, 1);
            SB.Append("\" />");
 
            litSettings.Text = SB.ToString();
        }
 
        protected void Page_Load(object sender, EventArgs e)
        {
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            SaveSilverlightDeploymentSettings(ParamInitParams);
        }
    }
}

The function "SaveSilverlightDeploymentSettings" reads the application settings from the Web.config file and writes the information to the Literal object "ParamInitParams" as comma delimitated name value pairs. The keys and values of the name value pairs are separated by the equal sign, "=".

Access the Configuration Information in the Silverlight Application

In order that the Silverlight application can access the configuration information passed over, we will add a public variable "DeploymentConfigurations" to the "App" class in the code behind file of App.xaml and initialize it in the "Application_Startup" function by the startup event argument "e.InitParams".

public IDictionary<string, string> DeploymentConfigurations;
 
private void Application_Startup(object sender, StartupEventArgs e)
{
 DeploymentConfigurations = e.InitParams;
 this.RootVisual = new MainPage();
}

After the initialization, the variable "DeploymentConfigurations" references an object of type "Dictionary". Each individual configuration parameter is saved in this "Dictionary" as a name value pair. Since the variable "DeploymentConfigurations" is defined in the "App" class, it is accessible throughout the Silverlight application.

To demonstrate a way to access the configuration parameters from the Silverlight application, we will make changes to the application's main XAML file, "MainPage.xaml", as follows:

<UserControl 
    xmlns:data="clr-namespace:System.Windows.Controls;
                assembly=System.Windows.Controls.Data"  
    x:Class="SilverlightConfigurationDemo.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="Verdana">
    
    <Grid x:Name="LayoutRoot" Margin="20, 20, 20, 20">
        <Grid.RowDefinitions>
            <RowDefinition Height="30"/>
            <RowDefinition Height="*"/>
            <RowDefinition Height="45"/>
        </Grid.RowDefinitions>
    
        <TextBlock Grid.Row="0"
           Text="Configure Silverlight Application 
                 from Web.config File Demonstration" 
           HorizontalAlignment="Center" 
           FontSize="14" 
           FontWeight="Bold" />
    
        <data:DataGrid Grid.Row="1"
           x:Name="dgConfigurations" AutoGenerateColumns="True"
           HeadersVisibility="All"  GridLinesVisibility="All"
           RowHeight="45" 
           RowBackground="White" 
           ColumnHeaderHeight="50"
           IsReadOnly="True" CanUserResizeColumns="True"
           VerticalAlignment="Stretch" 
           HorizontalAlignment="Stretch" />
            
        <Grid x:Name="ButtonRoot" 
                Grid.Row="2" HorizontalAlignment="Right">
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="300"></ColumnDefinition>
                <ColumnDefinition Width="20"></ColumnDefinition>
                <ColumnDefinition Width="250"></ColumnDefinition>
            </Grid.ColumnDefinitions>
            
            <Button x:Name="GetApplicationName" 
                Grid.Column="0" FontSize="12" 
                Content="Get Application Name from Configuration" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Center"
                Click="GetApplicationName_Click"/>
            
            <Button x:Name="DisplayAllConfiguration" 
                Grid.Column="2" FontSize="12" 
                Content="Display Configuration Information" 
                HorizontalAlignment="Stretch" 
                VerticalAlignment="Center"
                Click="DisplayAllConfiguration_Click"/>
        </Grid>
    </Grid>
</UserControl>

In "MainPage.xaml", we add a "DataGrid" and two "Button" controls. In the Click event of one of the "Button" controls, we will bind all the configuration data to the "DataGrid":

private void DisplayAllConfiguration_Click(object sender, RoutedEventArgs e)
{
  App application = (App)Application.Current;
  dgConfigurations.ItemsSource = application.DeploymentConfigurations;
}

In the Click event of the other "Button" control, we will obtain a particular configuration item using the "key" that we used in the "Web.config" file when configuring the parameters.

private void GetApplicationName_Click(object sender, RoutedEventArgs e)
{
  App application = (App)Application.Current;
  string ApplicationName = application.DeploymentConfigurations["ApplicationName"];
    
  MessageBox.Show(ApplicationName);
}

Run the Silverlight Application

After setting the project "SilverlightConfigurationDemoWeb" as the startup project and the "Default.aspx" file as the start page in Visual Studio, we can run the application in Debug mode. The following picture shows the application running in Google Chrome:

Run Application

Click the button "Display Configuration Information", and all the configuration information in the "Web.config" is shown in the "DataGrid". Click the button "Get Application Name from Configuration", and the configuration item "ApplicationName" is retrieved from the global "Dictionary" reference "DeploymentConfigurations" by the configuration key and is displayed using a "MessageBox".

Conclusion

This article introduced a simple way of configuring Silverlight applications using the "Web.config" file of the host ASP.NET application. The basic idea is to read the configuration information from the "web.config" file in ASP.NET and write it as a comma delimitated text string to the "InitParams" startup parameter of the Silverlight object. By the time the Silverlight application starts, this information is assigned to a public variable in the "App" class, so the configurations are globally accessible throughout the Silverlight application.

Points of Interest

  1. In Silverlight 2, Silverlight applications are inserted in to the host ASPX page as an ASP.NET web control. It was much easier to directly write the configuration information to the Silverlight web control than using the "Literal" web control as we did for Silverlight 3. This is not a bad thing, because the technique used in this article can be applied to pretty much all methods to authoring web pages, such as ASP, JSP, and Servlets.
  2. When writing the configuration information to the hosting ASPX page, the information is written as a comma delimited string and the "=" is used to separate the key and the parameter value. So, we should avoid using either comma or "=" signs in the configuration information. Since there is almost never a need to configure database connection strings in Silverlight applications, I do not feel this to be a big problem. But if you do need to pass comma or "=" in either your configuration key or value, you need to escape the two special characters.
  3. The configuration is written in plain text in the ASPX page, and any one can read it by viewing the source of your hosting web page. If security is a concern, you should encrypt your information.
  4. In most production environments, you may want to configure both the ASP.NET host and the Silverlight application in "Web.config". In this case, you may need to identify the configuration items for the Silverlight application and only pass these items to Silverlight.

History

This is the first edition of this article.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here