Ejemplo n.º 1
0
        protected void ParseRenderer(XmlElement element)
        {
            string attribute = element.GetAttribute("renderingClass");
            string typeName  = element.GetAttribute("renderedClass");

            string[] textArray1 = new string[] { "Rendering class [", attribute, "], Rendered class [", typeName, "]." };
            LogLog.Debug(declaringType, string.Concat(textArray1));
            IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(attribute, typeof(IObjectRenderer), null);

            if (renderer == null)
            {
                LogLog.Error(declaringType, "Could not instantiate renderer [" + attribute + "].");
            }
            else
            {
                try
                {
                    this.m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(typeName, true, true), renderer);
                }
                catch (Exception exception)
                {
                    LogLog.Error(declaringType, "Could not find class [" + typeName + "].", exception);
                }
            }
        }
Ejemplo n.º 2
0
 public void Init()
 {
     CLILogsTest.SurchargeLogs();
     Option  = new Options.AccountOptions();
     Config  = new DefaultRunConfiguration(ConfigType.Task, CommandApi.List);
     Convert = new OptionConverter(new UnitTestJsonDeserializer());
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Parses an object renderer.
        /// </summary>
        /// <param name="element">The renderer element.</param>
        /// <remarks>
        /// <para>
        /// Parse an XML element that represents a renderer.
        /// </para>
        /// </remarks>
        protected void ParseRenderer(XmlElement element)
        {
            string renderingClassName = element.GetAttribute(RENDERING_TYPE_ATTR);
            string renderedClassName  = element.GetAttribute(RENDERED_TYPE_ATTR);

            LogLog.Debug(declaringType, "Rendering class [" + renderingClassName + "], Rendered class [" + renderedClassName + "].");
            IObjectRenderer renderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(renderingClassName, typeof(IObjectRenderer), null);

            if (renderer == null)
            {
                LogLog.Error(declaringType, "Could not instantiate renderer [" + renderingClassName + "].");
                return;
            }
            else
            {
                try
                {
                    m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(renderedClassName, true, true), renderer);
                }
                catch (Exception e)
                {
                    LogLog.Error(declaringType, "Could not find class [" + renderedClassName + "].", e);
                }
            }
        }
Ejemplo n.º 4
0
        public void CheckConfigGetVerboseOptionsToQuiet()
        {
            Options.IVerboseOptions option = new Options.AccountOptions();
            option.Quiet = true;
            var convertOption = new OptionConverter(new JsonDeserializer());

            convertOption.ConfigGetVerboseOptions(option);
            Assert.AreEqual(CLILogs.Verbose, CLILogs.LogsLevel.NoVerbose);
        }
 /// <summary>
 /// Converts a string value to a target type.
 /// </summary>
 /// <param name="type">The type of object to convert the string to.</param>
 /// <param name="value">The string value to use as the value of the object.</param>
 /// <returns>
 /// An object of type <paramref name="type"/> with value <paramref name="value"/> or
 /// <c>null</c> when the conversion could not be performed.
 /// </returns>
 protected object ConvertStringTo(Type type, string value)
 {
     // Hack to allow use of Level in property
     if (type.IsAssignableFrom(typeof(Level)))
     {
         // Property wants a level
         return(m_hierarchy.LevelMap[value]);
     }
     return(OptionConverter.ConvertStringTo(type, value));
 }
Ejemplo n.º 6
0
        public void CheckConfigGetLogOptionsSetNoColor()
        {
            Options.ILogOptions option = new Options.AccountOptions();
            bool noColor = true;

            option.NoColor = noColor;
            var convertOption = new OptionConverter(new JsonDeserializer());

            convertOption.ConfigGetLogOptions(option);
            Assert.AreEqual(CLILogs.NoColor, noColor);
        }
Ejemplo n.º 7
0
 /// <summary>
 /// Converts a string value to a target type.
 /// </summary>
 /// <param name="type">The type of object to convert the string to.</param>
 /// <param name="value">The string value to use as the value of the object.</param>
 /// <returns>
 /// <para>
 /// An object of type <paramref name="type" /> with value <paramref name="value" /> or
 /// <c>null</c> when the conversion could not be performed.
 /// </para>
 /// </returns>
 protected object ConvertStringTo(Type type, string value)
 {
     if ((object)typeof(Level) == type)
     {
         Level level = m_hierarchy.LevelMap[value];
         if (level == null)
         {
             LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified [" + value + "]");
         }
         return(level);
     }
     return(OptionConverter.ConvertStringTo(type, value));
 }
Ejemplo n.º 8
0
        /// <summary>
        /// The current version of the NetStandard build of log4net does not replace environment variables.
        /// We will use the same functionality to replace the environment variables before we pass the xml
        /// into the standard XmlConfigurator
        /// </summary>
        /// <param name="xDocument"></param>
        private void ReplaceEnvironmentVariables(XDocument xDocument)
        {
            var environmentVariables = new Hashtable(Environment.GetEnvironmentVariables(), StringComparer.OrdinalIgnoreCase);

            var valueAttributes = xDocument
                                  .Descendants()
                                  .Select(x => x.Attribute("value"))
                                  .Where(x => x != null);

            foreach (var attribute in valueAttributes)
            {
                attribute.Value = OptionConverter.SubstituteVariables(attribute.Value, environmentVariables);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Parses a logger element.
        /// </summary>
        /// <param name="loggerElement">The logger element.</param>
        /// <remarks>
        /// <para>
        /// Parse an XML element that represents a logger.
        /// </para>
        /// </remarks>
        protected void ParseLogger(XmlElement loggerElement)
        {
            string attribute = loggerElement.GetAttribute("name");

            LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + attribute + "].");
            Logger logger = m_hierarchy.GetLogger(attribute) as Logger;

            lock (logger)
            {
                bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute("additivity"), defaultValue: true);
                LogLog.Debug(declaringType, "Setting [" + logger.Name + "] additivity to [" + additivity.ToString() + "].");
                logger.Additivity = additivity;
                ParseChildrenOfLoggerElement(loggerElement, logger, isRoot: false);
            }
        }
Ejemplo n.º 10
0
        public void CheckReadConfigurationFile()
        {
            OptionConverter convert  = new OptionConverter(new UnitTestJsonDeserializer());
            string          fileName = "fileName";
            string          line     = "{}";

            UnitTestJsonDeserializer.GetFileGet     = fileName;
            UnitTestJsonDeserializer.GetFileRetrun  = line;
            UnitTestJsonDeserializer.DeserializeGet = line;
            Console.WriteLine(line);
            AccountConfiguration readFile = convert.ReadConfigurationFile <AccountConfiguration>(fileName, ConfigType.Account, CommandApi.Info);

            Assert.AreEqual(readFile.Type, ConfigType.Account);
            Assert.AreEqual(readFile.Command, CommandApi.Info);
        }
Ejemplo n.º 11
0
        protected void ParseLogger(XmlElement loggerElement)
        {
            string attribute = loggerElement.GetAttribute("name");

            LogLog.Debug(declaringType, "Retrieving an instance of log4net.Repository.Logger for logger [" + attribute + "].");
            Logger log = this.m_hierarchy.GetLogger(attribute) as Logger;

            lock (log)
            {
                bool     flag      = OptionConverter.ToBoolean(loggerElement.GetAttribute("additivity"), true);
                object[] objArray1 = new object[] { "Setting [", log.Name, "] additivity to [", flag, "]." };
                LogLog.Debug(declaringType, string.Concat(objArray1));
                log.Additivity = flag;
                this.ParseChildrenOfLoggerElement(loggerElement, log, false);
            }
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Converts a string value to a target type.
        /// </summary>
        /// <param name="type">The type of object to convert the string to.</param>
        /// <param name="value">The string value to use as the value of the object.</param>
        /// <returns>
        /// <para>
        /// An object of type <paramref name="type"/> with value <paramref name="value"/> or
        /// <c>null</c> when the conversion could not be performed.
        /// </para>
        /// </returns>
        protected object ConvertStringTo(Type type, string value)
        {
            // Hack to allow use of Level in property
            if (typeof(Level) == type)
            {
                // Property wants a level
                Level levelValue = m_hierarchy.LevelMap[value];

                if (levelValue == null)
                {
                    LogLog.Error(declaringType, "XmlHierarchyConfigurator: Unknown Level Specified [" + value + "]");
                }

                return(levelValue);
            }
            return(OptionConverter.ConvertStringTo(type, value));
        }
Ejemplo n.º 13
0
        public void CheckConfigReadFile()
        {
            OptionConverter convert      = new OptionConverter(new UnitTestJsonDeserializer());
            string          fileName     = "fileName";
            int             verboseLevel = 5;
            bool            verbose      = true;
            bool            quiet        = true;
            string          line         = "{\"VerboseLevel\" : " + verboseLevel + ", \"Verbose\" : " + verbose.ToString().ToLower() + ", \"Quiet\" : " + quiet.ToString().ToLower() + "}";

            UnitTestJsonDeserializer.GetFileGet     = fileName;
            UnitTestJsonDeserializer.GetFileRetrun  = line;
            UnitTestJsonDeserializer.DeserializeGet = line;
            Console.WriteLine(line);
            Options.AccountOptions readFile = convert.ConfigReadFile <Options.AccountOptions>(fileName);
            Assert.AreEqual(readFile.Verbose, verbose);
            Assert.AreEqual(readFile.Quiet, quiet);
        }
        /// <summary>
        /// Parses a logger element.
        /// </summary>
        /// <param name="loggerElement">The logger element.</param>
        /// <remarks>
        /// <para>
        /// Parse an XML element that represents a logger.
        /// </para>
        /// </remarks>
        protected void ParseLogger(XmlElement loggerElement)
        {
            // Create a new GodLesZ.Library.Logging.Logger object from the <logger> element.
            string loggerName = loggerElement.GetAttribute(NAME_ATTR);

            LogLog.Debug(declaringType, "Retrieving an instance of GodLesZ.Library.Logging.Repository.Logger for logger [" + loggerName + "].");
            Logger log = m_hierarchy.GetLogger(loggerName) as Logger;

            // Setting up a logger needs to be an atomic operation, in order
            // to protect potential log operations while logger
            // configuration is in progress.
            lock (log) {
                bool additivity = OptionConverter.ToBoolean(loggerElement.GetAttribute(ADDITIVITY_ATTR), true);

                LogLog.Debug(declaringType, "Setting [" + log.Name + "] additivity to [" + additivity + "].");
                log.Additivity = additivity;
                ParseChildrenOfLoggerElement(loggerElement, log, false);
            }
        }
Ejemplo n.º 15
0
        public void TaskWithTagAndTagIntersectThrowAnExcption()
        {
            var commandLineParser       = new CommandLine.Parser();
            CommandLineParser parserObj = new CommandLineParser(new OptionConverter(new JsonDeserializer()), commandLineParser, new ParserUsage(), new VerbFormater());

            string[]       argv      = new string[] { "task info", "--tags", "t1", "t2", "--exclusive-tags", "t3", "t4" };
            ParseException ex        = null;
            var            converter = new OptionConverter(null);
            var            usage     = new ParserUsage();

            var parser = commandLineParser.ParseArguments <Options.InfoTaskOptions>(argv);

            ex = Assert.Throws <ParseException>(() => parser.MapResult(
                                                    (Options.InfoTaskOptions o) => converter.ConvertGenericGetterOption(ConfigType.Task, CommandApi.Info, o),
                                                    err => throw new ParseException(usage.PrintHelp(parser, err, argv))));

            Assert.IsNotNull(ex);
            commandLineParser.Dispose();
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Parses an object renderer.
        /// </summary>
        /// <param name="element">The renderer element.</param>
        /// <remarks>
        /// <para>
        /// Parse an XML element that represents a renderer.
        /// </para>
        /// </remarks>
        protected void ParseRenderer(XmlElement element)
        {
            string attribute  = element.GetAttribute("renderingClass");
            string attribute2 = element.GetAttribute("renderedClass");

            LogLog.Debug(declaringType, "Rendering class [" + attribute + "], Rendered class [" + attribute2 + "].");
            IObjectRenderer objectRenderer = (IObjectRenderer)OptionConverter.InstantiateByClassName(attribute, typeof(IObjectRenderer), null);

            if (objectRenderer == null)
            {
                LogLog.Error(declaringType, "Could not instantiate renderer [" + attribute + "].");
            }
            else
            {
                try
                {
                    m_hierarchy.RendererMap.Put(SystemInfo.GetTypeFromString(GetType().GetTypeInfo().Assembly, attribute2, throwOnError: true, ignoreCase: true), objectRenderer);
                }
                catch (Exception exception)
                {
                    LogLog.Error(declaringType, "Could not find class [" + attribute2 + "].", exception);
                }
            }
        }
Ejemplo n.º 17
0
        protected void SetParameter(XmlElement element, object target)
        {
            string attribute = element.GetAttribute("name");

            if ((element.LocalName != "param") || ((attribute == null) || (attribute.Length == 0)))
            {
                attribute = element.LocalName;
            }
            Type         targetType = target.GetType();
            Type         objA       = null;
            PropertyInfo property   = null;
            MethodInfo   info2      = null;

            property = targetType.GetProperty(attribute, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase);
            if ((property != null) && property.CanWrite)
            {
                objA = property.PropertyType;
            }
            else
            {
                property = null;
                info2    = this.FindMethodInfo(targetType, attribute);
                if (info2 != null)
                {
                    objA = info2.GetParameters()[0].ParameterType;
                }
            }
            if (objA == null)
            {
                string[] textArray1 = new string[] { "XmlHierarchyConfigurator: Cannot find Property [", attribute, "] to set object on [", target.ToString(), "]" };
                LogLog.Error(declaringType, string.Concat(textArray1));
            }
            else
            {
                string str2 = null;
                if (element.GetAttributeNode("value") != null)
                {
                    str2 = element.GetAttribute("value");
                }
                else if (element.HasChildNodes)
                {
                    IEnumerator enumerator = element.ChildNodes.GetEnumerator();
                    try
                    {
                        while (enumerator.MoveNext())
                        {
                            XmlNode current = (XmlNode)enumerator.Current;
                            if ((current.NodeType == XmlNodeType.CDATA) || (current.NodeType == XmlNodeType.Text))
                            {
                                str2 = (str2 != null) ? (str2 + current.InnerText) : current.InnerText;
                            }
                        }
                    }
                    finally
                    {
                        IDisposable disposable = enumerator as IDisposable;
                        if (disposable != null)
                        {
                            disposable.Dispose();
                        }
                    }
                }
                if (str2 == null)
                {
                    object obj3 = null;
                    if (ReferenceEquals(objA, typeof(string)) && !this.HasAttributesOrElements(element))
                    {
                        obj3 = string.Empty;
                    }
                    else
                    {
                        Type defaultTargetType = null;
                        if (IsTypeConstructible(objA))
                        {
                            defaultTargetType = objA;
                        }
                        obj3 = this.CreateObjectFromXml(element, defaultTargetType, objA);
                    }
                    if (obj3 == null)
                    {
                        LogLog.Error(declaringType, "Failed to create object to set param: " + attribute);
                    }
                    else if (property != null)
                    {
                        object[] objArray5 = new object[] { "Setting Property [", property.Name, "] to object [", obj3, "]" };
                        LogLog.Debug(declaringType, string.Concat(objArray5));
                        try
                        {
                            property.SetValue(target, obj3, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        catch (TargetInvocationException exception4)
                        {
                            object[] objArray6 = new object[] { "Failed to set parameter [", property.Name, "] on object [", target, "] using value [", obj3, "]" };
                            LogLog.Error(declaringType, string.Concat(objArray6), exception4.InnerException);
                        }
                    }
                    else if (info2 != null)
                    {
                        object[] objArray7 = new object[] { "Setting Collection Property [", info2.Name, "] to object [", obj3, "]" };
                        LogLog.Debug(declaringType, string.Concat(objArray7));
                        try
                        {
                            object[] parameters = new object[] { obj3 };
                            info2.Invoke(target, BindingFlags.InvokeMethod, null, parameters, CultureInfo.InvariantCulture);
                        }
                        catch (TargetInvocationException exception5)
                        {
                            object[] objArray9 = new object[] { "Failed to set parameter [", info2.Name, "] on object [", target, "] using value [", obj3, "]" };
                            LogLog.Error(declaringType, string.Concat(objArray9), exception5.InnerException);
                        }
                    }
                }
                else
                {
                    try
                    {
                        IDictionary environmentVariables = Environment.GetEnvironmentVariables();
                        if (this.HasCaseInsensitiveEnvironment)
                        {
                            environmentVariables = this.CreateCaseInsensitiveWrapper(environmentVariables);
                        }
                        str2 = OptionConverter.SubstituteVariables(str2, environmentVariables);
                    }
                    catch (SecurityException)
                    {
                        LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
                    }
                    Type   type3    = null;
                    string typeName = element.GetAttribute("type");
                    if ((typeName != null) && (typeName.Length > 0))
                    {
                        try
                        {
                            Type     c          = SystemInfo.GetTypeFromString(typeName, true, true);
                            string[] textArray2 = new string[] { "Parameter [", attribute, "] specified subtype [", c.FullName, "]" };
                            LogLog.Debug(declaringType, string.Concat(textArray2));
                            if (objA.IsAssignableFrom(c))
                            {
                                objA = c;
                            }
                            else if (OptionConverter.CanConvertTypeTo(c, objA))
                            {
                                type3 = objA;
                                objA  = c;
                            }
                            else
                            {
                                string[] textArray3 = new string[] { "subtype [", c.FullName, "] set on [", attribute, "] is not a subclass of property type [", objA.FullName, "] and there are no acceptable type conversions." };
                                LogLog.Error(declaringType, string.Concat(textArray3));
                            }
                        }
                        catch (Exception exception)
                        {
                            string[] textArray4 = new string[] { "Failed to find type [", typeName, "] set on [", attribute, "]" };
                            LogLog.Error(declaringType, string.Concat(textArray4), exception);
                        }
                    }
                    object sourceInstance = this.ConvertStringTo(objA, str2);
                    if ((sourceInstance != null) && (type3 != null))
                    {
                        string[] textArray5 = new string[] { "Performing additional conversion of value from [", sourceInstance.GetType().Name, "] to [", type3.Name, "]" };
                        LogLog.Debug(declaringType, string.Concat(textArray5));
                        sourceInstance = OptionConverter.ConvertTypeTo(sourceInstance, type3);
                    }
                    if (sourceInstance == null)
                    {
                        object[] objArray4 = new object[] { "Unable to set property [", attribute, "] on object [", target, "] using value [", str2, "] (with acceptable conversion types)" };
                        LogLog.Warn(declaringType, string.Concat(objArray4));
                    }
                    else if (property != null)
                    {
                        string[] textArray6 = new string[] { "Setting Property [", property.Name, "] to ", sourceInstance.GetType().Name, " value [", sourceInstance.ToString(), "]" };
                        LogLog.Debug(declaringType, string.Concat(textArray6));
                        try
                        {
                            property.SetValue(target, sourceInstance, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        catch (TargetInvocationException exception2)
                        {
                            object[] objArray1 = new object[] { "Failed to set parameter [", property.Name, "] on object [", target, "] using value [", sourceInstance, "]" };
                            LogLog.Error(declaringType, string.Concat(objArray1), exception2.InnerException);
                        }
                    }
                    else if (info2 != null)
                    {
                        string[] textArray7 = new string[] { "Setting Collection Property [", info2.Name, "] to ", sourceInstance.GetType().Name, " value [", sourceInstance.ToString(), "]" };
                        LogLog.Debug(declaringType, string.Concat(textArray7));
                        try
                        {
                            object[] parameters = new object[] { sourceInstance };
                            info2.Invoke(target, BindingFlags.InvokeMethod, null, parameters, CultureInfo.InvariantCulture);
                        }
                        catch (TargetInvocationException exception3)
                        {
                            object[] objArray3 = new object[] { "Failed to set parameter [", attribute, "] on object [", target, "] using value [", sourceInstance, "]" };
                            LogLog.Error(declaringType, string.Concat(objArray3), exception3.InnerException);
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
 public void Configure(XmlElement element)
 {
     if ((element != null) && (this.m_hierarchy != null))
     {
         if (element.LocalName != "log4net")
         {
             LogLog.Error(declaringType, "Xml element is - not a <log4net> element.");
         }
         else
         {
             if (!LogLog.EmitInternalMessages)
             {
                 string argValue = element.GetAttribute("emitDebug");
                 LogLog.Debug(declaringType, "emitDebug attribute [" + argValue + "].");
                 if ((argValue.Length > 0) && (argValue != "null"))
                 {
                     LogLog.EmitInternalMessages = OptionConverter.ToBoolean(argValue, true);
                 }
                 else
                 {
                     LogLog.Debug(declaringType, "Ignoring emitDebug attribute.");
                 }
             }
             if (!LogLog.InternalDebugging)
             {
                 string argValue = element.GetAttribute("debug");
                 LogLog.Debug(declaringType, "debug attribute [" + argValue + "].");
                 if ((argValue.Length > 0) && (argValue != "null"))
                 {
                     LogLog.InternalDebugging = OptionConverter.ToBoolean(argValue, true);
                 }
                 else
                 {
                     LogLog.Debug(declaringType, "Ignoring debug attribute.");
                 }
                 string str4 = element.GetAttribute("configDebug");
                 if ((str4.Length > 0) && (str4 != "null"))
                 {
                     LogLog.Warn(declaringType, "The \"configDebug\" attribute is deprecated.");
                     LogLog.Warn(declaringType, "Use the \"debug\" attribute instead.");
                     LogLog.InternalDebugging = OptionConverter.ToBoolean(str4, true);
                 }
             }
             ConfigUpdateMode merge     = ConfigUpdateMode.Merge;
             string           attribute = element.GetAttribute("update");
             if ((attribute != null) && (attribute.Length > 0))
             {
                 try
                 {
                     merge = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), attribute);
                 }
                 catch
                 {
                     LogLog.Error(declaringType, "Invalid update attribute value [" + attribute + "]");
                 }
             }
             LogLog.Debug(declaringType, "Configuration update mode [" + merge.ToString() + "].");
             if (merge == ConfigUpdateMode.Overwrite)
             {
                 this.m_hierarchy.ResetConfiguration();
                 LogLog.Debug(declaringType, "Configuration reset before reading config.");
             }
             IEnumerator enumerator = element.ChildNodes.GetEnumerator();
             try
             {
                 while (enumerator.MoveNext())
                 {
                     XmlNode current = (XmlNode)enumerator.Current;
                     if (current.NodeType == XmlNodeType.Element)
                     {
                         XmlElement loggerElement = (XmlElement)current;
                         if (loggerElement.LocalName == "logger")
                         {
                             this.ParseLogger(loggerElement);
                             continue;
                         }
                         if (loggerElement.LocalName == "category")
                         {
                             this.ParseLogger(loggerElement);
                             continue;
                         }
                         if (loggerElement.LocalName == "root")
                         {
                             this.ParseRoot(loggerElement);
                             continue;
                         }
                         if (loggerElement.LocalName == "renderer")
                         {
                             this.ParseRenderer(loggerElement);
                             continue;
                         }
                         if (loggerElement.LocalName != "appender")
                         {
                             this.SetParameter(loggerElement, this.m_hierarchy);
                         }
                     }
                 }
             }
             finally
             {
                 IDisposable disposable = enumerator as IDisposable;
                 if (disposable != null)
                 {
                     disposable.Dispose();
                 }
             }
             string str6 = element.GetAttribute("threshold");
             LogLog.Debug(declaringType, "Hierarchy Threshold [" + str6 + "]");
             if ((str6.Length > 0) && (str6 != "null"))
             {
                 Level level = (Level)this.ConvertStringTo(typeof(Level), str6);
                 if (level != null)
                 {
                     this.m_hierarchy.Threshold = level;
                 }
                 else
                 {
                     LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + str6 + "] (with acceptable conversion types)");
                 }
             }
         }
     }
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Creates an object as specified in XML.
        /// </summary>
        /// <param name="element">The XML element that contains the definition of the object.</param>
        /// <param name="defaultTargetType">The object type to use if not explicitly specified.</param>
        /// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param>
        /// <returns>The object or <c>null</c></returns>
        /// <remarks>
        /// <para>
        /// Parse an XML element and create an object instance based on the configuration
        /// data.
        /// </para>
        /// <para>
        /// The type of the instance may be specified in the XML. If not
        /// specified then the <paramref name="defaultTargetType" /> is used
        /// as the type. However the type is specified it must support the
        /// <paramref name="typeConstraint" /> type.
        /// </para>
        /// </remarks>
        protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
        {
            Type   type      = null;
            string attribute = element.GetAttribute("type");

            if (attribute == null || attribute.Length == 0)
            {
                if ((object)defaultTargetType == null)
                {
                    LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type.");
                    return(null);
                }
                type = defaultTargetType;
            }
            else
            {
                try
                {
                    type = SystemInfo.GetTypeFromString(GetType().GetTypeInfo().Assembly, attribute, throwOnError: true, ignoreCase: true);
                }
                catch (Exception exception)
                {
                    LogLog.Error(declaringType, "Failed to find type [" + attribute + "]", exception);
                    return(null);
                }
            }
            bool flag = false;

            if ((object)typeConstraint != null && !CompatibilityExtensions.IsAssignableFrom(typeConstraint, type))
            {
                if (!OptionConverter.CanConvertTypeTo(type, typeConstraint))
                {
                    LogLog.Error(declaringType, "Object type [" + type.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type conversions.");
                    return(null);
                }
                flag = true;
            }
            object obj = null;

            try
            {
                obj = Activator.CreateInstance(type);
            }
            catch (Exception ex)
            {
                LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + type.FullName + "] Exception: " + ex.ToString());
            }
            foreach (XmlNode childNode in element.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    SetParameter((XmlElement)childNode, obj);
                }
            }
            (obj as IOptionHandler)?.ActivateOptions();
            if (flag)
            {
                return(OptionConverter.ConvertTypeTo(obj, typeConstraint));
            }
            return(obj);
        }
        /// <summary>
        /// Sets a paramater on an object.
        /// </summary>
        /// <remarks>
        /// The parameter name must correspond to a writable property
        /// on the object. The value of the parameter is a string,
        /// therefore this function will attempt to set a string
        /// property first. If unable to set a string property it
        /// will inspect the property and its argument type. It will
        /// attempt to call a static method called 'Parse' on the
        /// type of the property. This method will take a single
        /// string argument and return a value that can be used to
        /// set the property.
        /// </remarks>
        /// <param name="element">The parameter element.</param>
        /// <param name="target">The object to set the parameter on.</param>
        protected void SetParameter(XmlElement element, object target)
        {
            // Get the property name
            string name = element.GetAttribute(NAME_ATTR);

            // If the name attribute does not exist then use the name of the element
            if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
            {
                name = element.LocalName;
            }

            // Look for the property on the target object
            Type targetType   = target.GetType();
            Type propertyType = null;

            PropertyInfo propInfo = null;
            MethodInfo   methInfo = null;

            // Try to find a writable property
            propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
            if (propInfo != null && propInfo.CanWrite)
            {
                // found a property
                propertyType = propInfo.PropertyType;
            }
            else
            {
                propInfo = null;

                // look for a method with the signature Add<property>(type)

                methInfo = targetType.GetMethod("Add" + name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.IgnoreCase);
                if (methInfo != null && methInfo.IsPublic && !methInfo.IsStatic)
                {
                    System.Reflection.ParameterInfo[] methParams = methInfo.GetParameters();
                    if (methParams.Length == 1)
                    {
                        propertyType = methParams[0].ParameterType;
                    }
                    else
                    {
                        methInfo = null;
                    }
                }
                else
                {
                    methInfo = null;
                }
            }

            if (propertyType == null)
            {
                LogLog.Error("DOMConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
            }
            else
            {
                if (element.GetAttributeNode(VALUE_ATTR) != null)
                {
                    string propertyValue = element.GetAttribute(VALUE_ATTR);

                    // Fixup embedded non-printable chars
                    propertyValue = OptionConverter.ConvertSpecialChars(propertyValue);

#if !NETCF
                    try
                    {
                        // Expand environment variables in the string.
                        propertyValue = OptionConverter.SubstVars(propertyValue, Environment.GetEnvironmentVariables());
                    }
                    catch (System.Security.SecurityException)
                    {
                        // This security exception will occur if the caller does not have
                        // unrestricted environment permission. If this occurs the expansion
                        // will be skipped with the following warning message.
                        LogLog.Debug("DOMConfigurator: Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
                    }
#endif
                    // Now try to convert the string value to an acceptable type
                    // to pass to this property.

                    object convertedValue = ConvertStringTo(propertyType, propertyValue);
                    if (convertedValue != null)
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

                            // Pass to the property
                            propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

                            // Pass to the property
                            methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture);
                        }
                    }
                    else
                    {
                        LogLog.Warn("DOMConfigurator: Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
                    }
                }
                else
                {
                    // No value specified
                    Type defaultObjectType = null;
                    if (propertyType.IsClass && !propertyType.IsAbstract)
                    {
                        defaultObjectType = propertyType;
                    }

                    object createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType);

                    if (createdObject == null)
                    {
                        LogLog.Error("DOMConfigurator: Failed to create object to set param: " + name);
                    }
                    else
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]");

                            // Pass to the property
                            propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug("DOMConfigurator: Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]");

                            // Pass to the property
                            methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture);
                        }
                    }
                }
            }
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Sets a parameter on an object.
        /// </summary>
        /// <param name="element">The parameter element.</param>
        /// <param name="target">The object to set the parameter on.</param>
        /// <remarks>
        /// The parameter name must correspond to a writable property
        /// on the object. The value of the parameter is a string,
        /// therefore this function will attempt to set a string
        /// property first. If unable to set a string property it
        /// will inspect the property and its argument type. It will
        /// attempt to call a static method called <c>Parse</c> on the
        /// type of the property. This method will take a single
        /// string argument and return a value that can be used to
        /// set the property.
        /// </remarks>
        protected void SetParameter(XmlElement element, object target)
        {
            string text = element.GetAttribute("name");

            if (element.LocalName != "param" || text == null || text.Length == 0)
            {
                text = element.LocalName;
            }
            Type         type         = target.GetType();
            Type         type2        = null;
            PropertyInfo propertyInfo = null;
            MethodInfo   methodInfo   = null;

            propertyInfo = type.GetProperty(text, BindingFlags.IgnoreCase | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
            if ((object)propertyInfo != null && propertyInfo.CanWrite)
            {
                type2 = propertyInfo.PropertyType;
            }
            else
            {
                propertyInfo = null;
                methodInfo   = FindMethodInfo(type, text);
                if ((object)methodInfo != null)
                {
                    type2 = methodInfo.GetParameters()[0].ParameterType;
                }
            }
            if ((object)type2 == null)
            {
                LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + text + "] to set object on [" + target.ToString() + "]");
                return;
            }
            string text2 = null;

            if (element.GetAttributeNode("value") != null)
            {
                text2 = element.GetAttribute("value");
            }
            else if (element.HasChildNodes)
            {
                foreach (XmlNode childNode in element.ChildNodes)
                {
                    if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text)
                    {
                        text2 = ((text2 != null) ? (text2 + childNode.InnerText) : childNode.InnerText);
                    }
                }
            }
            if (text2 != null)
            {
                Type   type3     = null;
                string attribute = element.GetAttribute("type");
                if (attribute != null && attribute.Length > 0)
                {
                    try
                    {
                        Type typeFromString = SystemInfo.GetTypeFromString(GetType().GetTypeInfo().Assembly, attribute, throwOnError: true, ignoreCase: true);
                        LogLog.Debug(declaringType, "Parameter [" + text + "] specified subtype [" + typeFromString.FullName + "]");
                        if (!CompatibilityExtensions.IsAssignableFrom(type2, typeFromString))
                        {
                            if (OptionConverter.CanConvertTypeTo(typeFromString, type2))
                            {
                                type3 = type2;
                                type2 = typeFromString;
                            }
                            else
                            {
                                LogLog.Error(declaringType, "subtype [" + typeFromString.FullName + "] set on [" + text + "] is not a subclass of property type [" + type2.FullName + "] and there are no acceptable type conversions.");
                            }
                        }
                        else
                        {
                            type2 = typeFromString;
                        }
                    }
                    catch (Exception exception)
                    {
                        LogLog.Error(declaringType, "Failed to find type [" + attribute + "] set on [" + text + "]", exception);
                    }
                }
                object obj = ConvertStringTo(type2, text2);
                if (obj != null && (object)type3 != null)
                {
                    LogLog.Debug(declaringType, "Performing additional conversion of value from [" + obj.GetType().Name + "] to [" + type3.Name + "]");
                    obj = OptionConverter.ConvertTypeTo(obj, type3);
                }
                if (obj != null)
                {
                    if ((object)propertyInfo != null)
                    {
                        LogLog.Debug(declaringType, "Setting Property [" + propertyInfo.Name + "] to " + obj.GetType().Name + " value [" + obj.ToString() + "]");
                        try
                        {
                            propertyInfo.SetValue(target, obj, null);
                        }
                        catch (TargetInvocationException ex)
                        {
                            LogLog.Error(declaringType, "Failed to set parameter [" + propertyInfo.Name + "] on object [" + target + "] using value [" + obj + "]", ex.InnerException);
                        }
                    }
                    else if ((object)methodInfo != null)
                    {
                        LogLog.Debug(declaringType, "Setting Collection Property [" + methodInfo.Name + "] to " + obj.GetType().Name + " value [" + obj.ToString() + "]");
                        try
                        {
                            methodInfo.Invoke(target, new object[1]
                            {
                                obj
                            });
                        }
                        catch (TargetInvocationException ex2)
                        {
                            LogLog.Error(declaringType, "Failed to set parameter [" + text + "] on object [" + target + "] using value [" + obj + "]", ex2.InnerException);
                        }
                    }
                }
                else
                {
                    LogLog.Warn(declaringType, "Unable to set property [" + text + "] on object [" + target + "] using value [" + text2 + "] (with acceptable conversion types)");
                }
                return;
            }
            object obj2 = null;

            if ((object)type2 == typeof(string) && !HasAttributesOrElements(element))
            {
                obj2 = "";
            }
            else
            {
                Type defaultTargetType = null;
                if (IsTypeConstructible(type2))
                {
                    defaultTargetType = type2;
                }
                obj2 = CreateObjectFromXml(element, defaultTargetType, type2);
            }
            if (obj2 == null)
            {
                LogLog.Error(declaringType, "Failed to create object to set param: " + text);
            }
            else if ((object)propertyInfo != null)
            {
                LogLog.Debug(declaringType, "Setting Property [" + propertyInfo.Name + "] to object [" + obj2 + "]");
                try
                {
                    propertyInfo.SetValue(target, obj2, null);
                }
                catch (TargetInvocationException ex3)
                {
                    LogLog.Error(declaringType, "Failed to set parameter [" + propertyInfo.Name + "] on object [" + target + "] using value [" + obj2 + "]", ex3.InnerException);
                }
            }
            else if ((object)methodInfo != null)
            {
                LogLog.Debug(declaringType, "Setting Collection Property [" + methodInfo.Name + "] to object [" + obj2 + "]");
                try
                {
                    methodInfo.Invoke(target, new object[1]
                    {
                        obj2
                    });
                }
                catch (TargetInvocationException ex4)
                {
                    LogLog.Error(declaringType, "Failed to set parameter [" + methodInfo.Name + "] on object [" + target + "] using value [" + obj2 + "]", ex4.InnerException);
                }
            }
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Sets a parameter on an object.
        /// </summary>
        /// <param name="element">The parameter element.</param>
        /// <param name="target">The object to set the parameter on.</param>
        /// <remarks>
        /// The parameter name must correspond to a writable property
        /// on the object. The value of the parameter is a string,
        /// therefore this function will attempt to set a string
        /// property first. If unable to set a string property it
        /// will inspect the property and its argument type. It will
        /// attempt to call a static method called <c>Parse</c> on the
        /// type of the property. This method will take a single
        /// string argument and return a value that can be used to
        /// set the property.
        /// </remarks>
        protected void SetParameter(XmlElement element, object target)
        {
            // Get the property name
            string name = element.GetAttribute(NAME_ATTR);

            // If the name attribute does not exist then use the name of the element
            if (element.LocalName != PARAM_TAG || name == null || name.Length == 0)
            {
                name = element.LocalName;
            }

            // Look for the property on the target object
            Type targetType   = target.GetType();
            Type propertyType = null;

            PropertyInfo propInfo = null;
            MethodInfo   methInfo = null;

            // Try to find a writable property
            propInfo = targetType.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.IgnoreCase);
            if (propInfo != null && propInfo.CanWrite)
            {
                // found a property
                propertyType = propInfo.PropertyType;
            }
            else
            {
                propInfo = null;

                // look for a method with the signature Add<property>(type)
                methInfo = FindMethodInfo(targetType, name);

                if (methInfo != null)
                {
                    propertyType = methInfo.GetParameters()[0].ParameterType;
                }
            }

            if (propertyType == null)
            {
                LogLog.Error(declaringType, "XmlHierarchyConfigurator: Cannot find Property [" + name + "] to set object on [" + target.ToString() + "]");
            }
            else
            {
                string propertyValue = null;

                if (element.GetAttributeNode(VALUE_ATTR) != null)
                {
                    propertyValue = element.GetAttribute(VALUE_ATTR);
                }
                else if (element.HasChildNodes)
                {
                    // Concatenate the CDATA and Text nodes together
                    foreach (XmlNode childNode in element.ChildNodes)
                    {
                        if (childNode.NodeType == XmlNodeType.CDATA || childNode.NodeType == XmlNodeType.Text)
                        {
                            if (propertyValue == null)
                            {
                                propertyValue = childNode.InnerText;
                            }
                            else
                            {
                                propertyValue += childNode.InnerText;
                            }
                        }
                    }
                }

                if (propertyValue != null)
                {
#if !NETCF
                    try
                    {
                        // Expand environment variables in the string.
                        propertyValue = OptionConverter.SubstituteVariables(propertyValue, Environment.GetEnvironmentVariables());
                    }
                    catch (System.Security.SecurityException)
                    {
                        // This security exception will occur if the caller does not have
                        // unrestricted environment permission. If this occurs the expansion
                        // will be skipped with the following warning message.
                        LogLog.Debug(declaringType, "Security exception while trying to expand environment variables. Error Ignored. No Expansion.");
                    }
#endif

                    Type parsedObjectConversionTargetType = null;

                    // Check if a specific subtype is specified on the element using the 'type' attribute
                    string subTypeString = element.GetAttribute(TYPE_ATTR);
                    if (subTypeString != null && subTypeString.Length > 0)
                    {
                        // Read the explicit subtype
                        try
                        {
                            Type subType = SystemInfo.GetTypeFromString(subTypeString, true, true);

                            LogLog.Debug(declaringType, "Parameter [" + name + "] specified subtype [" + subType.FullName + "]");

                            if (!propertyType.IsAssignableFrom(subType))
                            {
                                // Check if there is an appropriate type converter
                                if (OptionConverter.CanConvertTypeTo(subType, propertyType))
                                {
                                    // Must re-convert to the real property type
                                    parsedObjectConversionTargetType = propertyType;

                                    // Use sub type as intermediary type
                                    propertyType = subType;
                                }
                                else
                                {
                                    LogLog.Error(declaringType, "subtype [" + subType.FullName + "] set on [" + name + "] is not a subclass of property type [" + propertyType.FullName + "] and there are no acceptable type conversions.");
                                }
                            }
                            else
                            {
                                // The subtype specified is found and is actually a subtype of the property
                                // type, therefore we can switch to using this type.
                                propertyType = subType;
                            }
                        }
                        catch (Exception ex)
                        {
                            LogLog.Error(declaringType, "Failed to find type [" + subTypeString + "] set on [" + name + "]", ex);
                        }
                    }

                    // Now try to convert the string value to an acceptable type
                    // to pass to this property.

                    object convertedValue = ConvertStringTo(propertyType, propertyValue);

                    // Check if we need to do an additional conversion
                    if (convertedValue != null && parsedObjectConversionTargetType != null)
                    {
                        LogLog.Debug(declaringType, "Performing additional conversion of value from [" + convertedValue.GetType().Name + "] to [" + parsedObjectConversionTargetType.Name + "]");
                        convertedValue = OptionConverter.ConvertTypeTo(convertedValue, parsedObjectConversionTargetType);
                    }

                    if (convertedValue != null)
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

                            try
                            {
                                // Pass to the property
                                propInfo.SetValue(target, convertedValue, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
                            }
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to " + convertedValue.GetType().Name + " value [" + convertedValue.ToString() + "]");

                            try
                            {
                                // Pass to the property
                                methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { convertedValue }, CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(declaringType, "Failed to set parameter [" + name + "] on object [" + target + "] using value [" + convertedValue + "]", targetInvocationEx.InnerException);
                            }
                        }
                    }
                    else
                    {
                        LogLog.Warn(declaringType, "Unable to set property [" + name + "] on object [" + target + "] using value [" + propertyValue + "] (with acceptable conversion types)");
                    }
                }
                else
                {
                    object createdObject = null;

                    if (propertyType == typeof(string) && !HasAttributesOrElements(element))
                    {
                        // If the property is a string and the element is empty (no attributes
                        // or child elements) then we special case the object value to an empty string.
                        // This is necessary because while the String is a class it does not have
                        // a default constructor that creates an empty string, which is the behavior
                        // we are trying to simulate and would be expected from CreateObjectFromXml
                        createdObject = "";
                    }
                    else
                    {
                        // No value specified
                        Type defaultObjectType = null;
                        if (IsTypeConstructible(propertyType))
                        {
                            defaultObjectType = propertyType;
                        }

                        createdObject = CreateObjectFromXml(element, defaultObjectType, propertyType);
                    }

                    if (createdObject == null)
                    {
                        LogLog.Error(declaringType, "Failed to create object to set param: " + name);
                    }
                    else
                    {
                        if (propInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug(declaringType, "Setting Property [" + propInfo.Name + "] to object [" + createdObject + "]");

                            try
                            {
                                // Pass to the property
                                propInfo.SetValue(target, createdObject, BindingFlags.SetProperty, null, null, CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(declaringType, "Failed to set parameter [" + propInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
                            }
                        }
                        else if (methInfo != null)
                        {
                            // Got a converted result
                            LogLog.Debug(declaringType, "Setting Collection Property [" + methInfo.Name + "] to object [" + createdObject + "]");

                            try
                            {
                                // Pass to the property
                                methInfo.Invoke(target, BindingFlags.InvokeMethod, null, new object[] { createdObject }, CultureInfo.InvariantCulture);
                            }
                            catch (TargetInvocationException targetInvocationEx)
                            {
                                LogLog.Error(declaringType, "Failed to set parameter [" + methInfo.Name + "] on object [" + target + "] using value [" + createdObject + "]", targetInvocationEx.InnerException);
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Configure the hierarchy by parsing a DOM tree of XML elements.
        /// </summary>
        /// <param name="element">The root element to parse.</param>
        /// <remarks>
        /// <para>
        /// Configure the hierarchy by parsing a DOM tree of XML elements.
        /// </para>
        /// </remarks>
        public void Configure(XmlElement element)
        {
            if (element == null || m_hierarchy == null)
            {
                return;
            }
            if (element.LocalName != "log4net")
            {
                LogLog.Error(declaringType, "Xml element is - not a <log4net> element.");
                return;
            }
            if (!LogLog.EmitInternalMessages)
            {
                string attribute = element.GetAttribute("emitDebug");
                LogLog.Debug(declaringType, "emitDebug attribute [" + attribute + "].");
                if (attribute.Length > 0 && attribute != "null")
                {
                    LogLog.EmitInternalMessages = OptionConverter.ToBoolean(attribute, defaultValue: true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring emitDebug attribute.");
                }
            }
            if (!LogLog.InternalDebugging)
            {
                string attribute2 = element.GetAttribute("debug");
                LogLog.Debug(declaringType, "debug attribute [" + attribute2 + "].");
                if (attribute2.Length > 0 && attribute2 != "null")
                {
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(attribute2, defaultValue: true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring debug attribute.");
                }
                string attribute3 = element.GetAttribute("configDebug");
                if (attribute3.Length > 0 && attribute3 != "null")
                {
                    LogLog.Warn(declaringType, "The \"configDebug\" attribute is deprecated.");
                    LogLog.Warn(declaringType, "Use the \"debug\" attribute instead.");
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(attribute3, defaultValue: true);
                }
            }
            ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge;
            string           attribute4       = element.GetAttribute("update");

            if (attribute4 != null && attribute4.Length > 0)
            {
                try
                {
                    configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), attribute4);
                }
                catch
                {
                    LogLog.Error(declaringType, "Invalid update attribute value [" + attribute4 + "]");
                }
            }
            LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "].");
            if (configUpdateMode == ConfigUpdateMode.Overwrite)
            {
                m_hierarchy.ResetConfiguration();
                LogLog.Debug(declaringType, "Configuration reset before reading config.");
            }
            foreach (XmlNode childNode in element.ChildNodes)
            {
                if (childNode.NodeType == XmlNodeType.Element)
                {
                    XmlElement xmlElement = (XmlElement)childNode;
                    if (xmlElement.LocalName == "logger")
                    {
                        ParseLogger(xmlElement);
                    }
                    else if (xmlElement.LocalName == "category")
                    {
                        ParseLogger(xmlElement);
                    }
                    else if (xmlElement.LocalName == "root")
                    {
                        ParseRoot(xmlElement);
                    }
                    else if (xmlElement.LocalName == "renderer")
                    {
                        ParseRenderer(xmlElement);
                    }
                    else if (!(xmlElement.LocalName == "appender"))
                    {
                        SetParameter(xmlElement, m_hierarchy);
                    }
                }
            }
            string attribute5 = element.GetAttribute("threshold");

            LogLog.Debug(declaringType, "Hierarchy Threshold [" + attribute5 + "]");
            if (attribute5.Length > 0 && attribute5 != "null")
            {
                Level level = (Level)ConvertStringTo(typeof(Level), attribute5);
                if (level != null)
                {
                    m_hierarchy.Threshold = level;
                }
                else
                {
                    LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + attribute5 + "] (with acceptable conversion types)");
                }
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Convert string option into an arrangement using <see cref="ConverterRegistry.GetConvertFrom"/>
        /// </summary>
        /// <param name="option">pattern, see <seealso cref="ConvertFrom"/> for more info on formatting</param>
        /// <returns>the arrangement instance</returns>
        protected static IArrangement GetArrangementInternal(string option)
        {
            var arrangement = OptionConverter.ConvertStringTo(typeof(IArrangement), option) as IArrangement;

            return(arrangement);
        }
Ejemplo n.º 25
0
        protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
        {
            Type   c         = null;
            string attribute = element.GetAttribute("type");

            if ((attribute == null) || (attribute.Length == 0))
            {
                if (defaultTargetType == null)
                {
                    LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type.");
                    return(null);
                }
                c = defaultTargetType;
            }
            else
            {
                try
                {
                    c = SystemInfo.GetTypeFromString(attribute, true, true);
                }
                catch (Exception exception)
                {
                    LogLog.Error(declaringType, "Failed to find type [" + attribute + "]", exception);
                    return(null);
                }
            }
            bool flag = false;

            if ((typeConstraint != null) && !typeConstraint.IsAssignableFrom(c))
            {
                if (!OptionConverter.CanConvertTypeTo(c, typeConstraint))
                {
                    string[] textArray1 = new string[] { "Object type [", c.FullName, "] is not assignable to type [", typeConstraint.FullName, "]. There are no acceptable type conversions." };
                    LogLog.Error(declaringType, string.Concat(textArray1));
                    return(null);
                }
                flag = true;
            }
            object target = null;

            try
            {
                target = Activator.CreateInstance(c);
            }
            catch (Exception exception2)
            {
                LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + c.FullName + "] Exception: " + exception2.ToString());
            }
            IEnumerator enumerator = element.ChildNodes.GetEnumerator();

            try
            {
                while (enumerator.MoveNext())
                {
                    XmlNode current = (XmlNode)enumerator.Current;
                    if (current.NodeType == XmlNodeType.Element)
                    {
                        this.SetParameter((XmlElement)current, target);
                    }
                }
            }
            finally
            {
                IDisposable disposable = enumerator as IDisposable;
                if (disposable != null)
                {
                    disposable.Dispose();
                }
            }
            IOptionHandler handler = target as IOptionHandler;

            if (handler != null)
            {
                handler.ActivateOptions();
            }
            return(!flag ? target : OptionConverter.ConvertTypeTo(target, typeConstraint));
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Configure the hierarchy by parsing a DOM tree of XML elements.
        /// </summary>
        /// <param name="element">The root element to parse.</param>
        /// <remarks>
        /// <para>
        /// Configure the hierarchy by parsing a DOM tree of XML elements.
        /// </para>
        /// </remarks>
        public void Configure(XmlElement element)
        {
            if (element == null || m_hierarchy == null)
            {
                return;
            }

            string rootElementName = element.LocalName;

            if (rootElementName != CONFIGURATION_TAG)
            {
                LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element.");
                return;
            }

            if (!LogLog.EmitInternalMessages)
            {
                // Look for a emitDebug attribute to enable internal debug
                string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR);
                LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "].");

                if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null")
                {
                    LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute.");
                }
            }

            if (!LogLog.InternalDebugging)
            {
                // Look for a debug attribute to enable internal debug
                string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR);
                LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR + " attribute [" + debugAttribute + "].");

                if (debugAttribute.Length > 0 && debugAttribute != "null")
                {
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
                }

                string confDebug = element.GetAttribute(CONFIG_DEBUG_ATTR);
                if (confDebug.Length > 0 && confDebug != "null")
                {
                    LogLog.Warn(declaringType, "The \"" + CONFIG_DEBUG_ATTR + "\" attribute is deprecated.");
                    LogLog.Warn(declaringType, "Use the \"" + INTERNAL_DEBUG_ATTR + "\" attribute instead.");
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(confDebug, true);
                }
            }

            // Default mode is merge
            ConfigUpdateMode configUpdateMode = ConfigUpdateMode.Merge;

            // Look for the config update attribute
            string configUpdateModeAttribute = element.GetAttribute(CONFIG_UPDATE_MODE_ATTR);

            if (configUpdateModeAttribute != null && configUpdateModeAttribute.Length > 0)
            {
                // Parse the attribute
                try
                {
                    configUpdateMode = (ConfigUpdateMode)OptionConverter.ConvertStringTo(typeof(ConfigUpdateMode), configUpdateModeAttribute);
                }
                catch
                {
                    LogLog.Error(declaringType, "Invalid " + CONFIG_UPDATE_MODE_ATTR + " attribute value [" + configUpdateModeAttribute + "]");
                }
            }

            // IMPL: The IFormatProvider argument to Enum.ToString() is deprecated in .NET 2.0
            LogLog.Debug(declaringType, "Configuration update mode [" + configUpdateMode.ToString() + "].");

            // Only reset configuration if overwrite flag specified
            if (configUpdateMode == ConfigUpdateMode.Overwrite)
            {
                // Reset to original unset configuration
                m_hierarchy.ResetConfiguration();
                LogLog.Debug(declaringType, "Configuration reset before reading config.");
            }

            /* Building Appender objects, placing them in a local namespace
             * for future reference */

            /* Process all the top level elements */

            foreach (XmlNode currentNode in element.ChildNodes)
            {
                if (currentNode.NodeType == XmlNodeType.Element)
                {
                    XmlElement currentElement = (XmlElement)currentNode;

                    if (currentElement.LocalName == LOGGER_TAG)
                    {
                        ParseLogger(currentElement);
                    }
                    else if (currentElement.LocalName == CATEGORY_TAG)
                    {
                        // TODO: deprecated use of category
                        ParseLogger(currentElement);
                    }
                    else if (currentElement.LocalName == ROOT_TAG)
                    {
                        ParseRoot(currentElement);
                    }
                    else if (currentElement.LocalName == RENDERER_TAG)
                    {
                        ParseRenderer(currentElement);
                    }
                    else if (currentElement.LocalName == APPENDER_TAG)
                    {
                        // We ignore appenders in this pass. They will
                        // be found and loaded if they are referenced.
                    }
                    else
                    {
                        // Read the param tags and set properties on the hierarchy
                        SetParameter(currentElement, m_hierarchy);
                    }
                }
            }

            // Lastly set the hierarchy threshold
            string thresholdStr = element.GetAttribute(THRESHOLD_ATTR);

            LogLog.Debug(declaringType, "Hierarchy Threshold [" + thresholdStr + "]");
            if (thresholdStr.Length > 0 && thresholdStr != "null")
            {
                Level thresholdLevel = (Level)ConvertStringTo(typeof(Level), thresholdStr);
                if (thresholdLevel != null)
                {
                    m_hierarchy.Threshold = thresholdLevel;
                }
                else
                {
                    LogLog.Warn(declaringType, "Unable to set hierarchy threshold using value [" + thresholdStr + "] (with acceptable conversion types)");
                }
            }

            // Done reading config
        }
        /// <summary>
        /// Creates an object as specified in XML.
        /// </summary>
        /// <param name="element">The XML element that contains the definition of the object.</param>
        /// <param name="defaultTargetType">The object type to use if not explicitly specified.</param>
        /// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param>
        /// <returns>The object or <c>null</c></returns>
        protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
        {
            Type objectType = null;

            // Get the object type
            string objectTypeString = element.GetAttribute(TYPE_ATTR);

            if (objectTypeString == null || objectTypeString.Length == 0)
            {
                if (defaultTargetType == null)
                {
                    LogLog.Error("DOMConfigurator: Object type not specified. Cannot create object.");
                    return(null);
                }
                else
                {
                    // Use the default object type
                    objectType = defaultTargetType;
                }
            }
            else
            {
                // Read the explicit object type
                try
                {
                    objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true);
                }
                catch (Exception ex)
                {
                    LogLog.Error("DOMConfigurator: Failed to find type [" + objectTypeString + "]", ex);
                    return(null);
                }
            }

            bool requiresConversion = false;

            // Got the object type. Check that it meets the typeConstraint
            if (typeConstraint != null)
            {
                if (!typeConstraint.IsAssignableFrom(objectType))
                {
                    // Check if there is an appropriate type converter
                    if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint))
                    {
                        requiresConversion = true;
                    }
                    else
                    {
                        LogLog.Error("DOMConfigurator: Object type [" + objectType.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type convertions.");
                        return(null);
                    }
                }
            }

            // Look for the default constructor
            ConstructorInfo constInfo = objectType.GetConstructor(SystemInfo.EmptyTypes);

            if (constInfo == null)
            {
                LogLog.Error("DOMConfigurator: Failed to find default constructor for type [" + objectType.FullName + "]");
                return(null);
            }

            // Call the constructor
            object createdObject = constInfo.Invoke(BindingFlags.Public | BindingFlags.Instance, null, new object[0], CultureInfo.InvariantCulture);

            // Set any params on object
            foreach (XmlNode currentNode in element.ChildNodes)
            {
                if (currentNode.NodeType == XmlNodeType.Element)
                {
                    SetParameter((XmlElement)currentNode, createdObject);
                }
            }

            // Check if we need to call ActivateOptions
            if (createdObject is IOptionHandler)
            {
                ((IOptionHandler)createdObject).ActivateOptions();
            }

            // Ok object should be initialised

            if (requiresConversion)
            {
                // Convert the object type
                return(OptionConverter.ConvertTypeTo(createdObject, typeConstraint));
            }
            else
            {
                // The object is of the correct type
                return(createdObject);
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Creates an object as specified in XML.
        /// </summary>
        /// <param name="element">The XML element that contains the definition of the object.</param>
        /// <param name="defaultTargetType">The object type to use if not explicitly specified.</param>
        /// <param name="typeConstraint">The type that the returned object must be or must inherit from.</param>
        /// <returns>The object or <c>null</c></returns>
        /// <remarks>
        /// <para>
        /// Parse an XML element and create an object instance based on the configuration
        /// data.
        /// </para>
        /// <para>
        /// The type of the instance may be specified in the XML. If not
        /// specified then the <paramref name="defaultTargetType"/> is used
        /// as the type. However the type is specified it must support the
        /// <paramref name="typeConstraint"/> type.
        /// </para>
        /// </remarks>
        protected object CreateObjectFromXml(XmlElement element, Type defaultTargetType, Type typeConstraint)
        {
            Type objectType = null;

            // Get the object type
            string objectTypeString = element.GetAttribute(TYPE_ATTR);

            if (objectTypeString == null || objectTypeString.Length == 0)
            {
                if (defaultTargetType == null)
                {
                    LogLog.Error(declaringType, "Object type not specified. Cannot create object of type [" + typeConstraint.FullName + "]. Missing Value or Type.");
                    return(null);
                }
                else
                {
                    // Use the default object type
                    objectType = defaultTargetType;
                }
            }
            else
            {
                // Read the explicit object type
                try
                {
                    objectType = SystemInfo.GetTypeFromString(objectTypeString, true, true);
                }
                catch (Exception ex)
                {
                    LogLog.Error(declaringType, "Failed to find type [" + objectTypeString + "]", ex);
                    return(null);
                }
            }

            bool requiresConversion = false;

            // Got the object type. Check that it meets the typeConstraint
            if (typeConstraint != null)
            {
                if (!typeConstraint.IsAssignableFrom(objectType))
                {
                    // Check if there is an appropriate type converter
                    if (OptionConverter.CanConvertTypeTo(objectType, typeConstraint))
                    {
                        requiresConversion = true;
                    }
                    else
                    {
                        LogLog.Error(declaringType, "Object type [" + objectType.FullName + "] is not assignable to type [" + typeConstraint.FullName + "]. There are no acceptable type conversions.");
                        return(null);
                    }
                }
            }

            // Create using the default constructor
            object createdObject = null;

            try
            {
                createdObject = Activator.CreateInstance(objectType);
            }
            catch (Exception createInstanceEx)
            {
                LogLog.Error(declaringType, "XmlHierarchyConfigurator: Failed to construct object of type [" + objectType.FullName + "] Exception: " + createInstanceEx.ToString());
            }

            // Set any params on object
            foreach (XmlNode currentNode in element.ChildNodes)
            {
                if (currentNode.NodeType == XmlNodeType.Element)
                {
                    SetParameter((XmlElement)currentNode, createdObject);
                }
            }

            // Check if we need to call ActivateOptions
            IOptionHandler optionHandler = createdObject as IOptionHandler;

            if (optionHandler != null)
            {
                optionHandler.ActivateOptions();
            }

            // Ok object should be initialized

            if (requiresConversion)
            {
                // Convert the object type
                return(OptionConverter.ConvertTypeTo(createdObject, typeConstraint));
            }
            else
            {
                // The object is of the correct type
                return(createdObject);
            }
        }
        /// <summary>
        /// Configure the hierarchy by parsing a DOM tree of XML elements.
        /// </summary>
        /// <param name="element">The root element to parse.</param>
        /// <remarks>
        /// <para>
        /// Configure the hierarchy by parsing a DOM tree of XML elements.
        /// </para>
        /// </remarks>
        public void Configure(XmlElement element)
        {
            if (element == null || m_hierarchy == null)
            {
                return;
            }

            string rootelementname = element.LocalName;


            if (rootelementname != CONFIGURATION_TAG)
            {
                LogLog.Error(declaringType, "Xml element is - not a <" + CONFIGURATION_TAG + "> element.");
                return;
            }

            string quietModeAttribute = element.GetAttribute(QUIETMODE_ATTR);

            LogLog.Debug(declaringType, QUIETMODE_ATTR + " attribute [" + quietModeAttribute + "].");


            if (quietModeAttribute.Length > 0 && quietModeAttribute != "null")
            {
                LogLog.QuietMode = OptionConverter.ToBoolean(quietModeAttribute, false);
            }
            else
            {
                LogLog.Debug(declaringType, "Ignoring " + QUIETMODE_ATTR + " attribute.");
            }


            if (!LogLog.EmitInternalMessages)
            {
                // Look for a emitDebug attribute to enable internal debug
                string emitDebugAttribute = element.GetAttribute(EMIT_INTERNAL_DEBUG_ATTR);
                LogLog.Debug(declaringType, EMIT_INTERNAL_DEBUG_ATTR + " attribute [" + emitDebugAttribute + "].");

                if (emitDebugAttribute.Length > 0 && emitDebugAttribute != "null")
                {
                    LogLog.EmitInternalMessages = OptionConverter.ToBoolean(emitDebugAttribute, true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring " + EMIT_INTERNAL_DEBUG_ATTR + " attribute.");
                }
            }

            if (!LogLog.InternalDebugging)
            {
                // Look for a debug attribute to enable internal debug
                string debugAttribute = element.GetAttribute(INTERNAL_DEBUG_ATTR);
                LogLog.Debug(declaringType, INTERNAL_DEBUG_ATTR + " attribute [" + debugAttribute + "].");

                if (debugAttribute.Length > 0 && debugAttribute != "null")
                {
                    LogLog.InternalDebugging = OptionConverter.ToBoolean(debugAttribute, true);
                }
                else
                {
                    LogLog.Debug(declaringType, "Ignoring " + INTERNAL_DEBUG_ATTR + " attribute.");
                }
            }


            foreach (XmlNode node in element.ChildNodes)
            {
                if (node.NodeType != XmlNodeType.Element)
                {
                    continue;
                }

                XmlElement xe = (XmlElement)node;
                if (xe.LocalName == LOGGER_TAG)
                {
                    ParseLogger(xe);
                }
                else if (xe.LocalName == APPENDER_TAG)
                {
                    //....
                }
                else if (xe.LocalName == PLUGINS)
                {
                    ParsePlugins(xe);
                }
                else
                {
                    SetParameter(xe, m_hierarchy);
                }
            }

            //if (rootelementname !=
        }