예제 #1
0
        private static void DynamicProperty1()
        {
            var props = new DynamicProperty[]
            {
                new DynamicProperty("Name", typeof(string)),
                new DynamicProperty("Age", typeof(int))
            };

            Type type = DynamicClassFactory.CreateType(props);

            var dynamicClass = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass.SetDynamicPropertyValue("Name", "Abhik");
            dynamicClass.SetDynamicPropertyValue("Age", 40);

            var dynamicClass1 = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass1.SetDynamicPropertyValue("Name", "Pamli");
            dynamicClass1.SetDynamicPropertyValue("Age", 35);

            List <DynamicClass> customer = new List <DynamicClass>()
            {
                dynamicClass,
                dynamicClass1
            };

            var cust = customer.AsQueryable().Where("GetDynamicPropertyValue(Age)>20");

            foreach (DynamicClass item in cust)
            {
                Console.WriteLine(item.GetDynamicPropertyValue("Name"));
            }

            Console.Read();
        }
예제 #2
0
        public static void Main(string[] args)
        {
            Console.WriteLine("--start");

            DynamicProperty[] props   = { new DynamicProperty("Name", typeof(string)), new DynamicProperty("Birthday", typeof(DateTime)) };
            Type         type         = DynamicClassFactory.CreateType(props);
            DynamicClass dynamicClass = Activator.CreateInstance(type) as DynamicClass;

            dynamicClass.SetDynamicPropertyValue("Name", "Albert");
            dynamicClass.SetDynamicPropertyValue("Birthday", new DateTime(1879, 3, 14));
            Console.WriteLine(dynamicClass);

            string n1 = dynamicClass["Name"] as string;

            Console.WriteLine("dynamicClass[\"Name\"] = '" + n1 + "'");

            dynamicClass["NameX"] = "x";
            string n2 = dynamicClass["NameX"] as string;

            Console.WriteLine("dynamicClass[\"NameX\"] = '" + n2 + "'");

            //GroupByAndSelect_TestDynamicSelectMember();
            //Select();
            //TestDyn();
            //ExpressionTests_Enum();
            //Where();
            //ExpressionTests_Sum();

            Console.WriteLine("--end");
        }
        private GraphExpression CreateComplexGraphExpression(
            FieldNode fieldNode,
            ParameterExpression parameter,
            PropertyInfo prop,
            Type schemaType)
        {
            var childSchemaType = schemaType.GetProperty(prop.Name).PropertyType;

            List <GraphExpression> graphExpressions = CreateGraphExpressionList(
                fieldNode.SelectionSet.Selections,
                prop.PropertyType,
                childSchemaType,
                parameter,
                prop.Name);

            var resultType = DynamicClassFactory.CreateType(graphExpressions.Select(f => f.Property).ToList(), false);

            _typeCollection.AddIfNotExists(prop.PropertyType.FullName, resultType);

            var bindings = graphExpressions.Select(p => {
                return(Expression.Bind(resultType.GetProperty(p.Property.Name), p.Expression));
            });
            var newExpression = Expression.MemberInit(Expression.New(resultType), bindings);

            return(new GraphExpression()
            {
                Property = new DynamicProperty(prop.Name, resultType),
                Expression = newExpression
            });
        }
예제 #4
0
        public static void Main(string[] args)
        {
            var properties = new List <DynamicProperty>();

            properties.Add(new DynamicProperty("x", typeof(string)));
            properties.Add(new DynamicProperty("i", typeof(int)));

            var t = DynamicClassFactory.CreateType(properties);

            List <DynamicClass> d = new List <DynamicClass>();
            var x1 = (dynamic)Activator.CreateInstance(t);

            x1.i = 100;
            x1.x = "test 1";
            var x2 = (dynamic)Activator.CreateInstance(t);

            x2.i = 100;
            x2.x = "test 2";

            d.Add(x1);
            d.Add(x2);

            var g = d.AsQueryable().GroupBy(x => new { rrr = x.GetDynamicProperty <int>("i") });

            //TestEqualsOld();
            TestEqualsNew();
        }
        private MemberInitExpression CreateNewExpression(
            FieldNode fieldNode,
            Type type,
            Type schemaType,
            ParameterExpression parameter,
            params string[] filters)
        {
            var selections = fieldNode.SelectionSet.Selections;

            List <GraphExpression> graphExpressions = CreateGraphExpressionList(selections, type, schemaType, parameter, parentName: null, filters: filters);

            var unambiguousGraphExpressions = new List <GraphExpression>();

            foreach (var expression in graphExpressions)
            {
                if (!unambiguousGraphExpressions.Any(fge => fge.Property.Name == expression.Property.Name))
                {
                    unambiguousGraphExpressions.Add(expression);
                }
            }

            var resultType = DynamicClassFactory.CreateType(unambiguousGraphExpressions.Select(f => f.Property).ToList(), false);

            _typeCollection.AddIfNotExists(type.FullName, resultType);

            var bindings = unambiguousGraphExpressions.Select(p => {
                var property = resultType.GetProperty(p.Property.Name);
                return(Expression.Bind(property, p.Expression));
            });

            return(Expression.MemberInit(Expression.New(resultType), bindings));
        }
예제 #6
0
        public static IQueryable <dynamic> DynamicSelect <TEntity>(this IQueryable <TEntity> query, string select)
            where TEntity : class
        {
            if (string.IsNullOrWhiteSpace(select))
            {
                return(query);
            }

            try
            {
                var dynamicProperties = select.Replace(" ", "").Split(',').Select(x => $"{char.ToUpperInvariant(x[0])}{x.Substring(1)}");

                var properties = dynamicProperties
                                 .Select(f => typeof(TEntity).GetProperty(f))
                                 .Select(p => new DynamicProperty(p.Name, p.PropertyType))
                                 .ToList();

                var resultType = DynamicClassFactory.CreateType(properties, false);

                var source = Expression.Parameter(typeof(TEntity), "o");

                var bindings = properties.Select(p => Expression.Bind(resultType.GetProperty(p.Name), Expression.Property(source, p.Name)));

                var result = Expression.MemberInit(Expression.New(resultType), bindings);

                var dynamicExpression = Expression.Lambda <Func <TEntity, dynamic> >(result, source);

                return(query.Select(dynamicExpression));
            }
            catch
            {
                return(query);
            }
        }
예제 #7
0
        public IEnumerable <object> CreateDataClass1()
        {
            IList <dynamic> objects = new List <object>();



            var list = new Dictionary <string, string> {
                { "EmployeeID", "System.Int32" },
                { "EmployeeName", "System.String" },
                { "Service", "Lab.Linq101.DynamicDataClass.OpticalService" }
            };

            var props = list.Select(property => new DynamicProperty(property.Key, Type.GetType(property.Value))).ToList();

            Type type = DynamicClassFactory.CreateType(props);


            int n = 0;

            while (n < 5)
            {
                dynamic employee = new TestDynamicObject();
                employee.n = n;

                //object obj = Activator.CreateInstance(type);
                //type.GetProperty("EmployeeID").SetValue(obj, n, null);
                //type.GetProperty("EmployeeName").SetValue(obj, "Albert" + n, null);
                //type.GetProperty("Service").SetValue(obj, new OpticalService { Status = "Spare" }, null);

                objects.Add(employee);
                n++;
            }

            return(objects);
        }
        public static Type CreateType()
        {
            var properties = new List <DynamicProperty>();

            properties.Add(new DynamicProperty("Id", typeof(int)));
            properties.Add(new DynamicProperty("RowNumber", typeof(long)));
            return(DynamicClassFactory.CreateType(properties));
        }
예제 #9
0
        private static object Aggregate <T>(IQueryable <T> queryable, IEnumerable <Aggregator> aggregates)
        {
            if (aggregates != null && aggregates.Any())
            {
                var  objProps = new Dictionary <DynamicProperty, object>();
                var  groups   = aggregates.GroupBy(g => g.Field);
                Type type     = null;
                foreach (var group in groups)
                {
                    var fieldProps = new Dictionary <DynamicProperty, object>();
                    foreach (var aggregate in group)
                    {
                        var prop     = typeof(T).GetProperty(aggregate.Field);
                        var param    = Expression.Parameter(typeof(T), "s");
                        var selector = aggregate.Aggregate == "count" && (Nullable.GetUnderlyingType(prop.PropertyType) != null)
                                                        ? Expression.Lambda(Expression.NotEqual(Expression.MakeMemberAccess(param, prop), Expression.Constant(null, prop.PropertyType)), param)
                                                        : Expression.Lambda(Expression.MakeMemberAccess(param, prop), param);
                        var mi = aggregate.MethodInfo(typeof(T));
                        if (mi == null)
                        {
                            continue;
                        }

                        var val = queryable.Provider.Execute(Expression.Call(null, mi,
                                                                             aggregate.Aggregate == "count" && (Nullable.GetUnderlyingType(prop.PropertyType) == null)
                                                                ? new[] { queryable.Expression }
                                                                : new[] { queryable.Expression, Expression.Quote(selector) }));

                        fieldProps.Add(new DynamicProperty(aggregate.Aggregate, typeof(object)), val);
                    }

                    type = DynamicClassFactory.CreateType(fieldProps.Select(x => x.Key).ToList());
                    var fieldObj = Activator.CreateInstance(type);
                    foreach (var p in fieldProps.Keys)
                    {
                        type.GetProperty(p.Name).SetValue(fieldObj, fieldProps[p], null);
                    }
                    objProps.Add(new DynamicProperty(group.Key, fieldObj.GetType()), fieldObj);
                }

                type = DynamicClassFactory.CreateType(objProps.Select(x => x.Key).ToList());

                var obj = Activator.CreateInstance(type);

                foreach (var p in objProps.Keys)
                {
                    type.GetProperty(p.Name).SetValue(obj, objProps[p], null);
                }

                return(obj);
            }
            else
            {
                return(null);
            }
        }
        public static Expression <Func <TSource, dynamic> > DynamicFields <TSource>(IEnumerable <string> fields, List <DynamicProperty> properties)
        {
            var source = Expression.Parameter(typeof(TSource), "o");

            var resultType = DynamicClassFactory.CreateType(properties, false);
            var bindings   = properties.Select(p => Expression.Bind(resultType.GetProperty(p.Name), Expression.Property(source, p.Name)));
            var result     = Expression.MemberInit(Expression.New(resultType), bindings);

            return(Expression.Lambda <Func <TSource, dynamic> >(result, source));
        }
예제 #11
0
        public static Type CreateDynamicType(this Type mainType, IList <MemberExpression> exprList)
        {
            var properties = new List <DynamicProperty>();

            foreach (var expr in exprList)
            {
                var str = expr.ToString();
                str = str.Substring(str.IndexOf('.') + 1);
                properties.Add(new DynamicProperty(str, expr.Type));
            }
            return(DynamicClassFactory.CreateType(properties));
        }
예제 #12
0
        public static Type GenrateType()
        {
            var list = new Dictionary <string, string> {
                {
                    "_id",
                    "System.Int32"
                },
                {
                    "Name",
                    "System.String"
                },

                {
                    "Age",
                    "System.Int32"
                },

                {
                    "Gender",
                    "System.Boolean"
                },
                {
                    "ClassId",
                    "System.Int32"
                },
            };



            List <DynamicProperty> props = list.Select(property => new DynamicProperty(property.Key, Type.GetType(property.Value))).ToList();


            Type t = DynamicClassFactory.CreateType(props, false);

            //Type t = DynamicExpression.CreateClass(props);


            //object obj = Activator.CreateInstance(t);
            //t.GetProperty("EmployeeID").SetValue(obj, 34, null);
            //t.GetProperty("EmployeeName").SetValue(obj, "Albert", null);
            //t.GetProperty("Birthday").SetValue(obj, new DateTime(1976, 3, 14), null);


            // Console.WriteLine($"EmployeeID: { t.GetProperty("EmployeeID").GetValue(obj)} EmployeeName: {t.GetProperty("EmployeeName").GetValue(obj)} Birthday: {t.GetProperty("Birthday").GetValue(obj)}");

            return(t);
        }
예제 #13
0
        private Type CreateJoinType(IEnumerable <GraphSchema> schemaGroup)
        {
            var propertyLookup    = new PropertyLookup(schemaGroup.First().Property.PropertyType);
            var dynamicProperties = schemaGroup.Select(groupItem =>
            {
                var property = FindPropertyInfo(propertyLookup, groupItem.SchemaProperty.Name, groupItem.SchemaProperty);
                var propType = property.PropertyType;
                groupItem.FoundPropertyName = property.Name;
                if (!propType.IsTypePrimitive())
                {
                    propType = typeof(object);
                }
                return(new DynamicProperty(property.Name, propType));
            }).ToList();
            var resultType = DynamicClassFactory.CreateType(dynamicProperties, false);

            return(resultType);
        }
예제 #14
0
        /// <summary>
        /// Creates a pivot table (a table where columns are created from specified values in a collection) from a IEnumerable of <typeparamref name="T"/>, using the specified selector and aggregators.
        /// <code>
        /// Example to be added soon
        /// </code>
        /// </summary>
        /// <typeparam name="T">Items type</typeparam>
        /// <typeparam name="TPivoted">Type of the pivoted data</typeparam>
        /// <typeparam name="TKeys">Type of the keys</typeparam>
        /// <typeparam name="TAggregate">Type of computed aggregated data for each pivot</typeparam>
        /// <param name="src">Source collection</param>
        /// <param name="keysSelector">Keys selector (used as keys for the groups aggregation for pivoted values will be computed on)</param>
        /// <param name="pivotSelectorExpr">Expression to get the properties to compute the pivot on</param>
        /// <param name="aggregateSelector">Aggregation calculation method</param>
        /// <returns></returns>
        public static IEnumerable <dynamic> Pivot <T, TKeys, TPivoted, TAggregate>(this IEnumerable <T> src, Expression <Func <T, TKeys> > keysSelector, Expression <Func <T, TPivoted> > pivotSelectorExpr, Func <IEnumerable <T>, TAggregate> aggregateSelector)
        {
            Func <TPivoted, object[]> arraygetter;
            Func <T, TPivoted>        columnSelector;

            var pivoted = PivotDataInternal(src, keysSelector, pivotSelectorExpr, aggregateSelector, out arraygetter, out columnSelector);

            var memberKeys = keysSelector.GetMembers().Cast <PropertyInfo>().ToList();
            var properties = memberKeys.Select(m => new DynamicProperty(m.Name, m.PropertyType))
                             .Concat(src.SelectMany(c => arraygetter(columnSelector(c)))
                                     .Distinct()
                                     .Select(c => new DynamicProperty(c.ToString(), aggregateSelector.Method.ReturnType)))
                             .ToArray();
            //var properties = memberKeys.Concat(membersCols).Select(m => new DynamicProperty(m.Name, m.PropertyType));

            var dynobj = DynamicClassFactory.CreateType(properties);

            return(pivoted.Select(args => Activator.CreateInstance(dynobj, args)));
        }
        private GraphExpression CreateJoinGraphExpression(ParameterExpression parameter, IGrouping <string, GraphSchema> joinGroup)
        {
            var dynamicProperties = joinGroup.Select(f => new DynamicProperty(f.SchemaProperty.Name, f.SchemaProperty.PropertyType)).ToList();
            var resultType        = DynamicClassFactory.CreateType(dynamicProperties, false);

            var bindings = joinGroup.Select(p =>
            {
                var propExp = Expression.PropertyOrField(parameter, p.Property.Name);
                return(Expression.Bind(resultType.GetProperty(p.SchemaProperty.Name),
                                       Expression.PropertyOrField(propExp, p.SchemaProperty.Name)));
            });
            var newExpression = Expression.MemberInit(Expression.New(resultType), bindings);

            return(new GraphExpression()
            {
                Property = new DynamicProperty(joinGroup.First().Property.Name, typeof(object)),
                Expression = newExpression
            });
        }
예제 #16
0
        private MemberInitExpression CreateNewExpression(
            FieldNode fieldNode,
            Type type,
            ParameterExpression parameter)
        {
            var selections = fieldNode.SelectionSet.Selections;

            List <GraphExpression> graphExpressions = CreateGraphExpressionList(selections, type, parameter);

            var resultType = DynamicClassFactory.CreateType(graphExpressions.Select(f => f.Property).ToList(), false);

            _typeCollection.AddIfNotExists(type.FullName, resultType);

            var bindings = graphExpressions.Select(p => {
                return(Expression.Bind(resultType.GetProperty(p.Property.Name), p.Expression));
            });

            return(Expression.MemberInit(Expression.New(resultType), bindings));
        }
예제 #17
0
파일: Utils.cs 프로젝트: wattcode/rules
        public static Type CreateAbstractClassType(dynamic input)
        {
            List <DynamicProperty> props = new List <DynamicProperty>();

            if (input == null)
            {
                return(typeof(object));
            }
            if (!(input is ExpandoObject))
            {
                return(input.GetType());
            }

            else
            {
                foreach (var expando in (IDictionary <string, object>)input)
                {
                    Type value;
                    if (expando.Value is IList)
                    {
                        if (((IList)expando.Value).Count == 0)
                        {
                            value = typeof(List <object>);
                        }
                        else
                        {
                            var internalType = CreateAbstractClassType(((IList)expando.Value)[0]);
                            value = new List <object>().Cast(internalType).ToList(internalType).GetType();
                        }
                    }
                    else
                    {
                        value = CreateAbstractClassType(expando.Value);
                    }
                    props.Add(new DynamicProperty(expando.Key, value));
                }
            }

            var type = DynamicClassFactory.CreateType(props);

            return(type);
        }
        public void Something(List <TestEntity <Instant> > testEntities)
        {
            var zone  = Tzdb.Tzdb.GetAllZones().First();
            var z     = testEntities[0].TestProperty.InZone(zone);
            var count = testEntities.Where(x => x.TestProperty.InZone(zone) == z).Count();

            AddToDatabase(testEntities.ToArray());
            //ExecuteWithQueryable(q =>
            //{
            //    var count2 = q.Select(x => new { Entity = x, InZone = new { Instant = x.TestProperty, Zone = zone.MappedAs(new CustomType<TzdbDateTimeZoneType>()) } }).Where(x => x.InZone.Instant == z.ToInstant() && x.InZone.Zone == z.Zone.MappedAs(new CustomType<TzdbDateTimeZoneType>())).Count();
            //    count.Should().Be(count2);
            //});

            ExecuteWithQueryable(q =>
            {
                //var count2 = q.Where(x => x.TestProperty.InZone(zone)==z).ToList();

                var count2 = q.Select(x => new
                {
                    Instance = x,
                    InZone   = new ZonedDateTimeProxy {
                        Instant = x.TestProperty, Zone = zone.MappedAs(new CustomType <TzdbDateTimeZoneType>())
                    }
                }
                                      ).Count();

                //var count3 = q.Select(x => new ExpandoObject(Dictionary<string, object>() { { "Instance", x } }//,
                //                                                                                               //{ "InZone", new ZonedDateTimeProxy { Instant = x.TestProperty, Zone = zone.MappedAs(new CustomType<TzdbDateTimeZoneType>()) }

                //).Where(x => ((Instant)x["Instance"]) != null).ToList();// Where(x => ((ZonedDateTimeProxy)x["InZone"]).Instant == z.ToInstant() && ((ZonedDateTimeProxy)x["InZone"]).Zone == z.Zone.MappedAs(new CustomType<TzdbDateTimeZoneType>())).Select(x => (TestEntity<Instant>)x["Instance"]).Count();
                //count.Should().Be(count3);

                var type = DynamicClassFactory.CreateType(new List <DynamicProperty>
                {
                    new DynamicProperty("Instance", typeof(TestEntity <Instant>)),
                    new DynamicProperty("InZone", typeof(ZonedDateTimeProxy))
                });

                var rParam = Expression.Parameter(typeof(TestEntity <Instant>));

                var select = ReflectHelper.GetMethod(() => Queryable.Select <object, object>(default, default(Expression <System.Func <object, object> >))).GetGenericMethodDefinition().MakeGenericMethod(q.ElementType, type);
예제 #19
0
        //public static Type GetTypeObject(this object obj)
        //{
        //    if (obj is int)
        //        return typeof(int);

        //    if (obj is string)
        //        return typeof(string);

        //    if (obj is bool)
        //        return typeof(bool);

        //    if (obj is DateTime)
        //        return typeof(DateTime);

        //    return null;
        //}

        /// <summary>
        /// Build a new object with all the items from dictionaty.
        /// </summary>
        /// <param name="ruleTargets"></param>
        /// <returns></returns>
        public static object BuildTargetObject(this Dictionary<string, object> fields)
        {
            if (fields == null)
                throw new ArgumentNullException(nameof(fields));

            var listNullValues = fields.Where(x => x.Value == null).ToDictionary(x => x.Key, x => x.Value);
            if (listNullValues != null)
            {
                foreach (var nullItem in listNullValues)
                    fields.Remove(nullItem.Key);
            }

            var properties = fields.Select(x => new DynamicProperty(x.Key, x.Value.GetType())).ToList();

            Type type = DynamicClassFactory.CreateType(properties);
            var target = Activator.CreateInstance(type);

            properties.ForEach(x => type.GetProperty(x.Name)
                .SetValue(target,
                fields.First(k => k.Key == x.Name).Value, null));

            return target;
        }
        public void Contains_Dynamic_ListWithDynamicObjects()
        {
            // Arrange
            var baseQuery = User.GenerateSampleModels(100).AsQueryable();
            var list      = new List <dynamic> {
                new { UserName = "******" }
            };

            var keyType = DynamicClassFactory.CreateType(new[] { new DynamicProperty("UserName", typeof(string)) });
            var keyVals = (IList)CreateGenericInstance(typeof(List <>), new[] { keyType });

            var keyVal = Activator.CreateInstance(keyType);

            keyType.GetProperty("UserName").SetValue(keyVal, "User1");
            keyVals.Add(keyVal);

            // Act
            var realQuery = baseQuery.Where(x => list.Contains(new { UserName = x.UserName })).Select(x => x.Id);
            var testQuery = baseQuery.Where("@0.Contains(new(it.UserName as UserName))", keyVals).Select("Id");

            // Assert
            Assert.Equal(realQuery.ToArray(), testQuery.Cast <Guid>().ToArray());
        }
예제 #21
0
        public void TestEqual()
        {
            var properties = new List <(Type type, string propertyName)>()
            {
                (typeof(int), "Id"),
                (typeof(string), "FirstName"),
                (typeof(string), "LastName")
            };

            var type      = DynamicClassFactory.CreateType(properties);
            var instanceA = Activator.CreateInstance(type) as DynamicClass;
            var instanceB = Activator.CreateInstance(type) as DynamicClass;

            instanceA.SetDynamicPropertyValue("Id", 1);
            instanceA.SetDynamicPropertyValue("FirstName", "David");
            instanceA.SetDynamicPropertyValue("LastName", "Lebee");

            instanceB.SetDynamicPropertyValue("Id", 1);
            instanceB.SetDynamicPropertyValue("FirstName", "David");
            instanceB.SetDynamicPropertyValue("LastName", "Lebee");

            Assert.IsTrue(instanceA.Equals(instanceB));
        }
예제 #22
0
        /// <summary>
        /// Returns the content of a DataTable as a collection of strongly-typed objects having a System.Type created at runtime.
        /// </summary>
        /// <param name="dt">The DataTable.</param>
        /// <returns>A collection of objects having a runtime System.Type matching the types specified by the table columns.</returns>
        public static IList ToDynamicTypeCollection(this DataTable dt)
        {
            // Create a new System.Type representing the DataRow, and a collection of items of that type.
            var properties  = new List <DynamicProperty>();
            var columnNames = new List <string>();

            foreach (DataColumn col in dt.Columns)
            {
                columnNames.Add(col.ColumnName);
                properties.Add(new DynamicProperty(col.ColumnName, col.DataType));
            }

            var rowType  = DynamicClassFactory.CreateType(properties);
            var listType = typeof(List <>).MakeGenericType(rowType);
            var list     = ( IList )Activator.CreateInstance(listType);

            // Create a collection of objects representing the rows in the table.
            foreach (DataRow row in dt.Rows)
            {
                var listObject = Activator.CreateInstance(rowType) as DynamicClass;
                foreach (var columnName in columnNames)
                {
                    var value = row[columnName];
                    // Ensure DBNull value is propagated correctly.
                    if (value == DBNull.Value)
                    {
                        value = null;
                    }
                    listObject.SetDynamicPropertyValue(columnName, value);
                }

                list.Add(listObject);
            }

            return(list);
        }
예제 #23
0
        /// <summary>	Adds the actions to model. </summary>
        ///
        /// <param name="modelBuilder">		    The builder that defines the model for the context being
        ///                                     created. </param>
        /// <param name="schema">			    The schema. </param>
        /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
        ///
        /// <returns>	A Type. </returns>
        private static void AddActionsToModel(
            DbModelBuilder modelBuilder,
            DatabaseSchema schema,
            DynamicClassFactory dynamicClassFactory)
        {
            foreach (var function in schema.Functions)
            {
                try
                {
                    if (function.ReturnType != null)
                    {
                        var dynamicMethodData = new DynamicMethodData
                        {
                            FunctionType = FunctionType.ModelDefinedFunction,
                            ReturnType   = typeof(Int32),
                            Schema       = function.SchemaOwner
                        };
                        if (function.Arguments.Count > 0)
                        {
                            dynamicMethodData.Params = new DynamicParameterData[function.Arguments.Count];
                            for (int i = 0; i < function.Arguments.Count; i++)
                            {
                                dynamicMethodData.Params[i] = new DynamicParameterData()
                                {
                                    Name   = function.Arguments[i].Name,
                                    Type   = function.Arguments[i].DataType.GetNetType(),
                                    isIn   = function.Arguments[i].In,
                                    isOut  = function.Arguments[i].Out,
                                    Length = function.Arguments[i].Length
                                };
                            }
                        }
                        _dynamicActionMethods.Add(function.Name, dynamicMethodData);
                    }
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError(string.Format("AddActionsToModel: function '{0}'", function.Name), exception);
                }
            }

            foreach (var procedure in schema.StoredProcedures)
            {
                try
                {
                    var dynamicMethodData = new DynamicMethodData
                    {
                        FunctionType = FunctionType.ModelDefinedFunction,
                        ReturnType   = typeof(Int32),
                        Schema       = procedure.SchemaOwner
                    };
                    if (procedure.Arguments.Count > 0)
                    {
                        dynamicMethodData.Params = new DynamicParameterData[procedure.Arguments.Count];
                        for (int i = 0; i < procedure.Arguments.Count; i++)
                        {
                            dynamicMethodData.Params[i] = new DynamicParameterData()
                            {
                                Name   = procedure.Arguments[i].Name,
                                Type   = procedure.Arguments[i].DataType.GetNetType(),
                                isIn   = procedure.Arguments[i].In,
                                isOut  = procedure.Arguments[i].Out,
                                Length = procedure.Arguments[i].Length
                            };
                        }
                    }
                    _dynamicActionMethods.Add(procedure.Name, dynamicMethodData);
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError(string.Format("AddActionsToModel: procedure '{0}'", procedure.Name), exception);
                }
            }

            try
            {
                _dynamicActions = CreateTypeAction(dynamicClassFactory, "DbActions", _dynamicActionMethods);
                // https://www.nuget.org/packages/EntityFramework.Functions
                modelBuilder.AddFunctions(_dynamicActions, false);
            }
            catch (Exception exception)
            {
                DynamicLogger.Instance.WriteLoggerLogError("AddActionsToModel", exception);
            }
        }
        /// <summary>	Creates the model. </summary>
        ///
        /// <returns>	The new model. </returns>
        private static DbCompiledModel CreateModel()
        {
            // Create a model + register types to it.
            var modelBuilder = new DbModelBuilder();
            modelBuilder.Conventions.Remove<PluralizingEntitySetNameConvention>(); //For generating Entities without 's' at the end
            DbCompiledModel compiledDatabaseModel = null;

            try
            {
                #region Read Schema and Add to Model

                // https://www.nuget.org/packages/DatabaseSchemaReader/
                using (var dbReader = new DatabaseReader(cConnectionStringSettings.ConnectionString, cConnectionStringSettings.ProviderName, DynamicContext.cDefaultSchemaName))
                {
                    var schema = dbReader.ReadAll();
                    var dynamicClassFactory = new DynamicClassFactory();

                    #region Read Tables

                    var tableBuildHelperList = new List<TableBuildHelper>();
                    List<string> failedTableColumns = new List<string>();
                    foreach (var table in schema.Tables)
                    {
                        try
                        {
                            var tableBuildHelper = new TableBuildHelper();
                            tableBuildHelper.Name = table.Name;
                            tableBuildHelper.Properties = new List<TablePropertyBuildHelper>();

                            #region Field properties

                            foreach (var col in table.Columns)
                            {
                                if (col.DataType == null)
                                {
                                    failedTableColumns.Add(string.Format("{0} - {1}", table.Name, col.ToString()));
                                }
                                else
                                {
                                    Type colType = Type.GetType(col.DataType.NetDataType);
                                    if (col.Nullable)
                                    {
                                        if (col.DataType.IsInt)
                                        {
                                            colType = typeof(Nullable<int>);
                                        }
                                        else if (col.DataType.IsDateTime)
                                        {
                                            colType = typeof(Nullable<DateTime>);
                                        }
                                        else if (col.DataType.IsFloat)
                                        {
                                            colType = typeof(Nullable<float>);
                                        }
                                        else if (col.DataType.IsNumeric)
                                        {
                                            colType = typeof(Nullable<decimal>);
                                        }
                                        else if (col.DataType.TypeName == "datetimeoffset")
                                        {
                                            colType = typeof(Nullable<DateTimeOffset>);
                                        }
                                        else if (col.DataType.NetDataTypeCSharpName == "bool")
                                        {
                                            colType = typeof(Nullable<bool>);
                                        }
                                    }

                                    //Sequense logic
                                    string sequenceScript = null;
                                    if (col.IsPrimaryKey && !string.IsNullOrEmpty(col.DefaultValue) && col.DefaultValue.StartsWith("(NEXT VALUE FOR"))
                                        sequenceScript = col.DefaultValue.Substring(1, col.DefaultValue.Length - 2);

                                    FieldPropertyData fieldPropertyData = new FieldPropertyData()
                                    {
                                        IsPrimaryKey = col.IsPrimaryKey,
                                        IsForeignKey = col.IsForeignKey,
                                        Order = table.Columns.IndexOf(col) + 1,
                                        Nullable = col.Nullable,
                                        Type = colType,
                                        MaxLength = col.Length,
                                        IsComputedID = col.IsPrimaryKey && col.IdentityDefinition == null,
                                        SequenceScript = sequenceScript,
                                        ColumnName = col.Name
                                    };

                                    string name = col.Name;
                                    while (table.Name == name || tableBuildHelper.Properties.Exists(p => p.Name == name))
                                        name = name + "1";

                                    var tablePropertyBuildHelper = new TablePropertyBuildHelper();
                                    tablePropertyBuildHelper.Name = name;
                                    tablePropertyBuildHelper.Data = fieldPropertyData;
                                    tableBuildHelper.Properties.Add(tablePropertyBuildHelper);
                                }
                            }

                            #endregion

                            //Make all existing foreign keys as primary key if entity has no primary key
                            if (tableBuildHelper.Properties.FirstOrDefault(x => ((FieldPropertyData)x.Data).IsPrimaryKey) == null)
                            {
                                var foreignRows = tableBuildHelper.Properties.Where(x => (((FieldPropertyData)x.Data).IsForeignKey)).ToList();
                                foreignRows.ForEach(p => ((FieldPropertyData)p.Data).IsPrimaryKey = true);
                            }

                            var tableTypeBuilder = CreateTypeBuilder(dynamicClassFactory, table.Name, null);
                            tableBuildHelper.TypeBuilder = tableTypeBuilder;
                            tableBuildHelperList.Add(tableBuildHelper);
                        }
                        catch (Exception exception)
                        {
                            DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                        }
                    }

                    #region Navigation properties

                    foreach (var table in schema.Tables)
                    {
                        #region Foreign Keys

                        foreach (var foreignKey in table.ForeignKeys)
                        {
                            try
                            {
                                var tableBuildHelper = tableBuildHelperList.Find(table.Name);
                                var columnType = tableBuildHelperList.Find(foreignKey.RefersToTable).TypeBuilder;

                                //Foreign Key property
                                {
                                    ForeignKeyPropertyData foreignKeyPropertyData = new ForeignKeyPropertyData()
                                    {
                                        Type = columnType,
                                        ColumnName = tableBuildHelper.Properties.Find(foreignKey.Columns[0]).Name
                                    };

                                    string propName = foreignKey.RefersToTable;
                                    while (table.Name == propName || tableBuildHelper.Properties.Exists(propName))
                                    {
                                        propName = propName + "1";
                                    }

                                    var tablePropertyBuildHelper = new TablePropertyBuildHelper();
                                    tablePropertyBuildHelper.Name = propName;
                                    tablePropertyBuildHelper.Data = foreignKeyPropertyData;
                                    tableBuildHelper.Properties.Add(tablePropertyBuildHelper);
                                }

                                var fkTableBuildHelper = tableBuildHelperList.Find(foreignKey.RefersToTable);
                                var fkColumnType = typeof(ICollection<>).MakeGenericType(tableBuildHelper.TypeBuilder);

                                //if (table.Name == "BatchProductionRecord") //foreignKey.Columns[0] == "Events")
                                //Inverse property
                                {
                                    InversePropertyData inversePropertyData = new InversePropertyData()
                                    {
                                        Type = fkColumnType,
                                        ColumnName = tableBuildHelper.Properties.Last().Name //propName
                                    };

                                    string propName = foreignKey.TableName;
                                    while (foreignKey.RefersToTable == propName || fkTableBuildHelper.Properties.Exists(propName))
                                    {
                                        propName = propName + "1";
                                    }

                                    var tablePropertyBuildHelper = new TablePropertyBuildHelper();
                                    tablePropertyBuildHelper.Name = propName;
                                    tablePropertyBuildHelper.Data = inversePropertyData;
                                    fkTableBuildHelper.Properties.Add(tablePropertyBuildHelper);
                                }
                            }
                            catch (Exception exception)
                            {
                                DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                            }
                        }

                        #endregion
                    }

                    #endregion

                    #region Create properties and table types from type builder and add to DB model

                    foreach (var table in tableBuildHelperList)
                    {
                        foreach (var property in table.Properties)
                        {
                            try
                            {
                                dynamicClassFactory.CreateProperty(table.TypeBuilder, new KeyValuePair<string, DynamicPropertyData>(property.Name, property.Data), null);
                            }
                            catch (Exception exception)
                            {
                                DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                            }
                        }

                        try
                        {
                            var tableType = table.TypeBuilder.CreateType();
                            var entity = modelBuilder.Entity(tableType);
                        }
                        catch (Exception exception)
                        {
                            DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                        }
                    }

                    #endregion

                    #endregion

                    #region Read Views

                    List<string> failedViewColumns = new List<string>();
                    foreach (var view in schema.Views)
                    {
                        try
                        {
                            AddViewToModel(modelBuilder, dynamicClassFactory, failedViewColumns, view);
                        }
                        catch (Exception exception)
                        {
                            DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                        }
                    }

                    #endregion

                    #region Read Actions

                    AddActionsToModel(modelBuilder, schema, dynamicClassFactory);

                    #endregion
                }

                #endregion

                #region Add Metadata object for user rules custom metadata

                try
                {
                    var metadataObject = modelBuilder.Entity<DynamicMetadataObject>();
                    metadataObject.HasKey(a => a.Name);
                    metadataObject.Property(a => a.Type);
                    metadataObject.Property(a => a.Schema);
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                }

                #endregion

                #region Add service info object to model

                try
                {
                    var serviceInfoObject = modelBuilder.Entity<DynamicServiceInfoObject>();
                    serviceInfoObject.HasKey(a => a.IISVersion);
                    serviceInfoObject.Property(a => a.TargetFramework);
                    serviceInfoObject.Property(a => a.AppDomainAppPath);
                    serviceInfoObject.Property(a => a.AssemblyDictionary);
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                }

                #endregion

                var databaseModel = modelBuilder.Build(new System.Data.SqlClient.SqlConnection(cConnectionStringSettings.ConnectionString));
                compiledDatabaseModel = databaseModel.Compile();
            }
            catch (Exception exception)
            {
                DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                throw exception;
            }

            return compiledDatabaseModel;
        }
예제 #25
0
        private static void TestEqualsNew()
        {
            var props          = typeof(X).GetProperties();
            var prop           = props[0];
            var methodForSet   = prop.GetSetMethod();
            var parameterInfos = methodForSet.GetParameters();
            var parameterInfo  = parameterInfos[0];
            var customAttrs    = parameterInfo.GetCustomAttributes(false);

            int uyyyy = 0;

            var a1 = new { s = "1234" };
            var a2 = new { s = "1234" };

            Console.WriteLine("bool eq = a1 Equals a2 ===> {0}", a1.Equals(a2));

            var properties = new List <DynamicProperty>();

            properties.Add(new DynamicProperty("x", typeof(string)));
            properties.Add(new DynamicProperty("i", typeof(int)));

            var t = DynamicClassFactory.CreateType(properties);

            var x1    = (dynamic)Activator.CreateInstance(t);
            var index = t.GetProperty("i").GetIndexParameters();

            var method = t.GetMethod("get_i");

            ParameterInfo[] parameters = method.GetParameters();

            var m = t.GetProperty("i").GetGetMethod();

            MethodInfo miSetter = t.GetProperty("i").GetSetMethod();
            var        pars     = miSetter.GetParameters();

            foreach (ParameterInfo par in pars)
            {
                var ooo   = par.GetCustomAttributes(false);
                int uuuuu = 9;
            }

            int retValueI = (int)t.GetProperty("i").GetGetMethod().Invoke(x1, null);

            x1.SetDynamicProperty("i", 10);
            int retValue2 = x1.GetDynamicProperty <int>("i");
            int iii       = x1.i;

            // set
            x1.i = 999;


            dynamic x0 = t.GetConstructor(new Type[] { typeof(string), typeof(int) }).Invoke(new object[] { "inuuu", 140 });
            var     hc = x0.GetHashCode();



            string retValue = (string)t.GetProperty("x").GetGetMethod().Invoke(x0, null);

            string resss = x0.x;


            x0.x = "ddd";

            //var x1 = (dynamic) Activator.CreateInstance(t);

            x1.x = "ddd";

            int h0 = x0.GetHashCode();
            int h1 = x1.GetHashCode();

            Console.WriteLine("hashcode_0 = {0} , hashcode_1 = {1} : eq = {2} ?", h0, h1, h0 == h1);

            bool eq = x0 == x1;

            Console.WriteLine("bool eq = x0 == x1 ===> {0}", eq);

            bool eq2 = x0.Equals(x1);

            Console.WriteLine("bool eq = x0 Equals x1 ===> {0}", eq2);

            int u = 0;
        }
        /// <summary>	Adds a view to model. </summary>
        ///
        /// <param name="modelBuilder">		  	The builder that defines the model for the context being
        /// 									created. </param>
        /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
        /// <param name="failedViewColumns">  	The failed view columns. </param>
        /// <param name="view">				  	The view. </param>
        ///
        /// <returns>	A Type. </returns>
        private static Type AddViewToModel(
            DbModelBuilder modelBuilder,
            DynamicClassFactory dynamicClassFactory,
            List<string> failedViewColumns,
            DatabaseView view)
        {
            var property = new Dictionary<string, DynamicPropertyData>();
            foreach (var col in view.Columns)
            {
                if (col.DataType == null)
                {
                    failedViewColumns.Add(string.Format("{0} - {1}", view.Name, col.ToString()));
                }
                else
                {
                    Type colType = Type.GetType(col.DataType.NetDataType);
                    if (col.Nullable)
                    {
                        if (col.DataType.IsInt)
                        {
                            colType = typeof(Nullable<int>);
                        }
                        else if (col.DataType.IsDateTime)
                        {
                            colType = typeof(Nullable<DateTime>);
                        }
                        else if (col.DataType.IsFloat)
                        {
                            colType = typeof(Nullable<float>);
                        }
                        else if (col.DataType.IsNumeric)
                        {
                            colType = typeof(Nullable<decimal>);
                        }
                        else if (col.DataType.TypeName == "datetimeoffset")
                        {
                            colType = typeof(Nullable<DateTimeOffset>);
                        }
                        else if (col.DataType.NetDataTypeCSharpName == "bool")
                        {
                            colType = typeof(Nullable<bool>);
                        }
                    }
                    DynamicPropertyData dynamicPropertyData = new FieldPropertyData()
                    {
                        IsPrimaryKey = col.IsPrimaryKey,
                        IsForeignKey = col.IsForeignKey,
                        Order = view.Columns.IndexOf(col) + 1,
                        Nullable = col.Nullable,
                        Type = colType,
                        MaxLength = col.Length,
                        ColumnName = col.Name
                    };

                    string name = col.Name;
                    while (property.ContainsKey(name) || view.Name == name)
                    {
                        name = name + "1";
                    }
                    property.Add(name, dynamicPropertyData);
                }
            }

            //Make all existing foreign keys as primary key if entity has no primary key
            if (property.Values.FirstOrDefault(x => ((FieldPropertyData)x).IsPrimaryKey) == null)
            {
                var foreignRows = property.Values.Where(x => (((FieldPropertyData)x).IsForeignKey)).ToList();
                foreignRows.ForEach(p => ((FieldPropertyData)p).IsPrimaryKey = true);
            }

            var viewType = CreateType(dynamicClassFactory, view.Name, property);
            var entity = modelBuilder.Entity(viewType);
            var methodInfoMap = entity.TypeConfiguration.GetType().GetMethod("MapToStoredProcedures", new Type[] { });
            methodInfoMap.Invoke(entity.TypeConfiguration, new object[] { });

            return viewType;
        }
        /// <summary>	Adds the actions to model. </summary>
        ///
        /// <param name="modelBuilder">		  	The builder that defines the model for the context being
        /// 									created. </param>
        /// <param name="schema">			  	The schema. </param>
        /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
        ///
        /// <returns>	A Type. </returns>
        private static void AddActionsToModel(
            DbModelBuilder modelBuilder,
            DatabaseSchema schema,
            DynamicClassFactory dynamicClassFactory)
        {
            foreach (var function in schema.Functions)
            {
                try
                {
                    if (function.ReturnType != null)
                    {
                        var dynamicMethodData = new DynamicMethodData();
                        dynamicMethodData.FunctionType = FunctionType.ModelDefinedFunction;
                        dynamicMethodData.ReturnType = typeof(Int32);
                        dynamicMethodData.Schema = function.SchemaOwner;
                        if (function.Arguments.Count > 0)
                        {
                            dynamicMethodData.Params = new DynamicParameterData[function.Arguments.Count];
                            for (int i = 0; i < function.Arguments.Count; i++)
                            {
                                dynamicMethodData.Params[i] = new DynamicParameterData()
                                {
                                    Name = function.Arguments[i].Name,
                                    Type = function.Arguments[i].DataType.GetNetType(),
                                    isIn = function.Arguments[i].In,
                                    isOut = function.Arguments[i].Out,
                                    Length = function.Arguments[i].Length
                                };
                            }
                        }
                        _dynamicActionMethods.Add(function.Name, dynamicMethodData);
                    }
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError("AddActionsToModel", exception);
                }
            }

            foreach (var procedure in schema.StoredProcedures)
            {
                try
                {
                    var dynamicMethodData = new DynamicMethodData();
                    dynamicMethodData.FunctionType = FunctionType.ModelDefinedFunction;
                    dynamicMethodData.ReturnType = typeof(Int32);
                    dynamicMethodData.Schema = procedure.SchemaOwner;
                    if (procedure.Arguments.Count > 0)
                    {
                        dynamicMethodData.Params = new DynamicParameterData[procedure.Arguments.Count];
                        for (int i = 0; i < procedure.Arguments.Count; i++)
                        {
                            dynamicMethodData.Params[i] = new DynamicParameterData()
                            {
                                Name = procedure.Arguments[i].Name,
                                Type = procedure.Arguments[i].DataType.GetNetType(),
                                isIn = procedure.Arguments[i].In,
                                isOut = procedure.Arguments[i].Out,
                                Length = procedure.Arguments[i].Length
                            };
                        }
                    }
                    _dynamicActionMethods.Add(procedure.Name, dynamicMethodData);
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError("AddActionsToModel", exception);
                }
            }

            try
            {
                _dynamicActions = CreateTypeAction(dynamicClassFactory, "DbActions", _dynamicActionMethods);
                // https://www.nuget.org/packages/EntityFramework.Functions
                modelBuilder.AddFunctions(_dynamicActions, false);
            }
            catch (Exception exception)
            {
                DynamicLogger.Instance.WriteLoggerLogError("AddActionsToModel", exception);
            }
        }
 /// <summary>	Creates a type builder. </summary>
 ///
 /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
 /// <param name="name">				  	The name. </param>
 /// <param name="property">			  	The property. </param>
 ///
 /// <returns>	The new type builder. </returns>
 private static TypeBuilder CreateTypeBuilder(DynamicClassFactory dynamicClassFactory, string name, Dictionary<string, DynamicPropertyData> property)
 {
     var dynamicTypeBuilder = dynamicClassFactory.CreateDynamicTypeBuilder<DynamicEntity>(name, property);
     return dynamicTypeBuilder;
 }
예제 #29
0
        /// <summary>	Creates the model. </summary>
        ///
        /// <returns>	The new model. </returns>
        private static DbCompiledModel CreateModel()
        {
            // Create a model + register types to it.
            var modelBuilder = new DbModelBuilder();

            modelBuilder.Conventions.Remove <PluralizingEntitySetNameConvention>(); //For generating Entities without 's' at the end
            DbCompiledModel compiledDatabaseModel = null;

            try
            {
                #region Read Schema and Add to Model

                // https://www.nuget.org/packages/DatabaseSchemaReader/
                using (var dbReader = new DatabaseReader(cConnectionStringSettings.ConnectionString, cConnectionStringSettings.ProviderName))
                {
                    var schema = dbReader.ReadAll();
                    var dynamicClassFactory = new DynamicClassFactory();

                    #region Read Tables

                    var           tableBuildHelperList = new List <TableBuildHelper>();
                    List <string> failedTableColumns   = new List <string>();
                    foreach (var table in schema.Tables)
                    {
                        try
                        {
                            var tableBuildHelper = new TableBuildHelper
                            {
                                Name       = table.Name,
                                Properties = new List <TablePropertyBuildHelper>()
                            };

                            #region Field properties

                            foreach (var col in table.Columns)
                            {
                                if (col.DataType == null)
                                {
                                    failedTableColumns.Add(string.Format("{0} - {1}", table.Name, col.ToString()));
                                }
                                else
                                {
                                    Type colType = Type.GetType(col.DataType.NetDataType);
                                    if (col.Nullable)
                                    {
                                        if (col.DataType.IsInt)
                                        {
                                            colType = typeof(Nullable <int>);
                                        }
                                        else if (col.DataType.IsDateTime)
                                        {
                                            colType = typeof(Nullable <DateTime>);
                                        }
                                        else if (col.DataType.IsFloat)
                                        {
                                            colType = typeof(Nullable <float>);
                                        }
                                        else if (col.DataType.IsNumeric)
                                        {
                                            colType = typeof(Nullable <decimal>);
                                        }
                                        else if (col.DataType.TypeName == "datetimeoffset")
                                        {
                                            colType = typeof(Nullable <DateTimeOffset>);
                                        }
                                        else if (col.DataType.NetDataTypeCSharpName == "bool")
                                        {
                                            colType = typeof(Nullable <bool>);
                                        }
                                    }

                                    //Sequense logic
                                    string sequenceScript = null;
                                    if (col.IsPrimaryKey && !string.IsNullOrEmpty(col.DefaultValue) && col.DefaultValue.StartsWith("(NEXT VALUE FOR"))
                                    {
                                        sequenceScript = col.DefaultValue.Substring(1, col.DefaultValue.Length - 2);
                                    }

                                    FieldPropertyData fieldPropertyData = new FieldPropertyData()
                                    {
                                        IsPrimaryKey   = col.IsPrimaryKey,
                                        IsForeignKey   = col.IsForeignKey,
                                        Order          = table.Columns.IndexOf(col) + 1,
                                        Nullable       = col.Nullable,
                                        Type           = colType,
                                        MaxLength      = col.Length,
                                        IsComputedID   = col.IsPrimaryKey && col.IdentityDefinition == null,
                                        SequenceScript = sequenceScript,
                                        ColumnName     = col.Name
                                    };

                                    string name = col.Name;
                                    while (table.Name == name || tableBuildHelper.Properties.Exists(p => p.Name == name))
                                    {
                                        name = name + "1";
                                    }

                                    var tablePropertyBuildHelper = new TablePropertyBuildHelper
                                    {
                                        Name = name,
                                        Data = fieldPropertyData
                                    };
                                    tableBuildHelper.Properties.Add(tablePropertyBuildHelper);
                                }
                            }

                            #endregion

                            //Make all existing foreign keys as primary key if entity has no primary key
                            if (tableBuildHelper.Properties.FirstOrDefault(x => ((FieldPropertyData)x.Data).IsPrimaryKey) == null)
                            {
                                var foreignRows = tableBuildHelper.Properties.Where(x => (((FieldPropertyData)x.Data).IsForeignKey)).ToList();
                                foreignRows.ForEach(p => ((FieldPropertyData)p.Data).IsPrimaryKey = true);
                            }

                            var tableTypeBuilder = CreateTypeBuilder(dynamicClassFactory, table.SchemaOwner, table.Name, null);
                            tableBuildHelper.TypeBuilder = tableTypeBuilder;
                            tableBuildHelperList.Add(tableBuildHelper);
                        }
                        catch (Exception exception)
                        {
                            DynamicLogger.Instance.WriteLoggerLogError(string.Format("CreateModel: table '{0}'", table.Name), exception);
                        }
                    }

                    #region Navigation properties

                    foreach (var table in schema.Tables)
                    {
                        #region Foreign Keys

                        foreach (var foreignKey in table.ForeignKeys)
                        {
                            try
                            {
                                var tableBuildHelper = tableBuildHelperList.Find(table.Name);
                                var columnType       = tableBuildHelperList.Find(foreignKey.RefersToTable).TypeBuilder;

                                //Foreign Key property
                                {
                                    ForeignKeyPropertyData foreignKeyPropertyData = new ForeignKeyPropertyData()
                                    {
                                        Type       = columnType,
                                        ColumnName = tableBuildHelper.Properties.Find(foreignKey.Columns[0]).Name
                                    };

                                    string propName = foreignKey.RefersToTable;
                                    while (table.Name == propName || tableBuildHelper.Properties.Exists(propName))
                                    {
                                        propName = propName + "1";
                                    }

                                    var tablePropertyBuildHelper = new TablePropertyBuildHelper
                                    {
                                        Name = propName,
                                        Data = foreignKeyPropertyData
                                    };
                                    tableBuildHelper.Properties.Add(tablePropertyBuildHelper);
                                }

                                var fkTableBuildHelper = tableBuildHelperList.Find(foreignKey.RefersToTable);
                                var fkColumnType       = typeof(ICollection <>).MakeGenericType(tableBuildHelper.TypeBuilder);

                                //if (table.Name == "BatchProductionRecord") //foreignKey.Columns[0] == "Events")
                                //Inverse property
                                {
                                    InversePropertyData inversePropertyData = new InversePropertyData()
                                    {
                                        Type       = fkColumnType,
                                        ColumnName = tableBuildHelper.Properties.Last().Name //propName
                                    };

                                    string propName = foreignKey.TableName;
                                    while (foreignKey.RefersToTable == propName || fkTableBuildHelper.Properties.Exists(propName))
                                    {
                                        propName = propName + "1";
                                    }

                                    var tablePropertyBuildHelper = new TablePropertyBuildHelper
                                    {
                                        Name = propName,
                                        Data = inversePropertyData
                                    };
                                    fkTableBuildHelper.Properties.Add(tablePropertyBuildHelper);
                                }
                            }
                            catch (Exception exception)
                            {
                                DynamicLogger.Instance.WriteLoggerLogError(string.Format("CreateModel: foreignKey '{0}'", foreignKey.Name), exception);
                            }
                        }

                        #endregion
                    }

                    #endregion

                    #region Create properties and table types from type builder and add to DB model

                    foreach (var table in tableBuildHelperList)
                    {
                        foreach (var property in table.Properties)
                        {
                            try
                            {
                                dynamicClassFactory.CreateProperty(table.TypeBuilder, new KeyValuePair <string, DynamicPropertyData>(property.Name, property.Data), null);
                            }
                            catch (Exception exception)
                            {
                                DynamicLogger.Instance.WriteLoggerLogError(string.Format("CreateModel: property '{0}'", property.Name), exception);
                            }
                        }

                        try
                        {
                            var tableType = table.TypeBuilder.CreateType();
                            var entity    = modelBuilder.Entity(tableType);
                        }
                        catch (Exception exception)
                        {
                            DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                        }
                    }

                    #endregion

                    #endregion

                    #region Read Views

                    List <string> failedViewColumns = new List <string>();
                    foreach (var view in schema.Views)
                    {
                        try
                        {
                            AddViewToModel(modelBuilder, dynamicClassFactory, failedViewColumns, view);
                        }
                        catch (Exception exception)
                        {
                            DynamicLogger.Instance.WriteLoggerLogError(string.Format("CreateModel: view '{0}'", view.Name), exception);
                        }
                    }

                    #endregion

                    #region Read Actions

                    AddActionsToModel(modelBuilder, schema, dynamicClassFactory);

                    #endregion
                }

                #endregion

                #region Add Metadata object for user rules custom metadata

                try
                {
                    var metadataObject = modelBuilder.Entity <DynamicMetadataObject>();
                    metadataObject.HasKey(a => a.Name);
                    metadataObject.Property(a => a.Type);
                    metadataObject.Property(a => a.Schema);
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                }

                #endregion

                #region Add service info object to model

                try
                {
                    var serviceInfoObject = modelBuilder.Entity <DynamicServiceInfoObject>();
                    serviceInfoObject.HasKey(a => a.IISVersion);
                    serviceInfoObject.Property(a => a.TargetFramework);
                    serviceInfoObject.Property(a => a.AppDomainAppPath);
                    serviceInfoObject.Property(a => a.AssemblyDictionary);
                }
                catch (Exception exception)
                {
                    DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                }

                #endregion

                var databaseModel = modelBuilder.Build(new System.Data.SqlClient.SqlConnection(cConnectionStringSettings.ConnectionString));
                compiledDatabaseModel = databaseModel.Compile();
            }
            catch (Exception exception)
            {
                DynamicLogger.Instance.WriteLoggerLogError("CreateModel", exception);
                throw;
            }

            return(compiledDatabaseModel);
        }
예제 #30
0
        /// <summary>	Adds a view to model. </summary>
        ///
        /// <param name="modelBuilder">		    The builder that defines the model for the context being
        ///                                     created. </param>
        /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
        /// <param name="failedViewColumns">    The failed view columns. </param>
        /// <param name="view">				    The view. </param>
        ///
        /// <returns>	A Type. </returns>
        private static Type AddViewToModel(
            DbModelBuilder modelBuilder,
            DynamicClassFactory dynamicClassFactory,
            List <string> failedViewColumns,
            DatabaseView view)
        {
            var property = new Dictionary <string, DynamicPropertyData>();

            foreach (var col in view.Columns)
            {
                if (col.DataType == null)
                {
                    failedViewColumns.Add(string.Format("{0} - {1}", view.Name, col.ToString()));
                }
                else
                {
                    Type colType = Type.GetType(col.DataType.NetDataType);
                    if (col.Nullable)
                    {
                        if (col.DataType.IsInt)
                        {
                            colType = typeof(Nullable <int>);
                        }
                        else if (col.DataType.IsDateTime)
                        {
                            colType = typeof(Nullable <DateTime>);
                        }
                        else if (col.DataType.IsFloat)
                        {
                            colType = typeof(Nullable <float>);
                        }
                        else if (col.DataType.IsNumeric)
                        {
                            colType = typeof(Nullable <decimal>);
                        }
                        else if (col.DataType.TypeName == "datetimeoffset")
                        {
                            colType = typeof(Nullable <DateTimeOffset>);
                        }
                        else if (col.DataType.NetDataTypeCSharpName == "bool")
                        {
                            colType = typeof(Nullable <bool>);
                        }
                    }
                    DynamicPropertyData dynamicPropertyData = new FieldPropertyData()
                    {
                        IsPrimaryKey = col.IsPrimaryKey,
                        IsForeignKey = col.IsForeignKey,
                        Order        = view.Columns.IndexOf(col) + 1,
                        Nullable     = col.Nullable,
                        Type         = colType,
                        MaxLength    = col.Length,
                        ColumnName   = col.Name
                    };

                    string name = col.Name;
                    while (property.ContainsKey(name) || view.Name == name)
                    {
                        name = name + "1";
                    }
                    property.Add(name, dynamicPropertyData);
                }
            }

            //Make all existing foreign keys as primary key if entity has no primary key
            if (property.Values.FirstOrDefault(x => ((FieldPropertyData)x).IsPrimaryKey) == null)
            {
                var foreignRows = property.Values.Where(x => (((FieldPropertyData)x).IsForeignKey)).ToList();
                foreignRows.ForEach(p => ((FieldPropertyData)p).IsPrimaryKey = true);
            }

            var viewType = CreateType(dynamicClassFactory, view.SchemaOwner, view.Name, property);
            var entity   = modelBuilder.Entity(viewType);

            modelBuilder.HasDefaultSchema("Ordering");
            var methodInfoMap = entity.TypeConfiguration.GetType().GetMethod("MapToStoredProcedures", new Type[] { });

            methodInfoMap.Invoke(entity.TypeConfiguration, new object[] { });

            return(viewType);
        }
예제 #31
0
        /// <summary>	Creates a type builder. </summary>
        ///
        /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
        /// <param name="name">				    The name. </param>
        /// <param name="property">			    The property. </param>
        ///
        /// <returns>	The new type builder. </returns>
        private static TypeBuilder CreateTypeBuilder(DynamicClassFactory dynamicClassFactory, string schema, string name, Dictionary <string, DynamicPropertyData> property)
        {
            var dynamicTypeBuilder = dynamicClassFactory.CreateDynamicTypeBuilder <DynamicEntity>(schema, name, property);

            return(dynamicTypeBuilder);
        }
예제 #32
0
        /// <summary>	Creates type action. </summary>
        ///
        /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
        /// <param name="name">				    The name. </param>
        /// <param name="methods">			    The methods. </param>
        ///
        /// <returns>	The new type action. </returns>
        private static Type CreateTypeAction(DynamicClassFactory dynamicClassFactory, string name, Dictionary <string, DynamicMethodData> methods)
        {
            var dynamicType = dynamicClassFactory.CreateDynamicTypeAction <DynamicAction>(name, methods);

            return(dynamicType);
        }
예제 #33
0
        public async Task Invoke(
            HttpContext context,
            MetadataHolder metadataHolder,
            TContext dbContext)
        {
            var metadataHolderFromJson = new { Version = "", Entities = new List <MetadataEntity>() }; ///LOAD your metadata from cache   await _distributedCacheService.GetAsync<MetadataHolder>("MetadataJson");

            if (metadataHolderFromJson == null)
            {
                throw new NullReferenceException("MetadataJson load failed.");
            }

            var isNewMetadataJson = false;

            if (string.IsNullOrEmpty(metadataHolder.Version))
            {
                isNewMetadataJson = true;
            }
            else if (metadataHolder.Version != metadataHolderFromJson.Version)
            {
                isNewMetadataJson = true;
            }

            if (isNewMetadataJson)
            {
                Dictionary <string, TypeBuilder> entityTypeBuilderList = new Dictionary <string, TypeBuilder>();

                metadataHolder.Entities = new List <MetadataEntity>();

                var dynamicClassFactory = new DynamicClassFactory();
                foreach (var metadataEntity in metadataHolderFromJson.Entities)
                {
                    var metadataProps = new Dictionary <string, Type>();
                    foreach (var metaDataEntityProp in metadataEntity.Properties.Where(p => !p.IsNavigation))
                    {
                        // TODO YASIN datetime vb eklenebilir.
                        switch (metaDataEntityProp.Type)
                        {
                        case "String":
                            metadataProps.Add(metaDataEntityProp.Name, typeof(string));
                            break;

                        case "Int":
                            metadataProps.Add(metaDataEntityProp.Name, typeof(int));
                            break;

                        case "Guid":
                            metadataProps.Add(metaDataEntityProp.Name, typeof(Guid));
                            break;

                        default:
                            //Implement for Other types
                            break;
                        }
                    }
                    if (string.IsNullOrEmpty(metadataEntity.CustomAssemblyType))
                    {
                        var entityTypeBuilder = dynamicClassFactory.CreateDynamicTypeBuilder <DynamicEntity>(metadataEntity.Name, metadataProps);

                        entityTypeBuilderList.Add(metadataEntity.Name, entityTypeBuilder);
                    }

                    else
                    {
                        metadataEntity.EntityType = Type.GetType(metadataEntity.CustomAssemblyType);
                    }


                    metadataHolder.Entities.Add(metadataEntity);
                }

                metadataHolder.Version = metadataHolderFromJson.Version;

                foreach (var metadataEntity in metadataHolder.Entities)
                {
                    var existEntityTypeBuilder = entityTypeBuilderList.FirstOrDefault(p => p.Key == metadataEntity.Name).Value;

                    foreach (var metaDataEntityProp in metadataEntity.Properties.Where(p => p.IsNavigation))
                    {
                        var relatedEntityTypeBuilder = entityTypeBuilderList.FirstOrDefault(p => p.Key == metaDataEntityProp.Type).Value;

                        var relatedProp = new Dictionary <string, Type>();

                        if (metaDataEntityProp.NavigationType == "Single")
                        {
                            relatedProp.Add(metaDataEntityProp.Name, relatedEntityTypeBuilder);
                        }
                        else
                        {
                            Type listGenericType = typeof(List <>);

                            Type listRelateEntityType = listGenericType.MakeGenericType(relatedEntityTypeBuilder);

                            relatedProp.Add(metaDataEntityProp.Name, listRelateEntityType);
                        }
                        new DynamicClassFactory().CreatePropertiesForTypeBuilder(existEntityTypeBuilder, relatedProp, null);
                    }
                    metadataEntity.EntityType = existEntityTypeBuilder.CreateType();
                }
            }

            foreach (var metaDataEntity in metadataHolder.Entities)
            {
                dbContext.AddMetadata(metaDataEntity);
            }

            dbContext.SetContextVersion(metadataHolder.Version);

            await _next.Invoke(context);
        }
 /// <summary>	Creates type action. </summary>
 ///
 /// <param name="dynamicClassFactory">	The dynamic class factory. </param>
 /// <param name="name">				  	The name. </param>
 /// <param name="methods">			  	The methods. </param>
 ///
 /// <returns>	The new type action. </returns>
 private static Type CreateTypeAction(DynamicClassFactory dynamicClassFactory, string name, Dictionary<string, DynamicMethodData> methods)
 {
     var dynamicType = dynamicClassFactory.CreateDynamicTypeAction<DynamicAction>(name, methods);
     return dynamicType;
 }