Silverlight读取Web.config配置文件

Silverlight读取Web.config配置文件,第1张

概述Silverlight Application是客户端程序,没有也无法访问服务端的web.config,它自己也不允许添加.config文件,加上Silverilght 3.0之后,原来ASP.NET 2.0中的Silveright控件也被去掉了,要读取web.config就又更困难了一些。 不过如果仔细分析一下的话,可以发现Silverlight App是由一个Web Application来h

Silverlight Application是客户端程序,没有也无法访问服务端的web.config,它自己也不允许添加.config文件,加上Silverilght 3.0之后,原来ASP.NET 2.0中的Silveright控件也被去掉了,要读取web.config就又更困难了一些。

不过如果仔细分析一下的话,可以发现Silverlight App是由一个Web Application来host的,而那个Web Application是可以方便地配置的,于是,可以考虑由网站来把配置传给Silverlight,宿主Silverlight的Page文件中会有这样一段代码:

<param name="source" value="ClIEntBin/GetWebConfig.xap"/><param name="onError" value="onSilverlightError" /><param name="background" value="white" /><param name="minRuntimeVersion" value="4.0.50826.0" /><param name="autoUpgrade" value="true" />


可以看到这里有很多关于Silverlight的参数,我们可以从这段代码下手,在这里为其添加一个新的参数:

<param name="InitParams" value="127.0.0.1" /> 


可以看到其中有一个param标签的name为InitParams,其值可以在App.xaml.cs中的Application_Startup事件处理方法中,使用传入StartupEventArgs参数的InitParams属性取得,类型为IDictionary<string,string>。下面来看一下具体的方法:

1. 首先,我们需要在Page文件中加入一个literal控件,以便能够动态地将<param name="InitParams" value="" />赋到Page中,但是在Visual Studio 2010里,默认为我们创建的ASPX页面没有.cs文件,需要我们创建一个新的ASPX页面,把原先<HTML></HTML>当中的内容copy过来,并加上literal控件,如下方代码所示:

<%@ Page Language="C#" autoEventWireup="true" CodeBehind="HostPage.aspx.cs" inherits="GetWebConfig.Web.HostPage" %><!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 runat="server">    <Title>GetWebConfig</Title>    <style type="text/CSS">    HTML,body {	    height: 100%;	    overflow: auto;    }    body {	    padding: 0;	    margin: 0;    }    #silverlightControlHost {	    height: 100%;	    text-align:center;    }    </style>    <script type="text/JavaScript" src="Silverlight.Js"></script>    <script type="text/JavaScript">        function onSilverlightError(sender,args) {            var appSource = "";            if (sender != null && sender != 0) {                appSource = sender.getHost().source;            }            var errorType = args.ErrorType;            var IErrorCode = args.ErrorCode;            if (errorType == "ImageError" || errorType == "MediaError") {                return;            }            var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";            errMsg += "Code: " + IErrorCode + "    \n";            errMsg += "category: " + errorType + "       \n";            errMsg += "Message: " + args.ErrorMessage + "     \n";            if (errorType == "ParserError") {                errMsg += "file: " + args.xamlfile + "     \n";                errMsg += "line: " + args.lineNumber + "     \n";                errMsg += "position: " + args.charposition + "     \n";            }            else if (errorType == "RuntimeError") {                if (args.lineNumber != 0) {                    errMsg += "line: " + args.lineNumber + "     \n";                    errMsg += "position: " + args.charposition + "     \n";                }                errMsg += "Methodname: " + args.methodname + "     \n";            }            throw new Error(errMsg);        }    </script></head><body>    <form ID="form1" runat="server">    <div ID="silverlightControlHost">        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" wIDth="100%" height="100%">		  <param name="source" value="ClIEntBin/GetWebConfig.xap"/>		  <param name="onError" value="onSilverlightError" />		  <param name="background" value="white" />		  <param name="minRuntimeVersion" value="4.0.50826.0" />		  <param name="autoUpgrade" value="true" />                  <asp:literal ID="litinitParams" runat="server" />		  <a href="http://go.microsoft.com/fwlink/?linkID=149156&v=4.0.50826.0" > 			  <img src="http://go.microsoft.com/fwlink/?linkID=161376" alt="Get Microsoft Silverlight" />		  </a>	    </object><iframe ID="_sl_historyFrame" ></iframe></div>    </form></body></HTML>

2. 接下来,我们要在这个页面的后台.cs文件中读取web.config的内容,并且把它赋给literal控件:

using System;using System.Collections.Generic;using System.linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Collections.Specialized;using System.Web.Configuration;using System.Text; namespace SL_ReadConfigfile.Web{    public partial class SL_ReadConfigfile : System.Web.UI.Page    {        private string _seperator = ",";         protected voID Page_Load( object sender,EventArgs e )        {            Response.Cache.SetCacheability( httpCacheability.NoCache );            WriteInitParams();        }         private voID WriteInitParams()        {            nameValueCollection appSettings = WebConfigurationManager.AppSettings;            StringBuilder stringBuilder = new StringBuilder();            stringBuilder.Append( "<param name=\"InitParams\" value=\"" );            string paramContent = string.Empty;            for( int i = 0 ; i < appSettings.Count ; i++ )            {                if( paramContent.Length > 0 )                {                    paramContent += _seperator;                }                paramContent += string.Format( "{0}={1}",appSettings.GetKey( i ),appSettings[ i ] );             }             stringBuilder.Append(paramContent );             stringBuilder.Append( "\" />" );             this.litinitParams.Text = stringBuilder.ToString();         }     } }

3. 在App.xaml.cs中的Application_Startup事件处理方法中,使用传入StartupEventArgs参数的InitParams属性取得,类型为IDictionary<string,string>:

using System;using System.Collections.Generic;using System.windows; namespace SL_ReadConfigfile{    public partial class App : Application    {        private IDictionary<string,string> _configurations;        public IDictionary<string,string> Configurations        {            get            {                return _configurations;            }        }         public App()        {            this.Startup += this.Application_Startup;            this.Exit += this.Application_Exit;            this.UnhandledException += this.Application_UnhandledException;            InitializeComponent();        }         private voID Application_Startup( object sender,StartupEventArgs e )        {            _configurations = e.InitParams;            this.RootVisual = new MainPage();        }         private voID Application_Exit( object sender,EventArgs e )        {         }         private voID Application_UnhandledException( object sender,ApplicationUnhandledExceptionEventArgs e )        {            if( !System.Diagnostics.DeBUGger.IsAttached )            {                e.Handled = true;                Deployment.Current.dispatcher.BeginInvoke( delegate { ReportErrorTodoM( e ); } );            }        }          private voID ReportErrorTodoM( ApplicationUnhandledExceptionEventArgs e )        {            try            {                string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;                errorMsg = errorMsg.Replace( '"','\'' ).Replace( "\r\n",@"\n" );                System.windows.browser.HTMLPage.Window.Eval( "throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");" );            }            catch( Exception )            {            }        }    }}

4. 最后就是在Silverlight页面当中获取InitParams的值并显示到页面上:

<UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="SL_ReadConfigfile.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"    mc:Ignorable="d"    d:DesignWIDth="800" d:DesignHeight="600"    WIDth="auto" Height="auto" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">     <GrID x:name="LayoutRoot" Background="transparent">        <GrID.RowDeFinitions>            <RowDeFinition Height="50"></RowDeFinition>            <RowDeFinition></RowDeFinition>            <RowDeFinition Height="30"></RowDeFinition>        </GrID.RowDeFinitions>        <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24">Silverlight Reads web.config Demo</TextBlock>        <sdk:DataGrID GrID.Row="1" name="dgdConfigurations">        </sdk:DataGrID>        <StackPanel OrIEntation="Horizontal" GrID.Row="2" HorizontalAlignment="Center">            <@R_404_5554@ name="btnShowEntry" WIDth="200" margin="10,0" Click="btnShowEntry_Click">                <StackPanel OrIEntation="Horizontal">                    <TextBlock VerticalAlignment="Center">Read number</TextBlock>                    <toolkit:Numericupdown name="numericupdown" margin="5,0" DecimalPlaces="0"/>                    <TextBlock VerticalAlignment="Center">entry</TextBlock></StackPanel>            </@R_404_5554@>            <@R_404_5554@ name="btnBindConfig" WIDth="200" margin="10,0" Click="btnBindConfig_Click">Binding Configurations</@R_404_5554@>        </StackPanel>    </GrID></UserControl>
using System;using System.Collections.Generic;using System.linq;using System.Net;using System.windows;using System.windows.Controls;using System.windows.documents;using System.windows.input;using System.windows.Media;using System.windows.Media.Animation;using System.windows.Shapes; namespace SL_ReadConfigfile{    public partial class MainPage : UserControl    {        private IDictionary<string,string> _configurations;        public MainPage()        {            InitializeComponent();             _configurations =  ( Application.Current as App ).Configurations;             if( _configurations.Count > 0 )            {                numericupdown.Minimum = 1;                numericupdown.Maximum = _configurations.Count;            }         }         private voID btnBindConfig_Click( object sender,RoutedEventArgs e )        {            this.dgdConfigurations.ItemsSource = _configurations;        }         private voID btnShowEntry_Click( object sender,RoutedEventArgs e )        {            string entryContent = string.Format( "{0} = {1}",_configurations.ElementAt( ( int ) numericupdown.Value - 1 ).Key,_configurations.ElementAt( ( int ) numericupdown.Value - 1 ).Value );            MessageBox.Show( entryContent );        }    }}

 

5. 我们已经可以读取到web.config里面的值了,但是,要注意的是,在ASPX页面当中InitParams会以明文显示在Source Code当中,如果是数据库连接串或是其他需要加密的信息,请自己开发加密算法来解决这一问题,下一篇我会介绍如何加密InitParams中的值。

总结

以上是内存溢出为你收集整理的Silverlight读取Web.config配置文件全部内容,希望文章能够帮你解决Silverlight读取Web.config配置文件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/web/1074232.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-26
下一篇 2022-05-26

发表评论

登录后才能评论

评论列表(0条)

保存