void EnsureMapper(TypeAccessor typeAccessor)
		{
			if (_typeAccessor != typeAccessor)
			{
				_typeAccessor       = typeAccessor;
				_mapFieldAttributes = null;
			}
		}
		protected object[] GetMapFieldAttributes(TypeAccessor typeAccessor)
		{
			lock (_sync)
			{
				EnsureMapper(typeAccessor);

				return _mapFieldAttributes ?? (_mapFieldAttributes = TypeHelper.GetAttributes(typeAccessor.Type, typeof (MapFieldAttribute)));
			}
		}
				public object CreateInstance(TypeAccessor typeAccessor, InitContext context)
				{
					int id = context.DataSource.GetInt32(context.SourceObject,
						context.DataSource.GetOrdinal("PersonId"));
					
					context.ObjectMapper = context.MappingSchema.GetObjectMapper(Factory.GetType(id));

					return context.ObjectMapper.TypeAccessor.CreateInstance(context);
				}
		object[] GetNonUpdatableAttributes(TypeAccessor typeAccessor)
		{
			lock (_sync)
			{
				EnsureMapper(typeAccessor);

				return _nonUpdatableAttributes ?? (_nonUpdatableAttributes = TypeHelper.GetAttributes(typeAccessor.Type, typeof(NonUpdatableAttribute)));
			}
		}
        /// <summary>
        /// Initializes a new instance of the <see cref="DynamicProxy"/> class.
        /// </summary>
        /// <param name="wrapped">The wrapped object.</param>
        /// <param name="safeMode">if set to <c>true</c>, return null when name not found.</param>
        public DynamicProxy(object wrapped, bool safeMode)
        {
            if (wrapped == null)
                throw new ArgumentNullException("wrapped");

            _wrapped = wrapped;
            SafeMode = safeMode;

            Type type = _wrapped.GetType();
            _typeAccessor = TypeAccessor.GetAccessor(type);
        }
Example #6
0
        public object Get(INXmlElementReader nodeReader)
        {
            var typeName = nodeReader.Attributes.Get("type");
            var type = typeFinder.GetType(typeName);

            var typeAccessor = new TypeAccessor(type.GetTargetType(), docObjectRepository);
            var instance = typeAccessor.GetInstance();
            readObjects.Add(nodeReader.Attributes.GetInteger("ID"), instance);

            ((IBaseTypeMembersReader) this).ReadMembers(instance, nodeReader, type);

            return instance;
        }
Example #7
0
				public object /*[a]*/CreateInstance(TypeAccessor typeAccessor, InitContext context)/*[/a]*/
				{
					// Get the object type indicator field.
					//
					object objectType = context.DataSource.GetValue(context.SourceObject, "PersonType");

					// Target ObjectMapper must be changed in order to provide correct mapping.
					//
					switch ((string)objectType)
					{
						case "D": /*[a]*/context.ObjectMapper = ObjectMapper<Doctor>. Instance;/*[/a]*/ break;
						case "P": /*[a]*/context.ObjectMapper = ObjectMapper<Patient>.Instance;/*[/a]*/ break;
					}

					// Create an object instance.
					// Do not call ObjectMapper.CreateInstance as it will lead to infinite recursion.
					//
					return context.ObjectMapper./*[a]*/TypeAccessor/*[/a]*/.CreateInstance(context);
				}
Example #8
0
        public void Write(object owningObject, ISerialiserNode parentNode, Type type)
        {
            var typeAccessor = new TypeAccessor(type, null);

            var memberInfos = typeAccessor.GetMembers();
            foreach (var memberInfo in memberInfos)
            {
                if (memberInfo.GetCustomAttributes(typeof (NSerializerIgnoreAttribute), false).Length != 1)
                {
                    foreach (var writer in writers)
                    {
                        if (writer.CanWrite(owningObject, memberInfo))
                        {
                            writer.Write(owningObject, parentNode, memberInfo);
                            break;
                        }
                    }
                }
            }
        }
				public object CreateInstance(TypeAccessor typeAccessor, InitContext context)
				{
					Type t = typeAccessor.Type;

					ConstructorInfo[] ctis = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					ConstructorInfo   constructor = ctis[0];

					foreach (ConstructorInfo ci in ctis)
					{
						if (constructor.GetParameters().Length < ci.GetParameters().Length)
							constructor = ci;
					}
					
					ParameterInfo[] pis   = constructor.GetParameters();
					object[]        param = new object[pis.Length];

					for(int i = 0; i < pis.Length; i++)
					{
						ParameterInfo pi      = pis[i];
						Type          pType   = pi.ParameterType;
						string        pName   = pi.Name;
						int           ordinal = context.DataSource.GetOrdinal(pName);

						if (ordinal >= 0)
						{
							param[i] = context.MappingSchema.ConvertChangeType(
								context.DataSource.GetValue(context.SourceObject, ordinal),
								pType);
						}
						else
							param[i] = context.MappingSchema.GetDefaultValue(pType);
					}

					context.StopMapping = true;

					return constructor.Invoke(param);

				}
Example #10
0
        private static void RegisterDto(ContainerBuilder containerBuilder)
        {
            containerBuilder.Register(c => c.Resolve <IEnumerable <IDao <IDto> > >().OfType <IDao <II18NDto> >().ToDictionary(
                                          x => x.GetType().GetGenericArguments()[1], y => y.LoadAll().GroupBy(x => x !.Key ?? "")
                                          .ToDictionary(x => x.Key,
                                                        x => x.ToList().ToDictionary(o => o !.RegionType, o => o !))))
            .AsImplementedInterfaces()
            .SingleInstance()
            .AutoActivate();

            var registerDatabaseObject = typeof(Startup).GetMethod(nameof(RegisterDatabaseObject));
            var assemblyDto            = typeof(IStaticDto).Assembly.GetTypes();
            var assemblyDb             = typeof(Account).Assembly.GetTypes();

            assemblyDto.Where(p =>
                              typeof(IDto).IsAssignableFrom(p) &&
                              (!p.Name.Contains("InstanceDto") || p.Name.Contains("Inventory")) && p.IsClass)
            .ToList()
            .ForEach(t =>
            {
                var type = assemblyDb.First(tgo =>
                                            string.Compare(t.Name, $"{tgo.Name}Dto", StringComparison.OrdinalIgnoreCase) == 0);
                var typepk = type.GetProperties()
                             .Where(s => new NosCoreContext(new DbContextOptionsBuilder <NosCoreContext>().UseInMemoryDatabase(
                                                                Guid.NewGuid().ToString()).Options).Model.FindEntityType(type)
                                    .FindPrimaryKey().Properties.Select(x => x.Name)
                                    .Contains(s.Name)
                                    ).ToArray()[0];
                registerDatabaseObject?.MakeGenericMethod(t, type, typepk !.PropertyType)
                .Invoke(null, new object?[] { containerBuilder });
            });


            containerBuilder.RegisterType <Dao <ItemInstance, IItemInstanceDto?, Guid> >().As <IDao <IItemInstanceDto?, Guid> >().SingleInstance();

            containerBuilder.Register(c =>
            {
                var dic   = c.Resolve <IDictionary <Type, Dictionary <string, Dictionary <RegionType, II18NDto> > > >();
                var items = c.Resolve <IDao <ItemDto, short> >().LoadAll().ToList();
                var props = StaticDtoExtension.GetI18NProperties(typeof(ItemDto));

                var regions   = Enum.GetValues(typeof(RegionType));
                var accessors = TypeAccessor.Create(typeof(ItemDto));
                Parallel.ForEach(items, s => s.InjectI18N(props, dic, regions, accessors));
                var staticMetaDataAttribute = typeof(ItemDto).GetCustomAttribute <StaticMetaDataAttribute>();
                if ((items.Count != 0) || (staticMetaDataAttribute == null) ||
                    (staticMetaDataAttribute.EmptyMessage == LogLanguageKey.UNKNOWN))
                {
                    if ((items.Count != 0) && (staticMetaDataAttribute != null))
                    {
                        c.Resolve <ILogger>().Information(
                            LogLanguage.Instance.GetMessageFromKey(staticMetaDataAttribute.LoadedMessage),
                            items.Count);
                    }
                }
                else
                {
                    c.Resolve <ILogger>()
                    .Error(LogLanguage.Instance.GetMessageFromKey(staticMetaDataAttribute.EmptyMessage));
                }

                return(items);
            })
            .As <List <ItemDto> >()
            .SingleInstance()
            .AutoActivate();
        }
Example #11
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ClassMapping"/> class.
 /// </summary>
 /// <param name="typeAccessor">The type accessor.</param>
 public ClassMapping(TypeAccessor typeAccessor) : this()
 {
     TypeAccessor = typeAccessor;
 }
 public override void EnsureMapper(TypeAccessor typeAccessor, MappingSchema mappingSchema, EnsureMapperHandler handler)
 {
     base.EnsureMapper(typeAccessor, mappingSchema, handler);
 }
 private static TypeAccessor GetAccessor(Type type)
 {
     return(Accessors.GetOrAdd(type, TypeAccessor.Create(type)));
 }
Example #14
0
 string FormatObject(object obj, MemberSet members, TypeAccessor accessor)
 {
     return($"{{ {string.Join(", ", members.Select(m => $"{m.Name} = {FormatValue(accessor[obj, m.Name], null)}"))} }}");
 }
        private async Task QueryAndPopulateEdgeConnections(
            List <SelectValue> selections,
            List <object> results,
            IGraphRequestContext graphRequestContext,
            List <ConnectionEdgeDestinationFilter> connectionEdgeDestinationFilters,
            QueryExecutionContext queryExecutionContext)
        {
            var edgeQueryParameters = _connectionEdgeResolver.ListConnectionEdgeQueryParameter(results)
                                      .Where(x => selections.Any(y => y.FieldName.ToLower() == x.SourceFieldName.ToLower())).ToList();

            if (edgeQueryParameters.Count > 0)
            {
                var connectionEdges = (await GetConnectionEdgeRepository().QueryAsync <ConnectionEdge>(
                                           ConnectionEdgeQueryName,
                                           edgeQueryParameters.ToQueryParameters(), null, graphRequestContext)).ToList();

                if (connectionEdges.Count > 0)
                {
                    var accessor   = TypeAccessor.Create(results.First().GetType());
                    var dictionary = new Dictionary <string, object>();
                    results.ForEach(item => dictionary.Add(accessor.GetKey(item), item));

                    foreach (var connectionEdge in connectionEdges)
                    {
                        if (!dictionary.ContainsKey(connectionEdge.SourceId))
                        {
                            throw new InvalidOperationException($"{connectionEdge.SourceId} is invalid.");
                        }

                        var sourceObject = dictionary[connectionEdge.SourceId];

                        var edgeObject = DeserializeObject(connectionEdge.MetaValue, connectionEdge.MetaType);

                        var member = accessor.GetMembers().Single(x => x.Name == connectionEdge.SourceFieldName);
                        if (member.IsList())
                        {
                            member.CreateNewListIfNullThenAddItemToList(accessor, sourceObject, edgeObject);
                        }
                        else
                        {
                            accessor[sourceObject, connectionEdge.SourceFieldName] = edgeObject;
                        }

                        var selection = selections.SingleOrDefault(s => s.FieldName.ToLower() == connectionEdge.SourceFieldName.ToLower());

                        if (selection != null)
                        {
                            var edgeObjectType         = edgeObject.GetType();
                            var edgeObjectTypeAccessor = TypeAccessor.Create(edgeObjectType);
                            var entity = await GetValue(edgeObjectTypeAccessor, connectionEdge, graphRequestContext,
                                                        connectionEdgeDestinationFilters,
                                                        queryExecutionContext);

                            if (entity == null)
                            {
                                _logger.LogWarning($"The following connection edge did not yield a record: {JsonConvert.SerializeObject(connectionEdge)}");
                                continue;
                            }

                            edgeObjectTypeAccessor[edgeObject, connectionEdge.MetaFieldName] = entity;

                            var matchingFieldName  = connectionEdge.MetaFieldName.ToLower();
                            var matchingSelections = selections.Where(x => x.SelectValues.Any(y => y.FieldName.ToLower() == matchingFieldName));

                            foreach (var matchingSelection in matchingSelections)
                            {
                                var selectionWithSelects = matchingSelection.SelectValues.Single(x => x.FieldName.ToLower() == matchingFieldName)
                                                           .SelectValues.Where(x => x.SelectValues.Count > 0).ToList();

                                if (selectionWithSelects.Count > 0)
                                {
                                    await QueryAndPopulateEdgeConnections(selectionWithSelects, new List <object> {
                                        entity
                                    }, graphRequestContext,
                                                                          connectionEdgeDestinationFilters, queryExecutionContext);
                                }
                            }
                        }
                    }
                }
            }
        }
Example #16
0
 public object CreateInstance(TypeAccessor typeAccessor)
 {
     return(typeAccessor.CreateInstance());
 }
 public void NullArgTest()
 {
     TypeAccessor.CreateInstance(typeof(NullArgObject));
 }
Example #18
0
 protected override void CreateSettings()
 {
     settings = TypeAccessor <ClientParameters> .CreateInstanceEx();
 }
Example #19
0
        public static string GetUniquePropertyValues <T>(T entity, List <string> propertiesNames, TypeAccessor accessor)
        {
            string result = String.Empty;

            foreach (var propertyName in propertiesNames)
            {
                result += accessor[entity, propertyName];
            }
            return(result);
        }
Example #20
0
        public void Packaging_DependencyCheck_LoggingDependencies()
        {
            PackagingTest(() =>
            {
                var logger    = new StringBuilder();
                var loggers   = new[] { new PackagingTestLogger(logger) };
                var loggerAcc = new TypeAccessor(typeof(SenseNet.Packaging.Logger));
                loggerAcc.SetStaticField("_loggers", loggers);

                using (new Swindler <IPackagingLogger[]>(loggers,
                                                         () => (IPackagingLogger[])loggerAcc.GetStaticField("_loggers"),
                                                         value => loggerAcc.SetStaticField("_loggers", loggers)))
                {
                    for (var i = 0; i < 9; i++)
                    {
                        ExecutePhases($@"<?xml version='1.0' encoding='utf-8'?>
                            <Package type='Install'>
                                <Id>Component{i + 1}</Id>
                                <ReleaseDate>2017-01-01</ReleaseDate>
                                <Version>{i + 1}.0</Version>
                            </Package>");
                    }
                    logger.Clear();

                    // action
                    ExecutePhases(@"<?xml version='1.0' encoding='utf-8'?>
                            <Package type='Install'>
                                <Id>MyCompany.MyComponent</Id>
                                <ReleaseDate>2017-01-02</ReleaseDate>
                                <Version>1.2</Version>
                                <Dependencies>
                                    <Dependency id='Component1' version=            '1.0' />
                                    <Dependency id='Component2' minVersion=         '1.0' />
                                    <Dependency id='Component3' maxVersion=         '9.0' />
                                    <Dependency id='Component4' minVersionExclusive='1.0' />
                                    <Dependency id='Component5' maxVersionExclusive='9.0' />
                                    <Dependency id='Component6' minVersion=         '1.0' maxVersion=         '10.0' />
                                    <Dependency id='Component7' minVersion=         '1.0' maxVersionExclusive='10.0' />
                                    <Dependency id='Component8' minVersionExclusive='1.0' maxVersion=         '10.0' />
                                    <Dependency id='Component9' minVersionExclusive='1.0' maxVersionExclusive='10.0' />
                                </Dependencies>
                            </Package>");

                    // check
                    var log           = logger.ToString();
                    var relevantLines = new List <string>();
                    using (var reader = new StringReader(log))
                    {
                        string line;
                        while ((line = reader.ReadLine()) != null)
                        {
                            line = line.Trim();
                            if (line.StartsWith("Component") && !line.StartsWith("ComponentId"))
                            {
                                relevantLines.Add(line);
                            }
                        }
                    }

                    Assert.AreEqual("Component1: 1.0 = 1.0 (current)", relevantLines[0]);
                    Assert.AreEqual("Component2: 1.0 <= 2.0 (current)", relevantLines[1]);
                    Assert.AreEqual("Component3: 3.0 (current) <= 9.0", relevantLines[2]);
                    Assert.AreEqual("Component4: 1.0 < 4.0 (current)", relevantLines[3]);
                    Assert.AreEqual("Component5: 5.0 (current) <= 9.0", relevantLines[4]);
                    Assert.AreEqual("Component6: 1.0 <= 6.0 (current) <= 10.0", relevantLines[5]);
                    Assert.AreEqual("Component7: 1.0 <= 7.0 (current) <= 10.0", relevantLines[6]);
                    Assert.AreEqual("Component8: 1.0 < 8.0 (current) < 10.0", relevantLines[7]);
                    Assert.AreEqual("Component9: 1.0 < 9.0 (current) < 10.0", relevantLines[8]);
                }
            });
        }
Example #21
0
        public static string GetMemberStringValue <T>(this T item, string memberName)
        {
            var f = TypeAccessor.Create(typeof(T));

            return(f[item, memberName] as string);
        }
Example #22
0
        public static string GetKey <T>(this T item)
        {
            var f = TypeAccessor.Create(typeof(T));

            return(f.GetKey(item));
        }
 static SummaryIndexValues()
 {
     CachedSelectors = ReflectionExtensions.GetGetters <SummaryIndexValues, object>();
     CachedSetter    = TypeAccessor.Create(typeof(SummaryIndexValues));
 }
		protected static List<string> GetPrimaryKeyFields(MappingSchema schema, TypeAccessor ta, TypeExtension tex)
		{
			var mdp  = schema.MetadataProvider;
			var keys = new List<string>();

			foreach (MemberAccessor sma in ta)
			{
				bool isSetFlag;

				mdp.GetPrimaryKeyOrder(ta.Type, tex, sma, out isSetFlag);

				if (isSetFlag)
				{
					var name = mdp.GetFieldName(tex, sma, out isSetFlag);
					keys.Add(name);
				}
			}

			return keys;
		}
Example #25
0
        internal static T As <S, T>(this S item, TypeMemberIndex sourceIndexMembers, TypeMemberIndex targetIndexMembers, TypeAccessor sourceAccessor, TypeAccessor targetAccessor) where T : new()
        {
            T targetItem = new T();

            foreach (var targetFieldName in targetIndexMembers.Keys)
            {
                try
                {
                    if (sourceIndexMembers.ContainsKey(targetFieldName))
                    {
                        var sourcePropertyType = sourceIndexMembers[targetFieldName].Type;
                        sourcePropertyType = ((sourcePropertyType.Name.Contains("Nullable")) ? sourcePropertyType.GenericTypeArguments.First() : sourcePropertyType);

                        var targetPropertyType = targetIndexMembers[targetFieldName].Type;
                        var isTargetNullable   = targetPropertyType.Name.Contains("Nullable");
                        targetPropertyType = ((isTargetNullable) ? targetPropertyType.GenericTypeArguments.First() : targetPropertyType);
                        object sourceValue     = sourceAccessor[item, targetFieldName];
                        var    bForceSpecified = false;


                        if (sourceValue != null)
                        {
                            if ((targetPropertyType.Name.Equals("DateTime")) && (sourceValue.Equals(DateTime.Parse("1/1/0001 12:00:00 AM"))))
                            {
                                sourceValue = null;
                            }
                            else if ((targetPropertyType.Name.Equals("DateTime")) && (sourceValue.Equals(DateTime.MaxValue)))
                            {
                                sourceValue     = null;
                                bForceSpecified = true;
                            }
                            else if ((sourcePropertyType.IsEnum) && (targetPropertyType.Name.Contains("String")))
                            {
                                sourceValue = sourceValue?.ToString();
                            }
                            else if ((sourcePropertyType.Name.Contains("String")) && (targetPropertyType.IsEnum))
                            {
                                sourceValue = Enum.Parse(targetPropertyType, sourceValue?.ToString());
                            }
                        }

                        if ((sourceValue == null) || (sourceValue.Equals("DBNull")))
                        {
                            if ((targetPropertyType.Name.Equals("DateTime") && (!isTargetNullable)))
                            {
                                targetAccessor[targetItem, targetFieldName] = DateTime.Parse("1/1/0001 12:00:00 AM");
                            }
                            else
                            {
                                if (isTargetNullable)
                                {
                                    targetAccessor[targetItem, targetFieldName] = null;
                                }
                            }
                        }
                        else if ((targetPropertyType.FullName == sourcePropertyType.FullName) || (targetPropertyType.Name.Equals(sourceValue.GetType().Name)))
                        {
                            targetAccessor[targetItem, targetFieldName] = sourceValue;
                        }
                        else
                        {
                            if (targetPropertyType.GenericTypeArguments.Contains(targetPropertyType))
                            {
                                targetAccessor[targetItem, targetFieldName] = sourceValue;
                            }
                            else
                            {
                                var c = TypeDescriptor.GetConverter(targetPropertyType);
                                if (c.CanConvertTo(targetPropertyType))
                                {
                                    targetAccessor[targetItem, targetFieldName] = c.ConvertTo(sourceValue, targetPropertyType);
                                }
                                else
                                {
                                    try
                                    {
                                        targetAccessor[targetItem, targetFieldName] = System.Convert.ChangeType(sourceValue, targetPropertyType);
                                    }
                                    catch (System.Exception ex)
                                    {
                                        throw new System.Exception(string.Format("Could not convert field {0} of type {1} to {2}", targetFieldName, sourceIndexMembers[targetFieldName].Type.Name, targetPropertyType.Name), ex);
                                    }
                                }
                            }
                        }
                        if (targetIndexMembers.ContainsKey(targetFieldName + "Specified"))
                        {
                            try
                            {
                                targetAccessor[targetItem, targetFieldName + "Specified"] = ((sourceValue != null) || bForceSpecified);
                            }
                            catch (Exception ex)
                            {
                                var message = string.Format("Unable to set {0}Specified as {1}.  {2}", targetFieldName + "Specified", targetPropertyType.Name, ex.Message);
                                throw new Exception(message, ex);
                            }
                        }
                    }
                }
                catch (Exception exField)
                {
                    var message = string.Format("Unable to set {0}.  {1}", targetFieldName, exField.Message);
                    throw new Exception(message, exField);
                }
            }
            return(targetItem);
        }
Example #26
0
 public static A CreateInstance()
 {
     return(TypeAccessor <A> .CreateInstance());
 }
Example #27
0
 internal static T As <S, T>(this S item) where T : new()
 {
     return(item.As <S, T>(typeof(S).Members(), typeof(T).Members(), TypeAccessor.Create(typeof(S)), TypeAccessor.Create(typeof(T))));
 }
Example #28
0
 public ValueAccessor(Type type)
 {
     _accessor          = TypeAccessor.Create(type);
     _relatedProperties = new HashSet <string>(type.GetProperties().Select(i => i.Name));
 }
Example #29
0
        internal static T[] AsArray <S, T>(this List <S> sourceList) where T : new()
        {
            var returnList = new List <T>();

            foreach (var item in sourceList)
            {
                returnList.Add(item.As <S, T>(typeof(S).Members(), typeof(T).Members(), TypeAccessor.Create(typeof(S)), TypeAccessor.Create(typeof(T))));
            }
            return(returnList.ToArray());
        }
        private static async Task MergeAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, OperationType operationType, Action <decimal> progress, CancellationToken cancellationToken) where T : class
        {
            string providerName = context.Database.ProviderName;

            // -- SQL Server --
            if (providerName.EndsWith(DbServer.SqlServer.ToString()))
            {
                tableInfo.InsertToTempTable = true;
                await tableInfo.CheckHasIdentityAsync(context, cancellationToken).ConfigureAwait(false);

                var dropTempTableIfExists = tableInfo.BulkConfig.UseTempDB;

                if (dropTempTableIfExists)
                {
                    await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB)).ConfigureAwait(false);
                }

                await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo), cancellationToken).ConfigureAwait(false);

                if (tableInfo.CreatedOutputTable)
                {
                    await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempOutputTableName, tableInfo, true), cancellationToken).ConfigureAwait(false);

                    if (tableInfo.TimeStampColumnName != null)
                    {
                        await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.AddColumn(tableInfo.FullTempOutputTableName, tableInfo.TimeStampColumnName, tableInfo.TimeStampOutColumnType), cancellationToken).ConfigureAwait(false);
                    }
                }

                bool keepIdentity = tableInfo.BulkConfig.SqlBulkCopyOptions.HasFlag(SqlBulkCopyOptions.KeepIdentity);
                try
                {
                    await InsertAsync(context, type, entities, tableInfo, progress, cancellationToken).ConfigureAwait(false);

                    if (keepIdentity && tableInfo.HasIdentity)
                    {
                        await context.Database.OpenConnectionAsync(cancellationToken).ConfigureAwait(false);

                        await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.SetIdentityInsert(tableInfo.FullTableName, true), cancellationToken).ConfigureAwait(false);
                    }

                    await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.MergeTable(tableInfo, operationType), cancellationToken).ConfigureAwait(false);

                    if (tableInfo.CreatedOutputTable)
                    {
                        await tableInfo.LoadOutputDataAsync(context, type, entities, cancellationToken).ConfigureAwait(false);
                    }
                }
                finally
                {
                    if (!tableInfo.BulkConfig.UseTempDB)
                    {
                        if (tableInfo.CreatedOutputTable)
                        {
                            await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.DropTable(tableInfo.FullTempOutputTableName, tableInfo.BulkConfig.UseTempDB), cancellationToken).ConfigureAwait(false);
                        }
                        await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB), cancellationToken).ConfigureAwait(false);
                    }

                    if (keepIdentity && tableInfo.HasIdentity)
                    {
                        await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.SetIdentityInsert(tableInfo.FullTableName, false), cancellationToken).ConfigureAwait(false);

                        context.Database.CloseConnection();
                    }
                }
            }
            // -- SQLite --
            else if (providerName.EndsWith(DbServer.Sqlite.ToString()))
            {
                var connection = await OpenAndGetSqliteConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false);

                var transaction = tableInfo.BulkConfig.SqliteTransaction ?? connection.BeginTransaction();
                try
                {
                    var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);

                    var typeAccessor = TypeAccessor.Create(type, true);
                    int rowsCopied   = 0;
                    foreach (var item in entities)
                    {
                        LoadSqliteValues(tableInfo, typeAccessor, item, command);
                        await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);

                        SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
                    }

                    if (operationType != OperationType.Delete && tableInfo.BulkConfig.SetOutputIdentity && tableInfo.IdentityColumnName != null)
                    {
                        command.CommandText = SqlQueryBuilderSqlite.SelectLastInsertRowId();
                        long lastRowIdScalar = (long)await command.ExecuteScalarAsync(cancellationToken).ConfigureAwait(false);

                        var    identityPropertyInteger = false;
                        var    accessor             = TypeAccessor.Create(type, true);
                        string identityPropertyName = tableInfo.PropertyColumnNamesDict.SingleOrDefault(a => a.Value == tableInfo.IdentityColumnName).Key;
                        if (accessor.GetMembers().FirstOrDefault(x => x.Name == identityPropertyName)?.Type == typeof(int))
                        {
                            identityPropertyInteger = true;
                        }
                        for (int i = entities.Count - 1; i >= 0; i--)
                        {
                            if (identityPropertyInteger)
                            {
                                accessor[entities[i], identityPropertyName] = (int)lastRowIdScalar;
                            }
                            else
                            {
                                accessor[entities[i], identityPropertyName] = lastRowIdScalar;
                            }

                            lastRowIdScalar--;
                        }
                    }
                }
                finally
                {
                    if (tableInfo.BulkConfig.SqliteTransaction == null)
                    {
                        transaction.Commit();
                        transaction.Dispose();
                    }
                    if (tableInfo.BulkConfig.SqliteConnection == null)
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                throw new SqlProviderNotSupportedException(providerName);
            }
        }
		public override void EnsureMapper(TypeAccessor typeAccessor, MappingSchema mappingSchema, EnsureMapperHandler handler)
		{
			foreach (var p in _list)
				p.EnsureMapper(typeAccessor, mappingSchema, handler);
		}
        private static async Task InsertAsync <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, Action <decimal> progress, CancellationToken cancellationToken)
        {
            string providerName = context.Database.ProviderName; // "Microsoft.EntityFrameworkCore.*****"

            // -- SQL Server --
            if (providerName.EndsWith(DbServer.SqlServer.ToString()))
            {
                var connection = await OpenAndGetSqlConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false);

                var transaction = context.Database.CurrentTransaction;
                try
                {
                    using (var sqlBulkCopy = GetSqlBulkCopy((SqlConnection)connection, transaction, tableInfo.BulkConfig))
                    {
                        bool useFastMember = tableInfo.HasOwnedTypes == false &&
                                             tableInfo.ColumnNameContainsSquareBracket == false &&
                                             tableInfo.ShadowProperties.Count == 0 &&
                                             !tableInfo.ConvertibleProperties.Any() &&
                                             !tableInfo.HasAbstractList &&
                                             !tableInfo.BulkConfig.UseOnlyDataTable;
                        bool setColumnMapping = useFastMember;
                        tableInfo.SetSqlBulkCopyConfig(sqlBulkCopy, entities, setColumnMapping, progress);
                        try
                        {
                            if (useFastMember)
                            {
                                using (var reader = ObjectReaderEx.Create(type, entities, tableInfo.ShadowProperties, tableInfo.ConvertibleProperties, context, tableInfo.PropertyColumnNamesDict.Keys.ToArray()))
                                {
                                    await sqlBulkCopy.WriteToServerAsync(reader, cancellationToken).ConfigureAwait(false);
                                }
                            }
                            else
                            {
                                var dataTable = GetDataTable(context, type, entities, sqlBulkCopy, tableInfo);
                                await sqlBulkCopy.WriteToServerAsync(dataTable, cancellationToken).ConfigureAwait(false);
                            }
                        }
                        catch (InvalidOperationException ex)
                        {
                            if (ex.Message.Contains(ColumnMappingExceptionMessage))
                            {
                                if (!await tableInfo.CheckTableExistAsync(context, tableInfo, cancellationToken).ConfigureAwait(false))
                                {
                                    await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo), cancellationToken).ConfigureAwait(false);

                                    await context.Database.ExecuteSqlRawAsync(SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB), cancellationToken).ConfigureAwait(false);
                                }
                            }
                            throw ex;
                        }
                    }
                }
                finally
                {
                    if (transaction == null)
                    {
                        connection.Close();
                    }
                }
            }
            // -- SQLite --
            else if (providerName.EndsWith(DbServer.Sqlite.ToString()))
            {
                var connection = await OpenAndGetSqliteConnectionAsync(context, tableInfo.BulkConfig, cancellationToken).ConfigureAwait(false);

                var transaction = tableInfo.BulkConfig.SqliteTransaction ?? connection.BeginTransaction();
                try
                {
                    var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);

                    var typeAccessor = TypeAccessor.Create(type, true);
                    int rowsCopied   = 0;
                    foreach (var item in entities)
                    {
                        LoadSqliteValues(tableInfo, typeAccessor, item, command);
                        await command.ExecuteNonQueryAsync(cancellationToken).ConfigureAwait(false);

                        SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
                    }
                }
                finally
                {
                    if (tableInfo.BulkConfig.SqliteTransaction == null)
                    {
                        transaction.Commit();
                        transaction.Dispose();
                    }
                    if (tableInfo.BulkConfig.SqliteConnection == null)
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                throw new SqlProviderNotSupportedException(providerName);
            }
        }
Example #33
0
        public void DefCtorTest1()
        {
            DefCtorObject1 o = (DefCtorObject1)TypeAccessor.CreateInstance(typeof(DefCtorObject1));

            Assert.AreEqual(10, o.Value);
        }
				object IObjectFactory.CreateInstance(TypeAccessor typeAccessor, InitContext context)
				{
					return new TestObject(53);
				}
Example #35
0
				public object CreateInstance(TypeAccessor typeAccessor)
				{
					return typeAccessor.CreateInstance();
				}
Example #36
0
			object GetObject(object o)
			{
				var obj = MemberAccessor.GetValue(o);

				if (_createInstance && obj == null)
				{
					if (_typeAccessor == null)
						_typeAccessor = TypeAccessor.GetAccessor(MemberAccessor.Type);

					obj = _typeAccessor.CreateInstanceEx();

					MemberAccessor.SetValue(o, obj);
				}

				return obj;
			}
        private static void Insert <T>(DbContext context, Type type, IList <T> entities, TableInfo tableInfo, Action <decimal> progress)
        {
            string providerName = context.Database.ProviderName; // "Microsoft.EntityFrameworkCore.*****"

            // -- SQL Server --
            if (providerName.EndsWith(DbServer.SqlServer.ToString()))
            {
                var connection  = OpenAndGetSqlConnection(context, tableInfo.BulkConfig);
                var transaction = context.Database.CurrentTransaction;
                try
                {
                    using (var sqlBulkCopy = GetSqlBulkCopy((SqlConnection)connection, transaction, tableInfo.BulkConfig))
                    {
                        bool useFastMember = tableInfo.HasOwnedTypes == false &&                   // With OwnedTypes DataTable is used since library FastMember can not (https://github.com/mgravell/fast-member/issues/21)
                                             tableInfo.ColumnNameContainsSquareBracket == false && // FastMember does not support escaped columnNames  ] -> ]]
                                             tableInfo.ShadowProperties.Count == 0 &&              // With Shadow prop. Discriminator (TPH inheritance) also not used because FastMember is slow for Update (https://github.com/borisdj/EFCore.BulkExtensions/pull/17)
                                             !tableInfo.ConvertibleProperties.Any() &&             // With ConvertibleProperties FastMember is slow as well
                                             !tableInfo.HasAbstractList &&                         // AbstractList not working with FastMember
                                             !tableInfo.BulkConfig.UseOnlyDataTable;
                        bool setColumnMapping = useFastMember;
                        tableInfo.SetSqlBulkCopyConfig(sqlBulkCopy, entities, setColumnMapping, progress);
                        try
                        {
                            if (useFastMember)
                            {
                                using (var reader = ObjectReaderEx.Create(type, entities, tableInfo.ShadowProperties, tableInfo.ConvertibleProperties, context, tableInfo.PropertyColumnNamesDict.Keys.ToArray()))
                                {
                                    sqlBulkCopy.WriteToServer(reader);
                                }
                            }
                            else
                            {
                                var dataTable = GetDataTable(context, type, entities, sqlBulkCopy, tableInfo);
                                sqlBulkCopy.WriteToServer(dataTable);
                            }
                        }
                        catch (InvalidOperationException ex)
                        {
                            if (ex.Message.Contains(ColumnMappingExceptionMessage))
                            {
                                if (!tableInfo.CheckTableExist(context, tableInfo))
                                {
                                    context.Database.ExecuteSqlRaw(SqlQueryBuilder.CreateTableCopy(tableInfo.FullTableName, tableInfo.FullTempTableName, tableInfo)); // Will throw Exception specify missing db column: Invalid column name ''
                                    context.Database.ExecuteSqlRaw(SqlQueryBuilder.DropTable(tableInfo.FullTempTableName, tableInfo.BulkConfig.UseTempDB));
                                }
                            }
                            throw ex;
                        }
                    }
                }
                finally
                {
                    if (transaction == null)
                    {
                        connection.Close();
                    }
                }
            }
            // -- SQLite --
            else if (providerName.EndsWith(DbServer.Sqlite.ToString()))
            {
                var connection  = OpenAndGetSqliteConnection(context, tableInfo.BulkConfig);
                var transaction = tableInfo.BulkConfig.SqliteTransaction ?? connection.BeginTransaction();
                try
                {
                    var command = GetSqliteCommand(context, type, entities, tableInfo, connection, transaction);

                    var typeAccessor = TypeAccessor.Create(type, true);
                    int rowsCopied   = 0;
                    foreach (var item in entities)
                    {
                        LoadSqliteValues(tableInfo, typeAccessor, item, command);
                        command.ExecuteNonQuery();
                        SetProgress(ref rowsCopied, entities.Count, tableInfo.BulkConfig, progress);
                    }
                }
                finally
                {
                    if (tableInfo.BulkConfig.SqliteTransaction == null)
                    {
                        transaction.Commit();
                        transaction.Dispose();
                    }
                    if (tableInfo.BulkConfig.SqliteConnection == null)
                    {
                        connection.Close();
                    }
                }
            }
            else
            {
                throw new SqlProviderNotSupportedException(providerName);
            }
        }
Example #38
0
        protected Message ExecuteMessage(Message message, RequestAttributes requestAttributes, IRequest httpReq, IResponse httpRes)
        {
            var soapFeature = requestAttributes.ToSoapFeature();

            HostContext.AppHost.AssertFeatures(soapFeature);

            if (httpReq == null)
            {
                httpReq = HostContext.GetCurrentRequest();
            }

            if (httpRes == null && httpReq != null)
            {
                httpRes = httpReq.Response;
            }

            if (httpReq == null)
            {
                throw new ArgumentNullException("httpReq");
            }

            if (httpRes == null)
            {
                throw new ArgumentNullException("httpRes");
            }

            httpReq.UseBufferedStream = true;
            var requestMsg = message ?? GetRequestMessageFromStream(httpReq.InputStream);

            var soapAction = httpReq.GetHeader(HttpHeaders.SOAPAction)
                             ?? GetAction(requestMsg);

            if (soapAction != null)
            {
                httpReq.OperationName = soapAction.Trim('"');
            }

            if (HostContext.ApplyCustomHandlerRequestFilters(httpReq, httpRes))
            {
                return(PrepareEmptyResponse(message, httpReq));
            }

            string requestXml  = GetRequestXml(requestMsg);
            var    requestType = GetRequestType(requestMsg, requestXml);

            httpReq.OperationName = requestType.GetOperationName();
            if (!HostContext.Metadata.CanAccess(requestAttributes, soapFeature.ToFormat(), requestType.GetOperationName()))
            {
                throw HostContext.UnauthorizedAccess(requestAttributes);
            }

            try
            {
                var useXmlSerializerRequest = requestType.HasAttribute <XmlSerializerFormatAttribute>();

                var request = useXmlSerializerRequest
                    ? XmlSerializableSerializer.Instance.DeserializeFromString(requestXml, requestType)
                    : Serialization.DataContractSerializer.Instance.DeserializeFromString(requestXml, requestType);

                httpReq.Dto = request;

                var requiresSoapMessage = request as IRequiresSoapMessage;
                if (requiresSoapMessage != null)
                {
                    requiresSoapMessage.Message = requestMsg;
                }

                httpReq.SetItem("SoapMessage", requestMsg);

                httpRes.ContentType = GetSoapContentType(httpReq.ContentType);

                var hasRequestFilters = HostContext.GlobalRequestFilters.Count > 0 ||
                                        FilterAttributeCache.GetRequestFilterAttributes(request.GetType()).Any();

                if (hasRequestFilters && HostContext.ApplyRequestFilters(httpReq, httpRes, request))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                httpReq.RequestAttributes |= requestAttributes;
                var response = ExecuteService(request, httpReq);

                var taskResponse = response as Task;
                if (taskResponse != null)
                {
                    taskResponse.Wait();
                    response = TypeAccessor.Create(taskResponse.GetType())[taskResponse, "Result"];
                }

                var hasResponseFilters = HostContext.GlobalResponseFilters.Count > 0 ||
                                         FilterAttributeCache.GetResponseFilterAttributes(response.GetType()).Any();

                if (hasResponseFilters && HostContext.ApplyResponseFilters(httpReq, httpRes, response))
                {
                    return(EmptyResponse(requestMsg, requestType));
                }

                var httpResult = response as IHttpResult;
                if (httpResult != null)
                {
                    response = httpResult.Response;
                }

                var noMsgAction = requestMsg.Headers.Action == null;
                var responseMsg = CreateResponseMessage(response, requestMsg.Version, requestType, noMsgAction);

                if (httpResult != null)
                {
                    SetErrorStatusIfAny(httpReq.Response, responseMsg, httpResult.Status);
                }

                return(responseMsg);
            }
            catch (Exception ex)
            {
                throw new SerializationException("3) Error trying to deserialize requestType: "
                                                 + requestType
                                                 + ", xml body: " + requestXml, ex);
            }
        }
Example #39
0
        public void InitCtorTest2()
        {
            InitCtorObject2 o = (InitCtorObject2)TypeAccessor.CreateInstance(typeof(InitCtorObject2));

            Assert.AreEqual(10, o.Value);
        }
Example #40
0
        private IMapper GetObjectMapper(IObjectMapper mapper, ref int startIndex, TypeAccessor akTypeAccessor)
        {
            //Todo: Remove this Call!
            _extension = TypeExtension.GetTypeExtension(mapper.PropertyType /*_typeAccessor.OriginalType*/, MappingSchema.Extensions);

            Type mapperType = mapper.PropertyType;
            var objectMappers = new List<IObjectMapper>();

            TableDescription tableDescription = GetTableDescription(mapperType);

            lock (SetterHandlersLock)
            {
                if (!SettersHandlers.ContainsKey(mapperType))
                    SettersHandlers.Add(mapperType, new Dictionary<string, SetHandler>());

                if (!GettersHandlers.ContainsKey(mapperType))
                    GettersHandlers.Add(mapperType, new Dictionary<string, GetHandler>());
            }

            PropertyInfo[] properties = mapperType.GetProperties();

            MemberAccessor primaryKeyMemberAccessor = null;
            foreach (MemberAccessor ma in akTypeAccessor)
            {
                //  Setters
                lock (SetterHandlersLock)
                {
                    if (!SettersHandlers[mapper.PropertyType].ContainsKey(ma.Name))
                    {
                        SettersHandlers[mapper.PropertyType].Add(ma.Name, ma.SetValue);
                    }
                }

                if (GetPrimaryKey(ma) != null)
                {
                    primaryKeyMemberAccessor = ma;

                    lock (SetterHandlersLock)
                    {
                        if (!GettersHandlers[mapperType].ContainsKey(ma.Name))
                        {
                            GettersHandlers[mapperType].Add(ma.Name, ma.GetValue);
                        }
                    }
                    mapper.PrimaryKeyValueGetters.Add(GettersHandlers[mapperType][ma.Name]);
                    mapper.PrimaryKeyNames.Add(ma.Name);

                    if (mapper.Association != null && (mapper.Association.OtherKey == null || mapper.Association.OtherKey.Length == 0))
                    {
                        mapper.Association.OtherKey = new[] {ma.Name};
                    }
                }
            }
            if (primaryKeyMemberAccessor == null)
                throw new Exception("PrimaryKey attribute not found on type: " + mapperType);

            foreach (PropertyInfo prop in properties)
            {
                var ma = akTypeAccessor.First(x => x.Name == prop.Name);

                // Check if the accessor is an association
                var association = GetAssociation(ma);
                if (association != null)
                {
                    //  Getters for IObjectMapper
                    lock (SetterHandlersLock)
                        if (!GettersHandlers[mapperType].ContainsKey(prop.Name))
                        {
                            GettersHandlers[mapperType].Add(prop.Name, ma.GetValue);
                        }

                    bool isCollection = prop.PropertyType.GetInterfaces().ToList().Contains(typeof (IList));
                    IObjectMapper propertiesMapping;
                    if (!isCollection)
                    {
                        // TODO Generate this instance using the CreateObjectMapperInstance method of fullMappingSchema
                        // _db.MappingSchema.CreateObjectMapperInstance(prop.PropertyType)

                        propertiesMapping = new FullObjectMapper(_db, _ignoreLazyLoad, _factoryType)
                            {
                                PropertyType = prop.PropertyType,
                                IsNullable = association.CanBeNull,
                                Getter = GettersHandlers[mapperType][prop.Name],
                            };
                    }
                    else
                    {
                        Type listElementType = GetGenericType(prop.PropertyType);
                        TableDescription colElementTableDescription = GetTableDescription(listElementType);

                        // TODO Generate this instance using the CreateObjectMapperInstance method of fullMappingSchema
                        propertiesMapping = new CollectionFullObjectMapper(_db, _factoryType)
                            {
                                PropertyType = listElementType,
                                Getter = GettersHandlers[mapperType][prop.Name],
                                TableName = colElementTableDescription.TableName,
                                PropertyCollectionType = prop.PropertyType,
                            };

                        if (mapper is FullObjectMapper)
                            ((FullObjectMapper) mapper).ColParent = true;
                    }

                    if (association.ThisKey == null || association.ThisKey.Length == 0)
                        association.ThisKey = new[] {primaryKeyMemberAccessor.Name};

                    bool isLazy = false;
                    if (!_ignoreLazyLoad)
                    {
                        var lazy = GetLazyInstance(ma); // prop.GetCustomAttributes(typeof(LazyInstanceAttribute), true);
                        if (lazy)
                        {
                            isLazy = true;
                            mapper.ContainsLazyChild = true;

                            //  Getters
                            lock (SetterHandlersLock)
                                if (!GettersHandlers[mapperType].ContainsKey(primaryKeyMemberAccessor.Name))
                                {
                                    GettersHandlers[mapperType].Add(primaryKeyMemberAccessor.Name, primaryKeyMemberAccessor.GetValue);
                                }
                        }
                    }

                    propertiesMapping.Association = association;
                    propertiesMapping.PropertyName = prop.Name;
                    propertiesMapping.IsLazy = isLazy;
                    propertiesMapping.Setter = SettersHandlers[mapperType][prop.Name];

                    if (propertiesMapping.IsLazy)
                    {
                        propertiesMapping.ParentKeyGetter = GettersHandlers[mapperType][primaryKeyMemberAccessor.Name];
                    }
                    objectMappers.Add(propertiesMapping);
                }
                else
                {
                    var mapIgnore = GetMapIgnore(ma);
                    if (mapIgnore)
                        continue;

                    var mapField = GetMapField(ma);
                    string columnName = mapField != null ? mapField.MapName : prop.Name;

                    var map = new ValueMapper
                        {
                            PropertyName = prop.Name,
                            PropertyType = prop.PropertyType,
                            DataReaderIndex = startIndex,
                            Setter = SettersHandlers[mapperType][prop.Name],
                            TableName = tableDescription.TableName,
                            ColumnName = columnName,
                        };

                    var mapColumnName = map.GetColumnName(columnName);
                    map.ColumnAlias = columnName == mapColumnName ? null : mapColumnName;

                    mapper.PropertiesMapping.Add(map);

                    var pkField = GetPrimaryKey(ma);
                    if (pkField != null)
                        mapper.DataReaderIndex = startIndex;

                    startIndex++;
                }
            }

            foreach (IObjectMapper objMap in objectMappers)
            {
                #region Check mapping recursion

                IObjectMapper cel = mapper;
                while (cel != null)
                {
                    if (mapper.PropertyType == objMap.PropertyType)
                        continue;

                    cel = (IObjectMapper) cel.ParentMapping;
                }

                #endregion

                objMap.ParentMapping = mapper;
                mapper.PropertiesMapping.Add(GetObjectMapper(objMap, ref startIndex, MappingSchema.GetObjectMapper(objMap.PropertyType).TypeAccessor));
            }

            return mapper;
        }
Example #41
0
            public override Expression BuildExpression(Expression expression, int level, bool enforceServerSide)
            {
                if (_isObject)
                {
                    if (expression == null)
                    {
                        var type  = _methodCall.Method.GetGenericArguments()[0];
                        var nctor = (NewExpression)Expression.Find(e => e is NewExpression ne && e.Type == type && ne.Arguments?.Count > 0);

                        Expression expr;

                        if (nctor != null)
                        {
                            var members = nctor.Members
                                          .Select(m => m is MethodInfo info ? info.GetPropertyInfo() : m)
                                          .ToList();

                            expr = Expression.New(
                                nctor.Constructor,
                                members.Select(m => Expression.PropertyOrField(_unionParameter, m.Name)),
                                members);

                            var ex = Builder.BuildExpression(this, expr, enforceServerSide);
                            return(ex);
                        }

                        var isNew = Expression.Find(e => e is NewExpression && e.Type == type) != null;
                        if (isNew)
                        {
                            var ta = TypeAccessor.GetAccessor(type);

                            expr = Expression.MemberInit(
                                Expression.New(ta.Type),
                                _members.Select(m =>
                                                Expression.Bind(m.Value.MemberExpression.Member, m.Value.MemberExpression)));
                            var ex = Builder.BuildExpression(this, expr, enforceServerSide);
                            return(ex);
                        }
                        else
                        {
                            var tableContext = new TableBuilder.TableContext(Builder,
                                                                             new BuildInfo(Parent, Expression, new SelectQuery()), type);
                            var ex = tableContext.BuildExpression(null, 0, enforceServerSide);
                            return(ex);
                        }
                    }

                    if (level == 0 || level == 1)
                    {
                        var levelExpression = expression.GetLevelExpression(Builder.MappingSchema, 1);

                        if (ReferenceEquals(expression, levelExpression) && !IsExpression(expression, 1, RequestFor.Object).Result)
                        {
                            var idx = ConvertToIndex(expression, level, ConvertFlags.Field);
                            var n   = idx[0].Index;

                            if (Parent != null)
                            {
                                n = Parent.ConvertToParentIndex(n, this);
                            }

                            return(Builder.BuildSql(expression.Type, n));
                        }
                    }
                }

                var ret = _sequence1.BuildExpression(expression, level, enforceServerSide);

                //if (level == 1)
                //	_sequence2.BuildExpression(expression, level);

                return(ret);
            }
Example #42
0
				public object CreateInstance(TypeAccessor typeAccessor, InitContext context)
				{
					if (context == null)
						throw new Exception("InitContext is null while mapping from DataReader!");

					return typeAccessor.CreateInstance();
				}
        public virtual void Init(MappingSchema mappingSchema, Type type)
        {
            if (type == null)
            {
                throw new ArgumentNullException("type");
            }

            _typeAccessor  = TypeAccessor.GetAccessor(type);
            _mappingSchema = mappingSchema;
            _extension     = TypeExtension.GetTypeExtension(_typeAccessor.OriginalType, mappingSchema.Extensions);

            _inheritanceMapping.AddRange(GetInheritanceMapping());

            foreach (MemberAccessor ma in _typeAccessor)
            {
                var a = GetAssociation(ma);

                if (a != null)
                {
                    _associations.Add(a);
                    continue;
                }

                if (GetMapIgnore(ma))
                {
                    continue;
                }

                var mapFieldAttr = GetMapField(ma);             // ma.GetAttribute<MapFieldAttribute>();

                if (mapFieldAttr == null || (mapFieldAttr.OrigName == null && mapFieldAttr.Format == null))
                {
                    var mi = new MapMemberInfo();

                    var dbTypeAttribute = GetDbType(ma);                 // ma.GetAttribute<DbTypeAttribute>();

                    if (dbTypeAttribute != null)
                    {
                        mi.DbType      = dbTypeAttribute.DbType;
                        mi.IsDbTypeSet = true;

                        if (dbTypeAttribute.Size != null)
                        {
                            mi.DbSize      = dbTypeAttribute.Size.Value;
                            mi.IsDbSizeSet = true;
                        }
                    }

                    mi.MemberAccessor             = ma;
                    mi.Type                       = ma.Type;
                    mi.MappingSchema              = mappingSchema;
                    mi.MemberExtension            = _extension[ma.Name];
                    mi.Name                       = GetFieldName(ma);
                    mi.MemberName                 = ma.Name;
                    mi.Storage                    = GetFieldStorage(ma);
                    mi.IsInheritanceDiscriminator = GetInheritanceDiscriminator(ma);
                    mi.Trimmable                  = GetTrimmable(ma);
                    mi.SqlIgnore                  = GetSqlIgnore(ma);
                    mi.MapValues                  = GetMapValues(ma);
                    mi.DefaultValue               = GetDefaultValue(ma);
                    mi.Nullable                   = GetNullable(ma);
                    mi.NullValue                  = GetNullValue(ma, mi.Nullable);

                    Add(CreateMemberMapper(mi));
                }
                else if (mapFieldAttr.OrigName != null)
                {
                    EnsureMapper(mapFieldAttr.MapName, ma.Name + "." + mapFieldAttr.OrigName);
                }
                else                 //if (mapFieldAttr.Format != null)
                {
                    foreach (MemberMapper inner in _mappingSchema.GetObjectMapper(ma.Type))
                    {
                        EnsureMapper(string.Format(mapFieldAttr.Format, inner.Name), ma.Name + "." + inner.MemberName);
                    }
                }
            }

            foreach (var ae in _extension.Attributes["MapField"])
            {
                var mapName  = (string)ae["MapName"];
                var origName = (string)ae["OrigName"];

                if (mapName == null || origName == null)
                {
                    throw new MappingException(string.Format(
                                                   "Type '{0}' has invalid  extension. MapField MapName='{1}' OrigName='{2}'.",
                                                   type.FullName, mapName, origName));
                }

                EnsureMapper(mapName, origName);
            }

            MetadataProvider.EnsureMapper(TypeAccessor, MappingSchema, EnsureMapper);
        }
			public SortMemberComparer(TypeAccessor typeAccessor, ListSortDirection direction, string[] memberNames)
			{
				_typeAccessor = typeAccessor;
				_direction    = direction;
				_memberNames  = memberNames;
				_members      = new MemberAccessor[memberNames.Length];

				_member = _members[0] = _typeAccessor[memberNames[0]];

				if (_member == null)
					throw new InvalidOperationException(
						string.Format("Field '{0}.{1}' not found.",
							_typeAccessor.OriginalType.Name, _memberNames[0]));
			}
Example #45
0
        public static string GetUniquePropertyValues(object entity, List <string> propertiesNames, TypeAccessor accessor)
        {
            StringBuilder result = new StringBuilder(1024);

            foreach (var propertyName in propertiesNames)
            {
                result.Append(accessor[entity, propertyName]);
            }
            return(result.ToString());
        }
		public override void EnsureMapper(TypeAccessor typeAccessor, MappingSchema mappingSchema, EnsureMapperHandler handler)
		{
			foreach (MapFieldAttribute attr in GetMapFieldAttributes(typeAccessor))
			{
				if (attr.OrigName != null)
					handler(attr.MapName, attr.OrigName);
				else
				{
					var ma = typeAccessor[attr.MapName];

					foreach (MemberMapper inner in mappingSchema.GetObjectMapper(ma.Type))
						handler(string.Format(attr.Format, inner.Name), ma.Name + "." + inner.MemberName);
				}
			}
		}
Example #47
0
    /// <summary>
    /// Strings to type.
    /// </summary>
    /// <param name="strType">Type of the string.</param>
    /// <param name="typeConfig">The type configuration.</param>
    /// <param name="ctorFn">The ctor function.</param>
    /// <param name="typeAccessors">The type accessors.</param>
    /// <returns>System.Object.</returns>
    internal static object StringToType(ReadOnlySpan <char> strType,
                                        TypeConfig typeConfig,
                                        EmptyCtorDelegate ctorFn,
                                        KeyValuePair <string, TypeAccessor>[] typeAccessors)
    {
        var index = 0;
        var type  = typeConfig.Type;

        if (strType.IsEmpty)
        {
            return(null);
        }

        //if (!Serializer.EatMapStartChar(strType, ref index))
        if (strType[index++] != JsWriter.MapStartChar)
        {
            throw DeserializeTypeRef.CreateSerializationError(type, strType.ToString());
        }

        if (JsonTypeSerializer.IsEmptyMap(strType))
        {
            return(ctorFn());
        }

        var config = JsConfig.GetConfig();

        object instance = null;
        var    lenient  = config.PropertyConvention == PropertyConvention.Lenient || config.TextCase == TextCase.SnakeCase;

        var strTypeLength = strType.Length;

        while (index < strTypeLength)
        {
            var propertyName = Serializer.EatMapKey(strType, ref index).Trim();

            //Serializer.EatMapKeySeperator(strType, ref index);
            index++;

            var propertyValueStr = Serializer.EatValue(strType, ref index);
            var possibleTypeInfo = propertyValueStr != null && propertyValueStr.Length > 1;

            if (possibleTypeInfo && propertyName.Equals(typeAttr.Span, StringComparison.OrdinalIgnoreCase))
            {
                var explicitTypeName = Serializer.ParseString(propertyValueStr);
                var explicitType     = config.TypeFinder(explicitTypeName);

                if (explicitType == null || explicitType.IsInterface || explicitType.IsAbstract)
                {
                    Tracer.Instance.WriteWarning("Could not find type: " + propertyValueStr.ToString());
                }
                else if (!type.IsAssignableFrom(explicitType))
                {
                    Tracer.Instance.WriteWarning("Could not assign type: " + propertyValueStr.ToString());
                }
                else
                {
                    JsWriter.AssertAllowedRuntimeType(explicitType);
                    instance = explicitType.CreateInstance();
                }

                if (instance != null)
                {
                    //If __type info doesn't match, ignore it.
                    if (!type.IsInstanceOfType(instance))
                    {
                        instance = null;
                    }
                    else
                    {
                        var derivedType = instance.GetType();
                        if (derivedType != type)
                        {
                            var map = DeserializeTypeRef.GetCachedTypeAccessors(derivedType, Serializer);
                            if (map != null)
                            {
                                typeAccessors = map;
                            }
                        }
                    }
                }

                //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                if (index != strType.Length)
                {
                    index++;
                }

                continue;
            }

            instance ??= ctorFn();

            var typeAccessor = typeAccessors.Get(propertyName, lenient);

            var propType = possibleTypeInfo && propertyValueStr[0] == '_' ? TypeAccessor.ExtractType(Serializer, propertyValueStr) : null;
            if (propType != null)
            {
                try
                {
                    if (typeAccessor != null)
                    {
                        var parseFn       = Serializer.GetParseStringSpanFn(propType);
                        var propertyValue = parseFn(propertyValueStr);
                        if (typeConfig.OnDeserializing != null)
                        {
                            propertyValue = typeConfig.OnDeserializing(instance, propertyName.ToString(), propertyValue);
                        }
                        typeAccessor.SetProperty(instance, propertyValue);
                    }

                    //Serializer.EatItemSeperatorOrMapEndChar(strType, ref index);
                    if (index != strType.Length)
                    {
                        index++;
                    }

                    continue;
                }
                catch (Exception e)
                {
                    config.OnDeserializationError?.Invoke(instance, propType, propertyName.ToString(), propertyValueStr.ToString(), e);
                    if (config.ThrowOnError)
                    {
                        throw DeserializeTypeRef.GetSerializationException(propertyName.ToString(), propertyValueStr.ToString(), propType, e);
                    }
                    else
                    {
                        Tracer.Instance.WriteWarning("WARN: failed to set dynamic property {0} with: {1}", propertyName.ToString(), propertyValueStr.ToString());
                    }
                }
            }

            if (typeAccessor is { GetProperty : { }, SetProperty : { } })
Example #48
0
            public override Expression BuildExpression(Expression expression, int level)
            {
                if (_isObject)
                {
                    if (expression == null)
                    {
                        var type  = _methodCall.Method.GetGenericArguments()[0];
                        var nctor = (NewExpression)Expression.Find(e =>
                        {
                            if (e.NodeType == ExpressionType.New && e.Type == type)
                            {
                                var ne = (NewExpression)e;
                                return(ne.Arguments != null && ne.Arguments.Count > 0);
                            }

                            return(false);
                        });

                        Expression expr;

                        if (nctor != null)
                        {
                            var members = nctor.Members
                                          .Select(m => m is MethodInfo ? ((MethodInfo)m).GetPropertyInfo() : m)
                                          .ToList();

                            expr = Expression.New(
                                nctor.Constructor,
                                members
                                .Select(m => Expression.PropertyOrField(_unionParameter, m.Name))
                                .Cast <Expression>(),
                                members);
                        }
                        else
                        {
                            var ta = TypeAccessor.GetAccessor(type);

                            expr = Expression.MemberInit(
                                Expression.New(ta.Type),
                                _members
                                .Select(m => Expression.Bind(m.Value.MemberExpression.Member, m.Value.MemberExpression))
                                .Cast <MemberBinding>());
                        }

                        var ex = Builder.BuildExpression(this, expr);

                        return(ex);
                    }

                    if (level == 0 || level == 1)
                    {
                        var levelExpression = expression.GetLevelExpression(Builder.MappingSchema, 1);

                        if (ReferenceEquals(expression, levelExpression) && !IsExpression(expression, 1, RequestFor.Object).Result)
                        {
                            var idx = ConvertToIndex(expression, level, ConvertFlags.Field);
                            var n   = idx[0].Index;

                            if (Parent != null)
                            {
                                n = Parent.ConvertToParentIndex(n, this);
                            }

                            return(Builder.BuildSql(expression.Type, n));
                        }
                    }
                }

                var ret = _sequence1.BuildExpression(expression, level);

                //if (level == 1)
                //	_sequence2.BuildExpression(expression, level);

                return(ret);
            }
Example #49
0
        public static string SerializeProperties <T>(IEnumerable <string> properties, T entity, TypeAccessor accessor = null)
        {
            var result = new StringBuilder();

            accessor = accessor ?? TypeAccessor.Create(typeof(T));

            foreach (var prop in properties)
            {
                result.Append($"{prop}='{accessor[entity, prop]}', ");
            }

            result.ReplaceLastOccurrence(",", string.Empty);

            return(result.ToString());
        }
		public virtual void EnsureMapper(TypeAccessor typeAccessor, MappingSchema mappingSchema, EnsureMapperHandler handler)
		{
		}
Example #51
0
 protected EngineSerializer(T obj)
 {
     Obj      = obj;
     Accessor = TypeAccessor.Create(typeof(T), true);
 }