Могу ли я получить доступ к web.config с помощью XBAP? - PullRequest
0 голосов
/ 23 сентября 2011

Я портирую приложение Silverlight 4 на WPF / XBAP. Приложение использует initParams, инициализированный с помощью asp из параметров настройки приложения web.config.

В отличие от Silverlight, в WPF отсутствует свойство InitParams для StartupEventArgs .

Похоже, что это будет что-то BrowserInteropHelper поможет мне сделать это, но я ничего не вижу.

Есть ли какой-нибудь способ доступа к параметрам конфигурации из web.config к приложению при запуске?

1 Ответ

0 голосов
/ 24 сентября 2011

Мой обходной путь - добавить веб-сервис на веб-сайт, на котором размещен xbap, и вызывать его при запуске приложения, используя BrowserInteropHelper.Source для определения URI для адреса конечной точки.

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; }
}

Вот как это называет клиент:

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);
    }
}
...