diff --git a/src/Common.Logging.Portable/Logging/Configuration/ArgUtils.cs b/src/Common.Logging.Portable/Logging/Configuration/ArgUtils.cs index 6585d30..0a5cfb5 100644 --- a/src/Common.Logging.Portable/Logging/Configuration/ArgUtils.cs +++ b/src/Common.Logging.Portable/Logging/Configuration/ArgUtils.cs @@ -1,340 +1,343 @@ -#region License - -/* - * Copyright © 2002-2009 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#endregion - -using System; -using System.Collections.Generic; -using System.Diagnostics; -using System.Reflection; - -namespace Common.Logging.Configuration -{ - /// - /// Various utility methods for using during factory and logger instance configuration - /// - /// Erich Eichinger - public static class ArgUtils - { - /// - /// A delegate converting a string representation into the target type - /// - public delegate T ParseHandler(string strValue); - - private static readonly Dictionary s_parsers; - - /// - /// Initialize all members before any of this class' methods can be accessed (avoids beforeFieldInit) - /// - static ArgUtils() - { - s_parsers = new Dictionary(); - RegisterTypeParser(Convert.ToBoolean); - RegisterTypeParser(Convert.ToInt16); - RegisterTypeParser(Convert.ToInt32); - RegisterTypeParser(Convert.ToInt64); - RegisterTypeParser(Convert.ToSingle); - RegisterTypeParser(Convert.ToDouble); - RegisterTypeParser(Convert.ToDecimal); - } - - /// - /// Adds the parser to the list of known type parsers. - /// - /// - /// .NET intrinsic types are pre-registerd: short, int, long, float, double, decimal, bool - /// - public static void RegisterTypeParser(ParseHandler parser) - { - s_parsers[typeof(T)] = parser; - } - - /// - /// Retrieves the named value from the specified . - /// - /// may be null - /// the value's key - /// if is not null, the value returned by values[key]. null otherwise. - public static string GetValue(NameValueCollection values, string key) - { - return GetValue(values, key, null); - } - - /// - /// Retrieves the named value from the specified . - /// - /// may be null - /// the value's key - /// the default value, if not found - /// if is not null, the value returned by values[key]. null otherwise. - public static string GetValue(NameValueCollection values, string key, string defaultValue) - { - if (values != null) - { - foreach (string valueKey in values.Keys) - { - if (string.Compare(key, valueKey, StringComparison.OrdinalIgnoreCase) == 0) - { - return values[key]; - } - } - } - return defaultValue; - } - - /// - /// Returns the first nonnull, nonempty value among its arguments. - /// - /// - /// Returns null, if the initial list was null or empty. - /// - /// - public static string Coalesce(params string[] values) - { - return Coalesce(delegate(string v) { return !string.IsNullOrEmpty(v); }, values); - } - - /// - /// Returns the first nonnull, nonempty value among its arguments. - /// - /// - /// Also - /// - public static T Coalesce(Predicate predicate, params T[] values) where T : class - { - if (values == null || values.Length == 0) - { - return null; - } - - if (predicate == null) - { - predicate = delegate(T v) { return v != null; }; - } - - for (int i = 0; i < values.Length; i++) - { - T val = values[i]; - if (predicate(val)) - { - return val; - } - } - return null; - } - - /// - /// Tries parsing into an enum of the type of . - /// - /// the default value to return if parsing fails - /// the string value to parse - /// the successfully parsed value, otherwise. - public static T TryParseEnum(T defaultValue, string stringValue) where T : struct - { - Type enumType = typeof(T); -#if DOTNETCORE - if (!enumType.GetTypeInfo().IsEnum) -#elif WinRT - if (!enumType.IsEnum()) -#else - if (!enumType.IsEnum) -#endif - { - throw new ArgumentException(string.Format("Type '{0}' is not an enum type", typeof(T).FullName)); - } - - - try - { - // If a string is specified then try to parse and return it - if (!string.IsNullOrEmpty(stringValue)) - { - return (T)Enum.Parse(enumType, stringValue, true); - } - } - catch - { -#if PORTABLE - Debug.WriteLine(string.Format("WARN: failed converting value '{0}' to enum type '{1}'", stringValue, defaultValue.GetType().FullName)); -#else - Trace.WriteLine(string.Format("WARN: failed converting value '{0}' to enum type '{1}'", stringValue, defaultValue.GetType().FullName)); -#endif - } - return defaultValue; - } - - /// - /// Tries parsing into the specified return type. - /// - /// the default value to return if parsing fails - /// the string value to parse - /// the successfully parsed value, otherwise. - public static T TryParse(T defaultValue, string stringValue) - { - T result = defaultValue; - if (string.IsNullOrEmpty(stringValue)) - { - return defaultValue; - } - - object untypedParser; - if (!s_parsers.TryGetValue(typeof(T), out untypedParser) || !(untypedParser is ParseHandler)) - { - throw new ArgumentException(string.Format("There is no parser registered for type {0}", typeof(T).FullName)); - } - - var parser = (ParseHandler)untypedParser; - try - { - result = parser(stringValue); - } - catch - { -#if PORTABLE - Debug.WriteLine(string.Format("WARN: failed converting value '{0}' to type '{1}' - returning default '{2}'", stringValue, typeof(T).FullName, result)); -#else - Trace.WriteLine(string.Format("WARN: failed converting value '{0}' to type '{1}' - returning default '{2}'", stringValue, typeof(T).FullName, result)); -#endif - } - return result; - } - - /// - /// Throws a if is null. - /// - public static T AssertNotNull(string paramName, T val) where T : class - { - if (ReferenceEquals(val, null)) - { - throw new ArgumentNullException(paramName); - } - return val; - } - - /// - /// Throws a if is null. - /// - public static T AssertNotNull(string paramName, T val, string messageFormat, params object[] args) where T : class - { - if (ReferenceEquals(val, null)) - { - throw new ArgumentNullException(paramName, string.Format(messageFormat, args)); - } - return val; - } - - /// - /// Throws a if an object of type is not - /// assignable to type . - /// - public static Type AssertIsAssignable(string paramName, Type valType) - { - return AssertIsAssignable(paramName - , valType - , string.Format("Type '{0}' of parameter '{1}' is not assignable to target type '{2}'" - , valType == null ? "" : valType.AssemblyQualifiedName - , paramName - , typeof(T).AssemblyQualifiedName) - ); - } - - /// - /// Throws a if an object of type is not - /// assignable to type . - /// - public static Type AssertIsAssignable(string paramName, Type valType, string messageFormat, params object[] args) - { - if (valType == null) - { - throw new ArgumentNullException("valType"); - } - - if (!typeof(T).IsAssignableFrom(valType)) - { -#if PORTABLE - throw new ArgumentOutOfRangeException(paramName, string.Format(messageFormat, args)); -#else - throw new ArgumentOutOfRangeException(paramName, valType, string.Format(messageFormat, args)); -#endif - } - return valType; - } - - /// - /// An anonymous action delegate with no arguments and no return value. - /// - /// - public delegate void Action(); - - /// - /// Ensures any exception thrown by the given is wrapped with an - /// . - /// - /// - /// If already throws a ConfigurationException, it will not be wrapped. - /// - /// the action to execute - /// the message to be set on the thrown - /// args to be passed to to format the message - public static void Guard(Action action, string messageFormat, params object[] args) - { - Guard(delegate - { - action(); - return 0; - } - , messageFormat, args); - } - - /// - /// An anonymous action delegate with no arguments and no return value. - /// - /// - public delegate T Function(); - - /// - /// Ensures any exception thrown by the given is wrapped with an - /// . - /// - /// - /// If already throws a ConfigurationException, it will not be wrapped. - /// - /// the action to execute - /// the message to be set on the thrown - /// args to be passed to to format the message - public static T Guard(Function function, string messageFormat, params object[] args) - { - try - { - return function(); - } - catch (ConfigurationException) - { - throw; - } - catch (TargetInvocationException tex) - { - throw new ConfigurationException(string.Format(messageFormat, args), tex.InnerException); - } - catch (Exception ex) - { - throw new ConfigurationException(string.Format(messageFormat, args), ex); - } - } - } +#region License + +/* + * Copyright © 2002-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#endregion + +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Reflection; + +namespace Common.Logging.Configuration +{ + /// + /// Various utility methods for using during factory and logger instance configuration + /// + /// Erich Eichinger + public static class ArgUtils + { + /// + /// A delegate converting a string representation into the target type + /// + public delegate T ParseHandler(string strValue); + + private static readonly Dictionary s_parsers; + + /// + /// Initialize all members before any of this class' methods can be accessed (avoids beforeFieldInit) + /// + static ArgUtils() + { + s_parsers = new Dictionary(); + RegisterTypeParser(Convert.ToBoolean); + RegisterTypeParser(Convert.ToInt16); + RegisterTypeParser(Convert.ToInt32); + RegisterTypeParser(Convert.ToInt64); + RegisterTypeParser(Convert.ToSingle); + RegisterTypeParser(Convert.ToDouble); + RegisterTypeParser(Convert.ToDecimal); + } + + /// + /// Adds the parser to the list of known type parsers. + /// + /// + /// .NET intrinsic types are pre-registerd: short, int, long, float, double, decimal, bool + /// + public static void RegisterTypeParser(ParseHandler parser) + { + s_parsers[typeof(T)] = parser; + } + + /// + /// Retrieves the named value from the specified . + /// + /// may be null + /// the value's key + /// if is not null, the value returned by values[key]. null otherwise. + public static string GetValue(NameValueCollection values, string key) + { + return GetValue(values, key, null); + } + + /// + /// Retrieves the named value from the specified . + /// + /// may be null + /// the value's key + /// the default value, if not found + /// if is not null, the value returned by values[key]. null otherwise. + public static string GetValue(NameValueCollection values, string key, string defaultValue) + { + if (values != null) + { + foreach (string valueKey in values.Keys) + { + if (string.Compare(key, valueKey, StringComparison.OrdinalIgnoreCase) == 0) + { + return values[key]; + } + } + } + return defaultValue; + } + + /// + /// Returns the first nonnull, nonempty value among its arguments. + /// + /// + /// Returns null, if the initial list was null or empty. + /// + /// + public static string Coalesce(params string[] values) + { + return Coalesce(delegate (string v) { return !string.IsNullOrEmpty(v); }, values); + } + + /// + /// Returns the first nonnull, nonempty value among its arguments. + /// + /// + /// Also + /// + public static T Coalesce(Predicate predicate, params T[] values) where T : class + { + if (values == null || values.Length == 0) + { + return null; + } + + if (predicate == null) + { + predicate = delegate (T v) { return v != null; }; + } + + for (int i = 0; i < values.Length; i++) + { + T val = values[i]; + if (predicate(val)) + { + return val; + } + } + return null; + } + + /// + /// Tries parsing into an enum of the type of . + /// + /// the default value to return if parsing fails + /// the string value to parse + /// the successfully parsed value, otherwise. + public static T TryParseEnum(T defaultValue, string stringValue) where T : struct + { + Type enumType = typeof(T); +#if DOTNETCORE + if (!enumType.GetTypeInfo().IsEnum) +#elif WinRT + if (!enumType.IsEnum()) +#else + if (!enumType.IsEnum) +#endif + { + throw new ArgumentException(string.Format("Type '{0}' is not an enum type", typeof(T).FullName)); + } + + try + { + // If a string is specified then try to parse and return it + if (!string.IsNullOrEmpty(stringValue)) + { + return (T)Enum.Parse(enumType, stringValue, true); + } + } + catch + { +#if PORTABLE + Debug.WriteLine(string.Format("WARN: failed converting value '{0}' to enum type '{1}'", stringValue, defaultValue.GetType().FullName)); +#else + Trace.WriteLine(string.Format("WARN: failed converting value '{0}' to enum type '{1}'", stringValue, defaultValue.GetType().FullName)); +#endif + } + return defaultValue; + } + + /// + /// Tries parsing into the specified return type. + /// + /// the default value to return if parsing fails + /// the string value to parse + /// the successfully parsed value, otherwise. + public static T TryParse(T defaultValue, string stringValue) + { + T result = defaultValue; + if (string.IsNullOrEmpty(stringValue)) + { + return defaultValue; + } + + object untypedParser; + if (!s_parsers.TryGetValue(typeof(T), out untypedParser) || !(untypedParser is ParseHandler)) + { + throw new ArgumentException(string.Format("There is no parser registered for type {0}", typeof(T).FullName)); + } + + var parser = (ParseHandler)untypedParser; + try + { + result = parser(stringValue); + } + catch + { +#if PORTABLE + Debug.WriteLine(string.Format("WARN: failed converting value '{0}' to type '{1}' - returning default '{2}'", stringValue, typeof(T).FullName, result)); +#else + Trace.WriteLine(string.Format("WARN: failed converting value '{0}' to type '{1}' - returning default '{2}'", stringValue, typeof(T).FullName, result)); +#endif + } + return result; + } + + /// + /// Throws a if is null. + /// + public static T AssertNotNull(string paramName, T val) where T : class + { + if (ReferenceEquals(val, null)) + { + throw new ArgumentNullException(paramName); + } + return val; + } + + /// + /// Throws a if is null. + /// + public static T AssertNotNull(string paramName, T val, string messageFormat, params object[] args) where T : class + { + if (ReferenceEquals(val, null)) + { + throw new ArgumentNullException(paramName, string.Format(messageFormat, args)); + } + return val; + } + + /// + /// Throws a if an object of type is not + /// assignable to type . + /// + public static Type AssertIsAssignable(string paramName, Type valType) + { + return AssertIsAssignable(paramName + , valType + , string.Format("Type '{0}' of parameter '{1}' is not assignable to target type '{2}'" + , valType == null ? "" : valType.AssemblyQualifiedName + , paramName + , typeof(T).AssemblyQualifiedName) + ); + } + + /// + /// Throws a if an object of type is not + /// assignable to type . + /// + public static Type AssertIsAssignable(string paramName, Type valType, string messageFormat, params object[] args) + { + if (valType == null) + { + throw new ArgumentNullException("valType"); + } + +#if DOTNETCORE + if (!typeof(T).GetTypeInfo().IsAssignableFrom(valType.GetTypeInfo())) +#else + if (!typeof(T).IsAssignableFrom(valType)) +#endif + { +#if PORTABLE + throw new ArgumentOutOfRangeException(paramName, string.Format(messageFormat, args)); +#else + throw new ArgumentOutOfRangeException(paramName, valType, string.Format(messageFormat, args)); +#endif + } + return valType; + } + + /// + /// An anonymous action delegate with no arguments and no return value. + /// + /// + public delegate void Action(); + + /// + /// Ensures any exception thrown by the given is wrapped with an + /// . + /// + /// + /// If already throws a ConfigurationException, it will not be wrapped. + /// + /// the action to execute + /// the message to be set on the thrown + /// args to be passed to to format the message + public static void Guard(Action action, string messageFormat, params object[] args) + { + Guard(delegate + { + action(); + return 0; + } + , messageFormat, args); + } + + /// + /// An anonymous action delegate with no arguments and no return value. + /// + /// + public delegate T Function(); + + /// + /// Ensures any exception thrown by the given is wrapped with an + /// . + /// + /// + /// If already throws a ConfigurationException, it will not be wrapped. + /// + /// the action to execute + /// the message to be set on the thrown + /// args to be passed to to format the message + public static T Guard(Function function, string messageFormat, params object[] args) + { + try + { + return function(); + } + catch (ConfigurationException) + { + throw; + } + catch (TargetInvocationException tex) + { + throw new ConfigurationException(string.Format(messageFormat, args), tex.InnerException); + } + catch (Exception ex) + { + throw new ConfigurationException(string.Format(messageFormat, args), ex); + } + } + } } \ No newline at end of file diff --git a/src/Common.Logging.Portable/Logging/Configuration/DefaultConfigurationReader.cs b/src/Common.Logging.Portable/Logging/Configuration/DefaultConfigurationReader.cs index 8a00da0..feca674 100644 --- a/src/Common.Logging.Portable/Logging/Configuration/DefaultConfigurationReader.cs +++ b/src/Common.Logging.Portable/Logging/Configuration/DefaultConfigurationReader.cs @@ -1,76 +1,87 @@ -#region License - -/* - * Copyright © 2002-2009 the original author or authors. - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ - -#endregion - -using System; -namespace Common.Logging.Configuration -{ - /// - /// Implementation of that uses the standard .NET - /// configuration APIs, ConfigurationSettings in 1.x and ConfigurationManager in 2.0 - /// - /// Mark Pollack - public class DefaultConfigurationReader : IConfigurationReader - { - /// - /// Parses the configuration section and returns the resulting object. - /// Using the System.Configuration.ConfigurationManager - /// - /// Name of the configuration section. - /// - /// Object created by a corresponding IConfigurationSectionHandler" - /// - /// - ///

- /// Primary purpose of this method is to allow us to parse and - /// load configuration sections using the same API regardless - /// of the .NET framework version. - ///

- ///
- public object GetSection(string sectionName) - { -#if DOTNETCORE // No System.Configuration in DotNetCore, replace with something DotNetCore-specific? - return null; -#else -#if PORTABLE - // We should instead look for something implementing - // IConfigurationReader in (platform specific) Common.Logging dll and use that - const string configManager40 = "System.Configuration.ConfigurationManager, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; - var configurationManager = Type.GetType(configManager40); - if(configurationManager == null) - { - // Silverlight, and maybe if System.Configuration is not loaded? - return null; - } -#if !WinRT - var getSection = configurationManager.GetMethod("GetSection", new[] { typeof(string) }); -#else - var getSection = configurationManager.GetMethod("GetSection"); -#endif - if (getSection == null) - throw new PlatformNotSupportedException("Could not find System.Configuration.ConfigurationManager.GetSection method"); - - return getSection.Invoke(null, new[] {sectionName}); -#else - return System.Configuration.ConfigurationManager.GetSection(sectionName); -#endif -#endif - } - } +#region License + +/* + * Copyright © 2002-2009 the original author or authors. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#endregion + +using System; +namespace Common.Logging.Configuration +{ + /// + /// Implementation of that uses the standard .NET + /// configuration APIs, ConfigurationSettings in 1.x and ConfigurationManager in 2.0 + /// + /// Mark Pollack + public class DefaultConfigurationReader : IConfigurationReader + { + /// + /// Parses the configuration section and returns the resulting object. + /// Using the System.Configuration.ConfigurationManager + /// + /// Name of the configuration section. + /// + /// Object created by a corresponding IConfigurationSectionHandler" + /// + /// + ///

+ /// Primary purpose of this method is to allow us to parse and + /// load configuration sections using the same API regardless + /// of the .NET framework version. + ///

+ ///
+ public object GetSection(string sectionName) + { +#if DOTNETCORE + const string configManager40 = "System.Configuration.ConfigurationManager, System.Configuration.ConfigurationManager"; + var configurationManager = Type.GetType(configManager40); + if (configurationManager == null) + { + return null; + } + + var getSection = configurationManager.GetMethod("GetSection"); + if (getSection == null) + throw new PlatformNotSupportedException("Could not find System.Configuration.ConfigurationManager.GetSection method"); + + return getSection.Invoke(null, new[] { sectionName }); +#else +#if PORTABLE + // We should instead look for something implementing + // IConfigurationReader in (platform specific) Common.Logging dll and use that + const string configManager40 = "System.Configuration.ConfigurationManager, System.Configuration, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"; + var configurationManager = Type.GetType(configManager40); + if(configurationManager == null) + { + // Silverlight, and maybe if System.Configuration is not loaded? + return null; + } +#if !WinRT + var getSection = configurationManager.GetMethod("GetSection", new[] { typeof(string) }); +#else + var getSection = configurationManager.GetMethod("GetSection"); +#endif + if (getSection == null) + throw new PlatformNotSupportedException("Could not find System.Configuration.ConfigurationManager.GetSection method"); + + return getSection.Invoke(null, new[] {sectionName}); +#else + return System.Configuration.ConfigurationManager.GetSection(sectionName); +#endif +#endif + } + } } \ No newline at end of file diff --git a/src/Common.Logging.Portable/Logging/Configuration/NameValueCollectionHelper.cs b/src/Common.Logging.Portable/Logging/Configuration/NameValueCollectionHelper.cs index cab0c46..25333b9 100644 --- a/src/Common.Logging.Portable/Logging/Configuration/NameValueCollectionHelper.cs +++ b/src/Common.Logging.Portable/Logging/Configuration/NameValueCollectionHelper.cs @@ -1,29 +1,29 @@ -using System; -using System.Collections.Generic; -using System.Text; - -namespace Common.Logging.Configuration -{ - -#if !PORTABLE || NET20 - /// - /// Helper class for working with NameValueCollection - /// - public static class NameValueCollectionHelper - { - /// - /// Convert a into the corresponding - /// common logging equivalent - /// - /// The properties. - /// - public static NameValueCollection ToCommonLoggingCollection(System.Collections.Specialized.NameValueCollection properties) - { - var result = new NameValueCollection(); - foreach (var key in properties.AllKeys) - result.Add(key, properties.Get(key)); - return result; - } - } -#endif -} +using System; +using System.Collections.Generic; +using System.Text; + +namespace Common.Logging.Configuration +{ + +#if !PORTABLE || NET20 || DOTNETCORE + /// + /// Helper class for working with NameValueCollection + /// + public static class NameValueCollectionHelper + { + /// + /// Convert a into the corresponding + /// common logging equivalent + /// + /// The properties. + /// + public static NameValueCollection ToCommonLoggingCollection(System.Collections.Specialized.NameValueCollection properties) + { + var result = new NameValueCollection(); + foreach (var key in properties.AllKeys) + result.Add(key, properties.Get(key)); + return result; + } + } +#endif +}