public void ValidateTypeMapping(TypeMapping mapping)
		{
			var usingMultimapping = mappingBehaviors.HasFlag(MappingBehaviors.MultimapByDefault) || configurationDetails.IsMultimap(mapping.From);
			if (!usingMultimapping)
				CheckForExistingTypeMapping(target, mapping);
			CheckForExistingNamedMapping(target, mapping, configurationDetails);
		}
        private IMethodDefinition FindBestMatch(IMethodDefinition matchMethod, TypeMapping mapping, int typeIndex, int memberIndex)
        {
            // No matches if we don't have a matching type.
            if (mapping[typeIndex] == null)
                return null;

            foreach (IMethodDefinition method in mapping[typeIndex].Methods)
            {
                if (method.Name.Value != matchMethod.Name.Value) continue;

                if (method.ParameterCount != matchMethod.ParameterCount) continue;

                if (method.IsGeneric && matchMethod.IsGeneric &&
                    method.GenericParameterCount != matchMethod.GenericParameterCount)
                    continue;

                MemberMapping member = mapping.FindMember(method);

                // It is possible to find a match that was filtered at the mapping layer
                if (member == null) continue;

                // If the other member also doesn't have a match then this is our best match
                if (member[memberIndex] == null)
                    return method;
            }

            return null;
        }
		public String GetRegistrationName(TypeMapping typeMapping)
		{
			var namedMappingRequested = configurationDetails.IsMultimap(typeMapping.From) || configurationDetails.IsNamedMapping(typeMapping.To);
			var namedMappingRequired = mappingBehaviors.HasFlag(MappingBehaviors.MultimapByDefault) && multimapTypes.Contains(typeMapping.From);
			return (namedMappingRequested || namedMappingRequired) ? configurationDetails.GetNamedMapping(typeMapping)
																   : null;
		}
		private static void CheckForExistingTypeMapping(IUnityContainer target, TypeMapping mapping)
		{
			var existingRegistration = target.Registrations
										     .FirstOrDefault(r => r.RegisteredType.Equals(mapping.From));
			if (existingRegistration != null)
				throw new DuplicateMappingException(mapping.From, existingRegistration.MappedToType, mapping.To);
		}
Esempio n. 5
0
 public MMElement(TypeMapping typeMapping, object value, IElement container = null)
 {
     if (typeMapping == null) throw new ArgumentNullException(nameof(typeMapping));
     _typeMapping = typeMapping;
     _instance = value;
     _container = container;
 }
		/// <summary>
		/// Adds the given <paramref name="mapping"/> to <see cref="Mappings"/>.
		/// </summary>
		/// <param name="mapping">The <see cref="TypeMapping"/> which to add.</param>
		/// <exception cref="ArgumentNullException">Thrown if one of the parameters is null.</exception>
		public void Add(TypeMapping mapping)
		{
			// validate arguments
			if (mapping == null)
				throw new ArgumentNullException("mapping");

			// add the mapping
			Mappings.Add(mapping.Name, mapping);
		}
		public InjectionMember[] CreateInjectionMembers(TypeMapping typeMapping)
		{
			var requiresPolicyInjection = configurationDetails.IsMarkedForPolicyInjection(typeMapping.From)
									   || TypeHasHandlerAttribute(typeMapping.From)
									   || TypeHasHandlerAttribute(typeMapping.To);

			return requiresPolicyInjection ? new InjectionMember[] { new Interceptor<InterfaceInterceptor>(), new InterceptionBehavior<PolicyInjectionBehavior>() }
									       : new InjectionMember[0];
		}
		private static void CheckForExistingNamedMapping(IUnityContainer target, TypeMapping mapping, AutomapperConfig configurationDetails)
		{
			var mappingName = configurationDetails.GetNamedMapping(mapping);
			var existingRegistration = target.Registrations
												.Where(r => String.Equals(r.Name, mappingName))
												.Where(r => r.RegisteredType.Equals(mapping.From))
												.FirstOrDefault();
			if (existingRegistration != null)
				throw new DuplicateMappingException(mapping.From, existingRegistration.MappedToType, mapping.To, mappingName);
		}
 public bool Include(TypeMapping type)
 {
     var isAdded = type.Difference == DifferenceType.Added;
     var isRemoved = type.Difference == DifferenceType.Removed;
     var onBothSides = !isAdded && !isRemoved;
     var include = onBothSides ||
                   isAdded && _includeAddedTypes ||
                   isRemoved && _includeRemovedTypes;
     return _baseFilter.Include(type) && include;
 }
 public void TestMMObjects()
 {
     var typeMapper = new TypeMapping();
     typeMapper.CreateNewObject = () => new MapTestClass();
     typeMapper.GetId = (x) => (x as MapTestClass).Id.ToString();
     typeMapper.AddProperty(
         MapTestClass.IdProperty,
         (x) => (x as MapTestClass).Id,
         (x, v) => (x as MapTestClass).Id = v);
     typeMapper.AddProperty(
         MapTestClass.NameProperty,
         (x) => (x as MapTestClass).Name,
         (x, v) => (x as MapTestClass).Name = v);
 }
        public void Predicate_ForInterface_CanBuildPredicate()
        {
            var mapping = new TypeMapping<IPerson, Person>();
            var expression = mapping.Predicate("p => p.LastName == \"LName\"").Compile();

            var persons = new List<IPerson>
            {
                new Person{ Id = 1, LastName = "LName"},
                new Person{ Id = 2, LastName = "LName2"},
            };

            var filteredPersons = persons.Where(expression).ToList();

            Assert.AreEqual(1, filteredPersons.Count);
            Assert.AreEqual(1, filteredPersons[0].Id);
        }
Esempio n. 12
0
        public void CreateIndexMultiFieldMap()
        {
            var client = this.ConnectedClient;

            var typeMapping = new TypeMapping(Guid.NewGuid().ToString("n"));
            var property = new TypeMappingProperty
                           {
                               Type = "multi_field"
                           };

            var primaryField = new TypeMappingProperty
                               {
                                   Type = "string",
                                   Index = "not_analyzed"
                               };

            var analyzedField = new TypeMappingProperty
                                {
                                    Type = "string",
                                    Index = "analyzed"
                                };

            property.Fields = new Dictionary<string, TypeMappingProperty>();
            property.Fields.Add("name", primaryField);
            property.Fields.Add("name_analyzed", analyzedField);

            typeMapping.Properties.Add("name", property);

            var settings = new IndexSettings();
            settings.Mappings.Add(typeMapping);
            settings.NumberOfReplicas = 1;
            settings.NumberOfShards = 5;
            settings.Analysis.Analyzer.Add("snowball", new SnowballAnalyzerSettings { Language = "English" });

            var indexName = Guid.NewGuid().ToString();
            var response = client.CreateIndex(indexName, settings);

            Assert.IsTrue(response.IsValid);
            Assert.IsTrue(response.OK);

            Assert.IsNotNull(this.ConnectedClient.GetMapping(indexName, typeMapping.Name));

            response = client.DeleteIndex(indexName);

            Assert.IsTrue(response.IsValid);
            Assert.IsTrue(response.OK);
        }
Esempio n. 13
0
        public static APPSettModel ConvertGoodsInSql(AppModel model)
        {
            if (model != null)
            {
                var r = new APPSettModel();

                //映射处理
                var map = new TypeMapping<AppModel, APPSettModel>();
                map.AutoMap();
                map.CopyLeftToRight(model, r);
                //r.TaxonomyId = r.Categorys.Union(r.Tags).Distinct().Select(e => e.Key).ToList();

                return r;
            }

            return null;
        }
        public void Predicate_WithMultiStatementSetup_LF_ForInterface_CanBuildPredicate()
        {
            var mapping = new TypeMapping<IPerson, Person>();
            var setupStatement = "using System;\n var date = DateTime.Parse(\"1987-03-01\");";
            var expression = mapping.Predicate("p => p.Birthdate == date", setupStatement).Compile();

            var persons = new List<IPerson>
            {
                new Person{ Id = 1, Birthdate = DateTime.Parse("1987-03-01") },
                new Person{ Id = 2, Birthdate = DateTime.Parse("1987-03-02") },
            };

            var filteredPersons = persons.Where(expression).ToList();

            Assert.AreEqual(1, filteredPersons.Count);
            Assert.AreEqual(1, filteredPersons[0].Id);
        }
Esempio n. 15
0
        public static ShopInSql ConvertShopInSql(ShopDetail model)
        {
            if (model != null)
            {
                var r = new ShopInSql();

                //映射处理
                var map = new TypeMapping<ShopDetail, ShopInSql>();
                map.AutoMap();
                map.CopyLeftToRight(model, r);

                r.AreaId = r.Areas.Select(e => e.Key).ToList();

                return r;
            }

            return null;
        }
        public virtual bool Include(TypeMapping type)
        {
            bool anyIncluded = false;
            for (int i = 0; i < type.ElementCount; i++)
                if (type[i] != null && _filter.Include(type[i]))
                    anyIncluded = true;

            if (!anyIncluded)
                return false;

            if (Include(type.Difference))
                return true;

            if (type.ShouldDiffMembers)
                return type.Members.Any(Include);

            return false;
        }
Esempio n. 17
0
        public static ArchiveInSql ConvertArchiveInSql(ArticleDetail model)
        {
            if (model != null)
            {
                var r = new ArchiveInSql();

                //映射处理
                var map = new TypeMapping<ArticleDetail, ArchiveInSql>();
                map.AutoMap();
                map.CopyLeftToRight(model, r);

                r.TaxonomyId = r.Categorys.Union(r.Tags).Distinct().Select(e => e.Key).ToList();

                return r;
            }

            return null;
        }
		/// <summary>
		/// Adds <see cref="PropertyMapping"/>s of <paramref name="property"/> to the given <paramref name="typeMapping"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="property">The <see cref="IPropertyDefinition"/> of the property for which to add the <see cref="PropertyMapping"/>s.</param>
		/// <param name="typeMapping">The <see cref="TypeMapping"/> to which to add the new <see cref="PropertyMapping"/>s.</param>
		protected override void DoAddMappingTo(IMansionContext context, IPropertyDefinition property, TypeMapping typeMapping)
		{
			typeMapping.Add(new SingleValuedPropertyMapping("approved")
			                {
			                	Type = "boolean"
			                });
			typeMapping.Add(new SingleValuedPropertyMapping("archived")
			                {
			                	Type = "boolean"
			                });
			typeMapping.Add(new SingleValuedPropertyMapping("publicationDate")
			                {
			                	Type = "date"
			                });
			typeMapping.Add(new SingleValuedPropertyMapping("expirationDate")
			                {
			                	Type = "date"
			                });
		}
        public static GoodsDetailInSql ConvertGoodsInSql(GoodsDetail model)
        {
            if (model != null)
            {
                var r = new GoodsDetailInSql();

                //映射处理
                var map = new TypeMapping<GoodsDetail, GoodsDetailInSql>();
                map.AutoMap();
                map.CopyLeftToRight(model, r);

                r.CategoryId = r.ItemShopCats.Select(e => e.Id).ToList();
                //r.TaxonomyId = r.Categorys.Union(r.Tags).Distinct().Select(e => e.Key).ToList();

                return r;
            }

            return null;
        }
Esempio n. 20
0
 private void Print(object value, ExpressionPrinter expressionPrinter)
 => expressionPrinter.Append(TypeMapping?.GenerateSqlLiteral(value) ?? Value?.ToString() ?? "NULL");
 public void Visit(TypeMapping mapping)
 {
     Increment("type");
 }
Esempio n. 22
0
 public static FieldSchema FromDto(FieldSchemaDto fieldSchemaDto)
 {
     return(new FieldSchema(fieldSchemaDto.Name, TypeMapping.FromTypeName(fieldSchemaDto.TypeName)));
 }
Esempio n. 23
0
        private LVC.Model.test._InputMeta Createtest_InputMeta(TypeMapping typeMapping)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            LVC.Model.test._InputMeta obj = new LVC.Model.test._InputMeta();

            {
                // Assign MetaValues value to "TapVTx4" field
                FieldMapping fieldMapping = fieldLookup["TapVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.TapVTx4 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "MwVTx4" field
                FieldMapping fieldMapping = fieldLookup["MwVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MwVTx4 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "MvrVTx4" field
                FieldMapping fieldMapping = fieldLookup["MvrVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MvrVTx4 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "VoltsVTx4" field
                FieldMapping fieldMapping = fieldLookup["VoltsVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.VoltsVTx4 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "TapVTx5" field
                FieldMapping fieldMapping = fieldLookup["TapVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.TapVTx5 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "MwVTx5" field
                FieldMapping fieldMapping = fieldLookup["MwVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MwVTx5 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "MvrVTx5" field
                FieldMapping fieldMapping = fieldLookup["MvrVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MvrVTx5 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "VoltsVTx5" field
                FieldMapping fieldMapping = fieldLookup["VoltsVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.VoltsVTx5 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "BusBkrVCap1" field
                FieldMapping fieldMapping = fieldLookup["BusBkrVCap1"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.BusBkrVCap1 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "CapBkrVCap1" field
                FieldMapping fieldMapping = fieldLookup["CapBkrVCap1"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.CapBkrVCap1 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "LocKvVCap1" field
                FieldMapping fieldMapping = fieldLookup["LocKvVCap1"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.LocKvVCap1 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "BusBkrVCap2" field
                FieldMapping fieldMapping = fieldLookup["BusBkrVCap2"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.BusBkrVCap2 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "CapBkrVCap2" field
                FieldMapping fieldMapping = fieldLookup["CapBkrVCap2"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.CapBkrVCap2 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "LocKvVCap2" field
                FieldMapping fieldMapping = fieldLookup["LocKvVCap2"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.LocKvVCap2 = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "G1Mw" field
                FieldMapping fieldMapping = fieldLookup["G1Mw"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G1Mw = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "G1Mvr" field
                FieldMapping fieldMapping = fieldLookup["G1Mvr"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G1Mvr = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "G2Mw" field
                FieldMapping fieldMapping = fieldLookup["G2Mw"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G2Mw = GetMetaValues(measurement);
            }

            {
                // Assign MetaValues value to "G2Mvr" field
                FieldMapping fieldMapping = fieldLookup["G2Mvr"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G2Mvr = GetMetaValues(measurement);
            }

            return(obj);
        }
Esempio n. 24
0
 public override string GetValue(TypeMapping mapping)
 {
     return(mapping.Representative.IsVisibleOutsideAssembly()
                ? "Yes"
                : "No");
 }
Esempio n. 25
0
        static void WriteDeserializerCallClassMethod(TypeBuilder typeBuilder, ILGenerator il, Type type, int tag, MethodInfo setMethod, Type ownerType = null)
        {
            MethodBuilder method;
            var           local          = il.DeclareLocal(type);
            var           hasTypeMapping = TypeMapping.ContainsKey(type);

            il.Emit(OpCodes.Ldc_I4, tag);
            il.Emit(OpCodes.Ldarg_3);
            il.Emit(OpCodes.Call, MoveToNextBytesMethod);

            if (hasTypeMapping)
            {
                var index           = 0;
                var typeMapping     = TypeMapping[type];
                var count           = typeMapping.Count;
                var types           = typeMapping.Select(kv => kv.Key);
                var needBranchLabel = count > 1;
                var branchLabel     = needBranchLabel ? il.DefineLabel() : DefaultLabel;
                var valueTypeLocal  = il.DeclareLocal(TypeType);

                il.Emit(OpCodes.Ldarg_2);
                il.Emit(OpCodes.Ldtoken, type);
                il.Emit(OpCodes.Call, GetTypeFromHandleMethod);
                il.Emit(OpCodes.Ldarg_3);
                il.Emit(OpCodes.Call, ConvertBaseToConcreteTypeMethod);

                il.Emit(OpCodes.Stloc, valueTypeLocal.LocalIndex);

                foreach (var mapType in types)
                {
                    index++;
                    var isLastIndex     = index == count;
                    var isLastCondition = isLastIndex && needBranchLabel;
                    var conditionLabel  = !isLastCondition?il.DefineLabel() : DefaultLabel;

                    var currentConditionLabel = isLastCondition ? branchLabel : conditionLabel;
                    il.Emit(OpCodes.Ldloc, valueTypeLocal.LocalIndex);
                    il.Emit(OpCodes.Ldtoken, mapType);
                    il.Emit(OpCodes.Call, GetTypeFromHandleMethod);
                    il.Emit(OpCodes.Call, GetTypeOpEqualityMethod);
                    il.Emit(OpCodes.Brfalse, currentConditionLabel);

                    method = GenerateDeserializerClass(typeBuilder, mapType, ownerType: ownerType);
                    il.Emit(OpCodes.Newobj, mapType.GetConstructor(Type.EmptyTypes));
                    il.Emit(OpCodes.Stloc, local.LocalIndex);
                    il.Emit(OpCodes.Ldarg_0);
                    il.Emit(OpCodes.Ldloc, local.LocalIndex);
                    if (mapType.IsClass)
                    {
                        il.Emit(OpCodes.Castclass, mapType);
                    }
                    else
                    {
                        il.Emit(OpCodes.Unbox_Any, mapType);
                    }
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Ldarg_3);
                    il.Emit(OpCodes.Call, method);

                    if (!isLastIndex)
                    {
                        il.Emit(OpCodes.Br, branchLabel);
                    }
                    il.MarkLabel(currentConditionLabel);
                }
            }
            else
            {
                method = GenerateDeserializerClass(typeBuilder, type, ownerType: ownerType);
                var isTypeClass = type.IsClass;
                if (isTypeClass)
                {
                    il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
                    il.Emit(OpCodes.Stloc, local.LocalIndex);
                }
                else
                {
                    il.Emit(OpCodes.Ldloca, local.LocalIndex);
                    il.Emit(OpCodes.Initobj, type);
                }
                il.Emit(OpCodes.Ldarg_0);
                if (isTypeClass)
                {
                    il.Emit(OpCodes.Ldloc, local.LocalIndex);
                }
                else
                {
                    il.Emit(OpCodes.Ldloca, local.LocalIndex);
                }
                il.Emit(OpCodes.Ldarg_2);
                il.Emit(OpCodes.Ldarg_3);
                il.Emit(OpCodes.Call, method);
            }

            il.Emit(OpCodes.Ldarg_1);
            il.Emit(OpCodes.Ldloc, local.LocalIndex);
            il.Emit(OpCodes.Call, setMethod);
        }
		/// <summary>
		/// Maps the given <paramref name="type"/> in <paramref name="typeMapping"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="definition">The <see cref="IndexDefinition"/>.</param>
		/// <param name="type">The <see cref="ITypeDefinition"/>.</param>
		/// <param name="typeMapping">The <see cref="TypeMapping"/>.</param>
		private static void MapType(IMansionContext context, IndexDefinition definition, ITypeDefinition type, TypeMapping typeMapping)
		{
			// map the type descriptor, if any
			TypeMapping.TypeMappingDescriptor descriptor;
			if (type.TryGetDescriptor(out descriptor))
				descriptor.UpdateMapping(context, typeMapping);

			// map all the properties of this type
			MapProperties(context, type, typeMapping);

			// map all the analysis components defined on this type
			MapAnalysisComponents(context, type, definition);

			// loop over all the children of this type
			foreach (var childType in type.GetChildTypes(context))
			{
				// clone the parent mapping, children should include the properties of the parent
				var childMapping = typeMapping.Clone(childType);

				// map the the child
				MapType(context, definition, childType, childMapping);
			}

			// append the mapping to the index definition
			definition.Add(typeMapping);
		}
Esempio n. 27
0
 public override string GetValue(TypeMapping mapping)
 {
     return(GetTokenString(mapping));
 }
 public virtual DifferenceType Diff(IDifferences differences, TypeMapping mapping)
 {
     return(Diff(differences, mapping[0], mapping[1]));
 }
Esempio n. 29
0
        public void CreateProject(string projectName, string targetDirectory, TypeMapping inputMapping, TypeMapping outputMapping, string targetLanguage)
        {
            MappingCompiler mappingCompiler = CreateMappingCompiler();
            TypeMapping     compiledInput   = mappingCompiler.GetTypeMapping(inputMapping.Identifier);
            TypeMapping     compiledOutput  = mappingCompiler.GetTypeMapping(outputMapping.Identifier);

            if (targetLanguage == "C#")
            {
                ECAClientUtilities.Template.CSharp.ProjectGenerator projectGenerator = new ECAClientUtilities.Template.CSharp.ProjectGenerator(projectName, mappingCompiler);
                projectGenerator.Settings.SubscriberConnectionString = MainWindow.Model.Global.SubscriptionConnectionString;
                projectGenerator.Generate(targetDirectory, compiledInput, compiledOutput);
            }
            else if (targetLanguage == "F#")
            {
                ECAClientUtilities.Template.FSharp.ProjectGenerator projectGenerator = new ECAClientUtilities.Template.FSharp.ProjectGenerator(projectName, mappingCompiler);
                projectGenerator.Settings.SubscriberConnectionString = MainWindow.Model.Global.SubscriptionConnectionString;
                projectGenerator.Generate(targetDirectory, compiledInput, compiledOutput);
            }
            else if (targetLanguage == "VB")
            {
                ECAClientUtilities.Template.VisualBasic.ProjectGenerator projectGenerator = new ECAClientUtilities.Template.VisualBasic.ProjectGenerator(projectName, mappingCompiler);
                projectGenerator.Settings.SubscriberConnectionString = MainWindow.Model.Global.SubscriptionConnectionString;
                projectGenerator.Generate(targetDirectory, compiledInput, compiledOutput);
            }
            else if (targetLanguage == "IronPython")
            {
                ECAClientUtilities.Template.IronPython.ProjectGenerator projectGenerator = new ECAClientUtilities.Template.IronPython.ProjectGenerator(projectName, mappingCompiler);
                projectGenerator.Settings.SubscriberConnectionString = MainWindow.Model.Global.SubscriptionConnectionString;
                projectGenerator.Generate(targetDirectory, compiledInput, compiledOutput);
            }
            else if (targetLanguage == "MATLAB")
            {
                ECAClientUtilities.Template.Matlab.ProjectGenerator projectGenerator = new ECAClientUtilities.Template.Matlab.ProjectGenerator(projectName, mappingCompiler);
                projectGenerator.Settings.SubscriberConnectionString = MainWindow.Model.Global.SubscriptionConnectionString;
                projectGenerator.Generate(targetDirectory, compiledInput, compiledOutput);
            }
            else if (targetLanguage == "Java")
            {
            }
            else if (targetLanguage == "C++")
            {
            }
            else if (targetLanguage == "Python")
            {
            }
        }
Esempio n. 30
0
        private TypeMapping ParseTimeWindow(TypeMapping typeMapping)
        {
            for (int i = 0; i < typeMapping.FieldMappings.Count; ++i)
            {
                if (typeMapping.FieldMappings[i].TimeWindowExpression != "")
                {
                    try
                    {
                        int index = 0;

                        string[] parts = typeMapping.FieldMappings[i].TimeWindowExpression.Split(new char[0], StringSplitOptions.RemoveEmptyEntries);

                        if (parts[index].Equals("last", StringComparison.OrdinalIgnoreCase))
                        {
                            ArrayMapping am = new ArrayMapping();
                            am.Field                = typeMapping.FieldMappings[i].Field;
                            am.Expression           = typeMapping.FieldMappings[i].Expression;
                            am.RelativeTime         = typeMapping.FieldMappings[i].RelativeTime;
                            am.RelativeUnit         = typeMapping.FieldMappings[i].RelativeUnit;
                            am.SampleRate           = typeMapping.FieldMappings[i].SampleRate;
                            am.SampleUnit           = typeMapping.FieldMappings[i].SampleUnit;
                            am.TimeWindowExpression = "";

                            am.WindowSize = Convert.ToDecimal(parts[++index]);
                            ++index;

                            if (parts[index].Equals("points", StringComparison.OrdinalIgnoreCase))
                            {
                                index += 2;

                                am.WindowUnit = TimeSpan.Zero;
                                if (parts.Length - 1 > index)
                                {
                                    am.SampleRate = Convert.ToDecimal(parts[index]);
                                    index        += 2;
                                    am.SampleUnit = GetTimeSpan(parts[index]);
                                }
                            }
                            else
                            {
                                am.WindowUnit = GetTimeSpan(parts[index]);
                                index        += 2;
                                if (parts.Length - 1 > index)
                                {
                                    am.SampleRate = Convert.ToDecimal(parts[index]);
                                    index        += 2;
                                    am.SampleUnit = GetTimeSpan(parts[index]);
                                }
                            }

                            typeMapping.FieldMappings.RemoveAt(i);
                            am.TimeWindowExpression = "";
                            typeMapping.FieldMappings.Insert(i, am);
                        }
                        else if (parts[index].Equals("from", StringComparison.OrdinalIgnoreCase))
                        {
                            ArrayMapping am = new ArrayMapping();
                            am.Field                = typeMapping.FieldMappings[i].Field;
                            am.Expression           = typeMapping.FieldMappings[i].Expression;
                            am.RelativeTime         = typeMapping.FieldMappings[i].RelativeTime;
                            am.RelativeUnit         = typeMapping.FieldMappings[i].RelativeUnit;
                            am.SampleRate           = typeMapping.FieldMappings[i].SampleRate;
                            am.SampleUnit           = typeMapping.FieldMappings[i].SampleUnit;
                            am.TimeWindowExpression = "";

                            am.RelativeTime = Convert.ToDecimal(parts[++index]);
                            ++index;

                            if (parts[index].Equals("points", StringComparison.OrdinalIgnoreCase))
                            {
                                am.RelativeUnit = TimeSpan.Zero;
                            }
                            else
                            {
                                am.RelativeUnit = GetTimeSpan(parts[index]);
                            }

                            index += 3;

                            am.WindowSize = Convert.ToDecimal(parts[index++]);

                            if (parts[index].Equals("points", StringComparison.OrdinalIgnoreCase))
                            {
                                am.WindowUnit = TimeSpan.Zero;
                            }
                            else
                            {
                                am.WindowUnit = GetTimeSpan(parts[index]);
                            }

                            if (parts.Length > ++index)
                            {
                                am.SampleRate = Convert.ToDecimal(parts[++index]);
                                index        += 2;
                                am.SampleUnit = GetTimeSpan(parts[index]);
                            }

                            typeMapping.FieldMappings.RemoveAt(i);
                            am.TimeWindowExpression = "";
                            typeMapping.FieldMappings.Insert(i, am);
                        }
                        else
                        {
                            typeMapping.FieldMappings[i].RelativeTime = Convert.ToDecimal(parts[index]);
                            ++index;

                            if (parts[index].Equals("points", StringComparison.OrdinalIgnoreCase))
                            {
                                index += 3;
                                typeMapping.FieldMappings[i].RelativeUnit = TimeSpan.Zero;
                                if (parts.Length > index)
                                {
                                    typeMapping.FieldMappings[i].SampleRate = Convert.ToDecimal(parts[index]);
                                    index += 2;
                                    typeMapping.FieldMappings[i].SampleUnit = GetTimeSpan(parts[index]);
                                }
                            }
                            else
                            {
                                typeMapping.FieldMappings[i].RelativeUnit = GetTimeSpan(parts[index]);
                                index += 3;
                                if (parts.Length - 1 > index)
                                {
                                    typeMapping.FieldMappings[i].SampleRate = Convert.ToDecimal(parts[index]);
                                    index += 2;
                                    typeMapping.FieldMappings[i].SampleUnit = GetTimeSpan(parts[index]);
                                }
                            }
                        }
                    }
                    catch (Exception)
                    {
                    }
                }
            }

            return(typeMapping);
        }
Esempio n. 31
0
        private LVC.Model.test.Input CreatetestInput(TypeMapping typeMapping)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            LVC.Model.test.Input obj = new LVC.Model.test.Input();

            {
                // Assign short value to "TapVTx4" field
                FieldMapping fieldMapping = fieldLookup["TapVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.TapVTx4 = (short)measurement.Value;
            }

            {
                // Assign double value to "MwVTx4" field
                FieldMapping fieldMapping = fieldLookup["MwVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MwVTx4 = (double)measurement.Value;
            }

            {
                // Assign double value to "MvrVTx4" field
                FieldMapping fieldMapping = fieldLookup["MvrVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MvrVTx4 = (double)measurement.Value;
            }

            {
                // Assign double value to "VoltsVTx4" field
                FieldMapping fieldMapping = fieldLookup["VoltsVTx4"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.VoltsVTx4 = (double)measurement.Value;
            }

            {
                // Assign short value to "TapVTx5" field
                FieldMapping fieldMapping = fieldLookup["TapVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.TapVTx5 = (short)measurement.Value;
            }

            {
                // Assign double value to "MwVTx5" field
                FieldMapping fieldMapping = fieldLookup["MwVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MwVTx5 = (double)measurement.Value;
            }

            {
                // Assign double value to "MvrVTx5" field
                FieldMapping fieldMapping = fieldLookup["MvrVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.MvrVTx5 = (double)measurement.Value;
            }

            {
                // Assign double value to "VoltsVTx5" field
                FieldMapping fieldMapping = fieldLookup["VoltsVTx5"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.VoltsVTx5 = (double)measurement.Value;
            }

            {
                // Assign short value to "BusBkrVCap1" field
                FieldMapping fieldMapping = fieldLookup["BusBkrVCap1"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.BusBkrVCap1 = (short)measurement.Value;
            }

            {
                // Assign short value to "CapBkrVCap1" field
                FieldMapping fieldMapping = fieldLookup["CapBkrVCap1"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.CapBkrVCap1 = (short)measurement.Value;
            }

            {
                // Assign double value to "LocKvVCap1" field
                FieldMapping fieldMapping = fieldLookup["LocKvVCap1"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.LocKvVCap1 = (double)measurement.Value;
            }

            {
                // Assign short value to "BusBkrVCap2" field
                FieldMapping fieldMapping = fieldLookup["BusBkrVCap2"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.BusBkrVCap2 = (short)measurement.Value;
            }

            {
                // Assign short value to "CapBkrVCap2" field
                FieldMapping fieldMapping = fieldLookup["CapBkrVCap2"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.CapBkrVCap2 = (short)measurement.Value;
            }

            {
                // Assign double value to "LocKvVCap2" field
                FieldMapping fieldMapping = fieldLookup["LocKvVCap2"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.LocKvVCap2 = (double)measurement.Value;
            }

            {
                // Assign double value to "G1Mw" field
                FieldMapping fieldMapping = fieldLookup["G1Mw"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G1Mw = (double)measurement.Value;
            }

            {
                // Assign double value to "G1Mvr" field
                FieldMapping fieldMapping = fieldLookup["G1Mvr"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G1Mvr = (double)measurement.Value;
            }

            {
                // Assign double value to "G2Mw" field
                FieldMapping fieldMapping = fieldLookup["G2Mw"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G2Mw = (double)measurement.Value;
            }

            {
                // Assign double value to "G2Mvr" field
                FieldMapping fieldMapping = fieldLookup["G2Mvr"];
                IMeasurement measurement  = GetMeasurement(fieldMapping);
                obj.G2Mvr = (double)measurement.Value;
            }

            return(obj);
        }
 private string StreamName(Guid correlationId) =>
 TypeMapping.GetTypeName(typeof(TSaga)) + "-" + correlationId.ToString("N");
Esempio n. 33
0
 public IList <IColumnDefinition> GetColumnDefinitions(FolkeConnection connection, TypeMapping typeMap)
 {
     return(connection.Select <MySqlColumnDefinition>().All().From().Where(x => x.TABLE_NAME == typeMap.TableName && x.TABLE_SCHEMA == connection.Database).ToList().Cast <IColumnDefinition>().ToList());
 }
Esempio n. 34
0
        private static void AddParameters <T, TMe>(ISetTarget <T, TMe> target, object value, TypeMapping typeMapping, SelectedTable table,
                                                   BaseQueryBuilder baseQueryBuilder, string baseName)
        {
            foreach (var property in typeMapping.Columns.Values)
            {
                if (property.Readonly)
                {
                    continue;
                }

                var parameter = value != null?property.PropertyInfo.GetValue(value) : null;

                if (property.Reference != null && property.Reference.IsComplexType)
                {
                    AddParameters(target, parameter, property.Reference, table, baseQueryBuilder, property.ComposeName(baseName));
                }
                else
                {
                    if (property.IsJson)
                    {
                        parameter = JsonConvert.SerializeObject(parameter);
                    }
                    target.AppendSet();
                    string tableName = table.Alias;
                    baseQueryBuilder.StringBuilder.DuringColumn(tableName, property.ComposeName(baseName));
                    baseQueryBuilder.StringBuilder.Append("=");
                    var index = baseQueryBuilder.AddParameter(parameter);
                    baseQueryBuilder.StringBuilder.DuringParameter(index);
                }
            }
        }
        public void Properties_Array()
        {
            SetConfig();
            var mapping = new TypeMapping<ArrayObject, ArrayObject>();
            var properties = mapping.Properties.ToList();

            Assert.AreEqual(1, properties.Count);
            Assert.IsTrue(properties.Contains("Id"));
        }
Esempio n. 36
0
        static void WriteDeserializerReadValue(TypeBuilder typeBuilder, ILGenerator il, Type type, int tag, int itemLocalIndex)
        {
            var isCollection = type.IsCollectionType();
            var isClass      = !isCollection && type.IsComplexType();

            if (isClass)
            {
                MethodBuilder method;
                var           hasTypeMapping = TypeMapping.ContainsKey(type);

                if (hasTypeMapping)
                {
                    var index           = 0;
                    var typeMapping     = TypeMapping[type];
                    var count           = typeMapping.Count;
                    var types           = typeMapping.Select(kv => kv.Key);
                    var needBranchLabel = count > 1;
                    var branchLabel     = needBranchLabel ? il.DefineLabel() : DefaultLabel;
                    var valueTypeLocal  = il.DeclareLocal(TypeType);

                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Ldtoken, type);
                    il.Emit(OpCodes.Call, GetTypeFromHandleMethod);
                    il.Emit(OpCodes.Ldarg_3);
                    il.Emit(OpCodes.Call, ConvertBaseToConcreteTypeMethod);

                    il.Emit(OpCodes.Stloc, valueTypeLocal.LocalIndex);

                    foreach (var mapType in types)
                    {
                        index++;
                        var isLastIndex     = index == count;
                        var isLastCondition = isLastIndex && needBranchLabel;
                        var conditionLabel  = !isLastCondition?il.DefineLabel() : DefaultLabel;

                        var currentConditionLabel = isLastCondition ? branchLabel : conditionLabel;
                        il.Emit(OpCodes.Ldloc, valueTypeLocal.LocalIndex);
                        il.Emit(OpCodes.Ldtoken, mapType);
                        il.Emit(OpCodes.Call, GetTypeFromHandleMethod);
                        il.Emit(OpCodes.Call, GetTypeOpEqualityMethod);
                        il.Emit(OpCodes.Brfalse, currentConditionLabel);

                        method = GenerateDeserializerClass(typeBuilder, mapType);
                        il.Emit(OpCodes.Newobj, mapType.GetConstructor(Type.EmptyTypes));
                        il.Emit(OpCodes.Stloc, itemLocalIndex);
                        il.Emit(OpCodes.Ldarg_0);
                        il.Emit(OpCodes.Ldloc, itemLocalIndex);
                        if (mapType.IsClass)
                        {
                            il.Emit(OpCodes.Castclass, mapType);
                        }
                        else
                        {
                            il.Emit(OpCodes.Unbox_Any, mapType);
                        }
                        il.Emit(OpCodes.Ldarg_2);
                        il.Emit(OpCodes.Ldarg_3);
                        il.Emit(OpCodes.Call, method);

                        if (!isLastIndex)
                        {
                            il.Emit(OpCodes.Br, branchLabel);
                        }
                        il.MarkLabel(currentConditionLabel);
                    }
                }
                else
                {
                    method = GenerateDeserializerClass(typeBuilder, type);
                    var isTypeClass = type.IsClass;
                    if (isTypeClass)
                    {
                        il.Emit(OpCodes.Newobj, type.GetConstructor(Type.EmptyTypes));
                        il.Emit(OpCodes.Stloc, itemLocalIndex);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldloca, itemLocalIndex);
                        il.Emit(OpCodes.Initobj, type);
                    }
                    il.Emit(OpCodes.Ldarg_0);
                    if (isTypeClass)
                    {
                        il.Emit(OpCodes.Ldloc, itemLocalIndex);
                    }
                    else
                    {
                        il.Emit(OpCodes.Ldloca, itemLocalIndex);
                    }
                    il.Emit(OpCodes.Ldarg_2);
                    il.Emit(OpCodes.Ldarg_3);
                    il.Emit(OpCodes.Call, method);
                }
            }
            else if (isCollection)
            {
                WriteDeserializerClass(typeBuilder, il, type, tag, null, itemLocalIndex: itemLocalIndex);
            }
            else
            {
                var nonNullableType   = type.GetNonNullableType();
                var isTypeEnum        = type.IsEnum;
                var needTypeForReader = PrimitiveReadersWithTypes.Contains(isTypeEnum ? EnumType : nonNullableType);
                il.Emit(OpCodes.Ldarg_2);
                il.Emit(OpCodes.Ldarg_3);
                il.Emit(OpCodes.Ldc_I4, 1);
                il.Emit(OpCodes.Ldc_I4, type.IsBufferedTypeInt());
                il.Emit(OpCodes.Call, ReadNextBytesMethod);
                if (needTypeForReader)
                {
                    il.Emit(OpCodes.Ldtoken, type);
                    il.Emit(OpCodes.Call, GetTypeFromHandleMethod);
                }
                if (isTypeEnum)
                {
                    il.Emit(OpCodes.Call, PrimitiveReaderMethods[EnumType]);
                }
                else
                {
                    il.Emit(OpCodes.Call, PrimitiveReaderMethods[nonNullableType]);
                    if (type.IsNullable())
                    {
                        il.Emit(OpCodes.Newobj, type.GetNullableTypeCtor());
                    }
                }
                if (needTypeForReader)
                {
                    il.Emit(OpCodes.Unbox_Any, type);
                }
                il.Emit(OpCodes.Stloc, itemLocalIndex);
            }
        }
        public void OrderBy_CanBuildExpression()
        {
            var mapping = new TypeMapping<IPerson, Person>();
            var expression = mapping.OrderBy("p => p.Birthdate").Compile();

            var persons = new List<IPerson>
            {
                new Person{ Id = 1, Birthdate = DateTime.Parse("1987-03-02") },
                new Person{ Id = 2, Birthdate = DateTime.Parse("1987-03-01") },
            };

            var orderedPersons = persons.OrderBy(expression).ToList();

            Assert.AreEqual(2, orderedPersons[0].Id);
        }
        public void Properties_Nested()
        {
            SetConfig();
            var mapping = new TypeMapping<NestedObject, NestedObject>();
            var properties = mapping.Properties.ToList();

            Assert.AreEqual(4, properties.Count);
            Assert.IsTrue(properties.Contains("OuterName"));
            Assert.IsTrue(properties.Contains("Id"));
            Assert.IsTrue(properties.Contains("Inner.Name"));
            Assert.IsTrue(properties.Contains("Inner.Date"));
        }
Esempio n. 39
0
 public virtual string GetValue(TypeMapping mapping)
 {
     return(null);
 }
 public PersistParameterBinding(TypeMapping typeMapping, int fieldIndex)
     : this(typeMapping, fieldIndex, ParameterTransmissionType.Regular, PersistParameterBindingType.Regular)
 {
 }
 public InjectableType GetInjectableType(TypeMapping tm) => PropInjectable.GetOrAdd(tm, () => CheckSuitable(tm));
		/// <summary>
		/// Creates the type mapping for the given <paramref name="type"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="definition">The <see cref="IndexDefinition"/>.</param>
		/// <param name="type">The <see cref="ITypeDefinition"/>.</param>
		private static void CreateTypeMapping(IMansionContext context, IndexDefinition definition, ITypeDefinition type)
		{
			// create the type mapping
			var typeMapping = new TypeMapping(type);

			// map the type
			MapType(context, definition, type, typeMapping);
		}
Esempio n. 43
0
        private static void ConfigureContext()
        {
            var currentStatusPropertyConfig = new PropertyConfig("CurrentStatus")
            {
                Converter = typeof(StatusConverter)
            };

            var employeeMapping = new TypeMapping(typeof(Employee), "HashRangeTable");

            employeeMapping.AddProperty(new PropertyConfig("ManagerName")
            {
                Attribute = "Manager"
            });
            employeeMapping.AddProperty(new PropertyConfig("CompanyName")
            {
                Attribute = "Company"
            });
            employeeMapping.AddProperty(new PropertyConfig("InternalId")
            {
                Ignore = true
            });
            employeeMapping.AddProperty(currentStatusPropertyConfig);

            var employee2Mapping = new TypeMapping(typeof(Employee2), "HashRangeTable");

            employee2Mapping.AddProperty(currentStatusPropertyConfig);

            var employee3Mapping = new TypeMapping(typeof(Employee3), "HashRangeTable");

            employee3Mapping.AddProperty(currentStatusPropertyConfig);

            var versionedEmployeeMapping = new TypeMapping(typeof(VersionedEmployee), "FakeTable");

            versionedEmployeeMapping.AddProperty(new PropertyConfig("Version")
            {
                Ignore = true
            });

            var context = AWSConfigsDynamoDB.Context;

            context.TableAliases["FakeTable"] = "HashRangeTable";


            //to save retries
            if (!context.TypeMappings.ContainsKey(typeof(VersionedEmployee)))
            {
                context.AddMapping(versionedEmployeeMapping);
            }
            if (!context.TypeMappings.ContainsKey(typeof(Employee3)))
            {
                context.AddMapping(employee3Mapping);
            }

            if (!context.TypeMappings.ContainsKey(typeof(Employee2)))
            {
                context.AddMapping(employee2Mapping);
            }
            if (!context.TypeMappings.ContainsKey(typeof(Employee)))
            {
                context.AddMapping(employeeMapping);
            }
        }
		/// <summary>
		/// Maps the properties of the given <paramref name="type"/> in <paramref name="typeMapping"/>.
		/// </summary>
		/// <param name="context">The <see cref="IMansionContext"/>.</param>
		/// <param name="type">The <see cref="ITypeDefinition"/>.</param>
		/// <param name="typeMapping">The <see cref="TypeMapping"/>.</param>
		private static void MapProperties(IMansionContext context, ITypeDefinition type, TypeMapping typeMapping)
		{
			// loop over all the properties to find those with descriptors
			foreach (var property in type.Properties)
			{
				// try to get the property descriptor
				PropertyMappingDescriptor descriptor;
				if (!property.TryGetDescriptor(out descriptor))
					continue;

				// allow the descriptor to add property mappings to the type mapping
				descriptor.AddMappingTo(context, property, typeMapping);
			}
		}
Esempio n. 45
0
        public IList <IColumnDefinition> GetColumnDefinitions(FolkeConnection connection, TypeMapping typeMap)
        {
            var list = new List <IColumnDefinition>();

            using (var command = connection.CreateCommand())
            {
                command.CommandText = $"PRAGMA table_info({typeMap.TableName})";
                using (var reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        list.Add(new SqliteColumnDefinition
                        {
                            ColumnName = reader.GetString(1),
                            ColumnType = reader.GetString(2)
                        });
                    }
                }
            }
            return(list);
        }
Esempio n. 46
0
        private async Task <string> InitProcessor(string indexName)
        {
            indexName = "gdst_" + indexName.ToLower();

            _documentCount = (await _solrOperation.QueryAsync(SolrQuery.All, new QueryOptions()
            {
                StartOrCursor = new StartOrCursor.Start(0),
                Rows = 1
            })).NumFound;

            _logger.LogInformation($"{indexName} NumFound :{_documentCount}");

            var response = await _elasticClient.Indices.ExistsAsync(index : indexName.ToLower());

            var solrSchema = await _solrOperation.GetSchemaAsync("schema.xml");

            var filedTypes = solrSchema.SolrFields.Select(f => f.Type.Name).Distinct();

            _logger.LogInformation($"total fields: {solrSchema.SolrFields.Count} Types: {string.Join(",", filedTypes)}");

            if (!response.Exists)
            {
                var indexSettings = new IndexSettings()
                {
                    NumberOfReplicas = 0
                };
                var properties = new Properties();

                solrSchema.SolrFields.ForEach(sf =>
                {
                    switch (sf.Type.Name)
                    {
                    case "int":
                        properties.Add(sf.Name, new NumberProperty(NumberType.Integer));
                        break;

                    case "double":
                        properties.Add(sf.Name, new NumberProperty(NumberType.Double));
                        break;

                    case "float":
                        properties.Add(sf.Name, new NumberProperty(NumberType.Float));
                        break;

                    case "string":
                        properties.Add(sf.Name, new KeywordProperty());
                        break;

                    case "date":
                        properties.Add(sf.Name, new DateProperty());
                        break;

                    case "location_rpt":
                        if (sf.Name == "GEO")
                        {
                            properties.Add(sf.Name, new GeoShapeProperty());
                        }
                        else
                        {
                            properties.Add(sf.Name, new GeoPointProperty());
                        }

                        break;

                    default:
                        properties.Add(sf.Name, new TextProperty());
                        break;
                    }
                });

                var typeMappings = new TypeMapping()
                {
                    Properties = properties
                };

                _elasticClient.Indices.Create(indexName, p =>
                                              p.InitializeUsing(new IndexState()
                {
                    Settings = indexSettings,
                    Mappings = typeMappings
                }));
            }

            return(indexName);
        }
 public override string GetValue(TypeMapping mapping)
 {
     return(GetObsoletionMarker(mapping));
 }
Esempio n. 48
0
 public TypeMapperProvider(TypeMapping typeMapping)
 {
     _typeMapping = typeMapping;
 }
Esempio n. 49
0
 public MemberConfigurator(TypeMapping typeMapping)
 {
     _typeMapping = typeMapping;
 }
		public LifetimeManager CreateLifetimeManager(TypeMapping typeMapping)
		{
            var customLifetimeManager = configurationDetails.IsMarkedWithCustomLifetimeManager(typeMapping.From);
            return customLifetimeManager.Item1 ? customLifetimeManager.Item2 : new TransientLifetimeManager();
		}
Esempio n. 51
0
        private void CollectFromECAPhasorCollection(List <IMeasurement> measurements, TypeMapping typeMapping, TVA_LSETestHarness.Model.ECA.PhasorCollection data, TVA_LSETestHarness.Model.ECA._PhasorCollectionMeta meta)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            {
                // Convert values from TVA_LSETestHarness.Model.ECA.Phasor UDT array for "Phasors" field to measurements
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["Phasors"];
                int          dataLength   = data.Phasors.Length;
                int          metaLength   = meta.Phasors.Length;

                if (dataLength != metaLength)
                {
                    throw new InvalidOperationException($"Values array length ({dataLength}) and MetaValues array length ({metaLength}) for field \"Phasors\" must be the same.");
                }

                PushWindowFrameTime(arrayMapping);

                for (int i = 0; i < dataLength; i++)
                {
                    TypeMapping nestedMapping = GetUDTArrayTypeMapping(arrayMapping, i);
                    CollectFromECAPhasor(measurements, nestedMapping, data.Phasors[i], meta.Phasors[i]);
                }

                PopWindowFrameTime(arrayMapping);
            }
        }
        /// <summary>
        /// Initializes an instance of the EfMapping class
        /// </summary>
        /// <param name="db">The context to get the mapping from</param>
        public EfMapping(DbContext db)
        {
            this.TypeMappings = new Dictionary<Type, TypeMapping>();

            var metadata = ((IObjectContextAdapter)db).ObjectContext.MetadataWorkspace;

            //EF61Test(metadata);

            // Conceptual part of the model has info about the shape of our entity classes
            var conceptualContainer = metadata.GetItems<EntityContainer>(DataSpace.CSpace).Single();

            // Storage part of the model has info about the shape of our tables
            var storeContainer = metadata.GetItems<EntityContainer>(DataSpace.SSpace).Single();

            // Object part of the model that contains info about the actual CLR types
            var objectItemCollection = ((ObjectItemCollection)metadata.GetItemCollection(DataSpace.OSpace));

            // Loop thru each entity type in the model
            foreach (var set in conceptualContainer.BaseEntitySets.OfType<EntitySet>())
            {

                // Find the mapping between conceptual and storage model for this entity set
                var mapping = metadata.GetItems<EntityContainerMapping>(DataSpace.CSSpace)
                        .Single()
                        .EntitySetMappings
                        .Single(s => s.EntitySet == set);



                var typeMapping = new TypeMapping
                {
                    TableMappings = new List<TableMapping>(),
                    EntityType = GetClrType(metadata, objectItemCollection, set)
                };

                this.TypeMappings.Add(typeMapping.EntityType, typeMapping);

                var tableMapping = new TableMapping
                {
                    PropertyMappings = new List<PropertyMapping>(),
                };
                var mappingToLookAt = mapping.EntityTypeMappings.FirstOrDefault(m => m.IsHierarchyMapping) ?? mapping.EntityTypeMappings.First();
                tableMapping.Schema = mappingToLookAt.Fragments[0].StoreEntitySet.Schema;
                tableMapping.TableName = mappingToLookAt.Fragments[0].StoreEntitySet.Table ?? mappingToLookAt.Fragments[0].StoreEntitySet.Name;
                typeMapping.TableMappings.Add(tableMapping);

                Action<Type, System.Data.Entity.Core.Mapping.PropertyMapping, string> recurse = null;
                recurse = (t, item, path) =>
                {
                    if (item is ComplexPropertyMapping)
                    {
                        var complex = item as ComplexPropertyMapping;
                        foreach (var child in complex.TypeMappings[0].PropertyMappings)
                        {
                            recurse(t, child, path + complex.Property.Name + ".");
                        }
                    }
                    else if (item is ScalarPropertyMapping)
                    {
                        var scalar = item as ScalarPropertyMapping;
                        tableMapping.PropertyMappings.Add(new PropertyMapping
                        {
                            ColumnName = scalar.Column.Name,
                            DataType = scalar.Column.TypeName,
                            DataTypeFull = GetFullTypeName(scalar),
                            PropertyName = path + item.Property.Name,
                            ForEntityType = t
                        });
                    }
                };

                Func<MappingFragment, Type> getClr = m =>
                {
                    return GetClrTypeFromTypeMapping(metadata, objectItemCollection, m.TypeMapping as EntityTypeMapping);
                };

                if (mapping.EntityTypeMappings.Any(m => m.IsHierarchyMapping))
                {
                    var withConditions = mapping.EntityTypeMappings.Where(m => m.Fragments[0].Conditions.Any()).ToList();
                    tableMapping.TPHConfiguration = new TPHConfiguration
                       {
                           ColumnName = withConditions.First().Fragments[0].Conditions[0].Column.Name,
                           Mappings = new Dictionary<Type, string>()
                       };
                    foreach (var item in withConditions)
                    {
                        tableMapping.TPHConfiguration.Mappings.Add(
                            getClr(item.Fragments[0]),
                            ((ValueConditionMapping)item.Fragments[0].Conditions[0]).Value.ToString()
                            );
                    }
                }

                foreach (var entityType in mapping.EntityTypeMappings)
                {
                    foreach (var item in entityType.Fragments[0].PropertyMappings)
                    {
                        recurse(getClr(entityType.Fragments[0]), item, "");
                    }
                }

                //Inheriting propertymappings contains duplicates for id's. 
                tableMapping.PropertyMappings = tableMapping.PropertyMappings.GroupBy(p => p.PropertyName)
                    .Select(g => g.OrderByDescending(outer => g.Count(inner => inner.ForEntityType.IsSubclassOf(outer.ForEntityType))).First())
                    .ToList();
                foreach (var item in tableMapping.PropertyMappings)
                {
                    if ((mappingToLookAt.EntityType ?? mappingToLookAt.IsOfEntityTypes[0]).KeyProperties.Any(p => p.Name == item.PropertyName))
                    {
                        item.IsPrimaryKey = true;
                    }
                }
            }
        }
Esempio n. 53
0
        public TVA_LSETestHarness.Model.ECA.PhasorCollection FillOutputData()
        {
            TypeMapping outputMapping = MappingCompiler.GetTypeMapping(OutputMapping);

            return(FillECAPhasorCollection(outputMapping));
        }
 public virtual void Visit(TypeMapping type)
 {
     Visit(type.Fields);
     Visit(type.Methods.Where(m => ((IMethodDefinition)m.Representative).IsConstructor));
     Visit(type.Properties);
     Visit(type.Events);
     Visit(type.Methods.Where(m => !((IMethodDefinition)m.Representative).IsConstructor));
     Visit((IEnumerable<TypeMapping>)type.NestedTypes);
 }
Esempio n. 55
0
        public TVA_LSETestHarness.Model.ECA._PhasorCollectionMeta FillOutputMeta()
        {
            TypeMapping outputMeta = MappingCompiler.GetTypeMapping(OutputMapping);

            return(FillECA_PhasorCollectionMeta(outputMeta));
        }
Esempio n. 56
0
 public override void Visit(TypeMapping mapping)
 {
     Visit(mapping.Differences);
     if (mapping.ShouldDiffMembers)
         base.Visit(mapping);
 }
Esempio n. 57
0
        private TVA_LSETestHarness.Model.ECA._PhasorCollectionMeta FillECA_PhasorCollectionMeta(TypeMapping typeMapping)
        {
            Dictionary <string, FieldMapping> fieldLookup = typeMapping.FieldMappings.ToDictionary(mapping => mapping.Field.Identifier);

            TVA_LSETestHarness.Model.ECA._PhasorCollectionMeta obj = new TVA_LSETestHarness.Model.ECA._PhasorCollectionMeta();

            {
                // Initialize TVA_LSETestHarness.Model.ECA._PhasorMeta UDT array for "Phasors" field
                ArrayMapping arrayMapping = (ArrayMapping)fieldLookup["Phasors"];
                PushWindowFrameTime(arrayMapping);

                List <TVA_LSETestHarness.Model.ECA._PhasorMeta> list = new List <TVA_LSETestHarness.Model.ECA._PhasorMeta>();
                int count = GetUDTArrayTypeMappingCount(arrayMapping);

                for (int i = 0; i < count; i++)
                {
                    TypeMapping nestedMapping = GetUDTArrayTypeMapping(arrayMapping, i);
                    list.Add(FillECA_PhasorMeta(nestedMapping));
                }

                obj.Phasors = list.ToArray();
                PopWindowFrameTime(arrayMapping);
            }

            return(obj);
        }
 public void Add(TypeMapping typeMapping)
 {
     Items.Add(typeMapping);
 }
Esempio n. 59
0
 public DbMappingEntity(string tableId, TypeMapping typeMapping)
 {
     this.tableId = tableId;
     TypeMapping  = typeMapping;
 }