开发者

Can I access web.config with an XBAP?

I'm porting a Silverlight 4 app to WPF/XBAP. The app uses initParams initialized using asp from web.config app setting parameters.

Unlike Silverlight, WPF lacks an InitParams property on StartupEventArgs.

It sure seems like this would be something BrowserInteropHelper would help me do, but I don't see anything.

Is there some way to access config开发者_C百科 params from the web.config to the app at startup?


My workaround has been to add a web service to the web site that hosts the xbap, and call it when the app starts up using the BrowserInteropHelper.Source to determine the uri for the endpointaddress.

public class ConfigService : IConfigService
{
    public WebConfiguration GetWebConfig()
    {
        var outDict = new Dictionary<string, string>();
        foreach (string key in WebConfigurationManager.AppSettings.AllKeys)
        {
            outDict.Add(key, WebConfigurationManager.AppSettings[key]);
        }
        var webconfig = new WebConfiguration();
        webconfig.AppSettings = outDict;
        return webconfig;
    }
}

[DataContract]
public class WebConfiguration
{
    [DataMember]
    public Dictionary<string, string> AppSettings { get; set; }
}

Here's how the client calls it:

private void Application_Startup(object sender, StartupEventArgs e)
{
    try
    {
        var b = new System.ServiceModel.BasicHttpBinding();

        string url;

        // when running xbap directly in browser the port is -1
        if(BrowserInteropHelper.Source.Port != -1)
        {
            url = String.Format("http://{0}:{1}/ConfigService.svc",
            BrowserInteropHelper.Source.Host,
            BrowserInteropHelper.Source.Port);
        }
        else
        {
            url = @"http://localhost.:51007/ConfigService.svc";
        }
        var address = new System.ServiceModel.EndpointAddress(url);
        SDDM3.ConfigServiceReference.ConfigServiceClient c = new ConfigServiceClient(b, address);
        c.GetWebConfigCompleted +=new EventHandler<GetWebConfigCompletedEventArgs>(c_GetWebConfigCompleted);
        c.GetWebConfigAsync(url);
        this.MainWindow.Content = new UserControl1();
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}
void c_GetWebConfigCompleted(object sender, GetWebConfigCompletedEventArgs e)
{
    if (e.Error == null)
    {
        // MessageBox.Show(e2.Result.
        m_AppSettings = e.Result.AppSettings;
        MessageBox.Show("got appsettings: " +  e.Result.AppSettings.Count.ToString());                
        this.MainWindow.Content = new Page1();
    }
    else
    {
        string msg;
        if (e.UserState != null)
            msg = String.Format("Unable to get config from: \n{0} \n{1}", e.UserState, e.Error.Message);
        else
            msg = String.Format("Unable to get config: \n{0}", e.Error.Message);
        MessageBox.Show(msg);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜