本文介绍了在远程类中使用变量超出范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 29岁程序员,3月因学历无情被辞! 在主机服务器上: 命名空间JCart.Common 公共类JCartConfiguration:IConfigurationSectionHandler private static String dbConnectionString; public static String ConnectionString { get { 返回dbConnectionString; } } //初始化它: dbConnectionString ="我的数据库连接字符串" ;; 在远程服务器上: 命名空间JCart.DataAccess 公共类CustomerSystem:MarshalByRefObject 字符串testVar ; testVar = JCartConfiguration.ConnectionString; testVar返回为"。但是当使用这个确切的代码而没有远程使用testVar =我的数据库连接字符串; 这基本上是克隆的Duwamish .Net样本减去我用作购物车的购物车学习c#的方法。没有企业模板,但解决方案中的相同单独项目结构只包含实现帐户设置/修改系统部分所需的内容。 我不确定我是不是忽略一些基本概念,但我可以在必要时发布更多细节。 这是使用时的远程配置文件: < configuration> ; < system.runtime.remoting> < application> < channels> < ; channel ref =" http client" clientConnectionLimit =" 200"> < clientProviders> < formatter ref =" soap" /> < / clientProviders> < / channel> < / channels> < client url =" HTTP://192.168.1.13:80 / JCart_Facade"> < wellknown type =" JCart.BusinessFacade.CustomerSystem,JCart.BusinessFacade" url =" HTTP://192.168.1.13:80 / JCart_Facade / CustomerSystem.rem" /> < / client> < / application> < /system.runtime.remoting> < / configuration>On the host server:namespace JCart.Commonpublic class JCartConfiguration : IConfigurationSectionHandlerprivate static String dbConnectionString;public static String ConnectionString{get{return dbConnectionString;}}//Initialze it:dbConnectionString = "My Database Connection String";On remote server:namespace JCart.DataAccesspublic class CustomerSystem : MarshalByRefObjectString testVar;testVar = JCartConfiguration.ConnectionString;testVar comes back as "". However when this exact code is used without being remoted testVar = "My Database Connection String";This is basically the Duwamish .Net sample cloned minus the shopping cart that I useed as a way to learn c#. No enterprise template but the same seperate projects structure within the solution only containg the stuff needed to implement the account setup/modify system part.I''m not sure if I''m overlooking some basic concept, but I can post more details if necessary.Here is the remote config file when used:<configuration><system.runtime.remoting><application><channels><channel ref="http client" clientConnectionLimit="200"><clientProviders><formatter ref="soap"/></clientProviders></channel></channels><client url="HTTP://192.168.1.13:80/JCart_Facade"><wellknown type="JCart.BusinessFacade.CustomerSystem, JCart.BusinessFacade" url="HTTP://192.168.1.13:80/JCart_Facade/CustomerSystem.rem"/></client></application></system.runtime.remoting></configuration>推荐答案 该连接字符串在哪里被初始化?你没有显示那个。 - Jon Skeet - < sk *** @ pobox。 com> http://www.pobox.com/~skeet 如果回复群组,请不要给我发邮件Where is that connection string being initialised though? You haven''tshown that.--Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeetIf replying to the group, please do not mail me too 连接字符串在哪里被初始化?你还没有表现出来。 - Jon Skeet - < sk *** @ pobox.com> http://www.pobox.com/~skeet 如果回复该群组,请不要给我发邮件 Where is that connection string being initialised though? You haven''t shown that. -- Jon Skeet - <sk***@pobox.com> http://www.pobox.com/~skeet If replying to the group, please do not mail me too JCARTCONFIGURATION.cs 名称空间JCart.Common { 使用系统; 使用System.Collections; 使用System.Configuration; 使用System.Xml; 使用System.Collections.Specialized; 使用JCart.SystemFramework; 公共类JCartConfiguration:IConfigurationSectionHandler //公共类JCartConfiguration { // // DuwamishConfiguration部分中所有预期条目的常量值 // private const String WEB_ENABLEPAGECACHE =" JCart.Web.EnablePageCache"; private const String WEB_PAGECACHEEXPIRE SINSECONDS =" JCart.Web.PageCacheExpiresInSeconds"; private const String DATAACCESS_CONNECTIONSTRING =" JCart.DataAccess.ConnectionString"; private const String WEB_ENABLESSL =" JCart。 Web.EnableSsl" ;; 私有静态字符串dbConnectionString; // public static int test1p; / / private static bool enablePageCache; // private static int pageCacheExpiresInSeconds; // private static bool enableSsl; // //所有默认设置的常量值。 // private const bool WEB_ENABLEPAGECACHE_DEFAULT = true; private const int WEB_PAGECACHEEXPIRESINSECONDS_DEFAULT = 3600; private const String DATAACCESS_CONNECTIONSTRING_DEFAULT = " server = EMPIRE2; User ID = sa; Password =; database = JCart; Connection Reset = FALSE" ;; private const bool WEB_EN ABLESSL_DEFAULT = false; public Object Create(Object parent,object configContext,XmlNode section) { NameValueCollection设置; 尝试 { NameValueSectionHandler baseHandler = new NameValueSectionHandler(); settings =(NameValueCollection)baseHandler.Create(parent,configContext,section); } catch { settings = null; } if(settings == null) { dbConnectionString = DATAACCESS_CONNECTIONSTRING_DEFAULT; // pageCacheExpiresInSeconds = WEB_PAGECACHEEXPIRESINSECONDS_DEFAULT; // enablePageCache = WEB_ENABLEPAGECACHE_DEFAULT; // enableSsl = WEB_ENABLESSL_DEFAULT; } else { dbConnectionString = ApplicationConfiguration.ReadSetting(settings,DATAACCESS_CONNECTI ONSTRING,DATAACCESS_CONNECTIONSTRING_DEFAULT); // pageCacheExpiresInSeconds = ApplicationConfiguration.ReadSetting(settings,WEB_PAGECACHEEXPIRESINSECONDS,WEB_PAGECACHEEXPIRESINSECONDS_DEFAULT); // enablePageCache = ApplicationConfiguration.ReadSetting(settings,WEB_ENABLEPAGECACHE,WEB_ENABLEPAGECACHE_DEFAULT) ; // enableSsl = ApplicationConfiguration.ReadSetting(设置,WEB_ENABLESSL,WEB_ENABLESSL_DEFAULT); } 返回设置; } public static String ConnectionString { get { 返回dbConnectionString; } } // public static int test1 // { //获得 // { //返回test1p; //} //} } //类JCartConfiguration } //命名空间JCart7.Common APPLICATIONCONFIGURATION.CS 命名空间JCart.SystemFramework { 使用System; 使用System.Collections; 使用System.Diagnostics; 使用System.Configuration; 使用System.Xml; 使用System.Collections。专业化; ///< summary> ///启用跟踪和记录的标准配置设置 $ b带有ApplicationLog类的$ b ///。 ///< remarks> ///应用程序可以将此类用作 的模型///将其他设置添加到Web.Config文件。 ///特殊注意事项: ///必须从Global.asax中的Application_OnStart事件调用此类中的OnApplicationStart函数 ///。这是 ///当前用于确定应用程序的路径, /// HttpContext对象被传递给它以启用应用程序 ///将来读取其他设置,并尽量减少global.asax中的代码 ///。 ///< example> /// global.asax文件应类似于以下代码: /// < code> ///<%@ Import Namespace =" Duwamish7.SystemFramework" %> ///< script language =" c#" runat =" SERVER"> /// void Application_OnStart() /// { /// ApplicationConfiguration.OnApplicationStart( Contex t); ///} ///< / script> ///< / code> ///< / example> ///< / remarks> ///< / summary> 公共类ApplicationConfiguration:IConfigurationSectionHandler { // //所有SystemFramework标准的常量值设置 // private const String TRACING_ENABLED =" SystemFramework.Tracing.Enabled"; private const String TRACING_TRACEFILE =" SystemFramework。 Tracing.TraceFile" ;; private const String TRACING_TRACELEVEL =" SystemFramework.Tracing.TraceLevel"; private const String TRACING_SW ITCHNAME =" SystemFramework.Tracing.SwitchName"; private const String TRACING_SWITCHDESCRIPTION =" SystemFramework.Tracing.SwitchDescription"; private const String EVENTLOG_ENABLED =" SystemFramework。 EventLog.Enabled" ;; private const String EVENTLOG_MACHINENAME =" SystemFramework.EventLog.Machine"; private const String EVENTLOG_SOURCENAME =" SystemFramework.EventLog.SourceName" ;; private const String EVENTLOG_TRACELEVEL =" SystemFramework.EventLog.LogLevel"; // //静态成员变量。这些包含来自Config.Web的应用程序设置 //或默认值。 // private static bool tracingEnabled; private static String tracingTraceFile; private static TraceLevel tracingTraceLevel; private static String tracingSwitchName; private static String tracingSwitchDescription; private static bool eventLogEnabled; private static String eventLogMachineName; private static String eventLogSourceName; private static TraceLevel eventLogTraceLevel; // //应用程序的根目录。建立在 // OnApplicationStart回调表格Global.asax。 // 私有静态字符串appRoot; // //所有默认设置的常量值。 // private const bool TRACING_ENABLED_DEFAULT = true ; private const String TRACING_TRACEFILE_DEFAULT =" ApplicationTrace.txt"; private const TraceLevel TRACING_TRACELEVEL_DEFAULT = TraceLevel.Verbose; private const String TRACING_SWITCHNAME_DEFAULT =" ApplicationTraceSwitch"; private const String TRACING_SWITCHDESCRIPTION_DEFAULT ="应用程序错误和跟踪信息" ;; private const bool EVENTLOG_ENABLED_DEFAULT = true; private const String EVENTLOG_MACHINENAME_DEFAULT ="。" ;; private const String EVENTLOG_SOURCENAME_DEFAULT =" WebApplication"; private const TraceLevel EVENTLOG_TRACELEVEL_DEFAULT = TraceLe vel.Error; ///< summary> ///从OnApplicationStart调用来初始化设置来自 / // Web.Config文件。 ///< remarks> ///如果设置发生变化,app域会重启,所以有 ///不不止一次读取这些值的原因。这个函数 ///使用NameValueSectionHandler基类从XML生成一个 ///哈希表,然后用于存储当前的 ///设置。因为这里读取了所有设置,所以我们实际上并不是 ///存储生成的哈希表对象,以便以后通过 /// Context.GetConfig进行检索。应用程序应直接使用访问者 ///函数。 ///< / remarks> ///< param name =" parent">通过在父目录的Config.Web文件中处理带有此名称的部分 ///创建的对象。 // /< / param> ///< param name =" configContext"> config'的上下文。< / param> // /< param name =" section">要阅读的部分。< / param> ///< retvalue> ///< ; para> /// ConfigOutput对象:我们留空,因为此时存储了所有设置 ///。 ///< / para> ///< para> /// null:如果有错误。 ///< / para> ///< / retvalue> ///< / summary> public Object C reate(Object parent,object configContext,XmlNode section) { NameValueCollection设置; try { NameValueSectionHandler baseHandler = new NameValueSectionHandler(); settings =(NameValueCollection)baseHandler.Create(parent,configContext,section); } catch { settings = null; } if(settings == null) { tracingEnabled = TRACING_ENABLED_DEFAULT; tracingTraceFile = TRACING_TRACEFILE_DEFAULT; tracingTraceLevel = TRACING_TRACELEVEL_DEFAULT; tracingSwitchName = TRACING_SWITCHNAME_DEFAULT; tracingSwitchDescription = TRACING_SWITCHDESCRIPTION_DEFAULT; eventLogEnabled = EVENTLOG_ENABLED_DEFAULT; eventLogMachineName = EVENTLOG_MACHINENAME_DEFAULT; eventLogSourceName = EVENTLOG_SOURCENAME_DEFAULT; eventLogTraceLevel = EVENTLOG_TRACELEVEL_ DEFAULT; } 其他 { tracingEnabled = ReadSetting(设置,TRACING_ENABLED,TRACING_ENABLED_DEFAULT); tracingTraceFile = ReadSetting(设置,TRACING_TRACEFILE,TRACING_TRACEFILE_DEFAULT); tracingTraceLevel = ReadSetting(设置,TRACING_TRACELEVEL,TRACING_TRACELEVEL_DEFAULT); tracingSwitchName = ReadSetting(设置, TRACING_SWITCHNAME,TRACING_SWITCHNAME_DEFAULT); tracingSwitchDescription = ReadSetting(设置,TRACING_SWITCHDESCRIPTION,TRACING_SWITCHDESCRIPTION_DEFAULT); eventLogEnabled = ReadSetting(设置,EVENTLOG_ENABLED,EVENTLOG_ENABLED_DEFAULT); eventLogMachineName = ReadSetting(settings,EVENTLOG_MACHINENAME,EVENTLOG_MACHINENAME_DEFAULT); eventLogSourceName = ReadSetting(settings,EVENTLOG_SOURCENAME,EVENTLOG_SOURCENAME_DEFAULT); eventLogTraceLevel = ReadSetting(settings,EVENTLOG_TRACELEVEL,EVENTLOG_TRACELEVEL_DEFAULT); } 返回null; } ///< summary> / // ReadSetting的字符串版本。 ///< remarks> ///从哈希表中读取设置并将其转换为正确的 ///类型。为散列表中预期的每种类型提供了这些函数之一 ///。这些是公开的,所以其他 ///类不必复制它们来从 ///哈希表中读取设置。 ///< / remarks> ///< param name =" settings">要从中读取的Hashtable。< / param> ///< param name =" key"> Hashtable中值的键。< / param> ///< param name =" defaultValue" >如果找不到该项,则为默认值。< / param> ///< retvalue> ///< para> value:from哈希表< / para> ///< para> ///默认:如果项目不在表格中或者不能达到预期的情况类型。 ///< / para> ///< / retvalue> ///< / summary> public static String ReadSetting(NameValueCollection settings,String key,String defaultValue) { 尝试 { 对象设置=设置[关键]; 返回(设置== null)? defaultValue:(String)设置; } catch { return defaultValue; } } ///< summary> /// ReadSetting的布尔版本。 ///< remarks> ///从哈希表读取设置并将其转换为正确的 ///类型。为散列表中预期的每种类型提供了这些函数之一 ///。这些是公开的,所以其他 ///类不必复制它们来从 ///哈希表中读取设置。 ///< / remarks> ///< param name =" settings">要从中读取的Hashtable。< / param> ///< param name =" key"> Hashtable中值的键。< / param> ///< param name =" defaultValue" >如果找不到该项,则为默认值。< / param> ///< retvalue> ///< para> value:from哈希表< / para> ///< para> ///默认:如果项目不在表格中或者不能达到预期的情况类型。 ///< / para> ///< / retvalue> ///< / summary> public static bool ReadSetting(NameValueCollection settings,String key,bool defaultValue) { tr y { 对象设置=设置[键]; return(setting == null)? defaultValue:Convert.ToBoolean((String)setting); } catch { return defaultValue; } } ///< summary> /// int version ReadSetting。 ///< remarks> ///从哈希表中读取设置并将其转换为正确的 / //类型为散列表中预期的每种类型提供了这些函数之一 ///。这些是公开的,所以其他 ///类不必复制它们来从 ///哈希表中读取设置。 ///< / remarks> ///< param name =" settings">要从中读取的Hashtable。< / param> ///< param name =" key"> Hashtable中值的键。< / param> ///< param name =" defaultValue" >如果找不到该项,则为默认值。< / param> ///< retvalue> ///< para> value:from哈希表< / para> ///< para> ///默认:如果项目不在表格中或者不能达到预期的情况类型。 ///< / para> ///< / retvalue> ///< / summary> public static int ReadSetting(NameValueCollection settings,String key,int defaultValue) { try { 对象设置=设置[键]; return(setting == null)? defaultValue:Convert.ToInt32((String)setting); } catch { return defaultValue; } } ///< summary> /// TraceLevel版本ReadSetting。 ///< remarks> ///从哈希表中读取设置并将其转换为正确的 / //类型为散列表中预期的每种类型提供了这些函数之一 ///。这些是公开的,所以其他 ///类不必复制它们来从 ///哈希表中读取设置。 ///< / remarks> ///< param name =" settings">要从中读取的Hashtable。< / param> ///< param name =" key"> Hashtable中值的键。< / param> ///< param name =" defaultValue" >如果找不到该项,则为默认值。< / param> ///< retvalue> ///< para> value:from哈希表< / para> ///< para> ///默认:如果项目不在表格中或者不能达到预期的情况类型。 ///< / para> ///< / retvalue> ///< / summary> public static TraceLevel ReadSetting(NameValueCollection设置,String key,TraceLevel defaultValue) { 试试 { 对象设置=设置[关键]; 返回(设置==空值) ? defaultValue:(TraceLevel)Convert.ToInt32((String)setting); } catch { return defaultValue; } } ///< summary> // /函数由Application_OnStart调用,如 ///类描述中所述。初始化应用程序根目录。 ///< param name =" myAppPath">正在运行的应用程序的路径。< / param> /// < / summary> public static void OnApplicationStart(String myAppPath) { appRoot = myAppPath; // System.Configuration.ConfigurationSettings.GetConf ig(" ApplicationConfiguration"); System.Configuration.ConfigurationSettings.GetConf ig(" JCartConfiguration"); // System.Configuration.ConfigurationSettings.GetConf ig(" SourceViewer"); } ///< value> ///属性AppRoot用于获取应用程序的根路径。 ///< / value> public static String AppRoot { get { 返回appRoot; } } ///< value> /// Property TracingE nabled用于获取配置设置,错误时默认为False。 ///< / value> public static bool TracingEnabled { get { return tracingEnabled; } } ///< value> ///属性TracingTraceFile用于获取包含跟踪的文件的完整路径名 /// settings,默认为ApplicationTrace.txt。 ///< / value> public static String TracingTraceFile { get { 返回appRoot +" \\" + tracingTraceFile; } } ///< value> // / Property TracingTraceFile用于获取应写入 ///跟踪文件的最高日志记录级别,默认为TraceLevel.Verbose(但是,TracingEnabled默认值为 / //到False,所以你必须明确打开它。 ///< / value> public static TraceLevel TracingTraceLevel { get { 返回tracingTraceLevel; } } ///< value> ///属性TracingSwitchName用于获取跟踪开关名称,默认为ApplicationTraceSwitch。 ///< / value> public static String TracingSwitchName { get { 返回tracingSwitchName; } } ///< value> ///属性TracingSwitchDescription用于获取tra ce设置文件,默认为 ///应用程序错误和跟踪信息。 ///< / value> public static String TracingSwitchDescription { get { return tracingSwitchDescription; } } ///< value> ///属性EventLogEnabled用于获取是否写入事件日志是支持,默认为True。 ///< remarks>如果启用了写入事件日志,则返回true,否则返回false< / remarks> / //< / value> public static bool EventLogEnabled { get { 返回eventLogEnabled; } } ///< value> // / Property EventLogMachineName用于获取记录事件的机器名,默认为 ///空字符串,表示当前机器。机器名称 ///(不带\\)可能为空。 ///< / value> public static String EventLogMachineName { get { return eventLogMachineName; } } ///< value> ///属性EventLogMachineName用于获取源代码error to be written to the event log, /// defaults WebApplication. /// </value> public static String EventLogSourceName { get { return eventLogSourceName; } } /// <value> /// Property EventLogTraceLevel is used to get the highest logging level that should be written to the event log, /// defaults to TraceLevel.Error. /// </value> public static TraceLevel EventLogTraceLevel { get { re turn eventLogTraceLevel; } } } //class ApplicationConfiguration } //namespace JCart.SystemFramework WEB.CONFIG <?xml version="1.0"编码= QUOT; UTF-8英寸?> <configuration> <configSections> <section name="ApplicationConfiguration" type="JCart.SystemFramework.ApplicationConfigurati on, JCart.SystemFramework" /> <section name="JCartConfiguration" type="JCart.Common.JCartConfiguration, JCart.Common" /> </configSections> <system.web> <compilation defaultLanguage="c#"调试= QUOT;真" /> <!-- xx The sessionState is currently set to inproc: the lines following [mode="inproc"] are not used but are present for ease of configuration --> <sessionState cookieless="false"超时= QUOT; 20" mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" /> < globalization requestEncoding =" utf-8"的ResponseEncoding = QUOT; UTF-8英寸/> <!-- security --> <authentication mode="Windows" /> <!-- <authentication mode="Forms"> <forms name=".ADUAUTH2" loginUrl="logon.aspx" protection="All"超时= QUOT; 60" > </forms> </authentication> <authorization> <deny users="?" /> </authorization> --> <trace enabled="false" requestLimit = QUOT; 10" pageOutput="false" traceMode="SortByTime"设置LocalOnly ="真" /> </system.web> <ApplicationConfiguration> <!-- Trace file settings --> <add key="SystemFramework.Tracing.Enabled" value="False" /> <!-- Set this to the file with the trace settings. This file should be relative to the root application directory. --> <add key="SystemFramework.Tracing.TraceFile" value="DuwamishTrace.txt" /> <!-- The TraceLevel for this switch. --> <add key="SystemFramework.Tracing.TraceLevel"值= QUOT; 4英寸/> <!-- This switch name. The trace level for this name can be set through environment variables or the registry --> <add key="SystemFramework.Tracing.SwitchName" value="DuwamishTraceSwitch" /> <!-- This description of the Tracing.SwitchName switch --> <add key="SystemFramework.Tracing.SwitchDescription" value="Error and information tracing for Duwamish" /> <!-- Event log settings Note: The default Duwamish7 event source name is created in the local machine during setup. If you wish to log events to a different event source that event source must exist. --> <add key="SystemFramework.EventLog.Enabled" value="True" /> <add key="SystemFramework.EventLog.Machine" value="." /> <add key="SystemFramework.EventLog.SourceName" value="Duwamish7" /> <!-- Use the standard TraceLevel values: 0 = Off 1 = Error 2 = Warning 3 = Info 4 = Verbose --> <add key="SystemFramework.EventLog.LogLevel"值= QUOT 1 QUOT; /> </ApplicationConfiguration> <JCartConfiguration> <!-- Settings specific to the Duwamish application --> <add key="JCart.DataAccess.ConnectionString" value="server=EMPIRE2;User ID=sa;Password=;database=JCart;Connection Reset=FALSE" /> <add key="JCart.Web.EnablePageCache" value="True" /> <add key="JCart.Web.PageCacheExpiresInSeconds" value="3600" /> <add key="JCart.Web.EnableSsl" value="False" /> </JCartConfiguration> <!-- String dsn = ConfigurationSettings.AppSettings["JCart"]; <appSettings> <add key="JCart" value="server=EMPIRE2;User ID=sa;Password=;database=JCart;Connection Reset=FALSE" /> </appSettings> --> </configuration>JCARTCONFIGURATION.csnamespace JCart.Common{using System;using System.Collections;using System.Configuration;using System.Xml;using System.Collections.Specialized;using JCart.SystemFramework;public class JCartConfiguration : IConfigurationSectionHandler//public class JCartConfiguration{//// Constant values for all expected entries in the DuwamishConfiguration section//private const String WEB_ENABLEPAGECACHE = "JCart.Web.EnablePageCache";private const String WEB_PAGECACHEEXPIRESINSECONDS = "JCart.Web.PageCacheExpiresInSeconds";private const String DATAACCESS_CONNECTIONSTRING = "JCart.DataAccess.ConnectionString";private const String WEB_ENABLESSL = "JCart.Web.EnableSsl";private static String dbConnectionString;//public static int test1p;//private static bool enablePageCache;//private static int pageCacheExpiresInSeconds;//private static bool enableSsl;//// Constant values for all of the default settings.//private const bool WEB_ENABLEPAGECACHE_DEFAULT = true;private const int WEB_PAGECACHEEXPIRESINSECONDS_DEFAULT = 3600;private const String DATAACCESS_CONNECTIONSTRING_DEFAULT ="server=EMPIRE2;User ID=sa;Password=;database=JCart;Connection Reset=FALSE";private const bool WEB_ENABLESSL_DEFAULT = false;public Object Create(Object parent, object configContext, XmlNode section){NameValueCollection settings;try{NameValueSectionHandler baseHandler = new NameValueSectionHandler();settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);}catch{settings = null;}if ( settings == null ){dbConnectionString = DATAACCESS_CONNECTIONSTRING_DEFAULT;//pageCacheExpiresInSeconds = WEB_PAGECACHEEXPIRESINSECONDS_DEFAULT;//enablePageCache = WEB_ENABLEPAGECACHE_DEFAULT;//enableSsl = WEB_ENABLESSL_DEFAULT;}else{dbConnectionString = ApplicationConfiguration.ReadSetting(settings, DATAACCESS_CONNECTIONSTRING, DATAACCESS_CONNECTIONSTRING_DEFAULT);//pageCacheExpiresInSeconds = ApplicationConfiguration.ReadSetting(settings, WEB_PAGECACHEEXPIRESINSECONDS, WEB_PAGECACHEEXPIRESINSECONDS_DEFAULT);//enablePageCache = ApplicationConfiguration.ReadSetting(settings, WEB_ENABLEPAGECACHE, WEB_ENABLEPAGECACHE_DEFAULT);//enableSsl = ApplicationConfiguration.ReadSetting(settings, WEB_ENABLESSL, WEB_ENABLESSL_DEFAULT);}return settings;}public static String ConnectionString{get{return dbConnectionString;}}//public static int test1//{//get//{//return test1p;//}//}} //class JCartConfiguration} //namespace JCart7.CommonAPPLICATIONCONFIGURATION.CSnamespace JCart.SystemFramework{using System;using System.Collections;using System.Diagnostics;using System.Configuration;using System.Xml;using System.Collections.Specialized;/// <summary>/// Standard configuration settings to enable tracing and logging/// with the ApplicationLog class./// <remarks>/// An application can use this class as a model for/// adding additional settings to a Web.Config file./// Special Considerations:/// The OnApplicationStart function in this class must be called/// from the Application_OnStart event in Global.asax. This is/// currently used to determine the path of the application,/// the HttpContext object is passed it to enable the app/// to read other settings in the future, and to minimize the code/// in global.asax./// <example>/// The global.asax file should be similar to the following code:/// <code>/// <%@ Import Namespace="Duwamish7.SystemFramework" %>/// <script language="c#" runat="SERVER">/// void Application_OnStart()/// {/// ApplicationConfiguration.OnApplicationStart(Contex t);/// }/// </script>/// </code>/// </example>/// </remarks>/// </summary>public class ApplicationConfiguration : IConfigurationSectionHandler{//// Constant values for all of the SystemFramework standard settings//private const String TRACING_ENABLED = "SystemFramework.Tracing.Enabled";private const String TRACING_TRACEFILE = "SystemFramework.Tracing.TraceFile";private const String TRACING_TRACELEVEL = "SystemFramework.Tracing.TraceLevel";private const String TRACING_SWITCHNAME = "SystemFramework.Tracing.SwitchName";private const String TRACING_SWITCHDESCRIPTION = "SystemFramework.Tracing.SwitchDescription";private const String EVENTLOG_ENABLED = "SystemFramework.EventLog.Enabled";private const String EVENTLOG_MACHINENAME = "SystemFramework.EventLog.Machine";private const String EVENTLOG_SOURCENAME = "SystemFramework.EventLog.SourceName";private const String EVENTLOG_TRACELEVEL = "SystemFramework.EventLog.LogLevel";//// Static member variables. These contain the application settings// from Config.Web, or the default values.//private static bool tracingEnabled;private static String tracingTraceFile;private static TraceLevel tracingTraceLevel;private static String tracingSwitchName;private static String tracingSwitchDescription;private static bool eventLogEnabled;private static String eventLogMachineName;private static String eventLogSourceName;private static TraceLevel eventLogTraceLevel;//// The root directory of the application. Established in the// OnApplicationStart callback form Global.asax.//private static String appRoot;//// Constant values for all of the default settings.//private const bool TRACING_ENABLED_DEFAULT = true;private const String TRACING_TRACEFILE_DEFAULT = "ApplicationTrace.txt";private const TraceLevel TRACING_TRACELEVEL_DEFAULT = TraceLevel.Verbose;private const String TRACING_SWITCHNAME_DEFAULT = "ApplicationTraceSwitch";private const String TRACING_SWITCHDESCRIPTION_DEFAULT = "Application error and tracing information";private const bool EVENTLOG_ENABLED_DEFAULT = true;private const String EVENTLOG_MACHINENAME_DEFAULT = ".";private const String EVENTLOG_SOURCENAME_DEFAULT = "WebApplication";private const TraceLevel EVENTLOG_TRACELEVEL_DEFAULT = TraceLevel.Error;/// <summary>/// Called from OnApplicationStart to initialize settings from/// the Web.Config file(s)./// <remarks>/// The app domain will restart if settings change, so there is/// no reason to read these values more than once. This funtion/// uses the NameValueSectionHandler base class to generate a/// hashtablefrom the XML, which is then used to store the current/// settings. Because all settings are read here, we do not actually/// store the generated hashtable object for later retrieval by/// Context.GetConfig. The application should use the accessor/// functions directly./// </remarks>/// <param name="parent">An object created by processing a section/// with this name in a Config.Web file in a parent directory./// </param>/// <param name="configContext">The config''s context.</param>/// <param name="section">The section to be read.</param>/// <retvalue>/// <para>/// A ConfigOutput object: which we leave empty because all settings/// are stored at this point./// </para>/// <para>/// null: if there was an error./// </para>/// </retvalue>/// </summary>public Object Create(Object parent, object configContext, XmlNode section){NameValueCollection settings;try{NameValueSectionHandler baseHandler = new NameValueSectionHandler();settings = (NameValueCollection)baseHandler.Create(parent, configContext, section);}catch{settings = null;}if (settings == null){tracingEnabled = TRACING_ENABLED_DEFAULT;tracingTraceFile = TRACING_TRACEFILE_DEFAULT;tracingTraceLevel = TRACING_TRACELEVEL_DEFAULT;tracingSwitchName = TRACING_SWITCHNAME_DEFAULT;tracingSwitchDescription = TRACING_SWITCHDESCRIPTION_DEFAULT;eventLogEnabled = EVENTLOG_ENABLED_DEFAULT;eventLogMachineName = EVENTLOG_MACHINENAME_DEFAULT;eventLogSourceName = EVENTLOG_SOURCENAME_DEFAULT;eventLogTraceLevel = EVENTLOG_TRACELEVEL_DEFAULT;}else{tracingEnabled = ReadSetting(settings, TRACING_ENABLED, TRACING_ENABLED_DEFAULT);tracingTraceFile = ReadSetting(settings, TRACING_TRACEFILE, TRACING_TRACEFILE_DEFAULT);tracingTraceLevel = ReadSetting(settings, TRACING_TRACELEVEL, TRACING_TRACELEVEL_DEFAULT);tracingSwitchName = ReadSetting(settings, TRACING_SWITCHNAME, TRACING_SWITCHNAME_DEFAULT);tracingSwitchDescription = ReadSetting(settings, TRACING_SWITCHDESCRIPTION, TRACING_SWITCHDESCRIPTION_DEFAULT);eventLogEnabled = ReadSetting(settings, EVENTLOG_ENABLED, EVENTLOG_ENABLED_DEFAULT);eventLogMachineName = ReadSetting(settings, EVENTLOG_MACHINENAME, EVENTLOG_MACHINENAME_DEFAULT);eventLogSourceName = ReadSetting(settings, EVENTLOG_SOURCENAME, EVENTLOG_SOURCENAME_DEFAULT);eventLogTraceLevel = ReadSetting(settings, EVENTLOG_TRACELEVEL, EVENTLOG_TRACELEVEL_DEFAULT);}return null;}/// <summary>/// String version of ReadSetting./// <remarks>/// Reads a setting from a hashtable and converts it to the correct/// type. One of these functions is provided for each type/// expected in the hash table. These are public so that other/// classes don''t have to duplicate them to read settings from/// a hash table./// </remarks>/// <param name="settings">The Hashtable to read from.</param>/// <param name="key">A key for the value in the Hashtable.</param>/// <param name="defaultValue">The default value if the item is not found.</param>/// <retvalue>/// <para>value: from the hash table</para>/// <para>/// default: if the item is not in the table or cannot be case to the expected type./// </para>/// </retvalue>/// </summary>public static String ReadSetting(NameValueCollection settings, String key, String defaultValue){try{Object setting = settings[key];return (setting == null) ? defaultValue : (String)setting;}catch{return defaultValue;}}/// <summary>/// Boolean version of ReadSetting./// <remarks>/// Reads a setting from a hashtable and converts it to the correct/// type. One of these functions is provided for each type/// expected in the hash table. These are public so that other/// classes don''t have to duplicate them to read settings from/// a hash table./// </remarks>/// <param name="settings">The Hashtable to read from.</param>/// <param name="key">A key for the value in the Hashtable.</param>/// <param name="defaultValue">The default value if the item is not found.</param>/// <retvalue>/// <para>value: from the hash table</para>/// <para>/// default: if the item is not in the table or cannot be case to the expected type./// </para>/// </retvalue>/// </summary>public static bool ReadSetting(NameValueCollection settings, String key, bool defaultValue){try{Object setting = settings[key];return (setting == null) ? defaultValue : Convert.ToBoolean((String)setting);}catch{return defaultValue;}}/// <summary>/// int version of ReadSetting./// <remarks>/// Reads a setting from a hashtable and converts it to the correct/// type. One of these functions is provided for each type/// expected in the hash table. These are public so that other/// classes don''t have to duplicate them to read settings from/// a hash table./// </remarks>/// <param name="settings">The Hashtable to read from.</param>/// <param name="key">A key for the value in the Hashtable.</param>/// <param name="defaultValue">The default value if the item is not found.</param>/// <retvalue>/// <para>value: from the hash table</para>/// <para>/// default: if the item is not in the table or cannot be case to the expected type./// </para>/// </retvalue>/// </summary>public static int ReadSetting(NameValueCollection settings, String key, int defaultValue){try{Object setting = settings[key];return (setting == null) ? defaultValue : Convert.ToInt32((String)setting);}catch{return defaultValue;}}/// <summary>/// TraceLevel version of ReadSetting./// <remarks>/// Reads a setting from a hashtable and converts it to the correct/// type. One of these functions is provided for each type/// expected in the hash table. These are public so that other/// classes don''t have to duplicate them to read settings from/// a hash table./// </remarks>/// <param name="settings">The Hashtable to read from.</param>/// <param name="key">A key for the value in the Hashtable.</param>/// <param name="defaultValue">The default value if the item is not found.</param>/// <retvalue>/// <para>value: from the hash table</para>/// <para>/// default: if the item is not in the table or cannot be case to the expected type./// </para>/// </retvalue>/// </summary>public static TraceLevel ReadSetting(NameValueCollection settings, String key, TraceLevel defaultValue){try{Object setting = settings[key];return (setting == null) ? defaultValue : (TraceLevel)Convert.ToInt32((String)setting);}catch{return defaultValue;}}/// <summary>/// Function to be called by Application_OnStart as described in the/// class description. Initializes the application root./// <param name="myAppPath">The path of the running application.</param>/// </summary>public static void OnApplicationStart(String myAppPath){appRoot = myAppPath;//System.Configuration.ConfigurationSettings.GetConf ig("ApplicationConfiguration");System.Configuration.ConfigurationSettings.GetConf ig("JCartConfiguration");// System.Configuration.ConfigurationSettings.GetConf ig("SourceViewer");}/// <value>/// Property AppRoot is used to get the root path of the application./// </value>public static String AppRoot{get{return appRoot;}}/// <value>/// Property TracingEnabled is used to get the configuration setting, defaulting to False on error./// </value>public static bool TracingEnabled{get{return tracingEnabled;}}/// <value>/// Property TracingTraceFile is used to get the full path name to the file that contains trace/// settings, defaults to ApplicationTrace.txt./// </value>public static String TracingTraceFile{get{return appRoot + "\\" + tracingTraceFile;}}/// <value>/// Property TracingTraceFile is used to get the highest logging level that should be written to/// the tracing file, defaults to TraceLevel.Verbose (however, TracingEnabled defaults/// to False, so you have to turn it on explicitly)./// </value>public static TraceLevel TracingTraceLevel{get{return tracingTraceLevel;}}/// <value>/// Property TracingSwitchName is used to get the trace switch name, defaults to ApplicationTraceSwitch./// </value>public static String TracingSwitchName{get{return tracingSwitchName;}}/// <value>/// Property TracingSwitchDescription is used to get the trace settings file, defaults to/// "Application error and tracing information"./// </value>public static String TracingSwitchDescription{get{return tracingSwitchDescription;}}/// <value>/// Property EventLogEnabled is used to get whether writing to the event log is support, defaults to True./// <remarks>Returns true if writing to the event log is enabled, false otherwise</remarks>/// </value>public static bool EventLogEnabled{get{return eventLogEnabled;}}/// <value>/// Property EventLogMachineName is used to get the machine name to log the event to, defaults to an/// empty string, indicating the current machine. A machine name/// (without \\), may be empty./// </value>public static String EventLogMachineName{get{return eventLogMachineName;}}/// <value>/// Property EventLogMachineName is used to get the source of the error to be written to the event log,/// defaults WebApplication./// </value>public static String EventLogSourceName{get{return eventLogSourceName;}}/// <value>/// Property EventLogTraceLevel is used to get the highest logging level that should be written to the event log,/// defaults to TraceLevel.Error./// </value>public static TraceLevel EventLogTraceLevel{get{return eventLogTraceLevel;}}} //class ApplicationConfiguration} //namespace JCart.SystemFrameworkWEB.CONFIG<?xml version="1.0" encoding="utf-8" ?><configuration><configSections><section name="ApplicationConfiguration" type="JCart.SystemFramework.ApplicationConfigurati on, JCart.SystemFramework" /><section name="JCartConfiguration" type="JCart.Common.JCartConfiguration, JCart.Common" /></configSections><system.web><compilation defaultLanguage="c#" debug="true" /><!-- xx The sessionState is currently set to inproc: the lines following [mode="inproc"] are not used but are present for ease of configuration --><sessionState cookieless="false" timeout="20" mode="InProc" stateConnectionString="tcpip=127.0.0.1:42424" sqlConnectionString="data source=127.0.0.1;user id=sa;password=" /><globalization requestEncoding="utf-8" responseEncoding="utf-8" /><!-- security --><authentication mode="Windows" /><!--<authentication mode="Forms"><forms name=".ADUAUTH2" loginUrl="logon.aspx" protection="All" timeout="60" ></forms></authentication><authorization><deny users="?" /></authorization>--><trace enabled="false" requestLimit="10" pageOutput="false" traceMode="SortByTime" localOnly="true" /></system.web><ApplicationConfiguration><!-- Trace file settings --><add key="SystemFramework.Tracing.Enabled" value="False" /><!-- Set this to the file with the trace settings. This file should be relativeto the root application directory. --><add key="SystemFramework.Tracing.TraceFile" value="DuwamishTrace.txt" /><!-- The TraceLevel for this switch. --><add key="SystemFramework.Tracing.TraceLevel" value="4" /><!-- This switch name. The trace level for this name can be set throughenvironment variables or the registry --><add key="SystemFramework.Tracing.SwitchName" value="DuwamishTraceSwitch" /><!-- This description of the Tracing.SwitchName switch --><add key="SystemFramework.Tracing.SwitchDescription" value="Error and information tracing for Duwamish" /><!-- Event log settingsNote: The default Duwamish7 event source name is created in the local machine during setup. If you wish to log events to a different event sourcethat event source must exist.--><add key="SystemFramework.EventLog.Enabled" value="True" /><add key="SystemFramework.EventLog.Machine" value="." /><add key="SystemFramework.EventLog.SourceName" value="Duwamish7" /><!-- Use the standard TraceLevel values:0 = Off1 = Error2 = Warning3 = Info4 = Verbose --><add key="SystemFramework.EventLog.LogLevel" value="1" /></ApplicationConfiguration><JCartConfiguration><!-- Settings specific to the Duwamish application --><add key="JCart.DataAccess.ConnectionString" value="server=EMPIRE2;User ID=sa;Password=;database=JCart;Connection Reset=FALSE" /><add key="JCart.Web.EnablePageCache" value="True" /><add key="JCart.Web.PageCacheExpiresInSeconds" value="3600" /><add key="JCart.Web.EnableSsl" value="False" /></JCartConfiguration><!-- String dsn = ConfigurationSettings.AppSettings["JCart"];<appSettings><add key="JCart" value="server=EMPIRE2;User ID=sa;Password=;database=JCart;Connection Reset=FALSE" /></appSettings>--></configuration> 这篇关于在远程类中使用变量超出范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云! 09-02 19:27