Read appsetting in web.config from a Silverlight application

It’s a common request to be able to read app setting (connection string, user setup etc.) from the web.config file. In ASP.NET, you can just use “System.Configuration.ConfigurationManager”. However, Since Silverlight applications run on the client side; it cannot access server resources such as web.config. It’s might be possible to get app settings from the “ServiceReferences.ClientConfig” that is included in the XAP file, but it’s going to be cumbersome to change settings. There are two viable solutions:

The first solution is to actually not store configuration data in your web.config file, but to another XML file which would be made available by IIS like any other network resource. This file could then be downloaded, parsed and interpreted by the XAP. Sample code from Stackoverflow.

public static string GetSomeSetting(string settingName){
    var valueToGet = string.Empty;
    var reader = XmlReader.Create("XMLFileInYourRoot.Config");
    reader.MoveToContent();
 
    while (reader.Read()) {
        if (reader.NodeType == XmlNodeType.Element && reader.Name == "add") {
            if (reader.HasAttributes) {
                valueToGet = reader.GetAttribute("key");
                if (!string.IsNullOrEmpty(valueToGet) && valueToGet == setting) {
                    valueToGet = reader.GetAttribute("value");
                    return valueToGet;
                }
            }
        }
    }
    return valueToGet;
}

The second solution, usually simpler to implement, makes use of ASP.NET’s ConfigurationSettings class and passes the web.config values to the Silverlight.InitParameters property. This works as follows:

1. Add the Configuration Information to the Web.config File

The relevant part of config file.
<configuration>
  <appSettings>
    <add key="app_name" value="QC retention"/>    
    <add key="admin_password" value="abc"/>    
  </appSettings>
</configuration>

2. Pass the Configurations to the Silverlight Object

Add the following literal to the body section of the default.aspx (the one client access). It serves as a place holder waiting for the next step to fill in.

<asp:Literal ID="ParamInitParams" runat="server"></asp:Literal>

3. Prepare the InitParams for passing to client

At Page_Load event handler of the default.aspx use Configuration.ConfigurationManager to get all the settings formatted as “key=value” pair separated by a comma. Hash code the password section. Create a param with name “InitParams” and the setting string as value. Add the first line if there is no code behind file.

<script runat="server">
private void Page_Load() {
    //To pass appsettings from web.config to the client.
    Response.Cache.SetCacheability(HttpCacheability.NoCache);
    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++) {
        string _key = appSettings.GetKey(Idex);
        string _value = appSettings[Idex];
        SB.Append(_key);
        SB.Append("=");
		// send hashed code to the client, it's plain txt in client browser.
        if (_key.Contains("password")) { 
            _value = _value.GetHashCode().ToString();
        }
        SB.Append(_value);
        SB.Append(",");
    }
    SB.Remove(SB.Length - 1, 1); // remove the last ","
    SB.Append("\" />");
 
    ParamInitParams.Text = SB.ToString();
}
</script>

4. Access the Configuration Information in the Silverlight Application

If you look at client side page view source you can find the following:

<!-- This is ASP.NET code behind accessible object to add the configuration -->
<param name="InitParams" value="app_name=QC retention,admin_password=536991770" />

Please be noted that password has been replaced with its hash code.

In order for the Silverlight application to be able to access the configuration information passed over, a public variable “DeploymentConfigurations” is added 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”.
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.

public partial class App : Application {
    public IDictionary<string, string> DeploymentConfigurations;
 
    private void Application_Startup(object sender, StartupEventArgs e) {
        // added for reading from web.config
        DeploymentConfigurations = e.InitParams;
        this.RootVisual = new MainPage();
    }
}

5. All Done! use it wherever you want.

Since DeploymentConfigurations is a Dictionary, you can just pass in the key name in Web.config to get its value. The following is from a code behind file a xaml view.

void DoTheChecking() {
    App application = (App)(Application.Current);
    if (ThePasswordBox.Password.GetHashCode().ToString() != application.DeploymentConfigurations["admin_password"]) {
    //if (ThePasswordBox.Password != ThePassword) {
        MessageBox.Show("The entered password is invalid, please check and enter again.");
        ThePasswordBox.Password = "";
        ThePasswordBox.Focus();                
    }
    else {
        this.DialogResult = true;
    }
}

Conclusion

On the server side, app settings are read from Web.config file by useing ConfigurationManager. A comma delimitated text string formatted as key=value passed to the “InitParams” startup parameter of the Silverlight object. When 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. Since “=” and “,” are used for the data formatting, they can not be used in the setting as either key or value. The settings are in plain text in the ASPX page, any one can read it by viewing the source of the hosting web page, Hash code applies to all the password.

How to find my external IP address

If you computers are sitting behind a router/firewall, then running Ipconfig would not give you the external IP address. One can use http://www.whatsmyip.org/ for ad-hoc queries, but if you want to automate the checks you might want something simpler and easier to parse. The followings are the options I found.

The c# code to find out your external IP:

public string GetPublicIP() {
    String direction = "";
    WebRequest request = WebRequest.Create("http://checkip.dyndns.org/");
    using (WebResponse response = request.GetResponse())
    using (StreamReader stream = new StreamReader(response.GetResponseStream())) {
        direction = stream.ReadToEnd();
    }
 
    //Search for the ip in the html
    int first = direction.IndexOf("Address: ") + 9;
    int last = direction.LastIndexOf("</body>");
    direction = direction.Substring(first, last - first);
 
    return direction;
}