现在的位置: 首页 > 综合 > 正文

Silverlight读取Web.config配置文件(转)

2013年05月19日 ⁄ 综合 ⁄ 共 11038字 ⁄ 字号 评论关闭

http://blog.csdn.net/xuyue1987/article/details/6706495

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文件中会有
这样一段代码:

  1. <param name="source" value="ClientBin/GetWebConfig.xap"/>  
  2. <param name="onError" value="onSilverlightError" />  
  3. <param name="background" value="white" />  
  4. <param name="minRuntimeVersion" value="4.0.50826.0" />  
  5. <param name="autoUpgrade" value="true" />  

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

  1. <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控件,如下方代码所示:

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="HostPage.aspx.cs" Inherits="GetWebConfig.Web.HostPage" %>  
  2.   
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>GetWebConfig</title>  
  8.     <style type="text/css">  
  9.     html, body {  
  10.         height: 100%;  
  11.         overflow: auto;  
  12.     }  
  13.     body {  
  14.         padding: 0;  
  15.         margin: 0;  
  16.     }  
  17.     #silverlightControlHost {  
  18.         height: 100%;  
  19.         text-align:center;  
  20.     }  
  21.     </style>  
  22.     <script type="text/javascript" src="Silverlight.js"></script>  
  23.     <script type="text/javascript">  
  24.         function onSilverlightError(sender, args) {  
  25.             var appSource = "";  
  26.             if (sender != null && sender != 0) {  
  27.                 appSource = sender.getHost().Source;  
  28.             }  
  29.   
  30.             var errorType = args.ErrorType;  
  31.             var iErrorCode = args.ErrorCode;  
  32.   
  33.             if (errorType == "ImageError" || errorType == "MediaError") {  
  34.                 return;  
  35.             }  
  36.   
  37.             var errMsg = "Unhandled Error in Silverlight Application " + appSource + "\n";  
  38.   
  39.             errMsg += "Code: " + iErrorCode + "    \n";  
  40.             errMsg += "Category: " + errorType + "       \n";  
  41.             errMsg += "Message: " + args.ErrorMessage + "     \n";  
  42.   
  43.             if (errorType == "ParserError") {  
  44.                 errMsg += "File: " + args.xamlFile + "     \n";  
  45.                 errMsg += "Line: " + args.lineNumber + "     \n";  
  46.                 errMsg += "Position: " + args.charPosition + "     \n";  
  47.             }  
  48.             else if (errorType == "RuntimeError") {  
  49.                 if (args.lineNumber != 0) {  
  50.                     errMsg += "Line: " + args.lineNumber + "     \n";  
  51.                     errMsg += "Position: " + args.charPosition + "     \n";  
  52.                 }  
  53.                 errMsg += "MethodName: " + args.methodName + "     \n";  
  54.             }  
  55.   
  56.             throw new Error(errMsg);  
  57.         }  
  58.     </script>  
  59. </head>  
  60. <body>  
  61.     <form id="form1" runat="server">  
  62.     <div id="silverlightControlHost">  
  63.         <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">  
  64.           <param name="source" value="ClientBin/GetWebConfig.xap"/>  
  65.           <param name="onError" value="onSilverlightError" />  
  66.           <param name="background" value="white" />  
  67.           <param name="minRuntimeVersion" value="4.0.50826.0" />  
  68.           <param name="autoUpgrade" value="true" />  
  69.                   <asp:Literal ID="litInitParams" runat="server" />  
  70.           <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">  
  71.               <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>  
  72.           </a>  
  73.         </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>  
  74.     </form>  
  75. </body>  
  76. </html>  

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using System.Collections.Specialized;  
  8. using System.Web.Configuration;  
  9. using System.Text;  
  10.    
  11. namespace SL_ReadConfigFile.Web  
  12. {  
  13.     public partial class SL_ReadConfigFile : System.Web.UI.Page  
  14.     {  
  15.         private string _seperator = ",";  
  16.    
  17.         protected void Page_Load( object sender , EventArgs e )  
  18.         {  
  19.             Response.Cache.SetCacheability( HttpCacheability.NoCache );  
  20.             WriteInitParams();  
  21.         }  
  22.    
  23.         private void WriteInitParams()  
  24.         {  
  25.             NameValueCollection appSettings = WebConfigurationManager.AppSettings;  
  26.             StringBuilder stringBuilder = new StringBuilder();  
  27.             stringBuilder.Append( "<param name=\"InitParams\" value=\"" );  
  28.             string paramContent = string.Empty;  
  29.             forint i = 0 ; i < appSettings.Count ; i++ )  
  30.             {  
  31.                 if( paramContent.Length > 0 )  
  32.                 {  
  33.                     paramContent += _seperator;  
  34.                 }  
  35.                 paramContent += string.Format( "{0}={1}" , appSettings.GetKey( i ) , appSettings[ i ] );  
  36.              }  
  37.              stringBuilder.Append(paramContent );  
  38.              stringBuilder.Append( "\" />" );  
  39.              this.litInitParams.Text = stringBuilder.ToString();  
  40.          }  
  41.      }  
  42.  }  

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

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Windows;  
  4.    
  5. namespace SL_ReadConfigFile  
  6. {  
  7.     public partial class App : Application  
  8.     {  
  9.         private IDictionary<string , string> _configurations;  
  10.         public IDictionary<string , string> Configurations  
  11.         {  
  12.             get  
  13.             {  
  14.                 return _configurations;  
  15.             }  
  16.         }  
  17.    
  18.         public App()  
  19.         {  
  20.             this.Startup += this.Application_Startup;  
  21.             this.Exit += this.Application_Exit;  
  22.             this.UnhandledException += this.Application_UnhandledException;  
  23.             InitializeComponent();  
  24.         }  
  25.    
  26.         private void Application_Startup( object sender , StartupEventArgs e )  
  27.         {  
  28.             _configurations = e.InitParams;  
  29.             this.RootVisual = new MainPage();  
  30.         }  
  31.    
  32.         private void Application_Exit( object sender , EventArgs e )  
  33.         {  
  34.    
  35.         }  
  36.    
  37.         private void Application_UnhandledException( object sender , ApplicationUnhandledExceptionEventArgs e )  
  38.         {  
  39.             if( !System.Diagnostics.Debugger.IsAttached )  
  40.             {  
  41.                 e.Handled = true;  
  42.                 Deployment.Current.Dispatcher.BeginInvoke( delegate { ReportErrorToDOM( e ); } );  
  43.             }  
  44.         }  
  45.     
  46.         private void ReportErrorToDOM( ApplicationUnhandledExceptionEventArgs e )  
  47.         {  
  48.             try  
  49.             {  
  50.                 string errorMsg = e.ExceptionObject.Message + e.ExceptionObject.StackTrace;  
  51.                 errorMsg = errorMsg.Replace( '"' , '\'' ).Replace( "\r\n" , @"\n" );  
  52.                 System.Windows.Browser.HtmlPage.Window.Eval( "throw new Error(\"Unhandled Error in Silverlight Application " + errorMsg + "\");" );  
  53.             }  
  54.             catch( Exception )  
  55.             {  
  56.             }  
  57.         }  
  58.     }  
  59. }  

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

  1. <UserControl xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk"  x:Class="SL_ReadConfigFile.MainPage"  
  2.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"  
  3.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"  
  4.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008"  
  5.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"  
  6.     mc:Ignorable="d"  
  7.     d:DesignWidth="800" d:DesignHeight="600"  
  8.     Width="Auto" Height="Auto" xmlns:toolkit="http://schemas.microsoft.com/winfx/2006/xaml/presentation/toolkit">  
  9.    
  10.     <Grid x:Name="LayoutRoot" Background="Transparent">  
  11.         <Grid.RowDefinitions>  
  12.             <RowDefinition Height="50"></RowDefinition>  
  13.             <RowDefinition></RowDefinition>  
  14.             <RowDefinition Height="30"></RowDefinition>  
  15.         </Grid.RowDefinitions>  
  16.         <TextBlock HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24">Silverlight Reads web.config Demo</TextBlock>  
  17.         <sdk:DataGrid Grid.Row="1" Name="dgdConfigurations">  
  18.         </sdk:DataGrid>  
  19.         <StackPanel Orientation="Horizontal" Grid.Row="2" HorizontalAlignment="Center">  
  20.             <Button Name="btnShowEntry" Width="200" Margin="10,0" Click="btnShowEntry_Click">  
  21.                 <StackPanel Orientation="Horizontal">  
  22.                     <TextBlock VerticalAlignment="Center">Read number</TextBlock>  
  23.                     <toolkit:NumericUpDown Name="numericUpDown" Margin="5,0" DecimalPlaces="0"/>  
  24.                     <TextBlock VerticalAlignment="Center">entry</TextBlock></StackPanel>  
  25.             </Button>  
  26.             <Button Name="btnBindConfig" Width="200" Margin="10,0" Click="btnBindConfig_Click">Binding Configurations</Button>  
  27.         </StackPanel>  
  28.     </Grid>  
  29. </UserControl>  
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Net;  
  5. using System.Windows;  
  6. using System.Windows.Controls;  
  7. using System.Windows.Documents;  
  8. using System.Windows.Input;  
  9. using System.Windows.Media;  
  10. using System.Windows.Media.Animation;  
  11. using System.Windows.Shapes;  
  12.    
  13. namespace SL_ReadConfigFile  
  14. {  
  15.     public partial class MainPage : UserControl  
  16.     {  
  17.         private IDictionary<string , string> _configurations;  
  18.         public MainPage()  
  19.         {  
  20.             InitializeComponent();  
  21.    
  22.             _configurations =  ( Application.Current as App ).Configurations;  
  23.    
  24.             if( _configurations.Count > 0 )  
  25.             {  
  26.                 numericUpDown.Minimum = 1;  
  27.                 numericUpDown.Maximum = _configurations.Count;  
  28.             }  
  29.    
  30.         }  
  31.    
  32.         private void btnBindConfig_Click( object sender , RoutedEventArgs e )  
  33.         {  
  34.             this.dgdConfigurations.ItemsSource = _configurations;  
  35.         }  
  36.    
  37.         private void btnShowEntry_Click( object sender , RoutedEventArgs e )  
  38.         {  
  39.             string entryContent = string.Format( "{0} = {1}" , _configurations.ElementAt( ( int ) numericUpDown.Value - 1 ).Key , _configurations.ElementAt( ( int ) numericUpDown.Value - 1 ).Value );  
  40.             MessageBox.Show( entryContent );  
  41.         }  
  42.     }  
  43. }  

 

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

抱歉!评论已关闭.