Exemple #1
0
        public void TestObjectGetSetValueMethod()
        {
            DynamicTypeBuilder builder = new DynamicTypeBuilder(
                new DynamicMember[] {
                new DynamicProperty("StringProperty", typeof(string)),
                new DynamicProperty("DecimalProperty", typeof(decimal)),
                new DynamicProperty("NullableDecimalProperty", typeof(decimal?)),
                new DynamicProperty("DateTimeProperty", typeof(DateTime)),
                new DynamicProperty("TestClassProperty", typeof(TestClass))
            }
                );

            var conn = new TestClass();

            var instance = Activator.CreateInstance(builder.GeneratedType) as IDynamicPropertyHost;

            instance.SetValue("StringProperty", "TestString");
            instance.SetValue("DecimalProperty", 1.2m);
            instance.SetValue("NullableDecimalProperty", 1.3m);
            instance.SetValue("DateTimeProperty", DateTime.Today);
            instance.SetValue("TestClassProperty", conn);

            Assert.Null(instance.GetValue("NonExistingProperty"));

            Assert.Equal("TestString", instance.GetValue("StringProperty"));
            Assert.Equal(1.2m, instance.GetValue("DecimalProperty"));
            Assert.Equal(1.3m, instance.GetValue("NullableDecimalProperty"));
            Assert.Equal(DateTime.Today, instance.GetValue("DateTimeProperty"));
            Assert.Equal(conn, instance.GetValue("TestClassProperty"));
        }
Exemple #2
0
        public void TestSyncMethodsProxy()
        {
            var serviceCollection = new ServiceCollection();

            var dtb = new DynamicTypeBuilder <ScopeProxy <ISyncService> >();

            dtb.AddConvention(new ProxyConvention <ISyncService>());

            serviceCollection.AddConnectedService <ISyncService>();
            serviceCollection.AddConnectedLocal <ISyncService, SyncService>();
            serviceCollection.AddScoped <ScopedDependency>();
            serviceCollection.AddScopeProxy();

            var prov    = serviceCollection.BuildServiceProvider();
            var service = prov.GetRequiredService <ISyncService>();

            var text = Guid.NewGuid().ToString();
            var call = service.SyncMethodWithResult(text, 123);

            Assert.Equal(text, call);

            var ex  = Assert.Throws <SyncService.SyncServiceException>(() => service.SyncVoidMethod(text, 1234));
            var ex2 = Assert.Throws <SyncService.SyncServiceException>(() => service.SyncVoidMethod(text, 1234));

            Assert.NotEqual(ex.ScopedDependency.Id, ex2.ScopedDependency.Id);
        }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, ILGenerator il)
        {
            var evt = config.DynamicMembers.OfType <DynamicEvent>().Where(p => p.MemberName == "PropertyChanged").FirstOrDefault();

            if (evt == null)
            {
#if NETSTANDARD1_6
                throw new MissingMemberException($"Missiong member PropertyChanged on type {typeBuilder.Name}.");
#else
                throw new MissingMemberException(typeBuilder.Name, "PropertyChanged");
#endif
            }

            var endLabel = il.DefineLabel();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, evt.BackingField);
            il.Emit(OpCodes.Ldnull);
            il.Emit(OpCodes.Ceq);
            il.Emit(OpCodes.Brtrue_S, endLabel);

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, evt.BackingField);
            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Newobj, typeof(PropertyChangedEventArgs).GetConstructor(new[] { typeof(string) }));
            il.Emit(OpCodes.Callvirt, typeof(PropertyChangedEventHandler).GetMethod("Invoke"));

            il.MarkLabel(endLabel);
            il.Emit(OpCodes.Ret);
        }
 /// <summary>
 /// 查找并向方法体内注入代码。
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="members"></param>
 /// <param name="globalIntercepts"></param>
 /// <param name="interceptMethod">前面定义的拦截方法体。</param>
 private static void FindAndInjectMethods(DynamicTypeBuilder builder, IList <MemberInfo> members, IList <InterceptAttribute> globalIntercepts, DynamicMethodBuilder interceptMethod)
 {
     foreach (MethodInfo method in members.Where(s => s is MethodInfo))
     {
         InjectMethod(builder, globalIntercepts, interceptMethod, method);
     }
 }
        public override object VisitSelectExpression(QueryFilteringParser.SelectExpressionContext context)
        {
            var properties = context.PROPERTYACCESS()
                             .Select(x => x.Symbol.Text)
                             .ToHashSet();

            var typeProperties = _parameter.Type
                                 .GetCashedProperties()
                                 .Where(p => properties.Contains(p.Name))
                                 .ToDictionary(p => p.Name, p => p.PropertyType);

            var dynamicType = DynamicTypeBuilder.CreateDynamicType(typeProperties);

            var propExpressions = properties.ToDictionary(x => x, x => new PropertyNode(x, _parameter).CreateExpression());

            var body = Expression.MemberInit(
                Expression.New(dynamicType.GetConstructors().Single()),
                dynamicType.GetFields().Select(f => Expression.Bind(f, propExpressions[f.Name])));

            var lambda = ReflectionCache.Lambda.MakeGenericMethod(
                typeof(Func <,>).MakeGenericType(_parameter.Type, dynamicType));

            var expression = lambda.Invoke(null, new object[] { body, new ParameterExpression[] { _parameter } });

            var select = ReflectionCache.Select
                         .MakeGenericMethod(_parameter.Type, dynamicType);

            return(select.Invoke(null, new [] { _sourceQueryable, expression }));
        }
Exemple #6
0
        public void DynamicTypeBuilderSimplePropertyTest()
        {
            var props = new[] { "Key", "Category", "de", "en", "fr", "es", "ru", "zh", "ar" };

            var members = props.Select(p => new DynamicProperty(p, typeof(string)));

            var dtb = new DynamicTypeBuilder(members);

            dtb.AddConvention(new NotifyPropertyChangedConvention());

            var instance = Activator.CreateInstance(dtb.GeneratedType);

            var host = (IDynamicPropertyHost)instance;

            host.SetValue("Key", "123");

            host.SetValue("Category", "Category");
            host.SetValue("de", "loc_de");
            host.SetValue("en", "loc_en");
            host.SetValue("fr", "loc_fr");
            host.SetValue("ru", "loc_ru");
            host.SetValue("es", "loc_es");
            host.SetValue("zh", "loc_zh");
            host.SetValue("ar", "loc_ar");

            Assert.Equal("loc_de", host.GetValue("de"));
            Assert.Equal("loc_en", host.GetValue("en"));
            Assert.Equal("loc_fr", host.GetValue("fr"));
            Assert.Equal("loc_ru", host.GetValue("ru"));
            Assert.Equal("loc_es", host.GetValue("es"));
            Assert.Equal("loc_zh", host.GetValue("zh"));
            Assert.Equal("loc_ar", host.GetValue("ar"));
        }
Exemple #7
0
        protected override void Implement(DynamicTypeBuilder config, TypeBuilder typeBuilder, ILGenerator methodIl)
        {
            Label endLabel = methodIl.DefineLabel();

            Dictionary <DynamicProperty, Label> propLabels = GetSetValueHelper.CreateMethodBody(config, methodIl, ref endLabel);

            foreach (var item in propLabels)
            {
                methodIl.MarkLabel(item.Value);
                methodIl.Emit(OpCodes.Ldarg_0);
                methodIl.Emit(OpCodes.Ldarg_2);
                if (!item.Key.MemberType.IsValueType)
                {
                    methodIl.Emit(OpCodes.Castclass, item.Key.MemberType);
                }
                else
                {
                    methodIl.Emit(OpCodes.Unbox_Any, item.Key.MemberType);
                }

                methodIl.EmitCall(OpCodes.Callvirt, item.Key.Property.GetSetMethod(), null);
                methodIl.Emit(OpCodes.Nop);
                methodIl.Emit(OpCodes.Br, endLabel);
            }

            methodIl.MarkLabel(endLabel);
            methodIl.Emit(OpCodes.Ret);
        }
Exemple #8
0
        public void TestDynmaicEventForObject()
        {
            DynamicTypeBuilder <object> builder = new DynamicTypeBuilder <object>(
                new DynamicMember[] {
                new DynamicEvent("PropertyChanged", typeof(PropertyChangedEventHandler)),
            }
                );

            var type = builder.GeneratedType;

            var instance = Activator.CreateInstance(type);

            var eventInfo = type.GetEvent("PropertyChanged");

            Assert.NotNull(eventInfo);

            bool wasCalled = false;

            var handler = new PropertyChangedEventHandler((s, ea) => wasCalled = true);

            eventInfo.AddEventHandler(instance, handler);

            FireEvent <PropertyChangedEventArgs>(instance, "val_PropertyChanged", new PropertyChangedEventArgs("Test"));
            Assert.True(wasCalled);
            wasCalled = false;

            eventInfo.RemoveEventHandler(instance, handler);

            FireEvent <PropertyChangedEventArgs>(instance, "val_PropertyChanged", new PropertyChangedEventArgs("Test"));

            Assert.False(wasCalled);
        }
Exemple #9
0
        public void ShouldOverrideEqualsAndHashCode()
        {
            var schema = new SchemaDefinition()
                         .WithField("StringField", "string")
                         .WithField("IntField", "int");

            var type        = DynamicTypeBuilder.CreateFrom(schema);
            var stringField = type.GetProperty("StringField");
            var intField    = type.GetProperty("IntField");

            var objectOne    = Activator.CreateInstance(type);
            var objectOneToo = Activator.CreateInstance(type);
            var objectTwo    = Activator.CreateInstance(type);

            stringField.SetValue(objectOne, "One");
            stringField.SetValue(objectOneToo, "One");
            intField.SetValue(objectOne, 1);
            intField.SetValue(objectOneToo, 1);
            intField.SetValue(objectTwo, 2000);

            Assert.Equal(objectOne, objectOneToo);
            Assert.Equal(objectOne.GetHashCode(), objectOneToo.GetHashCode());
            Assert.NotEqual(objectOne, objectTwo);
            Assert.NotEqual(objectOne.GetHashCode(), objectTwo.GetHashCode());
        }
        public void InterceptionContextProxyInterceptionTest()
        {
            var  instance = new SimpleMethods();
            bool beforeStringCalled = false, afterStringCalled = false, insteadOfStringCalled = false;

            object[] arguments = null;

            var dtb = new DynamicTypeBuilder <DynamicProxyBase>();

            dtb.AddConvention(new ProxyConvention <ISimpleMethods>());

            var proxy = Activator.CreateInstance(dtb.GeneratedType) as ISimpleMethods;

            //var dtb2 = new DynamicTypeBuilder<DynamicProxyBase>();
            //dtb2.AddMember(new DynamicProperty("StringProperty", typeof(string)));
            //var proxy2 = Activator.CreateInstance(dtb2.GeneratedType) as ISimpleMethods;

            ((IDynamicProxy)proxy).SetProxyTarget <ISimpleMethods>(instance);

            ((DynamicProxyBase)proxy).InterceptorCalled += (m, t) =>
            {
                if (m == InterceptionMode.BeforeBody && t.MemberName == "StringWithParameters")
                {
                    beforeStringCalled = true;
                    arguments          = t.Arguments;
                }
                if (m == InterceptionMode.AfterBody && t.MemberName == "StringWithParameters")
                {
                    afterStringCalled = true;
                }
                if (m == InterceptionMode.InsteadOfBody && t.MemberName == "StringWithParameters")
                {
                    insteadOfStringCalled = true;
                }
            };

            var result = proxy.StringWithParameters("TestString", 1, null);

            proxy.Void();
            proxy.VoidWithParameters("test", 123, null);
            var intTest = proxy.Integer();

            proxy.String();
            proxy.TestClass();
            proxy.TestClassWithParameters("test", 2, null);
            var generic  = proxy.GenericText <int>(123, "test");
            var generic2 = proxy.GenericText <string>("testchen", "test");

            Assert.Equal(123, generic);
            Assert.Equal("testchen", generic2);

            Assert.True(beforeStringCalled);
            Assert.True(afterStringCalled);
            Assert.True(insteadOfStringCalled);

            Assert.Equal(3, arguments.Length);
            Assert.Equal("TestString", arguments[0]);
            Assert.Equal("TestString", result);
        }
Exemple #11
0
        public void Get_dynamic_type_one_field()
        {
            var type = DynamicTypeBuilder.GetDynamicType(new Dictionary <string, Type> {
                { "test", typeof(Int32) }
            });

            Assert.AreEqual(1, type.GetProperties().Count());
        }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldfld, convention.TargetsField.Field);
            il.Emit(OpCodes.Ret);
        }
        /// <summary>
        /// Добавляет к типу прокси реализацию метода.
        /// </summary>
        /// <param name="method">Исходный метод.</param>
        /// <returns>Динамический метод прокси.</returns>
        private MethodBuilder ImplementMethod(MethodInfo method)
        {
            var parameters    = method.GetParameters();
            var paramTypes    = ParameterConverter.GetTypes(parameters);
            var proxiedMethod = DynamicTypeBuilder.DefineMethod(method.Name,
                                                                MethodAttributes.Public | MethodAttributes.Virtual,
                                                                method.ReturnType, paramTypes);

            MakeGeneric(method, proxiedMethod);

            var ilGenerator       = proxiedMethod.GetILGenerator();
            var parametersEmitter = new ParametersEmitter(ilGenerator, paramTypes);
            var packedArgsEmitter = new PackedArgumentsEmitter(ilGenerator);

            ilGenerator.Emit(OpCodes.Nop);

            packedArgsEmitter.EmitProxy();

            // Обобщенные параметры будут известны только во время вызова
            // поэтому заранее собрать делегат не выйдетю
            var methodLambda = method.ContainsGenericParameters
                ? new ExtendedMethodInfo(method, null)
                : new ExtendedMethodInfo(method, Expressions.CreateMethodCall(method));

            var token = _methodLinkStore.CreateToken(methodLambda);

            packedArgsEmitter.EmitMethodToken(token);

            var argumentsEmitter = packedArgsEmitter.EmitArguments(parameters, parametersEmitter);

            if (method.ContainsGenericParameters)
            {
                packedArgsEmitter.EmitGenericArguments(method.GetGenericArguments());
            }

            ilGenerator.Emit(OpCodes.Ldarg_0);
            ilGenerator.Emit(OpCodes.Ldfld, _invokeDelegateField);
            packedArgsEmitter.EmitLoad();
            ilGenerator.Emit(OpCodes.Call, MethodReferences.ActionOfObjectArrayInvoke);

            // Странный блок, не уверен что он нужен.
            for (var i = 0; i < parameters.Length; i++)
            {
                // ReSharper disable once InvertIf
                if (parameters[i].ParameterType.IsByRef)
                {
                    parametersEmitter.EmitBeginSet(i);
                    argumentsEmitter.EmitGet(i);
                    parametersEmitter.EmitEndSet(i, typeof(object));
                }
            }

            packedArgsEmitter.EmitReturnValue(method.ReturnType);

            DynamicTypeBuilder.DefineMethodOverride(proxiedMethod, method);
            return(proxiedMethod);
        }
Exemple #14
0
 static void Main(string[] args)
 {
     using (AppContext context = new AppContext())
     {
         var type     = DynamicTypeBuilder.CreateType();
         var myObject = Activator.CreateInstance(type);
         Console.WriteLine("Hello World!");
     }
 }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.EmitCall(OpCodes.Callvirt, convention.GetValueEntiresTypedMethod.Method, null);
            il.Emit(OpCodes.Ret);
        }
        public override void Apply(DynamicTypeBuilder typeBuilder)
        {
            var properties = from p in typeBuilder.BaseType.GetProperties()
                             let set = p.GetSetMethod(true)
                                       where set != null && (set.IsPublic || set.IsFamily)
                                       select p;

            if (NotifyPropertyChanged)
            {
                foreach (var item in properties)
                {
                    typeBuilder.AddMember(new DynamicProperty(item.Name, item.PropertyType));
                }
            }

            this.TransactionProxyProperties = new Collection <TransactionProxyProperty>();

            foreach (var item in properties)
            {
                var tpp = new TransactionProxyProperty {
                    Property = item
                };
                tpp.HasMultipleValuesProperty = new DynamicProperty(
                    string.Format("{0}_HasMultipleValues", item.Name),
                    typeof(bool),
                    false);

                tpp.ValuesProperty = new DynamicProperty(
                    string.Format("{0}_Values", item.Name),
                    typeof(Dictionary <,>).MakeGenericType(typeof(Key <>).MakeGenericType(item.PropertyType), typeof(List <>).MakeGenericType(typeBuilder.BaseType)),
                    true);
                typeBuilder.AddMember(tpp.HasMultipleValuesProperty);
                typeBuilder.AddMember(tpp.ValuesProperty);
                this.TransactionProxyProperties.Add(tpp);
            }

            this.TargetsField = new DynamicField(Guid.NewGuid().ToString(), typeof(List <>).MakeGenericType(typeBuilder.BaseType));
            typeBuilder.AddMember(this.TargetsField);

            this.CommitMethod = new CommitMethod();
            typeBuilder.AddMember(this.CommitMethod);
            this.RollbackMethod = new RollbackMethod();
            typeBuilder.AddMember(this.RollbackMethod);
            this.GetTransactionProxyTargetsMethod = new Methods.GetTransactionProxyTargetsMethod();
            typeBuilder.AddMember(this.GetTransactionProxyTargetsMethod);
            this.GetTransactionProxyTypedTargetsMethod = new Methods.GetTransactionProxyTypedTargetsMethod(typeBuilder.BaseType);
            typeBuilder.AddMember(this.GetTransactionProxyTypedTargetsMethod);
            this.SetTransactionProxyTargetsMethod = new Methods.SetTransactionProxyTargetsMethod();
            typeBuilder.AddMember(this.SetTransactionProxyTargetsMethod);
            this.SetTransactionProxyTypedTargetsMethod = new Methods.SetTransactionProxyTypedTargetsMethod(typeBuilder.BaseType);
            typeBuilder.AddMember(this.SetTransactionProxyTypedTargetsMethod);

            typeBuilder.AddInterceptor(new ImplementInterfaceInterceptor <ICommitable>());
            typeBuilder.AddInterceptor(new ImplementInterfaceInterceptor <ITransactionProxy>());
            typeBuilder.AddInterceptor(new ImplementInterfaceInterceptor(typeof(ITransactionProxy <>).MakeGenericType(typeBuilder.BaseType)));
        }
        /// <summary>
        /// 在代理类中定义一个调用拦截器的方法。
        /// </summary>
        /// <param name="builder"></param>
        /// <returns></returns>
        private static DynamicMethodBuilder DefineInterceptMethod(DynamicTypeBuilder builder)
        {
            #region 方法原型

            /*
             * private void <Aspect>_Intercept(List<IInterceptor> interceptors, InterceptCallInfo callInfo, InterceptType interceptType)
             * {
             *  callInfo.InterceptType = interceptType;
             *  for (int i = 0; i < interceptors.Count; i++)
             *  {
             *      interceptors[i].Intercept(callInfo);
             *  }
             * }
             */
            #endregion
            var callMethod = builder.DefineMethod(
                string.Concat(AOP_PREFIX, "Intercept"),
                null,
                new[] { typeof(List <IInterceptor>), typeof(InterceptCallInfo), typeof(InterceptType) },
                VisualDecoration.Private, ilCoding: ctx =>
            {
                var l1 = ctx.Emitter.DefineLabel();
                var l2 = ctx.Emitter.DefineLabel();
                ctx.Emitter.DeclareLocal(typeof(int));
                ctx.Emitter
                .ldarg_2
                .ldarg_3
                .call(InterceptCache.CallInfoSetInterceptType)
                .ldc_i4_0
                .stloc_0
                .br_s(l2)
                .MarkLabel(l1)
                .ldarg_1
                .ldloc_0
                .call(InterceptCache.InterceptorsGetItem)
                .ldarg_2
                .call(InterceptCache.InterceptorIntercept)
                .ldloc_0
                .ldc_i4_1
                .add
                .stloc_0
                .MarkLabel(l2)
                .ldloc_0
                .ldarg_1
                .call(InterceptCache.InterceptorsGetCount)
                .blt_s(l1)
                .ret();
            });

            callMethod.DefineParameter("interceptors");
            callMethod.DefineParameter("callInfo");
            callMethod.DefineParameter("interceptType");

            return(callMethod);
        }
        public async Task Initialize()
        {
            Log.Debug("Initializing single table queue gateway");

            var schema = await DbSchemaReader.ReadTableSchema(_connectionFactory, _tableName).ConfigureAwait(false);

            _properties  = schema.Where(x => x.Name.ToLower() != "rownumber").Select(FromDbColumnInfo).ToArray();
            _messageType = DynamicTypeBuilder.BuildMessageType(new MessageTypeDefinition(_type, _properties));

            Log.Debug("Initialization complete");
        }
#pragma warning restore RECS0108 // Warns about static fields in generic types

        static ServiceScopeProxy()
        {
            var dtb = new DynamicTypeBuilder <ScopeProxy <TService> >(assemblyBuilderFactory: ScopeProxyHelper.AssemblyBuilderFactory);

            dtb.AddConvention(new ProxyConvention <TService>());
            _proxyType = dtb.GeneratedType;

            var param = Expression.Parameter(typeof(IServiceProvider), "p");
            var body  = Expression.New(_proxyType.GetConstructor(new[] { typeof(IServiceProvider) }), param);

            _createDelegate = Expression.Lambda <Func <IServiceProvider, TService> >(body, param).Compile();
        }
        /// <summary>
        /// Инициализирует экземпляр <see cref="ProxyTypeGenerator"/>
        /// </summary>
        public ProxyTypeGenerator(
            TypeBuilder dynamicTypeBuilder,
            ProxyAssembly proxyAssembly,
            MethodLinkStore methodLinkStore)
            : base(dynamicTypeBuilder)
        {
            _proxyAssembly   = proxyAssembly;
            _methodLinkStore = methodLinkStore;

            _invokeDelegateField = DynamicTypeBuilder.DefineField("invoke", typeof(Action <object[]>),
                                                                  FieldAttributes.Private);
        }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            var method = typeof(ITransactionProxy <>).MakeGenericType(convention.ItemType).GetMethod("SetTargets");

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Castclass, typeof(IEnumerable <>).MakeGenericType(convention.ItemType));
            il.EmitCall(OpCodes.Callvirt, method, null);
            il.Emit(OpCodes.Ret);
        }
        private static bool IsExplicitImplemented(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder builder, MethodInfo item)
        {
            var explicitMethod = config.DynamicMembers.OfType <DynamicMethod>().FirstOrDefault(p => p.IsExplicitImplementation(item));

            if (explicitMethod != null)
            {
                builder.DefineMethodOverride(explicitMethod.Method, item);
                return(true);
            }

            return(false);
        }
        public void GenericTypeContainingBackTick_CreatesCorrectName()
        {
            // Arrange
            string expectedName = "Generic`Type<TKey, TResult>";

            Type type = DynamicTypeBuilder.BuildType("Generic`Type`2", "TKey", "TResult");

            // Act
            string actualName = type.ToFriendlyName();

            // Assert
            Assert.AreEqual(expected: expectedName, actual: actualName);
        }
        public void GenericTypeWithIncorrectArgumentCountInName_CreatesCorrectName()
        {
            // Arrange
            string expectedName = "Generic<TKey, TResult>";

            Type type = DynamicTypeBuilder.BuildType("Generic`2", "TKey", "TResult");

            // Act
            string actualName = type.ToFriendlyName();

            // Assert
            Assert.AreEqual(expected: expectedName, actual: actualName);
        }
        public void GenericTypeWithoutBacktickAndArgumentNumber_CreatesCorrectName()
        {
            // Arrange
            string expectedName = "Generic<TKey, TResult>";

            Type type = DynamicTypeBuilder.BuildType("Generic", "TKey", "TResult");

            // Act
            string actualName = type.ToFriendlyName();

            // Assert
            Assert.AreEqual(expected: expectedName, actual: actualName);
        }
Exemple #26
0
        public void DynamicTypeBuilderTransactionalProxyHasMultipleValues()
        {
            var target1 = new TransactionProxyClass
            {
                DecimalProperty = 123,
                IntProperty     = 456,
                StringProperty  = "Test",
                Targets         = new Collection <TestTarget> {
                    new TestTarget()
                }
            };

            var target2 = new TransactionProxyClass
            {
                DecimalProperty = 123,
                IntProperty     = 457,
                StringProperty  = "Test",
                Targets         = new Collection <TestTarget> {
                    new TestTarget()
                }
            };

            var target3 = new TransactionProxyClass
            {
                DecimalProperty = 123,
                IntProperty     = 458,
                StringProperty  = "Test3",
                Targets         = new Collection <TestTarget> {
                    new TestTarget()
                }
            };

            var dtb = new DynamicTypeBuilder <TransactionProxyClass>();

            dtb.AddConvention(new TransactionProxyConvention(typeof(TransactionProxyClass), true));
            if (!dtb.Conventions.OfType <NotifyPropertyChangedConvention>().Any())
            {
                dtb.AddConvention(new NotifyPropertyChangedConvention());
            }

            var proxy = Activator.CreateInstance(dtb.GeneratedType) as TransactionProxyClass;

            ((ITransactionProxy <TransactionProxyClass>)proxy).SetTargets(new[] { target1, target2, target3 });

            var type = proxy.GetType();

            Assert.False((bool)type.GetProperty("DecimalProperty_HasMultipleValues").GetValue(proxy));
            Assert.True((bool)type.GetProperty("IntProperty_HasMultipleValues").GetValue(proxy));
            Assert.True((bool)type.GetProperty("StringProperty_HasMultipleValues").GetValue(proxy));
            Assert.True((bool)type.GetProperty("Targets_HasMultipleValues").GetValue(proxy));
        }
        protected override void Implement(DynamicTypeBuilder config, System.Reflection.Emit.TypeBuilder typeBuilder, System.Reflection.Emit.ILGenerator il)
        {
            var convention = config.Conventions.OfType <TransactionProxyConvention>().First();

            var listCtor = convention.TargetsField.MemberType.GetConstructor(new[] { typeof(IEnumerable <>).MakeGenericType(convention.ItemType) });

            il.Emit(OpCodes.Ldarg_0);
            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Newobj, listCtor);
            il.Emit(OpCodes.Stfld, convention.TargetsField.Field);
            il.Emit(OpCodes.Ldarg_0);
            il.EmitCall(OpCodes.Callvirt, typeof(ICommitable).GetMethod("Rollback"), null);
            il.Emit(OpCodes.Ret);
        }
Exemple #28
0
        public void TestDynmaicPropertiesForObject()
        {
            DynamicTypeBuilder <object> builder = new DynamicTypeBuilder <object>(
                new DynamicProperty[] {
                new DynamicProperty("StringProperty", typeof(string)),
                new DynamicProperty("DecimalProperty", typeof(decimal)),
                new DynamicProperty("NullableDecimalProperty", typeof(decimal?)),
                new DynamicProperty("DateTimeProperty", typeof(DateTime)),
                new DynamicProperty("TestClassProperty", typeof(TestClass))
            }
                );

            Assert.NotNull(builder.GeneratedType);

            var instance = Activator.CreateInstance(builder.GeneratedType);

            Assert.True(builder.GeneratedType.IsInstanceOfType(instance));

            var stringProperty          = builder.GeneratedType.GetProperty("StringProperty");
            var decimalProperty         = builder.GeneratedType.GetProperty("DecimalProperty");
            var nullableDecimalProperty = builder.GeneratedType.GetProperty("NullableDecimalProperty");
            var dateTimeProperty        = builder.GeneratedType.GetProperty("DateTimeProperty");
            var TestClassProperty       = builder.GeneratedType.GetProperty("TestClassProperty");

            Assert.NotNull(stringProperty);
            Assert.NotNull(decimalProperty);
            Assert.NotNull(nullableDecimalProperty);
            Assert.NotNull(dateTimeProperty);
            Assert.NotNull(TestClassProperty);

            Assert.Equal(typeof(string), stringProperty.PropertyType);
            Assert.Equal(typeof(decimal), decimalProperty.PropertyType);
            Assert.Equal(typeof(decimal?), nullableDecimalProperty.PropertyType);
            Assert.Equal(typeof(DateTime), dateTimeProperty.PropertyType);
            Assert.Equal(typeof(TestClass), TestClassProperty.PropertyType);

            var connection = new TestClass();

            stringProperty.SetValue(instance, "Teststring", null);
            decimalProperty.SetValue(instance, 0.1m, null);
            nullableDecimalProperty.SetValue(instance, 0.2m, null);
            dateTimeProperty.SetValue(instance, new DateTime(2012, 1, 1), null);
            TestClassProperty.SetValue(instance, connection, null);

            Assert.Equal("Teststring", stringProperty.GetValue(instance, null));
            Assert.Equal(0.1m, decimalProperty.GetValue(instance, null));
            Assert.Equal(0.2m, nullableDecimalProperty.GetValue(instance, null));
            Assert.Equal(new DateTime(2012, 1, 1), dateTimeProperty.GetValue(instance, null));
            Assert.Equal(connection, TestClassProperty.GetValue(instance, null));
        }
        public void DynamicTypeBuilder_NoParams(DynamicTypeBuilder builder, IExportLocatorScope scope, IDisposalScope disposalScope, IInjectionContext context)
        {
            var proxyType = builder.CreateType(typeof(IBasicServiceProvider), out List <DynamicTypeBuilder.DelegateInfo> methods);

            var newBasicService = new BasicService();

            var func = new ActivationStrategyDelegate((s, d, c) => newBasicService);

            var instance = (IBasicServiceProvider)Activator.CreateInstance(proxyType, scope, disposalScope, context, func);

            var basicService = instance.CreateBasicService();

            Assert.NotNull(basicService);
            Assert.Same(newBasicService, basicService);
        }
        public void NonGenericTypeContainingBackTick_CreatesCorrectName()
        {
            // Arrange
            // NSubstitute creates non-generic proxy types by postfixing the type name with "Proxy". This
            // could result in something as follows:
            string expectedName = "IQueryHandler`2Proxy";

            Type type = DynamicTypeBuilder.BuildType(expectedName);

            // Act
            string actualName = type.ToFriendlyName();

            // Assert
            Assert.AreEqual(expected: expectedName, actual: actualName);
        }
Exemple #31
0
        public void Import(string password)
        {
            listInvalidData = null;
            listImportData = null;
            listValueField = null;
            listDisplayField = null;
            listEntityResult = null;
            isDataSaved = false;

            if (!string.IsNullOrWhiteSpace(FileName))
            {
                using (var context = new VnrHrmDataContext())
                {
                    var unitOfWork = (IUnitOfWork)(new UnitOfWork(context));

                    if (ImportTemplateID != Guid.Empty)
                    {
                        var importTemplate = unitOfWork.CreateQueryable<Cat_Import>(Guid.Empty,
                            d => d.ID == ImportTemplateID).Select(d => new
                            {
                                d.StartColumnIndex,
                                d.StartRowIndex,
                                d.SheetIndex,
                                d.ObjectName
                            }).FirstOrDefault();

                        if (importTemplate != null)
                        {
                            #region InitExcel

                            Aspose.Cells.WorkbookDesigner excelPackage = null;
                            excelPackage = new Aspose.Cells.WorkbookDesigner();
                            excelPackage.Workbook = new Aspose.Cells.Workbook(FileName);

                            Type objectType = GetAssembly(importTemplate.ObjectName);
                            importObjectType = null;//kiểu dữ liệu ảo để nhận data

                            if (!string.IsNullOrEmpty(password))
                            {
                                excelPackage.Workbook.Settings.Password = password;
                            }

                            Int64 startRowIndex = importTemplate.StartRowIndex != null ? importTemplate.StartRowIndex.Value : 0;
                            Int64 startColIndex = importTemplate.StartColumnIndex != null ? importTemplate.StartColumnIndex.Value : 0;
                            Int64 sheetIndex = importTemplate.SheetIndex != null ? importTemplate.SheetIndex.Value : 0;
                            int skipRowNumber = (int)startColIndex;

                            startRowIndex = startRowIndex < FirstIndex ? FirstIndex : startRowIndex;
                            startColIndex = startColIndex < FirstIndex ? FirstIndex : startColIndex;
                            sheetIndex = sheetIndex < FirstIndex ? FirstIndex : sheetIndex;
                            Aspose.Cells.Worksheet worksheet = null;

                            if (excelPackage.Workbook != null && excelPackage.Workbook.Worksheets != null)
                            {
                                if (excelPackage.Workbook.Worksheets.Count > sheetIndex)
                                {
                                    worksheet = excelPackage.Workbook.Worksheets[(int)sheetIndex];
                                }

                                if (worksheet == null)
                                {
                                    int activeSheetIndex = excelPackage.Workbook.Worksheets.ActiveSheetIndex;
                                    worksheet = excelPackage.Workbook.Worksheets[activeSheetIndex];
                                }
                            }

                            #endregion

                            #region ImportData

                            if (worksheet != null && worksheet.Cells != null)
                            {
                                if (worksheet.Cells != null && worksheet.Cells.End != null)
                                {
                                    int maxRowCount = worksheet.Cells.End.Row + 1;

                                    if (maxRowCount > 0)
                                    {
                                        #region GetImportItem

                                        //Danh sách data những đối tượng khóa ngoại của đổi tượng cần import
                                        Dictionary<Type, IList> listParentObject = new Dictionary<Type, IList>();

                                        var listImportItem = unitOfWork.CreateQueryable<Cat_ImportItem>(Guid.Empty, d => d.ImportID == ImportTemplateID
                                                && (d.ExcelField != null || (d.IsDefaultValue.HasValue && d.IsDefaultValue.Value))
                                                && d.IsDelete == null).Select(d => new
                                                {
                                                    d.ChildFieldLevel1,
                                                    d.ChildFieldLevel2,
                                                    d.ExcelField,
                                                    d.AllowNull,
                                                    d.AllowDuplicate,
                                                    d.DuplicateGroup,
                                                    d.IsDefaultValue,
                                                    d.DefaultValue
                                                }).OrderBy(d => d.ExcelField).ToList();

                                        #region DynamicType

                                        var typeBuilder = new DynamicTypeBuilder(string.Empty);
                                        List<string> listFieldName = new List<string>();

                                        foreach (var importItem in listImportItem)
                                        {
                                            string childFieldLevel1 = importItem.ChildFieldLevel1.TrimAll();
                                            string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                            PropertyInfo propertyType = objectType.GetProperty(childFieldLevel1);

                                            if (propertyType != null)
                                            {
                                                if (unitOfWork.IsMetadataType(propertyType.PropertyType))
                                                {
                                                    propertyType = propertyType.PropertyType.GetProperty(childFieldLevel2);
                                                    string importFieldName = unitOfWork.GetFieldConstraint(objectType, childFieldLevel1);
                                                    string valueField = importFieldName + "_" + childFieldLevel2;

                                                    if (!listFieldName.Contains(importFieldName))
                                                    {
                                                        typeBuilder.AddProperty(importFieldName, objectType.GetPropertyType(importFieldName));
                                                        listFieldName.Add(importFieldName);
                                                    }

                                                    if (!listFieldName.Contains(valueField))
                                                    {
                                                        typeBuilder.AddProperty(valueField, propertyType.PropertyType);
                                                        listFieldName.Add(valueField);
                                                    }

                                                    if (!ListValueField.Contains(valueField))
                                                    {
                                                        ListValueField.Add(valueField);
                                                    }
                                                }
                                                else
                                                {
                                                    string valueField = childFieldLevel1;

                                                    if (!listFieldName.Contains(valueField))
                                                    {
                                                        typeBuilder.AddProperty(valueField, propertyType.PropertyType);
                                                        listFieldName.Add(valueField);
                                                    }

                                                    if (!ListValueField.Contains(valueField))
                                                    {
                                                        ListValueField.Add(valueField);
                                                    }
                                                }

                                                string displayField = childFieldLevel2;
                                                if (string.IsNullOrWhiteSpace(displayField))
                                                {
                                                    displayField = childFieldLevel1;
                                                }

                                                if (!ListDisplayField.Contains(displayField))
                                                {
                                                    ListDisplayField.Add(displayField);
                                                }
                                            }
                                        }

                                        if (!typeBuilder.HasProperty(Constant.ID))
                                        {
                                            //thêm thuộc tính ID để làm key cho dữ liệu
                                            typeBuilder.AddProperty(Constant.ID, typeof(Guid));
                                        }
                                        if (!typeBuilder.HasProperty(Constant.RowIndex))
                                        {
                                            //thêm thuộc tính RowIndex để xác định vị trí trên excel
                                            typeBuilder.AddProperty(Constant.RowIndex, typeof(int));
                                        }

                                        if (!typeBuilder.HasProperty(Constant.ObjectType))
                                        {
                                            //thêm thuộc tính RowIndex để xác định vị trí trên excel
                                            typeBuilder.AddProperty(Constant.ObjectType, typeof(Type));
                                        }

                                        if (!typeBuilder.HasProperty(Constant.Checking))
                                        {
                                            //thêm thuộc tính ID để làm key cho dữ liệu
                                            typeBuilder.AddProperty(Constant.Checking, typeof(string));
                                        }

                                        //Dynamic type dùng để nhận giá trị từ excel file
                                        importObjectType = typeBuilder.BuildType();

                                        listInvalidData = new List<InvalidImportData>();
                                        IList listAllData = importObjectType.CreateList();
                                        listImportData = importObjectType.CreateList();

                                        #endregion

                                        #endregion

                                        #region GetExcelData

                                        for (int i = (int)startRowIndex; i <= maxRowCount; i = i + 1 + skipRowNumber)
                                        {
                                            object importData = importObjectType.CreateInstance();
                                            importData.SetPropertyValue(Constant.ObjectType, objectType);
                                            importData.SetPropertyValue(Constant.RowIndex, i);

                                            bool isRowInvalidData = false;
                                            bool hasValue = false;

                                            foreach (var importItem in listImportItem)
                                            {
                                                #region CheckDataType

                                                string childFieldLevel1 = importItem.ChildFieldLevel1.TrimAll();
                                                string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();

                                                InvalidDataType invalidDataType = InvalidDataType.None;
                                                bool isInvalidData = false;

                                                PropertyInfo propertyLevel1 = objectType.GetProperty(childFieldLevel1);
                                                PropertyInfo propertyLevel2 = null;

                                                string importFieldName = childFieldLevel1;
                                                Type importFieldType = null;

                                                //Nếu có hai thuộc tính cấp một giống nhau thì có nghĩa là 2 thuộc tính cấp 2 của nó sẽ làm key
                                                var listSameObject = listImportItem.Where(d => d.ChildFieldLevel1.TrimAll() == childFieldLevel1 &&
                                                    d.ExcelField != importItem.ExcelField && !string.IsNullOrWhiteSpace(d.ChildFieldLevel2.TrimAll())
                                                    && d.ChildFieldLevel2.TrimAll() != childFieldLevel2).ToList();

                                                if (propertyLevel1 != null)
                                                {
                                                    importFieldType = propertyLevel1.PropertyType;

                                                    if (unitOfWork.IsMetadataType(propertyLevel1.PropertyType))
                                                    {
                                                        propertyLevel2 = propertyLevel1.PropertyType.GetProperty(childFieldLevel2);
                                                        importFieldName = unitOfWork.GetFieldConstraint(objectType, childFieldLevel1);
                                                        importFieldType = objectType.GetPropertyType(importFieldName);

                                                        if (i == startRowIndex)
                                                        {
                                                            List<string> listField = new List<string>();
                                                            listField.Add(Constant.ID);//Luôn lấy cột ID
                                                            listField.Add(childFieldLevel2);

                                                            foreach (var sameItem in listSameObject)
                                                            {
                                                                if (!listField.Contains(sameItem.ChildFieldLevel2.TrimAll()))
                                                                {
                                                                    listField.Add(sameItem.ChildFieldLevel2.TrimAll());
                                                                }
                                                            }

                                                            if (propertyLevel1.PropertyType == objectType)
                                                            {
                                                                foreach (var sameItem in listImportItem.Where(d => !d.AllowDuplicate))
                                                                {
                                                                    string duplicateField = sameItem.ChildFieldLevel1.TrimAll();

                                                                    if (!string.IsNullOrWhiteSpace(sameItem.ChildFieldLevel2))
                                                                    {
                                                                        duplicateField = unitOfWork.GetFieldConstraint(objectType, duplicateField);
                                                                    }

                                                                    if (!listField.Contains(duplicateField))
                                                                    {
                                                                        listField.Add(duplicateField);
                                                                    }
                                                                }
                                                            }

                                                            if (!listParentObject.ContainsKey(propertyLevel1.PropertyType))
                                                            {
                                                                listParentObject.Add(propertyLevel1.PropertyType, unitOfWork.CreateQueryable(Guid.Empty,
                                                                    propertyLevel1.PropertyType, string.Empty).SelectFields(null, listField.ToArray()).GetList());
                                                            }
                                                        }
                                                    }
                                                }

                                                #endregion

                                                #region GetFieldData

                                                object excelValue = null;
                                                string excelAddress = string.Empty;

                                                if (importItem.IsDefaultValue.GetBoolean())
                                                {
                                                    excelValue = importItem.DefaultValue;
                                                }
                                                else
                                                {
                                                    excelAddress = importItem.ExcelField + i;
                                                    var excelRange = worksheet.Cells[excelAddress];
                                                    excelValue = excelRange.Value;

                                                    if (!string.IsNullOrWhiteSpace(excelValue.GetString()))
                                                    {
                                                        hasValue = true;//có dữ liệu ở một cell bất kỳ
                                                    }

                                                    string defaultValueField = childFieldLevel1;

                                                    if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                    {
                                                        defaultValueField += "." + childFieldLevel2;
                                                    }

                                                    if (DefaultValues.ContainsKey(defaultValueField))
                                                    {
                                                        excelValue = DefaultValues[defaultValueField];
                                                    }
                                                }

                                                object value = excelValue;

                                                if (propertyLevel2 != null && propertyLevel2.PropertyType != null)
                                                {
                                                    if (listParentObject.ContainsKey(propertyLevel1.PropertyType))
                                                    {
                                                        IQueryable objectQueryable = null;

                                                        if (propertyLevel2.PropertyType == typeof(string))
                                                        {
                                                            objectQueryable = listParentObject[propertyLevel1.PropertyType].AsQueryable().Where(childFieldLevel2 + " != null && "
                                                                + childFieldLevel2 + ".ToString().Trim().ToLower() = @0", value.GetString().Trim().ToLower());
                                                        }
                                                        else
                                                        {
                                                            objectQueryable = listParentObject[propertyLevel1.PropertyType].AsQueryable()
                                                                .Where(childFieldLevel2 + "=@0", value.TryGetValue(propertyLevel2.PropertyType));
                                                        }

                                                        if (listSameObject != null && listSameObject.Count() > 0)
                                                        {
                                                            foreach (var sameItem in listSameObject)
                                                            {
                                                                string sameExcelAddress = sameItem.ExcelField + i;
                                                                var sameExcelRange = worksheet.Cells[sameExcelAddress];
                                                                object sameValue = sameExcelRange.Value;

                                                                string sameChildFieldLevel2 = sameItem.ChildFieldLevel2.TrimAll();
                                                                Type samePropertyType2 = propertyLevel1.PropertyType.GetPropertyType(sameChildFieldLevel2);

                                                                if (propertyLevel2.PropertyType == typeof(string))
                                                                {
                                                                    objectQueryable = objectQueryable.Where(sameChildFieldLevel2 + " != null && " + sameChildFieldLevel2
                                                                        + ".ToString().Trim().ToLower() = @0", sameValue.GetString().Trim().ToLower());
                                                                }
                                                                else
                                                                {
                                                                    objectQueryable = objectQueryable.Where(sameChildFieldLevel2 + "=@0", sameValue.TryGetValue(samePropertyType2));
                                                                }
                                                            }
                                                        }

                                                        value = objectQueryable.Select(Constant.ID).FirstOrDefault();

                                                        if (value.IsNullOrEmpty() || value.GetString() == Guid.Empty.ToString())
                                                        {
                                                            if (!string.IsNullOrWhiteSpace(excelValue.GetString()) || !importItem.AllowNull)
                                                            {
                                                                invalidDataType = InvalidDataType.ReferenceNotFound;
                                                                isInvalidData = true;
                                                            }
                                                        }
                                                    }
                                                }

                                                #endregion

                                                #region CheckInvalid

                                                if (!isInvalidData)
                                                {
                                                    if (!value.IsNullOrEmpty())
                                                    {
                                                        if (importFieldType.IsDateTime())
                                                        {
                                                            if (!value.IsTypeOf(typeof(DateTime)))
                                                            {
                                                                DateTime currentValue = DateTime.Now;

                                                                if (DateTime.TryParseExact(value.GetString(), DateTimeFormat,
                                                                   CultureInfo.GetCultureInfo("vi-vn"), DateTimeStyles.None,
                                                                    out currentValue))
                                                                {
                                                                    value = currentValue;
                                                                }
                                                                else
                                                                {
                                                                    object dateValue = value.TryGetValue(importFieldType, out isInvalidData);

                                                                    if (isInvalidData)
                                                                    {
                                                                        dateValue = value.TryGetValue(typeof(double),
                                                                            out isInvalidData);

                                                                        if (!isInvalidData)
                                                                        {
                                                                            value = DateTime.FromOADate(dateValue.TryGetValue<double>());
                                                                        }
                                                                    }
                                                                    else
                                                                    {
                                                                        value = dateValue;
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            value = value.TryGetValue(importFieldType, out isInvalidData);

                                                            if (isInvalidData)
                                                            {
                                                                invalidDataType = InvalidDataType.InvalidFormat;
                                                            }
                                                            else if (!string.IsNullOrWhiteSpace(value.GetString()) && importFieldType == typeof(string))
                                                            {
                                                                //value = value.GetString().Replace("<", string.Empty).Replace("lt;", string.Empty).Replace(">", string.Empty)
                                                                //    .Replace("gt;", string.Empty).Replace("{", string.Empty).Replace("}", string.Empty).Replace("\"", string.Empty)
                                                                //    .Replace("'", string.Empty).Replace("amp;", string.Empty).Replace("quot;", string.Empty)
                                                                //    .Replace("#x27;", string.Empty).Replace("#x2F;", string.Empty).Replace("&", string.Empty);

                                                                string checkField = propertyLevel2 != null ? propertyLevel2.Name : propertyLevel1.Name;
                                                                Type checkType = propertyLevel2 != null ? propertyLevel1.PropertyType : objectType;

                                                                if (value.GetString().Length > unitOfWork.GetMaxLength(checkType, checkField))
                                                                {
                                                                    invalidDataType = InvalidDataType.TruncateData;
                                                                    isInvalidData = true;
                                                                }
                                                            }
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (!importItem.AllowNull)
                                                        {
                                                            invalidDataType = InvalidDataType.NullData;
                                                            isInvalidData = true;
                                                        }
                                                    }
                                                }

                                                if (childFieldLevel1 == Constant.Checking)
                                                {
                                                    if (!unitOfWork.IsMetadataField(objectType, Constant.Checking))
                                                    {
                                                        if (!string.IsNullOrWhiteSpace(excelValue.GetString()))
                                                        {
                                                            invalidDataType = InvalidDataType.Custom;
                                                            isInvalidData = true;
                                                        }
                                                    }
                                                }

                                                importData.SetPropertyValue(importFieldName + "_"
                                                    + childFieldLevel2, excelValue.GetString());

                                                if (isInvalidData)
                                                {
                                                    isRowInvalidData = true;//1 cell lỗi là cả row lỗi
                                                    InvalidImportData invalidData = new InvalidImportData();

                                                    if (invalidDataType == InvalidDataType.Custom)
                                                    {
                                                        invalidData.Desciption = excelValue.GetString();
                                                    }
                                                    else
                                                    {
                                                        invalidData.Desciption = invalidDataType.ToString().TranslateString();
                                                        invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                        invalidData.ValueType = importFieldType.Name;
                                                        invalidData.ExcelValue = excelValue;
                                                    }

                                                    invalidData.ExcelField = excelAddress;
                                                    invalidData.ImportData = importData;
                                                    invalidData.Type = invalidDataType;
                                                    listInvalidData.Add(invalidData);
                                                }
                                                else
                                                {
                                                    importData.SetPropertyValue(importFieldName,
                                                        value.TryGetValue(importFieldType));
                                                }

                                                #endregion
                                            }

                                            if (!isRowInvalidData && hasValue)
                                            {
                                                listAllData.Add(importData);
                                            }
                                            else if (!hasValue)
                                            {
                                                listInvalidData = listInvalidData.Where(d =>
                                                    d.ImportData != importData).ToList();
                                            }

                                            if (ProgressChanged != null)
                                            {
                                                double percent = ((double)i / (double)(maxRowCount + (int)startRowIndex)) * 100;
                                                ProgressChanged(new ProgressEventArgs
                                                {
                                                    ID = UserID,
                                                    Name = "ReadData",
                                                    Value = "ReadData".TranslateString(),
                                                    Percent = (int)percent
                                                });
                                            }
                                        }

                                        #endregion

                                        #region CheckDuplicate

                                        if (listAllData != null && listAllData.Count > 0)
                                        {
                                            var listImportItemDuplicate = listImportItem.Where(d =>
                                                !d.AllowDuplicate).ToList();

                                            var listDuplicateGroup = listImportItemDuplicate.GroupBy(d =>
                                                d.DuplicateGroup).ToList();

                                            if (listDuplicateGroup.Count() > 0)
                                            {
                                                var listDuplicateByType = listImportItemDuplicate.Where(d => unitOfWork.IsMetadataType(objectType.GetPropertyType(d.ChildFieldLevel1.TrimAll()))).ToList();
                                                var listFields = listDuplicateByType.Select(d => unitOfWork.GetFieldConstraint(objectType, d.ChildFieldLevel1.TrimAll())).ToList();
                                                listFields.AddRange(listImportItemDuplicate.Where(d => !listDuplicateByType.Contains(d)).Select(d => d.ChildFieldLevel1.TrimAll()));
                                                listFields = listFields.Where(d => !string.IsNullOrWhiteSpace(d)).ToList();

                                                if (listFields.Count() > 0 && !listParentObject.ContainsKey(objectType))
                                                {
                                                    if (!listFields.Contains(Constant.ID))
                                                    {
                                                        listFields.Add(Constant.ID);
                                                    }

                                                    listParentObject.Add(objectType, unitOfWork.CreateQueryable(Guid.Empty,
                                                        objectType, string.Empty).SelectFields(null, listFields.Distinct().ToArray()).GetList());
                                                }

                                                foreach (var importData in listAllData)
                                                {
                                                    foreach (var itemDuplicate in listDuplicateGroup)
                                                    {
                                                        #region CheckData

                                                        Dictionary<string, object> listExcelValue = new Dictionary<string, object>();
                                                        Dictionary<string, string> listCheckField = new Dictionary<string, string>();

                                                        IQueryable dbQueryable = null;
                                                        IQueryable fileQueryable1 = null;
                                                        IQueryable fileQueryable2 = null;

                                                        bool isDuplicateFile = false;
                                                        bool isDuplicateDb = false;

                                                        foreach (var importItem in itemDuplicate)
                                                        {
                                                            string checkField = importItem.ChildFieldLevel1.TrimAll();
                                                            string templateField = checkField;

                                                            if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                            {
                                                                checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                templateField = checkField + "_" + importItem.ChildFieldLevel2.TrimAll();
                                                            }

                                                            if (dbQueryable == null && listParentObject.ContainsKey(objectType))
                                                            {
                                                                dbQueryable = listParentObject[objectType].AsQueryable();
                                                            }

                                                            if (fileQueryable1 == null)
                                                            {
                                                                fileQueryable1 = listAllData.AsQueryable().Where("it!=@0", importData);
                                                            }

                                                            if (fileQueryable2 == null)
                                                            {
                                                                fileQueryable2 = listInvalidData.Where(d => d.ImportData != null
                                                                    && d.ImportData != importData).Select(d => d.ImportData).AsQueryable();
                                                            }

                                                            if (!string.IsNullOrWhiteSpace(checkField))
                                                            {
                                                                Type checkFieldType = importData.GetRealPropertyType(checkField);
                                                                listCheckField.Add(checkField, templateField);

                                                                if (dbQueryable != null)
                                                                {
                                                                    if (checkFieldType == typeof(string))
                                                                    {
                                                                        dbQueryable = dbQueryable.Where(checkField + " != null && " + checkField + ".ToString().Trim().ToLower() = @0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType).GetString().Trim().ToLower());
                                                                    }
                                                                    else
                                                                    {
                                                                        dbQueryable = dbQueryable.Where(checkField + "=@0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType));
                                                                    }
                                                                }

                                                                if (fileQueryable1 != null)
                                                                {
                                                                    if (checkFieldType == typeof(string))
                                                                    {
                                                                        fileQueryable1 = fileQueryable1.Where(checkField + " != null && " + checkField + ".ToString().Trim().ToLower() = @0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType).GetString().Trim().ToLower());
                                                                    }
                                                                    else
                                                                    {
                                                                        fileQueryable1 = fileQueryable1.Where(checkField + "=@0",
                                                                            importData.GetPropertyValue(checkField).TryGetValue(checkFieldType));
                                                                    }
                                                                }

                                                                if (fileQueryable2 != null)
                                                                {
                                                                    fileQueryable2 = fileQueryable2.OfType<object>().Where(d =>
                                                                        d.GetPropertyValue(checkField) == importData.GetPropertyValue(checkField));
                                                                }
                                                            }
                                                        }

                                                        if (dbQueryable != null)
                                                        {
                                                            object selectedID = dbQueryable.Select(Constant.ID).FirstOrDefault();
                                                            if (selectedID != null && selectedID.ToString() != Guid.Empty.ToString())
                                                            {
                                                                isDuplicateDb = true;//dữ liệu import bị trùng với database.
                                                                importData.SetPropertyValue(Constant.ID, selectedID);

                                                                if (listCheckField != null && listCheckField.Count() > 0)
                                                                {
                                                                    foreach (var checkField in listCheckField)
                                                                    {
                                                                        var excelValue = importData.GetPropertyValue(checkField.Value);

                                                                        if (!listExcelValue.ContainsKey(checkField.Value))
                                                                        {
                                                                            listExcelValue.Add(checkField.Value, excelValue);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        if (fileQueryable1 != null && fileQueryable1.Any())
                                                        {
                                                            isDuplicateFile = true;//dữ liệu bị trùng với file.

                                                            if (listCheckField != null && listCheckField.Count() > 0)
                                                            {
                                                                foreach (var checkField in listCheckField)
                                                                {
                                                                    var excelValue = fileQueryable1.Select(checkField.Value).FirstOrDefault();

                                                                    if (!listExcelValue.ContainsKey(checkField.Value))
                                                                    {
                                                                        listExcelValue.Add(checkField.Value, excelValue);
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        if (fileQueryable2 != null && fileQueryable2.Any())
                                                        {
                                                            isDuplicateFile = true;//dữ liệu bị trùng với file.

                                                            if (listCheckField != null && listCheckField.Count() > 0)
                                                            {
                                                                foreach (var checkField in listCheckField)
                                                                {
                                                                    var excelValue = fileQueryable2.OfType<object>().Select(d =>
                                                                        d.GetPropertyValue(checkField.Value)).FirstOrDefault();

                                                                    if (!listExcelValue.ContainsKey(checkField.Value))
                                                                    {
                                                                        listExcelValue.Add(checkField.Value, excelValue);
                                                                    }
                                                                }
                                                            }
                                                        }

                                                        #endregion

                                                        #region ProcessData

                                                        if (isDuplicateDb || isDuplicateFile)
                                                        {
                                                            if (ImportMode == ImportDataMode.Update
                                                                || ImportMode == ImportDataMode.Skip)
                                                            {
                                                                if (isDuplicateDb)
                                                                {
                                                                    if (!listImportData.Contains(importData))
                                                                    {
                                                                        //Cập nhật dữ liệu vào database
                                                                        listImportData.Add(importData);
                                                                    }
                                                                }
                                                                else
                                                                {
                                                                    foreach (var importItem in itemDuplicate)
                                                                    {
                                                                        InvalidImportData invalidData = new InvalidImportData();
                                                                        object row = importData.GetPropertyValue(Constant.RowIndex);
                                                                        invalidData.ExcelField = importItem.ExcelField + row.GetString();
                                                                        invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                                        string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                                                        string checkField = importItem.ChildFieldLevel1.TrimAll();

                                                                        if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                                        {
                                                                            checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                            checkField = checkField + "_" + childFieldLevel2;
                                                                        }

                                                                        if (listExcelValue.ContainsKey(checkField))
                                                                        {
                                                                            invalidData.ExcelValue = listExcelValue[checkField];
                                                                        }

                                                                        if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                                        {
                                                                            invalidData.DataField += "." + childFieldLevel2.TranslateString();
                                                                        }

                                                                        invalidData.Type = InvalidDataType.DataNotFound;//không tìm thấy
                                                                        invalidData.Desciption = invalidData.Type.ToString().TranslateString();
                                                                        invalidData.ImportData = importData;
                                                                        listInvalidData.Add(invalidData);

                                                                        if (listImportData.Contains(importData))
                                                                        {
                                                                            listImportData.Remove(importData);
                                                                        }
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                foreach (var importItem in itemDuplicate)
                                                                {
                                                                    InvalidImportData invalidData = new InvalidImportData();
                                                                    object row = importData.GetPropertyValue(Constant.RowIndex);
                                                                    invalidData.ExcelField = importItem.ExcelField + row.GetString();
                                                                    invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                                    string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                                                    string checkField = importItem.ChildFieldLevel1.TrimAll();

                                                                    if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                                    {
                                                                        checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                        checkField = checkField + "_" + childFieldLevel2;
                                                                    }

                                                                    if (listExcelValue.ContainsKey(checkField))
                                                                    {
                                                                        invalidData.ExcelValue = listExcelValue[checkField];
                                                                    }

                                                                    if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                                    {
                                                                        invalidData.DataField += "." + childFieldLevel2.TranslateString();
                                                                    }

                                                                    if (isDuplicateDb && isDuplicateFile)
                                                                    {
                                                                        invalidData.Type = InvalidDataType.Duplicate;
                                                                    }
                                                                    else if (isDuplicateDb)
                                                                    {
                                                                        invalidData.Type = InvalidDataType.DuplicateInDb;
                                                                    }
                                                                    else if (isDuplicateFile)
                                                                    {
                                                                        invalidData.Type = InvalidDataType.DuplicateInFile;
                                                                    }

                                                                    invalidData.Desciption = invalidData.Type.ToString().TranslateString();
                                                                    invalidData.ImportData = importData;
                                                                    listInvalidData.Add(invalidData);

                                                                    if (listImportData.Contains(importData))
                                                                    {
                                                                        listImportData.Remove(importData);
                                                                    }
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            if (ImportMode == ImportDataMode.Update)
                                                            {
                                                                foreach (var importItem in itemDuplicate)
                                                                {
                                                                    InvalidImportData invalidData = new InvalidImportData();
                                                                    object row = importData.GetPropertyValue(Constant.RowIndex);
                                                                    invalidData.ExcelField = importItem.ExcelField + row.GetString();
                                                                    invalidData.DataField = importItem.ChildFieldLevel1.TrimAll().TranslateString();
                                                                    string childFieldLevel2 = importItem.ChildFieldLevel2.TrimAll();
                                                                    string checkField = importItem.ChildFieldLevel1.TrimAll();

                                                                    if (unitOfWork.IsMetadataType(objectType.GetPropertyType(checkField)))
                                                                    {
                                                                        checkField = unitOfWork.GetFieldConstraint(objectType, checkField);
                                                                        checkField = checkField + "_" + childFieldLevel2;
                                                                    }

                                                                    if (listExcelValue.ContainsKey(checkField))
                                                                    {
                                                                        invalidData.ExcelValue = listExcelValue[checkField];
                                                                    }

                                                                    if (!string.IsNullOrWhiteSpace(childFieldLevel2))
                                                                    {
                                                                        invalidData.DataField += "." + childFieldLevel2.TranslateString();
                                                                    }

                                                                    invalidData.Type = InvalidDataType.DataNotFound;//không tìm thấy
                                                                    invalidData.Desciption = invalidData.Type.ToString().TranslateString();
                                                                    invalidData.ImportData = importData;
                                                                    listInvalidData.Add(invalidData);

                                                                    if (listImportData.Contains(importData))
                                                                    {
                                                                        listImportData.Remove(importData);
                                                                    }
                                                                }
                                                            }
                                                            else if (!listImportData.Contains(importData) &&
                                                                !listInvalidData.Any(d => d.ImportData == importData))
                                                            {
                                                                listImportData.Add(importData);
                                                            }
                                                        }

                                                        #endregion
                                                    }

                                                    if (ProgressChanged != null)
                                                    {
                                                        double percent = ((double)listAllData.IndexOf(importData) / (double)listAllData.Count) * 100;
                                                        ProgressChanged(new ProgressEventArgs
                                                        {
                                                            ID = UserID,
                                                            Name = "CheckDuplicate",
                                                            Value = "CheckDuplicate".TranslateString(),
                                                            Percent = (int)percent
                                                        });
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                listImportData = listAllData;
                                            }
                                        }

                                        #endregion
                                    }
                                }
                            }
                            #endregion

                            #region ImportCompleted

                            if (ProgressChanged != null)
                            {
                                ProgressChanged(new ProgressEventArgs
                                {
                                    ID = UserID,
                                    Name = "ReadData",
                                    Value = "ReadData".TranslateString(),
                                    Percent = 100
                                });
                            }

                            #endregion
                        }
                    }
                }
            }
        }