Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Web Config Files in Silverlight

Im trying to use my web Config files in Silverlight.

I've put the following in web.config:

<configuration>
  <appSettings>
    <add key="FileHeader" value="file://***.com/Builds/"/>
    <add key="WebHeader" value="http://***.com/dev/builds"/>    
  </appSettings>

Im trying to use them like

string temp= System.Configuration!System.Configuration.ConfigurationManager.AppSettings.Get("FileHeader");

However it does not work, it gives an error "Only assignment, calls, increment, decrement...can be used as a statement"

like image 951
RKM Avatar asked May 20 '11 17:05

RKM


2 Answers

You cannot read web.config from your Silverlight application, because the Silverlight application runs on the client (in the browser) and not on the server.

From your server code you can access app settings with

string temp = Configuration.ConfigurationManager.AppSettings["FileHeader"];

but you have to send them to the client. You could do that by using InitParams

<param name="initParams" value="param1=value1,param2=value2" />

Within your server code (Page_Load of Default.aspx) you could loop through all AppSettings and create the value for the initParams dynamically.

In the Silverlight Application you can access the parameters in the Application_Startup event:

private void Application_Startup(object sender, StartupEventArgs e) 
{           
   this.RootVisual = new Page();
   if (e.InitParams.ContainsKey("param1"))
      var p1 = e.InitParams["param1"];
}

or loop through all parameters and store them in a configuration dictionary. Like this you have your app settings in the Silverlight application on the client.

like image 110
slfan Avatar answered Sep 30 '22 22:09

slfan


You can't read web.config from your Silverlight application because the configuration namespace does not exist in the SL .NET Framework, but what you can do is this:

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;
        }
like image 22
Keith Adler Avatar answered Sep 30 '22 21:09

Keith Adler