示例#1
0
 public DefaultMemberMapper(MappingContainer container, MemberMapOptions options, MappingMember targetMember, MappingMember sourceMember,
                            ValueConverter converter)
     : base(container, options, targetMember, converter)
 {
     Throw.IfArgumentNull(sourceMember, nameof(sourceMember));
     _sourceMember = sourceMember;
 }
示例#2
0
 protected MemberMapper(MappingContainer container, MemberMapOptions options, MappingMember targetMember, ValueConverter converter)
 {
     _container   = container;
     _options     = options;
     TargetMember = targetMember;
     _converter   = converter;
 }
		public BugzillaProfile()
		{
			UserMapping = new MappingContainer();
			StatesMapping = new MappingContainer();
			SeveritiesMapping = new MappingContainer();
			PrioritiesMapping = new MappingContainer();
			RolesMapping = new MappingContainer();
		}
示例#4
0
 public BugzillaProfile()
 {
     UserMapping       = new MappingContainer();
     StatesMapping     = new MappingContainer();
     SeveritiesMapping = new MappingContainer();
     PrioritiesMapping = new MappingContainer();
     RolesMapping      = new MappingContainer();
 }
 internal ConventionContext(MappingContainer container, Type sourceType, Type targetType, MemberMapOptions options)
 {
     _container    = container;
     SourceType    = sourceType;
     TargetType    = targetType;
     Options       = options;
     SourceMembers = new MappingMemberCollection(GetMembers(sourceType, true, false));
     TargetMembers = new MappingMemberCollection(GetMembers(targetType, false, true));
 }
		public TfsPluginProfile()
		{
			UserMapping = new MappingContainer();
			EntityMapping = new SimpleMappingContainer();
			ProjectsMapping = new MappingContainer();
			SourceControlEnabled = true;
			WorkItemsEnabled = false;
			StartRevision = "1";
			StartWorkItem = "1";
		}
示例#7
0
 public TfsPluginProfile()
 {
     UserMapping          = new MappingContainer();
     EntityMapping        = new SimpleMappingContainer();
     ProjectsMapping      = new MappingContainer();
     SourceControlEnabled = true;
     WorkItemsEnabled     = false;
     StartRevision        = "1";
     StartWorkItem        = "1";
 }
示例#8
0
        public void SetTable_RegisterTable()
        {
            var mapping = new MappingContainer();

            mapping.SetTable <User>("users");
            mapping.SetTable <Role>("roles");

            Assert.IsTrue(mapping.IsTableRegistered <User>());
            Assert.IsTrue(mapping.IsTableRegistered <Role>());
        }
示例#9
0
 public static bool TryCreate(Type sourceType, Type targetType, MappingContainer container, out ValueConverter converter)
 {
     converter = null;
     if (sourceType.IsEnumerable(out var sourceElementType) && targetType.IsEnumerable(out var targetElementType))
     {
         converter = new EnumerableValueConverter(container, sourceElementType, targetElementType);
         return(true);
     }
     return(false);
 }
示例#10
0
        public override TypeConverter.StandardValuesCollection GetStandardValues(ITypeDescriptorContext context)
        {
            // ensure that the mapping table is available for the enumeration type
            // it builds the standard value collection too
            EnsureMappingsAvailable(EnumType, CultureInfo.CurrentCulture);
            MappingContainer container = mappings[EnumType];

            // wrap it with the right type. it is also possible to use Enum.GetValues
            TypeConverter.StandardValuesCollection values = new StandardValuesCollection(container.standardValues);
            return(values);
        }
示例#11
0
        public void ContainsProperty()
        {
            var mapping = new MappingContainer();

            mapping
            .SetTable <User>("users")
            .SetPrimaryKeyColumn("id", p => p.Id);

            Assert.IsTrue(mapping.GetTable <User>().ContainsProperty("Id"));
            Assert.IsFalse(mapping.GetTable <User>().ContainsProperty("id"));
            Assert.IsFalse(mapping.GetTable <User>().ContainsProperty("UserName"));
        }
示例#12
0
 public static bool TryCreate(Type sourceType, Type targetType, MappingContainer container, out ValueMapper mapper)
 {
     mapper = null;
     if (sourceType.IsEnumerable(out var sourceElementType) && targetType.IsEnumerable(out var targetElementType))
     {
         var sourceElementTypeInfo = sourceElementType.GetTypeInfo();
         var targetElementTypeInfo = targetElementType.GetTypeInfo();
         if (!sourceElementTypeInfo.IsValueType && !sourceElementTypeInfo.IsPrimitive &&
             !targetElementTypeInfo.IsValueType && !targetElementTypeInfo.IsPrimitive)
         {
             mapper = new EnumerableMapper(container, sourceElementType, targetElementType);
             return(true);
         }
     }
     return(false);
 }
示例#13
0
        public void GetColumnsByPropertyName()
        {
            var mapping = new MappingContainer();

            mapping
            .SetTable <User>("users")
            .SetPrimaryKeyColumn("id", p => p.Id);

            var result = mapping.GetTable <User>().GetColumnByPropertyName("Id");

            Assert.AreEqual(typeof(User), result.ModelType);
            Assert.AreEqual("users", result.TableName);
            Assert.AreEqual(typeof(PrimaryKeyColumn), result.GetType());
            Assert.AreEqual("id", result.ColumnName);
            Assert.AreEqual("Id", result.Property.Name);
            Assert.AreEqual(typeof(User), result.ModelType);
            Assert.AreEqual(true, result.IsDatabaseGenerated);
            Assert.AreEqual(false, result.IsIgnored);
        }
        public WorkItemsContext()
        {
            EntityMapping = new SimpleMappingContainer()
            {
                new SimpleMappingElement {
                    First = "Bug", Second = "Bug"
                },
                new SimpleMappingElement {
                    First = "User Story", Second = "User Story"
                },
                new SimpleMappingElement {
                    First = "Task", Second = "Feature"
                },
                new SimpleMappingElement {
                    First = "Issue", Second = "Request"
                }
            };
            ProjectsMapping = new MappingContainer()
            {
                new MappingElement()
                {
                    Key   = ConfigHelper.Instance.TestCollectionProject,
                    Value = new MappingLookup()
                    {
                        Id = 1, Name = "Test"
                    }
                }
            };
            WorkItems      = new List <WorkItem>();
            Uri            = ConfigHelper.Instance.TestCollection;
            Credential     = new NetworkCredential(ConfigHelper.Instance.Login, ConfigHelper.Instance.Password, ConfigHelper.Instance.Domen);
            _tfsCollection = new TfsTeamProjectCollection(new Uri(Uri), Credential);
            _workItemStore = _tfsCollection.GetService <WorkItemStore>();

            ObjectFactory.Configure(x => x.AddRegistry <WorkItemsUnitTestsRegistry>());
            AddReplyForCreateCommand <BugDTO, BugCreatedMessage>(_bugs);
            AddReplyForCreateCommand <UserStoryDTO, UserStoryCreatedMessage>(_userStories);
            AddReplyForCreateCommand <FeatureDTO, FeatureCreatedMessage>(_features);
            AddReplyForCreateCommand <RequestDTO, RequestCreatedMessage>(_requests);

            AddReplyForUpdateCommand <UserStoryDTO, UserStoryField, UserStoryUpdatedMessage>(TpUserStories, UserStoryField.EntityStateID);
        }
示例#15
0
    void Start()
    {
        /*
         * sparql = WWW.EscapeURL("prefix rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nprefix owl: <http://www.w3.org/2002/07/owl#>\nSELECT distinct ?p ?o ?predicate_label ?object_label\nWHERE {\n   <http://purl.obolibrary.org/obo/FLOPO_0001906> ?p ?o .\n   OPTIONAL { ?p rdfs:label ?predicate_label . }\n   OPTIONAL { ?o rdfs:label ?object_label . }\n}");
         * url = url + sparql;
         * print(url);
         * var headers = new Dictionary<string, string>();
         * WWWForm form = new WWWForm();
         * form.
         * //headers.Add("Content-Type", "application/sparql-results+json");
         * headers.Add("Accept", "application/sparql-results+json");
         * headers.Add("Content-Type", "application/sparql-results+json");
         * www = new WWW(url, null, headers);
         * StartCoroutine(WaitForRequest(www));
         */

        MappingContainer mc = new MappingContainer();

        mc.loadFromFile(@"Assets/xml_sample.rdf");
    }
		private static MappingContainer GetMappingFor(MappingSourceEntry source, IEnumerable<MappingElement> mapped)
		{
			var elements = new List<MappingElement>();
			IEnumerable<string> thirdPartyItems = source.ThirdPartyItems;

			var existingMappingElements = mapped
				.FilterOutObsoleteItemsBy(thirdPartyItems)
				.FilterOutEmptyItems();

			elements.AddRange(existingMappingElements);

			var newMappingElements = thirdPartyItems
				.FilterOutDuplicateThirdPartyItemsBy(elements)
				.ToMappingElements(source);
			elements.AddRange(newMappingElements);

			var container = new MappingContainer();
			container.AddRange(elements.OrderBy(r => r.Key).ToList());

			return container;
		}
示例#17
0
        public void SetTable_WithPrimaryKeyInfos()
        {
            var mapping = new MappingContainer();

            mapping
            .SetTable <User>("users")
            .SetPrimaryKeyColumn("id", p => p.Id, false, true);

            var table  = mapping.GetTable <User>();
            var result = table.MappingByColumnName["id"] as PrimaryKeyColumn;

            Assert.AreEqual(typeof(User), table.ModelType);
            Assert.AreEqual("users", table.TableName);
            Assert.AreEqual(typeof(User), result.ModelType);
            Assert.AreEqual("users", result.TableName);
            Assert.AreEqual(typeof(PrimaryKeyColumn), result.GetType());
            Assert.AreEqual("id", result.ColumnName);
            Assert.AreEqual("Id", result.Property.Name);
            Assert.AreEqual(typeof(User), result.ModelType);
            Assert.AreEqual(false, result.IsDatabaseGenerated);
            Assert.AreEqual(true, result.IsIgnored);
        }
示例#18
0
        public void SetTable_WithColumnInfos()
        {
            var mapping = new MappingContainer();

            mapping
            .SetTable <User>("users")
            .SetColumn("username", p => p.UserName, true, true);

            var table  = mapping.GetTable <User>();
            var result = table.MappingByColumnName["username"] as Column;

            Assert.AreEqual(typeof(User), table.ModelType);
            Assert.AreEqual("users", table.TableName);
            Assert.AreEqual(typeof(User), result.ModelType);
            Assert.AreEqual("users", result.TableName);
            Assert.AreEqual(typeof(Column), result.GetType());
            Assert.AreEqual("username", result.ColumnName);
            Assert.AreEqual("UserName", result.Property.Name);
            Assert.AreEqual(typeof(User), result.ModelType);
            Assert.AreEqual(true, result.IsDatabaseGenerated);
            Assert.AreEqual(true, result.IsIgnored);
        }
示例#19
0
        private static MappingContainer GetMappingFor(MappingSourceEntry source, IEnumerable <MappingElement> mapped)
        {
            var elements = new List <MappingElement>();
            IEnumerable <string> thirdPartyItems = source.ThirdPartyItems;

            var existingMappingElements = mapped
                                          .FilterOutObsoleteItemsBy(thirdPartyItems)
                                          .FilterOutEmptyItems();

            elements.AddRange(existingMappingElements);

            var newMappingElements = thirdPartyItems
                                     .FilterOutDuplicateThirdPartyItemsBy(elements)
                                     .ToMappingElements(source);

            elements.AddRange(newMappingElements);

            var container = new MappingContainer();

            container.AddRange(elements.OrderBy(r => r.Key).ToList());

            return(container);
        }
示例#20
0
 public static InstanceMapper <TSource, TTarget> GetInstance(MappingContainer container)
 {
     return(_mappers.GetOrAdd(container, key => new InstanceMapper <TSource, TTarget>(key)));
 }
示例#21
0
 void Initialize(MappingContainer source)
 {
     this.source = source;
     sourceIndex = 0;
     rePopulateQueue();
 }
示例#22
0
        public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
        {
            object result = value;

            //
            // source value have to be a enumeration type or string, destination a string type
            //
            if (destinationType == typeof(string) &&
                value != null)
            {
                if (value.GetType().IsEnum)
                {
                    // ensure that the mapping table is available for the enumeration type
                    EnsureMappingsAvailable(value.GetType(), culture);
                    MappingContainer  container = mappings[value.GetType()];
                    MappingPerCulture mapping   = container.mappingsPerCulture[culture];
                    string            valueStr  = value.ToString();

                    if (mapping.fieldDisplayNameFound)
                    {
                        if (valueStr.IndexOf(',') < 0)
                        {
                            // simple enum value
                            if (mapping.mappings.ContainsKey(valueStr))
                            {
                                result = mapping.mappings[valueStr];
                            }
                            else
                            {
                                throw GetConvertToException(valueStr, destinationType);
                            }
                        }
                        else
                        {
                            // flag enum with more then one enum value
                            string[] parts = valueStr.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                            System.Text.StringBuilder builder = new System.Text.StringBuilder();
                            string tmp;
                            for (int index = 0; index < parts.Length; index++)
                            {
                                tmp = parts[index];
                                if (mapping.mappings.ContainsKey(tmp))
                                {
                                    builder.Append(mapping.mappings[tmp]);
                                    builder.Append(", ");
                                }
                                else
                                {
                                    throw GetConvertToException(valueStr, destinationType);
                                }
                            }

                            builder.Length -= 2;
                            result          = builder.ToString();
                        }
                    }
                    else
                    {
                        result = value.ToString();
                    }
                }
            }
            else
            {
                result = base.ConvertTo(context, culture, value, destinationType);
            }

            return(result);
        }
		public GitPluginProfile()
		{
			UserMapping = new MappingContainer();
			StartRevision = GitRevisionId.UtcTimeMin.ToShortDateString();
		}
示例#24
0
 public EnumerableConverterBuilder(MappingContainer container)
 {
     _container = container;
 }
		public SubversionPluginProfile()
		{
			UserMapping = new MappingContainer();
			StartRevision = string.Empty;
		}
 public GitPluginProfile()
 {
     UserMapping   = new MappingContainer();
     StartRevision = GitRevisionId.UtcTimeMin.ToShortDateString();
 }
示例#27
0
        public void DiscoverTable()
        {
            var mapping = new MappingContainer();

            var result = mapping.DiscoverMappingFor <UserWithAttributes>();

            Assert.AreEqual("Users", result.TableName);
            Assert.AreEqual(typeof(UserWithAttributes), result.ModelType);

            Assert.AreEqual(5, result.MappingByColumnName.Count);

            // Id
            var idColumn = result.MappingByColumnName["Id"];

            Assert.AreEqual(typeof(PrimaryKeyColumn), idColumn.GetType());
            Assert.AreEqual("Id", idColumn.ColumnName);
            Assert.AreEqual("Id", idColumn.Property.Name);
            Assert.AreEqual(typeof(UserWithAttributes), idColumn.ModelType);
            Assert.AreEqual("Users", idColumn.TableName);
            Assert.AreEqual(true, idColumn.IsDatabaseGenerated);
            Assert.AreEqual(false, idColumn.IsIgnored);

            // UserName
            var userNameColumn = result.MappingByColumnName["UserName"];

            Assert.AreEqual(typeof(Column), userNameColumn.GetType());
            Assert.AreEqual("UserName", userNameColumn.ColumnName);
            Assert.AreEqual("UserName", userNameColumn.Property.Name);
            Assert.AreEqual(typeof(UserWithAttributes), userNameColumn.ModelType);
            Assert.AreEqual("Users", userNameColumn.TableName);
            Assert.AreEqual(false, userNameColumn.IsDatabaseGenerated);
            Assert.AreEqual(false, userNameColumn.IsIgnored);

            // RowVersion
            var rowVersionColumn = result.MappingByColumnName["RowVersion"];

            Assert.AreEqual(typeof(Column), rowVersionColumn.GetType());
            Assert.AreEqual("RowVersion", rowVersionColumn.ColumnName);
            Assert.AreEqual("RowVersion", rowVersionColumn.Property.Name);
            Assert.AreEqual(typeof(UserWithAttributes), rowVersionColumn.ModelType);
            Assert.AreEqual("Users", rowVersionColumn.TableName);
            Assert.AreEqual(true, rowVersionColumn.IsDatabaseGenerated);
            Assert.AreEqual(false, userNameColumn.IsIgnored);

            // role id
            var roleIdColumn = result.MappingByColumnName["role_id"];

            Assert.AreEqual(typeof(Column), roleIdColumn.GetType());
            Assert.AreEqual("role_id", roleIdColumn.ColumnName);
            Assert.AreEqual("RoleId", roleIdColumn.Property.Name);
            Assert.AreEqual(typeof(UserWithAttributes), roleIdColumn.ModelType);
            Assert.AreEqual("Users", roleIdColumn.TableName);
            Assert.AreEqual(false, roleIdColumn.IsDatabaseGenerated);
            Assert.AreEqual(false, roleIdColumn.IsIgnored);

            // Age
            var ageColumn = result.MappingByColumnName["Age"];

            Assert.AreEqual(typeof(Column), ageColumn.GetType());
            Assert.AreEqual("Age", ageColumn.ColumnName);
            Assert.AreEqual("Age", ageColumn.Property.Name);
            Assert.AreEqual(typeof(UserWithAttributes), ageColumn.ModelType);
            Assert.AreEqual("Users", ageColumn.TableName);
            Assert.AreEqual(false, ageColumn.IsDatabaseGenerated);
            Assert.AreEqual(true, ageColumn.IsIgnored);
        }
示例#28
0
        public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
        {
            object result = null;

            //
            // source value should be a string
            //
            if (value != null &&
                value is string)
            {
                // ensure that the mapping table is available for the enumeration type
                EnsureMappingsAvailable(context.PropertyDescriptor.PropertyType, culture);
                MappingContainer  container = mappings[context.PropertyDescriptor.PropertyType];
                MappingPerCulture mapping   = container.mappingsPerCulture[culture];
                string            valueStr  = value.ToString();

                if (mapping.fieldDisplayNameFound)
                {
                    if (valueStr.IndexOf(',') < 0)
                    {
                        // simple value
                        if (mapping.reverseMappings.ContainsKey(valueStr))
                        {
                            result = mapping.reverseMappings[valueStr];
                        }
                        else
                        {
                            throw GetConvertFromException(valueStr);
                        }
                    }
                    else
                    {
                        // concated values (Flags enumeration)
                        string[] valueParts = valueStr.Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                        string   tmp        = valueParts[0];
                        int      tmpResult;
                        if (mapping.reverseMappings.ContainsKey(tmp))
                        {
                            tmpResult = (int)mapping.reverseMappings[tmp];
                        }
                        else
                        {
                            throw GetConvertFromException(valueStr);
                        }
                        for (int index = 1; index < valueParts.Length; index++)
                        {
                            tmp = valueParts[index];
                            if (mapping.reverseMappings.ContainsKey(tmp))
                            {
                                tmpResult |= (int)mapping.reverseMappings[tmp];
                            }
                            else
                            {
                                throw GetConvertFromException(valueStr);
                            }
                        }
                        result = Enum.ToObject(context.PropertyDescriptor.PropertyType, tmpResult);
                    }
                }
                else
                {
                    result = Enum.Parse(context.PropertyDescriptor.PropertyType, valueStr);
                }
            }
            else
            {
                result = base.ConvertFrom(context, culture, value);
            }

            return(result);
        }
示例#29
0
 private TypeMapper(MappingContainer container)
 {
     _container = container;
 }
 public ValueConverterCollection(MappingContainer container)
 {
     _container = container;
 }
示例#31
0
 private InstanceMapper(MappingContainer container)
 {
     _converter = container.GetMapFunc <TSource, TTarget>();
     _mapper    = container.GetMapAction <TSource, TTarget>();
 }
示例#32
0
        /// <summary>
        /// Build the mappings between the field values of the enumeration type and the display name for the field
        /// </summary>
        /// <param name="enumType">Type of the enum.</param>
        private void EnsureMappingsAvailable(Type enumType, CultureInfo culture)
        {
            if (mappings == null)
            {
                mappings = new Dictionary <Type, MappingContainer>();
            }

            MappingContainer container;

            if (mappings.ContainsKey(enumType))
            {
                container = mappings[enumType];
                if (container.mappingsPerCulture.ContainsKey(culture))
                {
                    return;
                }
            }
            else
            {
                container = new MappingContainer();
                container.mappingsPerCulture = new Dictionary <CultureInfo, MappingPerCulture>();
            }

            MappingPerCulture            mapping = new MappingPerCulture();
            IDictionary <object, string> enumTypeValueMapping        = new Dictionary <object, string>();
            IDictionary <string, object> enumTypeValueReverseMapping = new Dictionary <string, object>();
            List <object> enumTypeStandardValues = new List <object>();

            ResourceManager man;
            GetFieldName    getDisplayName;

            // look for a resource manager
            if (resourceManagers != null &&
                resourceManagers.ContainsKey(enumType))
            {
                man            = resourceManagers[enumType];
                getDisplayName = delegate(string key) { string displayName = man.GetString(key, culture); if (displayName == null)
                                                        {
                                                            return(key);
                                                        }
                                                        return(displayName); };
            }
            else
            {
                getDisplayName = delegate(string key) { return(key); };
            }

            // build the mapping (reflection of the enum type)
            string enumTypeFullNameForKey = enumType.FullName.Replace('.', '_');

            FieldInfo[] fields = enumType.GetFields();
            foreach (var field in fields)
            {
                if (field.FieldType == enumType)
                {
                    object fieldValue  = Enum.Parse(enumType, field.Name);
                    string key         = enumTypeFullNameForKey + "_" + field.Name;
                    string displayName = getDisplayName(key);
                    if (String.Compare(key, displayName) == 0)
                    {
                        object[] attributes = field.GetCustomAttributes(typeof(DisplayNameAttribute), false);
                        if (attributes != null &&
                            attributes.Length > 0)
                        {
                            DisplayNameAttribute attrib = (DisplayNameAttribute)(attributes[0]);
                            displayName = attrib.DisplayName;
                            mapping.fieldDisplayNameFound = true;
                        }
                        else
                        {
                            displayName = field.Name;
                        }
                    }
                    else
                    {
                        mapping.fieldDisplayNameFound = true;
                    }
                    if (!enumTypeValueMapping.ContainsKey(field.Name))
                    {
                        enumTypeValueMapping.Add(field.Name, displayName);
                    }
                    enumTypeValueReverseMapping.Add(displayName, fieldValue);
                    enumTypeStandardValues.Add(fieldValue);
                }
            }

            mapping.reverseMappings = enumTypeValueReverseMapping;
            if (mapping.fieldDisplayNameFound)
            {
                mapping.mappings = enumTypeValueMapping;
            }

            // add mapping for culture to the mapping container for the enum type
            lock (container.mappingsPerCulture)
            {
                if (!container.mappingsPerCulture.ContainsKey(culture))
                {
                    container.mappingsPerCulture.Add(culture, mapping);
                }
            }
            // if standardValues == null the container is the new
            if (container.standardValues == null)
            {
                // lock the mapping dictionary because it is static and should be thread safe
                lock (mappings)
                {
                    container.standardValues = enumTypeStandardValues;
                    // double check is necessary because of concurrent threads
                    if (!mappings.ContainsKey(enumType))
                    {
                        mappings.Add(enumType, container);
                    }
                    else
                    {
                        // a new container for this enum type is added before our new container
                        // but we have to check that a mapping for the current culture is available
                        container = mappings[enumType];
                        if (!container.mappingsPerCulture.ContainsKey(culture))
                        {
                            lock (container.mappingsPerCulture)
                            {
                                if (!container.mappingsPerCulture.ContainsKey(culture))
                                {
                                    container.mappingsPerCulture.Add(culture, mapping);
                                }
                            }
                        }
                    }
                }
            }
        }
 public LambdaMemberMapper(MappingContainer container, MemberMapOptions options, MappingMember targetMember, Func <TSource, TMember> expression)
     : base(container, options, targetMember, null)
 {
     Throw.IfArgumentNull(expression, nameof(expression));
     _expression = expression;
 }
示例#34
0
 public EnumerableValueConverter(MappingContainer container, Type sourceElementType, Type targetElementType)
 {
     _container         = container;
     _sourceElementType = sourceElementType;
     _targetElementType = targetElementType;
 }
示例#35
0
        /// <summary>
        /// Build the mappings between the field values of the enumeration type and the display name for the field
        /// </summary>
        /// <param name="enumType">Type of the enum.</param>
        private void EnsureMappingsAvailable(Type enumType, CultureInfo culture)
        {
            if (mappings == null)
                mappings = new Dictionary<Type, MappingContainer>();

            MappingContainer container;
            if (mappings.ContainsKey(enumType))
            {
                container = mappings[enumType];
                if (container.mappingsPerCulture.ContainsKey(culture))
                    return;
            }
            else
            {
                container = new MappingContainer();
                container.mappingsPerCulture = new Dictionary<CultureInfo, MappingPerCulture>();
            }

            MappingPerCulture mapping = new MappingPerCulture();
            IDictionary<object, string> enumTypeValueMapping = new Dictionary<object, string>();
            IDictionary<string, object> enumTypeValueReverseMapping = new Dictionary<string, object>();
            List<object> enumTypeStandardValues = new List<object>();

            ResourceManager man;
            GetFieldName getDisplayName;
            // look for a resource manager
            if (resourceManagers != null &&
                resourceManagers.ContainsKey(enumType))
            {
                man = resourceManagers[enumType];
                getDisplayName = delegate(string key) { string displayName = man.GetString(key, culture); if (displayName == null) return key; return displayName; };
            }
            else
            {
                getDisplayName = delegate(string key) { return key; };
            }

            // build the mapping (reflection of the enum type)
            string enumTypeFullNameForKey = enumType.FullName.Replace('.', '_');
            FieldInfo[] fields = enumType.GetFields();
            foreach (var field in fields)
            {
                if (field.FieldType == enumType)
                {
                    object fieldValue = Enum.Parse(enumType, field.Name);
                    string key = enumTypeFullNameForKey + "_" + field.Name;
                    string displayName = getDisplayName(key);
                    if (String.Compare(key, displayName) == 0)
                    {
                        object[] attributes = field.GetCustomAttributes(typeof(DisplayNameAttribute), false);
                        if (attributes != null &&
                            attributes.Length > 0)
                        {
                            DisplayNameAttribute attrib = (DisplayNameAttribute)(attributes[0]);
                            displayName = attrib.DisplayName;
                            mapping.fieldDisplayNameFound = true;
                        }
                        else
                        {
                            displayName = field.Name;
                        }
                    }
                    else
                    {
                        mapping.fieldDisplayNameFound = true;
                    }
                    if (!enumTypeValueMapping.ContainsKey(field.Name))
                        enumTypeValueMapping.Add(field.Name, displayName);
                    enumTypeValueReverseMapping.Add(displayName, fieldValue);
                    enumTypeStandardValues.Add(fieldValue);
                }
            }

            mapping.reverseMappings = enumTypeValueReverseMapping;
            if (mapping.fieldDisplayNameFound)
                mapping.mappings = enumTypeValueMapping;

            // add mapping for culture to the mapping container for the enum type
            lock (container.mappingsPerCulture)
            {
                if (!container.mappingsPerCulture.ContainsKey(culture))
                    container.mappingsPerCulture.Add(culture, mapping);
            }
            // if standardValues == null the container is the new
            if (container.standardValues == null)
            {
                // lock the mapping dictionary because it is static and should be thread safe
                lock (mappings)
                {
                    container.standardValues = enumTypeStandardValues;
                    // double check is necessary because of concurrent threads
                    if (!mappings.ContainsKey(enumType))
                    {
                        mappings.Add(enumType, container);
                    }
                    else
                    {
                        // a new container for this enum type is added before our new container
                        // but we have to check that a mapping for the current culture is available
                        container = mappings[enumType];
                        if (!container.mappingsPerCulture.ContainsKey(culture))
                        {
                            lock (container.mappingsPerCulture)
                            {
                                if (!container.mappingsPerCulture.ContainsKey(culture))
                                    container.mappingsPerCulture.Add(culture, mapping);
                            }
                        }
                    }
                }
            }
        }
示例#36
0
 public MemberMapperCollection(MappingContainer container, MemberMapOptions options)
 {
     _container = container;
     _options   = options;
 }