示例#1
0
        /// <summary>
        /// Registers <see cref="TypeConverter"/> for the specified type.
        /// </summary>
        /// <remarks>
        /// This is a convinience method that accepts the names of both
        /// type to register converter for and the converter itself,
        /// resolves them using <see cref="ECode.TypeResolution.TypeResolverRegistry"/>, creates an
        /// instance of type converter and calls overloaded
        /// <see cref="RegisterConverter(Type, TypeConverter)"/> method.
        /// </remarks>
        /// <param name="typeName">Type name of the type to register the converter for (can be a type alias).</param>
        /// <param name="converterTypeName">Type name of the type converter to register (can be a type alias).</param>
        /// <exception cref="ArgumentNullException">If either of arguments is <c>null</c> or empty string.</exception>
        /// <exception cref="TypeLoadException">
        /// If either of arguments fails to resolve to a valid <see cref="Type"/>.
        /// </exception>
        /// <exception cref="ArgumentException">
        /// If type converter does not derive from <see cref="TypeConverter"/> or if it cannot be instantiated.
        /// </exception>
        public static void RegisterConverter(string typeName, string converterTypeName)
        {
            if (string.IsNullOrWhiteSpace(typeName))
            {
                throw new ArgumentNullException(nameof(typeName));
            }

            if (string.IsNullOrWhiteSpace(converterTypeName))
            {
                throw new ArgumentNullException(nameof(converterTypeName));
            }

            try
            {
                var type          = TypeResolutionUtil.ResolveType(typeName);
                var converterType = TypeResolutionUtil.ResolveType(converterTypeName);
                if (!typeof(TypeConverter).GetTypeInfo().IsAssignableFrom(converterType))
                {
                    throw new ArgumentException($"Type specified as a '{converterTypeName}' does not inherit from System.ComponentModel.TypeConverter");
                }

                RegisterConverter(type, (TypeConverter)ObjectUtil.InstantiateType(converterType));
            }
            catch (ReflectionException ex)
            { throw new ArgumentException("Failed to create an instance of the specified type converter.", ex); }
        }
示例#2
0
        public override void Validate()
        {
            if (this.ResolvedType != null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(this.Type))
            {
                this.ResolvedType = TypeResolutionUtil.ResolveType(this.Type);
            }

            if (this.ResolvedType != null)
            {
                if (this.ValueDefinition.ResolvedType != null)
                {
                    if (!this.ResolvedType.IsAssignableFrom(this.ValueDefinition.ResolvedType))
                    {
                        throw new InvalidCastException($"Type '{this.ValueDefinition.ResolvedType.FullName}' cannot convert to target type '{this.ResolvedType.FullName}'.");
                    }
                }
                else
                {
                    if (!this.ValueDefinition.CanConvertTo(this.ResolvedType))
                    {
                        throw new InvalidCastException($"Value '{this.ValueDefinition.GetValue()}' cannot convert to target type '{this.ResolvedType.FullName}'.");
                    }
                }
            }
            else
            {
                this.ResolvedType = this.ValueDefinition.ResolvedType;
            }
        }
示例#3
0
        /// <summary>
        /// Convert from a <see cref="System.String"/> value to a <see cref="System.Resources.ResourceManager"/> instance.
        /// </summary>
        /// <param name="context">
        /// A <see cref="System.ComponentModel.ITypeDescriptorContext"/> that provides a format context.
        /// </param>
        /// <param name="culture">
        /// The <see cref="System.Globalization.CultureInfo"/> to use as the current culture.
        /// </param>
        /// <param name="value">
        /// The value that is to be converted.
        /// </param>
        /// <returns>
        /// A <see cref="System.Resources.ResourceManager"/> if successful.
        /// </returns>
        /// <exception cref="ArgumentException">If the specified <paramref name="value"/> does not denote a valid resource</exception>
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            if (value is string)
            {
                try
                {
                    // convert incoming string into ResourceManager...
                    var resourceManagerDescription = ((string)value).Split(',');
                    if (resourceManagerDescription.Length != 2)
                    {
                        throw new ArgumentException("The string to specify a ResourceManager must be a comma delimited list of length two.  i.e. resourcename, assembly parial name.");
                    }

                    var resourceName = resourceManagerDescription[0].Trim();
                    if (string.IsNullOrWhiteSpace(resourceName))
                    {
                        throw new ArgumentException("Empty value set for the resource name in ResourceManager string.");
                    }

                    var assemblyName = resourceManagerDescription[1].Trim();
                    if (string.IsNullOrWhiteSpace(assemblyName))
                    {
                        throw new ArgumentException("Empty value set for the assembly name in ResourceManager string.");
                    }


                    if (assemblyName == APP_GLOBALRESOURCES_ASSEMBLYNAME)
                    {
                        try
                        {
                            var resourcesType = TypeResolutionUtil.ResolveType(resourceName);
                            // look both, NonPublic and Public properties (SPRNET-861)
                            var resourceManagerProperty = resourcesType.GetProperty("ResourceManager", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
                            return((ResourceManager)resourceManagerProperty.GetValue(resourcesType, null));
                        }
                        catch (TypeLoadException ex)
                        {
                            throw new ArgumentException($"Could not load resources '{resourceName}'", ex);
                        }
                    }

                    //Assembly ass = Assembly.LoadWithPartialName(assemblyName);
                    var ass = AssemblyLoadContext.Default.LoadFromAssemblyPath(assemblyName);
                    if (ass == null)
                    {
                        throw new ArgumentException($"Could not find assembly with name '{assemblyName}'.");
                    }

                    return(new ResourceManager(resourceName, ass));
                }
                catch (Exception ex)
                { throw new TypeConvertException(value, typeof(ResourceManager), ex); }
            }
            else
            {
                throw new TypeConvertException(value, typeof(ResourceManager));
            }
        }
示例#4
0
        public override void Validate()
        {
            if (this.ResolvedType != null)
            {
                return;
            }

            this.ResolvedType = TypeResolutionUtil.ResolveType(this.Type);
        }
示例#5
0
        public override void Validate()
        {
            if (this.ResolvedType != null)
            {
                return;
            }

            if (!string.IsNullOrEmpty(this.Type))
            {
                this.ResolvedType = TypeResolutionUtil.ResolveType(this.Type);
            }
        }
示例#6
0
        public static void RegisterAssemblies(string[] assemblyNames)
        {
            foreach (string assemblyName in assemblyNames)
            {
                var assembly = TypeResolutionUtil.ResolveAssembly(assemblyName);
                if (assembly == null)
                {
                    throw new AssemblyLoadException($"Cannot load assembly '{assemblyName}'.");
                }

                RegisterAssembly(assembly);
            }
        }
示例#7
0
        private static IAppender CreateAppender(AppenderInfo appenderInfo)
        {
            try
            {
                var appenderType = TypeResolutionUtil.ResolveType(appenderInfo.TypeClass);
                var appender     = (IAppender)Activator.CreateInstance(appenderType);
                appender.Initialize(appenderInfo.Options);

                return(appender);
            }
            catch (Exception ex)
            {
                LogLog.Error($"Logging config: cannot create appender '{appenderInfo.TypeClass}'.", ex);
                return(null);
            }
        }
示例#8
0
 /// <summary>
 /// Converts the given value to the type of this converter.
 /// </summary>
 /// <param name="context">
 /// A <see cref="System.ComponentModel.ITypeDescriptorContext"/>
 /// that provides a format context.
 /// </param>
 /// <param name="culture">
 /// The <see cref="System.Globalization.CultureInfo"/> to use
 /// as the current culture.
 /// </param>
 /// <param name="value">
 /// The value that is to be converted.
 /// </param>
 /// <returns>
 /// A <see cref="System.Type"/> that represents the converted value.
 /// </returns>
 public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
 {
     if (value is string)
     {
         try
         {
             return(TypeResolutionUtil.ResolveType(value as string));
         }
         catch (Exception ex)
         { throw new TypeConvertException(value, typeof(Type), ex); }
     }
     else
     {
         throw new TypeConvertException(value, typeof(Type));
     }
 }
示例#9
0
        public override void Validate()
        {
            if (this.ResolvedType != null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(this.ElementType))
            {
                this.resolvedElementType = TypeResolutionUtil.ResolveType(this.ElementType);
                foreach (var itemDefinition in this.Items)
                {
                    if (!itemDefinition.CanConvertTo(this.resolvedElementType))
                    {
                        if (itemDefinition.ResolvedType != null)
                        {
                            throw new InvalidCastException($"Type '{itemDefinition.ResolvedType.FullName}' cannot convert to target type '{this.resolvedElementType.FullName}'.");
                        }
                        else
                        {
                            throw new InvalidCastException($"Value '{itemDefinition.GetValue()}' cannot convert to target type '{this.resolvedElementType.FullName}'.");
                        }
                    }
                }
            }
            else
            {
                bool containsNullValue   = false;
                Type possibleElementType = null;  // string or other ref object type
                foreach (var itemDefinition in this.Items)
                {
                    if (itemDefinition.ResolvedType == null)
                    {
                        if (itemDefinition == ValueDefinition.NULL)
                        {
                            containsNullValue = true;
                            if (possibleElementType == null)
                            {
                                continue;
                            }
                        }

                        if (possibleElementType == null)
                        {
                            possibleElementType = typeof(string);
                        }
                        else
                        {
                            if (possibleElementType == typeof(string))
                            {
                                continue;
                            }

                            if (possibleElementType.IsAssignableFrom(typeof(string)))
                            {
                                // use current possible type.
                            }
                            else if (typeof(string).IsAssignableFrom(possibleElementType))
                            {
                                possibleElementType = typeof(string);
                            }
                            else
                            {
                                possibleElementType = typeof(object); // final type.
                                break;
                            }
                        }
                    }
                    else
                    {
                        if (possibleElementType == null)
                        {
                            possibleElementType = itemDefinition.ResolvedType;
                        }
                        else
                        {
                            if (possibleElementType.IsAssignableFrom(itemDefinition.ResolvedType))
                            {
                                // use current possible type.
                            }
                            else if (itemDefinition.ResolvedType.IsAssignableFrom(possibleElementType))
                            {
                                possibleElementType = itemDefinition.ResolvedType;
                            }
                            else
                            {
                                possibleElementType = typeof(object); // final type.
                                break;
                            }
                        }
                    }
                }

                if (possibleElementType == null)
                {
                    possibleElementType = typeof(object);
                }
                else if (containsNullValue == true)
                {
                    if (possibleElementType.IsPrimitive)
                    {
                        possibleElementType = typeof(Nullable <>).MakeGenericType(possibleElementType);
                    }
                    else if (possibleElementType.IsValueType)
                    {
                        if (possibleElementType.IsGenericType && possibleElementType.GetGenericTypeDefinition() == typeof(Nullable <>))
                        {
                            // use current possible type.
                        }
                        else
                        {
                            possibleElementType = typeof(Nullable <>).MakeGenericType(possibleElementType);
                        }
                    }
                }

                this.resolvedElementType = possibleElementType;
            }


            this.ResolvedType  = typeof(HashSet <>).MakeGenericType(this.resolvedElementType);
            this.addItemMethod = this.ResolvedType.GetMethod("Add", BindingFlags.Instance | BindingFlags.Public);
        }
示例#10
0
        public override void Validate()
        {
            if (this.ResolvedType != null)
            {
                return;
            }

            if (!string.IsNullOrWhiteSpace(this.Type))
            {
                this.ResolvedType = TypeResolutionUtil.ResolveType(this.Type);
                if (!string.IsNullOrWhiteSpace(this.FactoryMethod))
                {
                    var nameMatchedMethods = new List <MethodInfo>();
                    var methods            = this.ResolvedType.GetMethods(BindingFlags.Static | BindingFlags.Public);
                    foreach (var methodInfo in methods)
                    {
                        if (methodInfo.Name == this.FactoryMethod)
                        {
                            nameMatchedMethods.Add(methodInfo);
                        }
                    }

                    if (nameMatchedMethods.Count == 0)
                    {
                        throw new InvalidOperationException($"Cannot find public static named method '{this.FactoryMethod}' on type '{this.ResolvedType.FullName}'.");
                    }

                    foreach (var methodInfo in nameMatchedMethods)
                    {
                        var parms = methodInfo.GetParameters();
                        if (!ValidateParametersMatched(parms, this.FactoryArgs))
                        {
                            continue;
                        }

                        this.factoryMethod = methodInfo;
                        break;
                    }

                    if (this.factoryMethod == null)
                    {
                        throw new InvalidOperationException($"Doesnot contain matched named method '{this.FactoryMethod}' with arguments.");
                    }

                    this.ResolvedType = this.factoryMethod.ReturnType;
                }
                else
                {
                    var ctorMethods = this.ResolvedType.GetConstructors();
                    foreach (var ctorMethodInfo in ctorMethods)
                    {
                        var parms = ctorMethodInfo.GetParameters();
                        if (!ValidateParametersMatched(parms, this.ConstructorArgs))
                        {
                            continue;
                        }

                        this.ctorMethod = ctorMethodInfo;
                        break;
                    }

                    if (this.ctorMethod == null)
                    {
                        throw new InvalidOperationException("Doesnot contain matched constructor method with arguments.");
                    }
                }
            }
            else
            {
                var nameMatchedMethods = new List <MethodInfo>();
                var methods            = this.FactoryObject.ResolvedType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                foreach (var methodInfo in methods)
                {
                    if (methodInfo.Name == this.FactoryMethod)
                    {
                        nameMatchedMethods.Add(methodInfo);
                    }
                }

                if (nameMatchedMethods.Count == 0)
                {
                    throw new InvalidOperationException($"Cannot find public instance named method '{this.FactoryMethod}' on type '{this.FactoryObject.ResolvedType.FullName}'.");
                }

                foreach (var methodInfo in nameMatchedMethods)
                {
                    var parms = methodInfo.GetParameters();
                    if (!ValidateParametersMatched(parms, this.FactoryArgs))
                    {
                        continue;
                    }

                    this.factoryMethod = methodInfo;
                    break;
                }

                if (this.factoryMethod == null)
                {
                    throw new InvalidOperationException($"Doesnot contain matched named method '{this.FactoryMethod}' with arguments on type '{this.FactoryObject.ResolvedType.FullName}'.");
                }

                this.ResolvedType = this.factoryMethod.ReturnType;
            }

            foreach (var property in this.Properties)
            {
                var propInfo = this.ResolvedType.GetProperty(property.Name, BindingFlags.Instance | BindingFlags.Public);
                if (propInfo == null)
                {
                    throw new InvalidOperationException($"Doesnot contain instance property '{property.Name}' on type '{this.ResolvedType.FullName}'.");
                }
                else
                {
                    if (!propInfo.CanWrite)
                    {
                        throw new InvalidOperationException($"Property '{property.Name}' cannot be set on type '{this.ResolvedType.FullName}'.");
                    }

                    if (!property.CanConvertTo(propInfo.PropertyType))
                    {
                        throw new InvalidOperationException($"Cannot assign value '{property.GetValue()}' to property '{propInfo.Name}'.");
                    }

                    propertyMaps[property] = propInfo;
                }
            }

            foreach (var listener in this.Listeners)
            {
                var eventInfo = this.ResolvedType.GetEvent(listener.Event, BindingFlags.Instance | BindingFlags.Public);
                if (eventInfo == null)
                {
                    throw new InvalidOperationException($"Doesnot contain instance event '{listener.Event}' on type '{this.ResolvedType.FullName}'.");
                }
                else
                {
                    listener.ValidateListener(eventInfo.EventHandlerType);
                    listenerMaps[listener] = eventInfo;
                }
            }

            if (!string.IsNullOrWhiteSpace(this.InitMethod))
            {
                var nameMatchedMethods = new List <MethodInfo>();
                var methods            = this.ResolvedType.GetMethods(BindingFlags.Instance | BindingFlags.Public);
                foreach (var methodInfo in methods)
                {
                    if (methodInfo.Name == this.InitMethod)
                    {
                        nameMatchedMethods.Add(methodInfo);
                    }
                }

                if (nameMatchedMethods.Count == 0)
                {
                    throw new InvalidOperationException($"Cannot find public instance named method '{this.InitMethod}' on type '{this.ResolvedType.FullName}'.");
                }

                foreach (var methodInfo in nameMatchedMethods)
                {
                    var parms = methodInfo.GetParameters();
                    if (!ValidateParametersMatched(parms, this.InitializeArgs))
                    {
                        continue;
                    }

                    this.initMethod = methodInfo;
                    break;
                }

                if (this.initMethod == null)
                {
                    throw new InvalidOperationException($"Doesnot contain matched named method '{this.InitMethod}' with arguments on type '{this.ResolvedType.FullName}'.");
                }
            }
        }