Наследование: ConfigurationException
		[Test] // ctor (String)
		public void Constructor2 ()
		{
			string msg;
			ConfigurationErrorsException cee;

			msg = "MSG";
			cee = new ConfigurationErrorsException (msg);
			Assert.AreSame (msg, cee.BareMessage, "#A1");
			Assert.IsNotNull (cee.Data, "#A2");
			Assert.AreEqual (0, cee.Data.Count, "#A3");
			Assert.IsNull (cee.Filename, "#A4");
			Assert.IsNull (cee.InnerException, "#A5");
			Assert.AreEqual (0, cee.Line, "#A6");
			Assert.AreSame (msg, cee.Message, "#A7");

			msg = null;
			cee = new ConfigurationErrorsException (msg);
			Assert.AreEqual (new ConfigurationErrorsException ().Message, cee.BareMessage, "#B1");
			Assert.IsNotNull (cee.Data, "#B2");
			Assert.AreEqual (0, cee.Data.Count, "#B3");
			Assert.IsNull (cee.Filename, "#B4");
			Assert.IsNull (cee.InnerException, "#B5");
			Assert.AreEqual (0, cee.Line, "#B6");
			Assert.AreEqual (cee.BareMessage, cee.Message, "#B7");
		}
Пример #2
0
        internal static ConfigurationErrorsException WrapAsConfigException(string outerMessage, Exception e, string filename, int line)
        {
            ConfigurationErrorsException exception = e as ConfigurationErrorsException;

            if (exception != null)
            {
                return(exception);
            }
            ConfigurationException exception2 = e as ConfigurationException;

            if (exception2 != null)
            {
                return(new ConfigurationErrorsException(exception2));
            }
            XmlException inner = e as XmlException;

            if (inner != null)
            {
                if (inner.LineNumber != 0)
                {
                    line = inner.LineNumber;
                }
                return(new ConfigurationErrorsException(inner.Message, inner, filename, line));
            }
            if (e != null)
            {
                return(new ConfigurationErrorsException(System.Configuration.SR.GetString("Wrapped_exception_message", new object[] { outerMessage, e.Message }), e, filename, line));
            }
            return(new ConfigurationErrorsException(System.Configuration.SR.GetString("Wrapped_exception_message", new object[] { outerMessage, NoExceptionInformation }), filename, line));
        }
Пример #3
0
        static internal void AddError(ref List <ConfigurationException> errors, ConfigurationException e)
        {
            Debug.Assert(e != null, "e != null");

            // Create on demand
            if (errors == null)
            {
                errors = new List <ConfigurationException>();
            }

            ConfigurationErrorsException ce = e as ConfigurationErrorsException;

            if (ce == null)
            {
                errors.Add(e);
            }
            else
            {
                ICollection <ConfigurationException> col = ce.ErrorsGeneric;
                if (col.Count == 1)
                {
                    errors.Add(e);
                }
                else
                {
                    errors.AddRange(col);
                }
            }
        }
Пример #4
0
        // Verify and Retrieve the Boolean Attribute.  If it is not
        // a valid value then log an error and set the value to a given default.
        internal void VerifyAndGetBooleanAttribute(
            ExceptionAction action, bool defaultValue, out bool newValue)
        {
            if (Reader.Value == "true")
            {
                newValue = true;
            }
            else
            {
                if (Reader.Value == "false")
                {
                    newValue = false;
                }
                else
                {
                    // Unrecognized value
                    newValue = defaultValue;

                    ConfigurationErrorsException ex = new ConfigurationErrorsException(
                        string.Format(SR.Config_invalid_boolean_attribute, Reader.Name),
                        this);

                    SchemaErrors.AddError(ex, action);
                }
            }
        }
        internal static void AddError(ref List <ConfigurationException> errors, ConfigurationException e)
        {
            if (errors == null)
            {
                errors = new List <ConfigurationException>();
            }
            ConfigurationErrorsException exception = e as ConfigurationErrorsException;

            if (exception == null)
            {
                errors.Add(e);
            }
            else
            {
                ICollection <ConfigurationException> errorsGeneric = exception.ErrorsGeneric;
                if (errorsGeneric.Count == 1)
                {
                    errors.Add(e);
                }
                else
                {
                    errors.AddRange(errorsGeneric);
                }
            }
        }
Пример #6
0
 private object CreateSectionImpl(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader)
 {
     if (this._sectionCtor != null)
     {
         ConfigurationSection section = (ConfigurationSection)System.Configuration.TypeUtil.InvokeCtorWithReflectionPermission(this._sectionCtor);
         section.SectionInformation.SetRuntimeConfigurationInformation(configRecord, factoryRecord, sectionRecord);
         section.CallInit();
         ConfigurationSection parentElement = (ConfigurationSection)parentConfig;
         section.Reset(parentElement);
         if (reader != null)
         {
             section.DeserializeSection(reader);
         }
         ConfigurationErrorsException errors = section.GetErrors();
         if (errors != null)
         {
             throw errors;
         }
         section.SetReadOnly();
         section.ResetModified();
         return(section);
     }
     if (reader != null)
     {
         XmlNode xmlNode = ErrorInfoXmlDocument.CreateSectionXmlNode(reader);
         CheckForLockAttributes(factoryRecord.ConfigKey, xmlNode);
         object configContext = configRecord.Host.CreateDeprecatedConfigContext(configRecord.ConfigPath);
         return(this._sectionHandler.Create(parentConfig, configContext, xmlNode));
     }
     return(null);
 }
Пример #7
0
            internal object CreateSection(bool inputIsTrusted, RuntimeConfigurationRecord configRecord,
                                          FactoryRecord factoryRecord, SectionRecord sectionRecord, object parentConfig, ConfigXmlReader reader)
            {
                object config;

                if (_sectionCtor != null)
                {
                    ConfigurationSection configSection =
                        (ConfigurationSection)_sectionCtor.Invoke(null);

                    configSection.SectionInformation.SetRuntimeConfigurationInformation(configRecord, factoryRecord,
                                                                                        sectionRecord);

                    configSection.CallInit();

                    ConfigurationSection parentSection = (ConfigurationSection)parentConfig;
                    configSection.Reset(parentSection);

                    if (reader != null)
                    {
                        configSection.DeserializeSection(reader);
                    }

                    // throw if there are any cached errors
                    ConfigurationErrorsException errors = configSection.GetErrors();
                    if (errors != null)
                    {
                        throw errors;
                    }

                    // don't allow changes to sections at runtime
                    configSection.SetReadOnly();

                    // reset the modified bit
                    configSection.ResetModified();

                    config = configSection;
                }
                else
                {
                    if (reader != null)
                    {
                        XmlNode xmlNode = ErrorInfoXmlDocument.CreateSectionXmlNode(reader);

                        CheckForLockAttributes(factoryRecord.ConfigKey, xmlNode);

                        // In v1, our old section handler expects a context that contains the virtualPath from the configPath
                        object configContext = configRecord.Host.CreateDeprecatedConfigContext(configRecord.ConfigPath);

                        config = _sectionHandler.Create(parentConfig, configContext, xmlNode);
                    }
                    else
                    {
                        config = null;
                    }
                }

                return(config);
            }
Пример #8
0
        internal void AddErrorRequiredAttribute(string attrib, ExceptionAction action)
        {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                SR.GetString(SR.Config_missing_required_attribute, attrib, _reader.Name),
                this);

            SchemaErrors.AddError(ex, action);
        }
Пример #9
0
        /// <summary>
        /// 使用缓冲池的键、缓冲对象的类型和已发生的 
        /// <see cref="System.Configuration.ConfigurationErrorsException"/> 初始化 
        /// <see cref="CacheResolveEventArgs"/> 类的新实例。
        /// </summary>
        /// <param name="key">缓冲池的键。</param>
        /// <param name="keyType">缓冲对象的键的类型。</param>
        /// <param name="valueType">缓冲对象的类型。</param>
        /// <param name="exception">已发生的 <see cref="System.Exception"/>。</param>
        public CacheResolveEventArgs(string key, Type keyType, Type valueType,
			ConfigurationErrorsException exception)
        {
            this.Key = key;
            this.CacheKeyType = keyType;
            this.CacheValueType = valueType;
            this.Exception = exception;
        }
Пример #10
0
        internal void AddErrorReservedAttribute(ExceptionAction action)
        {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                SR.GetString(SR.Config_reserved_attribute, _reader.Name),
                this);

            SchemaErrors.AddError(ex, action);
        }
Пример #11
0
        internal void AddErrorUnrecognizedAttribute(ExceptionAction action)
        {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                string.Format(SR.Config_base_unrecognized_attribute, Reader.Name),
                this);

            SchemaErrors.AddError(ex, action);
        }
Пример #12
0
 /// <summary>
 /// 使用缓冲池的键、缓冲对象的类型和发生的内部异常初始化 <see cref="CacheResolveEventArgs"/> 类的新实例。
 /// </summary>
 /// <param name="key">缓冲池的键。</param>
 /// <param name="keyType">缓冲对象的键的类型。</param>
 /// <param name="valueType">缓冲对象的类型。</param>
 /// <param name="innerException">发生的内部异常。</param>
 public CacheResolveEventArgs(string key, Type keyType, Type valueType, ConfigurationErrorsException innerException)
 {
     Contract.Requires(key != null && keyType != null && valueType != null);
     this.key = key;
     this.keyType = keyType;
     this.valueType = valueType;
     this.innerException = innerException;
 }
Пример #13
0
        internal void AddErrorUnrecognizedElement(ExceptionAction action)
        {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                SR.GetString(SR.Config_base_unrecognized_element),
                this);

            SchemaErrors.AddError(ex, action);
        }
        internal static void ThrowOnErrors(List <ConfigurationException> errors)
        {
            ConfigurationErrorsException errorsException = GetErrorsException(errors);

            if (errorsException != null)
            {
                throw errorsException;
            }
        }
Пример #15
0
        static internal void ThrowOnErrors(List <ConfigurationException> errors)
        {
            ConfigurationErrorsException e = GetErrorsException(errors);

            if (e != null)
            {
                throw e;
            }
        }
Пример #16
0
        static internal ConfigurationErrorsException WrapAsConfigException(string outerMessage, Exception e, string filename, int line)
        {
            //
            // Preserve ConfigurationErrorsException
            //
            ConfigurationErrorsException ce = e as ConfigurationErrorsException;

            if (ce != null)
            {
                return(ce);
            }

            //
            // Promote deprecated ConfigurationException to ConfigurationErrorsException
            //
            ConfigurationException deprecatedException = e as ConfigurationException;

            if (deprecatedException != null)
            {
                return(new ConfigurationErrorsException(deprecatedException));
            }

            //
            // For XML exceptions, preserve the text of the exception in the outer message.
            //
            XmlException xe = e as XmlException;

            if (xe != null)
            {
                if (xe.LineNumber != 0)
                {
                    line = xe.LineNumber;
                }

                return(new ConfigurationErrorsException(xe.Message, xe, filename, line));
            }

            //
            // Wrap other exceptions in an inner exception, and give as much info as possible
            //
            if (e != null)
            {
                return(new ConfigurationErrorsException(
                           SR.GetString(SR.Wrapped_exception_message, outerMessage, e.Message),
                           e,
                           filename,
                           line));
            }

            //
            // If there is no exception, create a new exception with no further information.
            //
            return(new ConfigurationErrorsException(
                       SR.GetString(SR.Wrapped_exception_message, outerMessage, ExceptionUtil.NoExceptionInformation),
                       filename,
                       line));
        }
Пример #17
0
        internal void VerifyIgnorableNodeType(ExceptionAction action)
        {
            XmlNodeType nodeType = this._reader.NodeType;

            if ((nodeType != XmlNodeType.Comment) && (nodeType != XmlNodeType.EndElement))
            {
                ConfigurationException ce = new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_unrecognized_element"), this);
                this.SchemaErrors.AddError(ce, action);
            }
        }
 internal static bool TryGetHttpHandlerType(string virtualPath, Type hostedXamlType, out Type httpHandlerType)
 {
     XamlHostingSection section = LoadXamlHostingSection(virtualPath);
     if (null == section) 
     { 
         ConfigurationErrorsException configException = new ConfigurationErrorsException(SR.ConfigSectionNotFound);                 
         throw FxTrace.Exception.AsError(configException); 
     }
     return section.Handlers.TryGetHttpHandlerType(hostedXamlType, out httpHandlerType);
 }
		[Test] // ctor ()
		public void Constructor1 ()
		{
			ConfigurationErrorsException cee = new ConfigurationErrorsException ();
			Assert.IsNotNull (cee.BareMessage, "#1");
			Assert.IsTrue (cee.BareMessage.IndexOf ("'" + typeof (ConfigurationErrorsException).FullName + "'") != -1, "#2:" + cee.BareMessage);
			Assert.IsNotNull (cee.Data, "#3");
			Assert.AreEqual (0, cee.Data.Count, "#4");
			Assert.IsNull (cee.Filename, "#5");
			Assert.IsNull (cee.InnerException, "#6");
			Assert.AreEqual (0, cee.Line, "#7");
			Assert.AreEqual (cee.BareMessage, cee.Message, "#8");
		}
Пример #20
0
		private static void TryLogConfigurationError(ConfigurationErrorsException configurationException, string instanceName)
		{
			try
			{
				DefaultCachingEventLogger eventLogger = EnterpriseLibraryFactory.BuildUp<DefaultCachingEventLogger>();
				if (eventLogger != null)
				{
					eventLogger.LogConfigurationError(instanceName, configurationException);
				}
			}
			catch { }
		}
Пример #21
0
 private static void TryLogConfigurationError(ConfigurationErrorsException configurationException, string instanceName)
 {
     try
     {
         DefaultSecurityEventLogger eventLogger = EnterpriseLibraryFactory.BuildUp<DefaultSecurityEventLogger>();
         if (eventLogger != null)
         {
             eventLogger.LogConfigurationError(instanceName, Resources.ErrorAuthorizationConfigurationFailedMessage, configurationException);
         }
     }
     catch { }
 }
Пример #22
0
        //
        // Add an error if the node type is not permitted by the configuration schema.
        //
        internal void VerifyIgnorableNodeType(ExceptionAction action)
        {
            XmlNodeType nodeType = _reader.NodeType;

            if (nodeType != XmlNodeType.Comment && nodeType != XmlNodeType.EndElement)
            {
                ConfigurationException ex = new ConfigurationErrorsException(
                    SR.GetString(SR.Config_base_unrecognized_element),
                    this);

                SchemaErrors.AddError(ex, action);
            }
        }
Пример #23
0
 internal void VerifyAndGetNonEmptyStringAttribute(ExceptionAction action, out string newValue)
 {
     if (!string.IsNullOrEmpty(this._reader.Value))
     {
         newValue = this._reader.Value;
     }
     else
     {
         newValue = null;
         ConfigurationException ce = new ConfigurationErrorsException(System.Configuration.SR.GetString("Empty_attribute", new object[] { this._reader.Name }), this);
         this.SchemaErrors.AddError(ce, action);
     }
 }
Пример #24
0
 private static void TryLogConfigurationError(ConfigurationErrorsException configurationException, string instanceName)
 {
     try
     {
         DefaultDataEventLogger logger = EnterpriseLibraryFactory.BuildUp<DefaultDataEventLogger>();
         if (logger != null)
         {
             logger.LogConfigurationError(configurationException, instanceName);
         }
     }
     catch
     {
     }
 }
		public void DefaultLoggerFiresWmiEvent()
		{
			DefaultCachingEventLogger logger
				= new DefaultCachingEventLogger(false, true);
			ConfigurationErrorsException exception = new ConfigurationErrorsException(exceptionMessage);

			using (WmiEventWatcher eventListener = new WmiEventWatcher(1))
			{
				logger.LogConfigurationError(instanceName, exception);

				eventListener.WaitForEvents();
				Assert.AreEqual(1, eventListener.EventsReceived.Count);
				Assert.AreEqual("CacheConfigurationFailureEvent", eventListener.EventsReceived[0].ClassPath.ClassName);
				Assert.AreEqual(instanceName, eventListener.EventsReceived[0].GetPropertyValue("InstanceName"));
			}
		}
		public void DefaultLoggerWritesToEventLog()
		{
			DefaultCachingEventLogger logger
				= new DefaultCachingEventLogger(true, false);
			ConfigurationErrorsException exception = new ConfigurationErrorsException(exceptionMessage);

			using (EventLog eventLog = GetEventLog())
			{
				int eventCount = eventLog.Entries.Count;

				logger.LogConfigurationError(instanceName, exception);

				Assert.AreEqual(eventCount + 1, eventLog.Entries.Count);
				Assert.IsTrue(eventLog.Entries[eventCount].Message.IndexOf(exceptionMessage) > -1);
			}
		}
Пример #27
0
 internal void VerifyAndGetBooleanAttribute(ExceptionAction action, bool defaultValue, out bool newValue)
 {
     if (this._reader.Value == "true")
     {
         newValue = true;
     }
     else if (this._reader.Value == "false")
     {
         newValue = false;
     }
     else
     {
         newValue = defaultValue;
         ConfigurationErrorsException ce = new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_invalid_boolean_attribute", new object[] { this._reader.Name }), this);
         this.SchemaErrors.AddError(ce, action);
     }
 }
        public void DefaultLoggerWritesToEventLog()
        {
            DefaultCachingEventLogger logger
                = new DefaultCachingEventLogger(true);
            ConfigurationErrorsException exception = new ConfigurationErrorsException(exceptionMessage);

            using (var eventLog = new EventLogTracker(GetEventLog()))
            {
                logger.LogConfigurationError(instanceName, exception);

                var newEntries = from entry in eventLog.NewEntries()
                                 where entry.Message.IndexOf(exceptionMessage) > -1
                                 select entry;

                Assert.AreEqual(1, newEntries.ToList().Count);
            }
        }
Пример #29
0
        internal void VerifyAndGetNonEmptyStringAttribute(ExceptionAction action, out string newValue)
        {
            if (!String.IsNullOrEmpty(_reader.Value))
            {
                newValue = _reader.Value;
            }
            else
            {
                newValue = null;

                ConfigurationException ex = new ConfigurationErrorsException(
                    SR.GetString(SR.Empty_attribute, _reader.Name),
                    this);

                SchemaErrors.AddError(ex, action);
            }
        }
Пример #30
0
 public WebConfigSettingService(string configLocation = null, bool isVirtualPath = false)
     : base(configLocation)
 {
     //http://stackoverflow.com/questions/4738/using-configurationmanager-to-load-config-from-an-arbitrary-location/4746#4746
     try
     {
         if (configLocation != null)
         {
             if (isVirtualPath)
             {
                 _configuration = WebConfigurationManager.OpenWebConfiguration(configLocation);
                 _settings = _configuration.AppSettings;
             }
             else
             {
                 //ConfigurationFileMap fileMap = new ConfigurationFileMap(configLocation); //Path to your config file
                 //_configuration = ConfigurationManager.OpenMappedMachineConfiguration(fileMap);
                 ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
                 fileMap.ExeConfigFilename = configLocation;
                 _configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                 //_settings = (AppSettingsSection)_configuration.GetSection("AppSettings");
                 _settings = _configuration.AppSettings;
             }
         }
         else
         {
             //No config file was sent in so we use default one
             _configuration = WebConfigurationManager.OpenWebConfiguration(HttpContext.Current != null ? HttpContext.Current.Request.ApplicationPath : null);
             _settings = _configuration.AppSettings;
         }
     }
     catch (ConfigurationErrorsException e)
     {
         var eNew = new ConfigurationErrorsException("Could not load configuration. Either incorrect path was sent in or if no path was sent in web.config could not be found where expected",e);
         throw eNew;
     }
 }
Пример #31
0
        internal void AddErrorRequiredAttribute(string attrib, ExceptionAction action)
        {
            ConfigurationErrorsException ce = new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_missing_required_attribute", new object[] { attrib, this._reader.Name }), this);

            this.SchemaErrors.AddError(ce, action);
        }
        Exception BuildParseError(Exception e, string capsKey) {
            string message = SR.GetString(SR.Invalid_string_from_browser_caps, e.Message, capsKey, this[capsKey]);

            // to show ConfigurationException in stack trace
            ConfigurationErrorsException configEx = new ConfigurationErrorsException(message, e);

            // I want it to look like an unhandled exception
            HttpUnhandledException httpUnhandledEx = new HttpUnhandledException(null, null);

            // but show message from outer exception (it normally shows the inner-most)
            httpUnhandledEx.SetFormatter(new UseLastUnhandledErrorFormatter(configEx));

            return httpUnhandledEx;
        }
        // GetErrors
        //
        // Get a ConfigurationErrorsException that contains the errors
        // for this ConfigurationElement and its children
        //
        internal ConfigurationErrorsException GetErrors() {
            ArrayList errorsList;

            errorsList = GetErrorsList();
            
            if (errorsList.Count == 0) {
                return null;
            }
            
            ConfigurationErrorsException e = new ConfigurationErrorsException(errorsList);
            return e;
        }
Пример #34
0
		private static void TryLogConfigurationError(ConfigurationErrorsException configurationException, string hashInstance, string template)
		{
			try
			{
				DefaultCryptographyEventLogger eventLogger = EnterpriseLibraryFactory.BuildUp<DefaultCryptographyEventLogger>();
				if (eventLogger != null)
				{
					eventLogger.LogConfigurationError(hashInstance, template, configurationException);
				}
			}
			catch { }
		}
Пример #35
0
		private static void TryLogHashConfigurationError(ConfigurationErrorsException configurationException, string hashInstance)
		{
			TryLogConfigurationError(configurationException, Resources.ErrorHashProviderConfigurationFailedMessage, hashInstance);
		}
Пример #36
0
        internal void AddErrorUnrecognizedElement(ExceptionAction action)
        {
            ConfigurationErrorsException ce = new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_unrecognized_element"), this);

            this.SchemaErrors.AddError(ce, action);
        }
Пример #37
0
        internal void AddErrorUnrecognizedAttribute(ExceptionAction action)
        {
            ConfigurationErrorsException ce = new ConfigurationErrorsException(System.Configuration.SR.GetString("Config_base_unrecognized_attribute", new object[] { this._reader.Name }), this);

            this.SchemaErrors.AddError(ce, action);
        }
 private IHttpHandler GetHandlerFirstTime(HttpContext context, string requestType, string url, string pathTranslated)
 {
     Type type;
     ConfigurationErrorsException exception;
     if (this.hostedXamlType == null)
     {
         this.hostedXamlType = this.GetCompiledCustomString(context.Request.AppRelativeCurrentExecutionFilePath);
     }
     if (XamlHostingConfiguration.TryGetHttpHandlerType(url, this.hostedXamlType, out type))
     {
         if (TD.HttpHandlerPickedForUrlIsEnabled())
         {
             TD.HttpHandlerPickedForUrl(url, this.hostedXamlType.FullName, type.FullName);
         }
         if (typeof(IHttpHandler).IsAssignableFrom(type))
         {
             IHttpHandler handler = (IHttpHandler) XamlHttpHandlerFactory.CreateInstance(type);
             if (handler.IsReusable)
             {
                 this.cachedResult = handler;
                 return handler;
             }
             this.cachedResult = type;
             return handler;
         }
         if (typeof(IHttpHandlerFactory).IsAssignableFrom(type))
         {
             IHttpHandlerFactory factory = (IHttpHandlerFactory) XamlHttpHandlerFactory.CreateInstance(type);
             this.cachedResult = factory;
             return XamlHttpHandlerFactory.HandlerWrapper.Create(factory.GetHandler(context, requestType, url, pathTranslated), factory);
         }
         exception = new ConfigurationErrorsException(System.Xaml.Hosting.SR.NotHttpHandlerType(url, this.hostedXamlType, type.FullName));
         this.cachedResult = exception;
         throw FxTrace.Exception.AsError(exception);
     }
     exception = new ConfigurationErrorsException(System.Xaml.Hosting.SR.HttpHandlerForXamlTypeNotFound(url, this.hostedXamlType, "system.xaml.hosting/httpHandlers"));
     this.cachedResult = exception;
     throw FxTrace.Exception.AsError(exception);
 }
            //This function is invoked the first time a request is made to XAMLx file 
            //It caches url as key and one of the 
            //following 4 as value -> "Handler/Factory/HandlerCLRType/Exception"
            IHttpHandler GetHandlerFirstTime(HttpContext context, string requestType,
                string url, string pathTranslated)
            {
                Type httpHandlerType;
                ConfigurationErrorsException configException;

                //GetCompiledType is costly - invoke it just once. 
                //This null check is required for "error after GetCompiledType on first attempt" cases only
                if (this.hostedXamlType == null)
                {
                    this.hostedXamlType = GetCompiledCustomString(context.Request.AppRelativeCurrentExecutionFilePath);
                }

                if (XamlHostingConfiguration.TryGetHttpHandlerType(url, this.hostedXamlType, out httpHandlerType))
                {
                    if (TD.HttpHandlerPickedForUrlIsEnabled())
                    {
                        TD.HttpHandlerPickedForUrl(url, hostedXamlType.FullName, httpHandlerType.FullName);
                    }
                    if (typeof(IHttpHandler).IsAssignableFrom(httpHandlerType))
                    {
                        IHttpHandler handler = (IHttpHandler)CreateInstance(httpHandlerType);
                        if (handler.IsReusable)
                        {
                            this.cachedResult = handler;
                        }
                        else
                        {
                            this.cachedResult = httpHandlerType;
                        }
                        return handler;
                    }
                    else if (typeof(IHttpHandlerFactory).IsAssignableFrom(httpHandlerType))
                    {
                        IHttpHandlerFactory factory = (IHttpHandlerFactory)CreateInstance(httpHandlerType);
                        this.cachedResult = factory;
                        IHttpHandler handler = factory.GetHandler(context, requestType, url, pathTranslated);
                        return HandlerWrapper.Create(handler, factory);
                    }
                    else
                    {
                        configException =
                            new ConfigurationErrorsException(SR.NotHttpHandlerType(url, this.hostedXamlType, httpHandlerType.FullName));
                        this.cachedResult = configException;
                        throw FxTrace.Exception.AsError(configException);
                    }
                }
                configException =
                    new ConfigurationErrorsException(SR.HttpHandlerForXamlTypeNotFound(url, this.hostedXamlType, XamlHostingConfiguration.XamlHostingSection));
                this.cachedResult = configException;
                throw FxTrace.Exception.AsError(configException);
            }
Пример #40
0
 //
 // Add an error if the node type is not permitted by the configuration schema.
 //
 internal void VerifyIgnorableNodeType(ExceptionAction action) {
     XmlNodeType nodeType = _reader.NodeType;
     
     if (nodeType != XmlNodeType.Comment && nodeType != XmlNodeType.EndElement) {
         ConfigurationException ex = new ConfigurationErrorsException(
             SR.GetString(SR.Config_base_unrecognized_element), 
             this);
                         
         SchemaErrors.AddError(ex, action);
     }
 }
Пример #41
0
        private static void InitializeDefaultProvider(RoleManagerSection settings) {
            bool canInitializeDefaultProvider = (!HostingEnvironment.IsHosted || BuildManager.PreStartInitStage == PreStartInitStage.AfterPreStartInit);
            if (!s_InitializedDefaultProvider && canInitializeDefaultProvider) {
                Debug.Assert(s_Providers != null);
                s_Providers.SetReadOnly();

                if (settings.DefaultProvider == null) {
                    s_InitializeException = new ProviderException(SR.GetString(SR.Def_role_provider_not_specified));
                }
                else {
                    try {
                        s_Provider = s_Providers[settings.DefaultProvider];
                    }
                    catch { }
                }

                if (s_Provider == null) {
                    s_InitializeException = new ConfigurationErrorsException(SR.GetString(SR.Def_role_provider_not_found), settings.ElementInformation.Properties["defaultProvider"].Source, settings.ElementInformation.Properties["defaultProvider"].LineNumber);
                }

                s_InitializedDefaultProvider = true;
            }
        }
Пример #42
0
        internal void AddErrorRequiredAttribute(string attrib, ExceptionAction action) {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                SR.GetString(SR.Config_missing_required_attribute, attrib, _reader.Name),
                this);

            SchemaErrors.AddError(ex, action);
        }
Пример #43
0
		private static void TryLogSymmetricConfigurationError(ConfigurationErrorsException configurationException, string symmetricInstance)
		{
			TryLogConfigurationError(configurationException, Resources.ErrorSymmetricEncryptionConfigurationFailedMessage, symmetricInstance);
		}
Пример #44
0
        internal void AddErrorReservedAttribute(ExceptionAction action) {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                SR.GetString(SR.Config_reserved_attribute, _reader.Name),
                this);

            SchemaErrors.AddError(ex, action);
        }
        private object DeserializePropertyValue(ConfigurationProperty prop, XmlReader reader) {
            Debug.Assert(prop != null, "prop != null");
            Debug.Assert(reader != null, "reader != null");

            // By default we try to load (i.e. parse/validate ) all properties
            // If a property value is invalid ( cannot be parsed or is not valid ) we will keep the value
            // as string ( from the xml ) and will write it out unchanged if needed
            // If the property value is needed by users the actuall exception will be thrown

            string xmlValue = reader.Value;
            object propertyValue = null;

            try {
                propertyValue = prop.ConvertFromString(xmlValue);

                // Validate the loaded and converted value
                prop.Validate(propertyValue);
            }
            catch (ConfigurationException ce) {
                // If the error is incomplete - complete it :)
                if (string.IsNullOrEmpty(ce.Filename)) {
                    ce = new ConfigurationErrorsException(ce.Message, reader);
                }

                // Cannot parse/validate the value. Keep it as string
                propertyValue = new InvalidPropValue(xmlValue, ce);
            }
            catch {
                // If this is an exception related to the parsing/validating the 
                // value ConfigurationErrorsException should be thrown instead.
                // If not - the exception is ok to surface out of here
                Debug.Fail("Unknown exception type thrown");
            }

            return propertyValue;
        }
Пример #46
0
        internal void AddErrorUnrecognizedElement(ExceptionAction action) {
            ConfigurationErrorsException ex = new ConfigurationErrorsException(
                SR.GetString(SR.Config_base_unrecognized_element),
                this);

            SchemaErrors.AddError(ex, action);
        }
 internal void FireConfigurationFailureEvent(ConfigurationErrorsException configurationException)
 {
     if (configurationFailure != null) configurationFailure(this, new ValidationConfigurationFailureEventArgs(configurationException));
 }
Пример #48
0
        internal void VerifyAndGetNonEmptyStringAttribute(ExceptionAction action, out string newValue) {
            if (!String.IsNullOrEmpty(_reader.Value)) {
                newValue = _reader.Value;
            }
            else {
                newValue = null;

                ConfigurationException ex = new ConfigurationErrorsException(
                    SR.GetString(SR.Empty_attribute, _reader.Name),
                    this);

                SchemaErrors.AddError(ex, action);
            }
        }
 private object DeserializePropertyValue(ConfigurationProperty prop, XmlReader reader)
 {
     string str = reader.Value;
     object obj2 = null;
     try
     {
         obj2 = prop.ConvertFromString(str);
         prop.Validate(obj2);
     }
     catch (ConfigurationException exception)
     {
         if (string.IsNullOrEmpty(exception.Filename))
         {
             exception = new ConfigurationErrorsException(exception.Message, reader);
         }
         obj2 = new InvalidPropValue(str, exception);
     }
     catch
     {
     }
     return obj2;
 }
Пример #50
0
        // VerifyAndGetBooleanAttribute
        //
        // Verify and Retrieve the Boolean Attribute.  If it is not
        // a valid value then log an error and set the value to a given default.
        //
        internal void VerifyAndGetBooleanAttribute(
                ExceptionAction action, bool defaultValue, out bool newValue) {

            if (_reader.Value == "true") {
                newValue = true;
            }
            else if (_reader.Value == "false") {
                newValue = false;
            }
            else {
                // Unrecognized value
                newValue = defaultValue;

                ConfigurationErrorsException ex = new ConfigurationErrorsException(
                    SR.GetString(SR.Config_invalid_boolean_attribute, _reader.Name), 
                    this);

                SchemaErrors.AddError(ex, action);
            }
        }
 public void NotifyConfigurationFailure(ConfigurationErrorsException configurationException)
 {
     // Intentional no-op
 }
Пример #52
0
        /// <summary>
        /// Transfers settings from/to the stick according to the direction.
        /// </summary>
        /// <param name="direction">The direction.</param>
        /// <remarks>Documented by Dev02, 2007-12-06</remarks>
        static void SettingsOnStick(SettingsOnStickDirection direction)
        {
            if (!RunningFromStick())
            {
                return;
            }

            if (direction == SettingsOnStickDirection.Save)
            {
                //replace settings with placeholders
                Properties.Settings.Default.DicDir      = ReplacePath(Properties.Settings.Default.DicDir, SettingsOnStickReplaceDirection.PathToPlaceholder);
                Properties.Settings.Default.RecentFiles = ReplacePath(Properties.Settings.Default.RecentFiles, SettingsOnStickReplaceDirection.PathToPlaceholder);
                //save current properties before copying to stick
                Properties.Settings.Default.Save();
            }

            System.Configuration.Configuration localconfig = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.PerUserRoamingAndLocal);
            System.Configuration.Configuration config      = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);

            FileInfo sourcefile, destfile;
            string   userconfigfileformat = Properties.Resources.SETUP_STICKMODE_CONFIGFILE;

            switch (direction)
            {
            case SettingsOnStickDirection.Load:
                sourcefile = new FileInfo(string.Format(userconfigfileformat, config.FilePath));
                destfile   = new FileInfo(localconfig.FilePath);
                break;

            case SettingsOnStickDirection.Save:
                sourcefile = new FileInfo(localconfig.FilePath);
                destfile   = new FileInfo(string.Format(userconfigfileformat, config.FilePath));
                break;

            default:
                return;
            }

            try
            {
                sourcefile.Directory.Create();
                destfile.Directory.Create();
                File.Copy(sourcefile.FullName, destfile.FullName, true);
            }
            catch
            {
                return;
            }

            //load current properties after loading from stick
            try
            {
                Properties.Settings.Default.Reload();
                Properties.Settings.Default.DicDir      = ReplacePath(Properties.Settings.Default.DicDir, SettingsOnStickReplaceDirection.PlaceholderToPath);
                Properties.Settings.Default.RecentFiles = ReplacePath(Properties.Settings.Default.RecentFiles, SettingsOnStickReplaceDirection.PlaceholderToPath);
                Properties.Settings.Default.Save();
            }
            catch (System.Configuration.ConfigurationErrorsException exp)
            {
                bool errorfixed = false;
                if (exp.InnerException != null && exp.InnerException is System.Configuration.ConfigurationErrorsException)
                {
                    System.Configuration.ConfigurationErrorsException innerexception = exp.InnerException as System.Configuration.ConfigurationErrorsException;
                    if (System.IO.File.Exists(innerexception.Filename))
                    {
                        try
                        {
                            System.IO.File.Delete(innerexception.Filename);
                            errorfixed = true;
                        }
                        catch { }
                    }
                }
                if (System.IO.File.Exists(exp.Filename))
                {
                    try
                    {
                        System.IO.File.Delete(exp.Filename);
                    }
                    catch { }
                }
                if (System.IO.File.Exists(sourcefile.FullName))
                {
                    try
                    {
                        System.IO.File.Delete(sourcefile.FullName);
                        errorfixed = true;
                    }
                    catch { }
                }
                if (errorfixed)
                {
                    Program.MainForm.BringToFront();
                    Program.MainForm.TopMost = true;
                    Application.DoEvents();

                    MessageBox.Show(Properties.Resources.INITIALIZE_SETTINGS_ERROR, Properties.Resources.INITIALIZE_SETTINGS_CAPTION);
                    Environment.Exit(-1);
                }
                else
                {
                    throw exp;
                }
            }
            catch (Exception exp)
            {
                throw exp;
            }
        }