Example #1
0
        internal IEnumerable <KeyValuePair <Row, T> > ToObjectsWithEcho_Core <T>(ConstructorMetadata constructor)
        {
            if (constructor == null)
            {
                throw new ArgumentNullException(nameof(constructor), $"{nameof(constructor)} is null.");
            }

            var constructorParameters = constructor.ParameterNames;

            for (var i = 0; i < constructorParameters.Length; i++)
            {
                if (!ColumnNames.Any(p => p.Equals(constructorParameters[i], StringComparison.OrdinalIgnoreCase)))
                {
                    throw new MappingException($"Cannot find a column that matches the parameter {constructorParameters[i]}");
                }
            }

            foreach (var item in Rows)
            {
                var parameters = new object?[constructorParameters.Length];
                for (var i = 0; i < constructorParameters.Length; i++)
                {
                    parameters[i] = item[constructorParameters[i]];
                }
                var result = constructor.ConstructorInfo.Invoke(parameters);
                yield return(new KeyValuePair <Row, T>(item, (T)result));
            }
        }
Example #2
0
        public TypeMetadata(Type type)
        {
            TypeEnum = TypeEnumFactory.CreateTypeMetadataClass(type);

            FullTypeName     = type.FullName;
            TypeName         = type.Name;
            NamespaceName    = type.Namespace;
            GenericArguments = !type.IsGenericTypeDefinition && !type.IsConstructedGenericType ? null : EmitGenericArguments(type.GetGenericArguments());
            Modifiers        = EmitModifiers(type);
            Attributes       = AttributeMetadata.EmitAttributes(type);

            DeclaringType = EmitDeclaringType(type.DeclaringType);

            BaseType = EmitExtends(type.BaseType);
            ImplementedInterfaces = EmitImplements(type.GetInterfaces());

            BindingFlags flagsToGetAll = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static | BindingFlags.DeclaredOnly;

            Fields       = FieldMetadata.EmitFields(type.GetFields(flagsToGetAll));
            Methods      = MethodMetadata.EmitMethods(type.GetMethods(flagsToGetAll));
            Properties   = PropertyMetadata.EmitProperties(type.GetProperties(flagsToGetAll));
            Indexers     = IndexerMetadata.EmitIndexers(type.GetProperties(flagsToGetAll));
            Events       = EventMetadata.EmitEvents(type.GetEvents(flagsToGetAll));
            Constructors = ConstructorMetadata.EmitConstructors(type.GetConstructors(flagsToGetAll));
            NestedTypes  = EmitNestedTypes(type.GetNestedTypes(flagsToGetAll));
        }
Example #3
0
        public StreamingObjectConstructor(DbDataReader source, IReadOnlyList <Type> constructorSignature)
        {
            m_Source   = source;
            m_Ordinals = new Dictionary <string, int>(source.FieldCount, StringComparer.OrdinalIgnoreCase);
            for (var i = 0; i < source.FieldCount; i++)
            {
                m_Ordinals.Add(source.GetName(i), i);
            }

            constructorSignature = constructorSignature ?? s_DefaultConstructor;

            var desiredType = typeof(T);

            m_Constructor = MetadataCache.GetMetadata(desiredType).Constructors.Find(constructorSignature);

            if (m_Constructor == null)
            {
                var types = string.Join(", ", constructorSignature.Select(t => t.Name));
                throw new MappingException($"Cannot find a constructor on {desiredType.Name} with the types [{types}]");
            }

            var constructorParameters = m_Constructor.ParameterNames;

            for (var i = 0; i < constructorParameters.Length; i++)
            {
                if (!m_Ordinals.ContainsKey(constructorParameters[i]))
                {
                    throw new MappingException($"Cannot find a column that matches the parameter {constructorParameters[i]}");
                }
            }

            m_PopulateComplexObject = constructorSignature.Count == 0;
            m_Dictionary            = new StreamingObjectConstructorDictionary(this);
        }
Example #4
0
 private static ConstructorMetadata InstantiateConstructorWithType(
     ConstructorMetadata constructorTemplate,
     TypeMetadata typeMetadata)
 {
     return(new ConstructorMetadata(
                constructorTemplate.ProtectionLevel,
                constructorTemplate.IsStatic,
                constructorTemplate.CustomAttributes));
 }
Example #5
0
    public StreamingObjectConstructor(DbDataReader source, ConstructorMetadata?constructor, IReadOnlyList <ColumnMetadata> nonNullableColumns, MaterializerTypeConverter converter)
    {
        m_Converter       = converter ?? new();
        m_Source          = source;
        m_Ordinals        = new Dictionary <string, int>(source.FieldCount, StringComparer.OrdinalIgnoreCase);
        m_NullableColumns = new Dictionary <int, bool>(source.FieldCount);
        for (var i = 0; i < source.FieldCount; i++)
        {
            var columnName = source.GetName(i);
            m_Ordinals.Add(columnName, i);
            m_NullableColumns.Add(i, !nonNullableColumns.Any(c => c.SqlName == columnName));             //assume nullable unless proven otherwise
        }

        if (constructor == null)
        {
            constructor = MetadataCache.GetMetadata(typeof(T)).Constructors.Find(s_DefaultConstructor);
        }
        if (constructor == null)
        {
            throw new MappingException($"Cannot find a default constructor for {typeof(T).Name}");
        }

        var desiredType = typeof(T);

        m_Constructor = constructor;

        var constructorParameters = m_Constructor.ParameterNames;

        for (var i = 0; i < constructorParameters.Length; i++)
        {
            if (!m_Ordinals.ContainsKey(constructorParameters[i]))
            {
                throw new MappingException($"Cannot find a column that matches the parameter {constructorParameters[i]}");
            }
        }

        m_Dictionary = new StreamingObjectConstructorDictionary(this);

        if (constructor.Signature.Length == 0)
        {
            m_MappedProperties = new List <OrdinalMappedProperty <T> >();

            foreach (var mapper in s_AllMappedProperties)
            {
                if (m_Dictionary.ContainsKey(mapper.MappedColumnName))
                {
                    m_MappedProperties.Add(new OrdinalMappedProperty <T>(mapper, m_Ordinals[mapper.MappedColumnName]));
                }
            }
        }
    }
        public StreamingObjectConstructor(DbDataReader source, IReadOnlyList <Type> constructorSignature, IReadOnlyList <ColumnMetadata> nonNullableColumns)
        {
            m_Source          = source;
            m_Ordinals        = new Dictionary <string, int>(source.FieldCount, StringComparer.OrdinalIgnoreCase);
            m_NullableColumns = new Dictionary <int, bool>(source.FieldCount);
            for (var i = 0; i < source.FieldCount; i++)
            {
                var columnName = source.GetName(i);
                m_Ordinals.Add(columnName, i);
                m_NullableColumns.Add(i, !nonNullableColumns.Any(c => c.SqlName == columnName)); //assume nullable unless proven otherwise
            }
            constructorSignature = constructorSignature ?? s_DefaultConstructor;

            var desiredType = typeof(T);

            m_Constructor = MetadataCache.GetMetadata(desiredType).Constructors.Find(constructorSignature);

            if (m_Constructor == null)
            {
                var types = string.Join(", ", constructorSignature.Select(t => t.Name));
                throw new MappingException($"Cannot find a constructor on {desiredType.Name} with the types [{types}]");
            }

            var constructorParameters = m_Constructor.ParameterNames;

            for (var i = 0; i < constructorParameters.Length; i++)
            {
                if (!m_Ordinals.ContainsKey(constructorParameters[i]))
                {
                    throw new MappingException($"Cannot find a column that matches the parameter {constructorParameters[i]}");
                }
            }

            m_PopulateComplexObject = constructorSignature.Count == 0;
            m_Dictionary            = new StreamingObjectConstructorDictionary(this);

            if (m_PopulateComplexObject)
            {
                m_MappedProperties = new List <OrdinalMappedProperty <T> >();

                foreach (var mapper in s_AllMappedProperties)
                {
                    if (m_Dictionary.ContainsKey(mapper.MappedColumnName))
                    {
                        m_MappedProperties.Add(new OrdinalMappedProperty <T>(mapper, m_Ordinals[mapper.MappedColumnName]));
                    }
                }
            }
        }
Example #7
0
        /// <summary>
        /// Get the metadata for the constructors of a type.
        /// </summary>
        /// <param name="type">the type to get the constructors of.</param>
        /// <returns>a list of the constructors of the given type.</returns>
        private static IImmutableList <ConstructorMetadata> GetConstructorMetadata(Type type)
        {
            var constructors = new List <ConstructorMetadata>();

            foreach (ConstructorInfo ctor in type.GetConstructors())
            {
                var ctorMetadata = new ConstructorMetadata(
                    GetProtectionLevel(ctor.Attributes),
                    ctor.IsStatic)
                {
                    CustomAttributes = GetCustomAttributes(type.GetCustomAttributesData())
                };
            }

            return(constructors.ToImmutableArray());
        }
Example #8
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="kernel"></param>
        /// <param name="binding"></param>
        /// <param name="constructor"></param>
        /// <returns></returns>
        private static object[] ResolveParameters(IKernel kernel, IBinding binding, ConstructorMetadata constructor)
        {
            var parameters = constructor.Parameters;

            if (parameters.Length == 0)
            {
                return(null);
            }

            var arguments = new object[parameters.Length];

            for (var i = 0; i < arguments.Length; i++)
            {
                var parameter = parameters[i];
                var pi        = parameter.Parameter;

                // Constructor argument
                var argument = binding.ConstructorArguments.GetParameter(pi.Name);
                if (argument != null)
                {
                    arguments[i] = argument.Resolve(kernel);
                    continue;
                }

                // Multiple
                if (parameter.ElementType != null)
                {
                    arguments[i] = ResolverHelper.ConvertArray(parameter.ElementType, kernel.ResolveAll(parameter.ElementType, constructor.Constraints[i]));
                    continue;
                }

                // Resolve
                bool resolve;
                var  obj = kernel.TryResolve(pi.ParameterType, constructor.Constraints[i], out resolve);
                if (resolve)
                {
                    arguments[i] = obj;
                }
            }

            return(arguments);
        }
Example #9
0
        static internal T ConstructObject <T>(IReadOnlyDictionary <string, object> source, ConstructorMetadata constructor, bool?populateComplexObject = null)
        {
            if (!populateComplexObject.HasValue)
            {
                populateComplexObject = constructor.ParameterNames.Length == 0;
            }

            var constructorParameters = constructor.ParameterNames;
            var parameters            = new object[constructorParameters.Length];

            for (var i = 0; i < constructorParameters.Length; i++)
            {
                parameters[i] = source[constructorParameters[i]];
            }
            var result = (T)constructor.ConstructorInfo.Invoke(parameters);

            if (populateComplexObject.Value)
            {
                PopulateComplexObject(source, result, null);
            }

            //Change tracking objects should be materialized as unchanged.
            (result as IChangeTracking)?.AcceptChanges();

            return(result);
        }
Example #10
0
 public ConstructorViewModel(ConstructorMetadata metadata) : base(metadata)
 {
     mName     = metadata.Name + GetParameters(metadata.Parameters);
     mTypeName = metadata.ReturnType;
 }
Example #11
0
        public TypeMetadata(Type inputType)
        {
            Namespace             = inputType.Namespace;
            Name                  = inputType.ToString();
            AssemblyQualifiedName = inputType.AssemblyQualifiedName;

            // Get the properties of the type
            var properties = inputType.GetProperties();

            // Sort the properties by name to retain ordering when loading cmdlets
            Array.Sort(properties, delegate(PropertyInfo p1, PropertyInfo p2)
            {
                return(p1.PropertyType.ToString().CompareTo(p2.PropertyType.ToString()));
            });

            var methods = inputType.GetMethods()
                          .Where(m => !m.IsSpecialName)
                          .ToArray();

            var constructors = inputType.GetConstructors();

            ModuleMetadata moduleMetadata = CmdletLoader.ModuleMetadata;

            // If the type is an array
            if (inputType.HasElementType)
            {
                // Get the element type of the array
                ElementType = inputType.GetElementType().ToString();

                // If the element type is not in the type dictionary,
                // add it and check its properties
                if (!moduleMetadata.TypeDictionary.ContainsKey(ElementType))
                {
                    moduleMetadata.TypeDictionary.Add(ElementType, new TypeMetadata()
                    {
                        Name = ElementType
                    });
                    var typeMetadata = new TypeMetadata(inputType.GetElementType());
                    moduleMetadata.TypeDictionary[ElementType] = typeMetadata;
                }

                return;
            }

            // If the type is a generic
            if (inputType.IsGenericType)
            {
                // Get the argument types
                var genericTypeArguments = inputType.GetGenericArguments();

                // For each of the arguments, add them to the list of arguments
                // and check if the type is in the type dictionary
                foreach (var arg in genericTypeArguments)
                {
                    _genericTypeArguments.Add(arg.ToString());

                    if (!moduleMetadata.TypeDictionary.ContainsKey(arg.ToString()))
                    {
                        moduleMetadata.TypeDictionary.Add(arg.ToString(), new TypeMetadata()
                        {
                            Name = arg.ToString()
                        });
                        var typeMetadata = new TypeMetadata(arg);
                        moduleMetadata.TypeDictionary[arg.ToString()] = typeMetadata;
                    }
                }

                return;
            }

            // If the type is in the System namespace, don't look at any of its properties
            if (Namespace.StartsWith("System"))
            {
                return;
            }

            // For each property, check to see if we have already processed its type before,
            // and if not, we will add it to the global dictionary and process the TypeMetadata.
            foreach (var property in properties)
            {
                // Get the property type
                var propertyType = property.PropertyType;

                // If the type has not been seen before, we will map it to a null value in the
                // global dictionary so we don't repeat the computation, and then create the
                // TypeMetadata object associated with it, and finally set it as the value
                // associated with the type name key in the dictionary.
                if (!moduleMetadata.TypeDictionary.ContainsKey(propertyType.ToString()))
                {
                    moduleMetadata.TypeDictionary.Add(propertyType.ToString(), new TypeMetadata()
                    {
                        Name = propertyType.ToString()
                    });
                    var typeMetadata = new TypeMetadata(propertyType);
                    moduleMetadata.TypeDictionary[propertyType.ToString()] = typeMetadata;
                }

                // Add the property to the dictionary
                if (!_properties.ContainsKey(property.Name.ToString()))
                {
                    _properties.Add(property.Name, propertyType.ToString());
                }
            }

            foreach (var method in methods)
            {
                var            methodParameterMetadata = new List <MethodParameterMetadata>();
                MethodMetadata methodMetadata          = null;
                if (moduleMetadata.TypeDictionary.ContainsKey(method.ReturnType.ToString()))
                {
                    var typeMetadata = moduleMetadata.TypeDictionary[method.ReturnType.ToString()];
                    methodMetadata = new MethodMetadata()
                    {
                        Name       = method.Name,
                        ReturnType = typeMetadata.Name
                    };
                }
                else
                {
                    moduleMetadata.TypeDictionary.Add(method.ReturnType.ToString(), new TypeMetadata()
                    {
                        Name = method.ReturnType.ToString()
                    });
                    var typeMetadata = new TypeMetadata(method.ReturnType);
                    moduleMetadata.TypeDictionary[method.ReturnType.ToString()] = typeMetadata;
                    methodMetadata = new MethodMetadata()
                    {
                        Name       = method.Name,
                        ReturnType = typeMetadata.Name
                    };
                }


                foreach (var parameter in method.GetParameters())
                {
                    var parameterMetadata = new MethodParameterMetadata()
                    {
                        Name = parameter.Name,
                        Type = parameter.GetType().ToString()
                    };

                    methodParameterMetadata.Add(parameterMetadata);
                }

                methodMetadata.Parameters = methodParameterMetadata;
                _methods.Add(methodMetadata);
            }

            foreach (var constructor in constructors)
            {
                var constructorParameterMetadata = new List <MethodParameterMetadata>();
                var constructorMetadata          = new ConstructorMetadata();

                foreach (var parameter in constructor.GetParameters())
                {
                    var parameterMetadata = new MethodParameterMetadata()
                    {
                        Name = parameter.Name,
                        Type = parameter.GetType().ToString()
                    };

                    constructorParameterMetadata.Add(parameterMetadata);
                }

                constructorMetadata.Parameters = constructorParameterMetadata;
                _constructors.Add(constructorMetadata);
            }
        }