コード例 #1
0
 /// <summary>
 /// Creates a new AGIConnectionHandler to handle the given socket connection.
 /// </summary>
 /// <param name="socket">the socket connection to handle.</param>
 /// <param name="mappingStrategy">the strategy to use to determine which script to run.</param>
 public AGIConnectionHandler(IO.SocketConnection socket, IMappingStrategy mappingStrategy, bool SC511_CAUSES_EXCEPTION, bool SCHANGUP_CAUSES_EXCEPTION)
 {
     this.socket = socket;
     this.mappingStrategy = mappingStrategy;
     this._SC511_CAUSES_EXCEPTION = SC511_CAUSES_EXCEPTION;
     this._SCHANGUP_CAUSES_EXCEPTION = SCHANGUP_CAUSES_EXCEPTION;
 }
コード例 #2
0
 /// <summary>
 ///     Creates a new AsteriskFastAGI.
 /// </summary>
 public AsteriskFastAGI(string mappingStrategy)
 {
     address              = Common.AGI_BIND_ADDRESS;
     port                 = Common.AGI_BIND_PORT;
     poolSize             = Common.AGI_POOL_SIZE;
     this.mappingStrategy = new ResourceMappingStrategy(mappingStrategy);
 }
コード例 #3
0
        public void The_strategy_set_for_the_type_is_returned()
        {
            IMappingStrategy theStrategy = null;

            _sut.UpdateStrategy <IConvertible>(strategy => { theStrategy = (IMappingStrategy)strategy; });
            _sut.GetStrategyFor <IConvertible>().Should().Be(theStrategy);
        }
コード例 #4
0
 public AsteriskFastAGI(IMappingStrategy mappingStrategy, string ipaddress, int port, int poolSize)
 {
     address              = ipaddress;
     this.port            = port;
     this.poolSize        = poolSize;
     this.mappingStrategy = mappingStrategy;
 }
コード例 #5
0
 /// <summary>
 ///     Creates a new AsteriskFastAGI.
 /// </summary>
 public AsteriskFastAGI(IMappingStrategy mappingStrategy)
 {
     address              = Common.AGI_BIND_ADDRESS;
     port                 = Common.AGI_BIND_PORT;
     poolSize             = Common.AGI_POOL_SIZE;
     this.mappingStrategy = mappingStrategy;
 }
コード例 #6
0
 /// <summary>
 ///     Creates a new AsteriskFastAGI.
 /// </summary>
 /// <param name="ipaddress">The address to listen on.</param>
 /// <param name="port">The port to listen on.</param>
 /// <param name="poolSize">
 ///     The number of worker threads in the thread pool.
 ///     This equals the maximum number of concurrent requests this AGIServer can serve.
 /// </param>
 public AsteriskFastAGI(string ipaddress, int port, int poolSize)
 {
     address         = ipaddress;
     this.port       = port;
     this.poolSize   = poolSize;
     mappingStrategy = new ResourceMappingStrategy();
 }
コード例 #7
0
 /// <summary>
 ///     Creates a new AsteriskFastAGI.
 /// </summary>
 /// <param name="port">The port to listen on.</param>
 /// <param name="poolSize">
 ///     The number of worker threads in the thread pool.
 ///     This equals the maximum number of concurrent requests this AGIServer can serve.
 /// </param>
 public AsteriskFastAGI(int port, int poolSize)
 {
     address         = Common.AGI_BIND_ADDRESS;
     this.port       = port;
     this.poolSize   = poolSize;
     mappingStrategy = new ResourceMappingStrategy();
 }
コード例 #8
0
ファイル: AsteriskFastAGI.cs プロジェクト: jgowdy/AsterNET
 /// <summary>
 /// Creates a new AsteriskFastAGI.
 /// </summary>
 public AsteriskFastAGI()
 {
     this.address         = Common.AGI_BIND_ADDRESS;
     this.port            = Common.AGI_BIND_PORT;
     this.poolSize        = Common.AGI_POOL_SIZE;
     this.mappingStrategy = new ResourceMappingStrategy();
 }
コード例 #9
0
ファイル: AsteriskFastAGI.cs プロジェクト: jgowdy/AsterNET
 /// <summary>
 /// Creates a new AsteriskFastAGI.
 /// </summary>
 public AsteriskFastAGI(string mappingStrategy)
 {
     this.address = Common.AGI_BIND_ADDRESS;
     this.port = Common.AGI_BIND_PORT;
     this.poolSize = Common.AGI_POOL_SIZE;
     this.mappingStrategy = new ResourceMappingStrategy(mappingStrategy);
 }
コード例 #10
0
ファイル: AsteriskFastAGI.cs プロジェクト: jgowdy/AsterNET
 /// <summary>
 /// Creates a new AsteriskFastAGI.
 /// </summary>
 public AsteriskFastAGI(IMappingStrategy mappingStrategy)
 {
     this.address = Common.AGI_BIND_ADDRESS;
     this.port = Common.AGI_BIND_PORT;
     this.poolSize = Common.AGI_POOL_SIZE;
     this.mappingStrategy = mappingStrategy;
 }
コード例 #11
0
ファイル: EntityMappingBase.cs プロジェクト: windygu/wms_rfid
 public void EntityMapping(IMappingStrategy <string> tableNameMappingStrategy)
 {
     if (tableNameMappingStrategy != null)
     {
         ToTable(tableNameMappingStrategy.To(typeof(TEntity).Name));
     }
 }
コード例 #12
0
ファイル: AsteriskFastAGI.cs プロジェクト: vincomi/OSm
 /// <summary>
 ///     Creates a new AsteriskFastAGI.
 /// </summary>
 public AsteriskFastAGI()
 {
     address = Common.AGI_BIND_ADDRESS;
     port = Common.AGI_BIND_PORT;
     poolSize = Common.AGI_POOL_SIZE;
     mappingStrategy = new ResourceMappingStrategy();
 }
コード例 #13
0
        /// <summary>
        /// Convert xml node into the collection.
        /// </summary>
        /// <param name="node">The node</param>
        /// <param name="collectionType">collection's type.</param>
        /// <param name="configurationReader">The IConfigurationReader instance.</param>
        /// <returns>The collection.</returns>
        public object Map(XmlNode node, Type collectionType, IConfigurationReader configurationReader)
        {
            Type itemType = collectionType.GetElementType();
            var  d1       = typeof(List <>);

            Type[]     typeArgs  = { itemType };
            var        makeme    = d1.MakeGenericType(typeArgs);
            var        list      = Activator.CreateInstance(makeme);
            MethodInfo addMethod = makeme.GetMethod("Add");

            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                XmlNode childNode = node.ChildNodes[i];

                if (itemType.IsPrimitive || itemType == typeof(string) || itemType.IsEnum)
                {
                    IPrimitiveMappingStrategy mappingStrategy = mappingStrategyFactory.CreatePrimitiveStrategy(itemType);
                    var item = mappingStrategy.Map(childNode.InnerText, itemType);
                    addMethod.Invoke(list, new[] { item });
                }
                else
                {
                    IMappingStrategy mappingStrategy = mappingStrategyFactory.CreateComplexStrategy(itemType);
                    var item = mappingStrategy.Map(childNode, itemType, configurationReader);
                    addMethod.Invoke(list, new[] { item });
                }
            }

            MethodInfo toArrayMethod = makeme.GetMethod("ToArray");

            return(toArrayMethod.Invoke(list, null));
        }
コード例 #14
0
 /// <summary>
 /// Initializes a new instance of the <see cref="T:System.Object"/> class.
 /// </summary>
 public MappedDawgBuilder(IDawgBuilder <Dawg <TCKey, TCValue>, TCKey, TCValue> innerBuilder,
                          IMappingStrategy <TKey, TCKey> keyMapper,
                          IMappingStrategy <TValue, TCValue> valueMapper) : base(innerBuilder)
 {
     this.keyMapper   = keyMapper;
     this.valueMapper = valueMapper;
 }
コード例 #15
0
        public Section GetSection <T>(IMappingStrategy mappingStrategy, string configFilePath = null)
        {
            var sectionName = mappingStrategy.SectionNameFor <T>();

            var section = _configurationSystem.GetSection(sectionName, configFilePath);

            if (section != null)
            {
                return(section);
            }

            var alternativeNames = _nameConvention.GetAlternativeNames(sectionName).ToList();

            if (!alternativeNames.Any())
            {
                throw new AutoConfigMappingException(
                          string.Format("Could not map type '{0}', looked for a config section named '{1}' but didn't find one. Make sure the section exists and is correctly cased.",
                                        typeof(T), sectionName));
            }

            foreach (var alternative in alternativeNames)
            {
                section = _configurationSystem.GetSection(alternative, configFilePath);

                if (section != null)
                {
                    return(section);
                }
            }

            throw new AutoConfigMappingException(
                      string.Format("Could not map type '{0}', looked for a config section named '{1}'{2} but didn't find one. Make sure the section exists and is correctly cased.",
                                    typeof(T), sectionName, alternativeNames.Aggregate(string.Empty, (acc, name) => acc + " or '" + name + "'")));
        }
コード例 #16
0
 /// <summary>
 /// Creates a new AGIConnectionHandler to handle the given socket connection.
 /// </summary>
 /// <param name="socket">the socket connection to handle.</param>
 /// <param name="mappingStrategy">the strategy to use to determine which script to run.</param>
 public AGIConnectionHandler(IO.SocketConnection socket, IMappingStrategy mappingStrategy, bool SC511_CAUSES_EXCEPTION, bool SCHANGUP_CAUSES_EXCEPTION)
 {
     this.socket                     = socket;
     this.mappingStrategy            = mappingStrategy;
     this._SC511_CAUSES_EXCEPTION    = SC511_CAUSES_EXCEPTION;
     this._SCHANGUP_CAUSES_EXCEPTION = SCHANGUP_CAUSES_EXCEPTION;
 }
コード例 #17
0
        /// <summary>
        /// Register mapping strategy using object's type.
        /// </summary>
        /// <param name="itemType">The object's type.</param>
        /// <param name="mappingStrategy">The <see cref="IMappingStrategy"/> instance.</param>
        public void Register(Type itemType, IMappingStrategy mappingStrategy)
        {
            if (mappingStrategies.ContainsKey(itemType))
            {
                string msg = string.Format("The strategy for the {0} has been already existed.", itemType);
                throw new MappingStrategyFactoryException(msg);
            }

            mappingStrategies.Add(itemType, mappingStrategy);
        }
コード例 #18
0
        public TDest Map <TSrc, TDest>(TSrc src,
                                       IPropNamesMatcher propsMatcher             = null,
                                       IPropValueConverter propertyValueConverter = null,
                                       IMappingStrategy mappingStrategy           = null,
                                       Dictionary <string, object> externalData   = null)
        {
            var dest = (TDest)_mapperConfiguration.ObjectFactory.CreateInstance(typeof(TDest));

            Map(src, dest, propsMatcher, propertyValueConverter, mappingStrategy, externalData);
            return(dest);
        }
コード例 #19
0
ファイル: MemberMapper.cs プロジェクト: JulianR/ThisMember
        public MemberMapper(MapperOptions options = null, IMappingStrategy strategy = null, IMapGeneratorFactory generator = null, IProjectionGeneratorFactory projection = null)
        {
            this.MappingStrategy = strategy ?? new DefaultMappingStrategy(this);

            this.MapGeneratorFactory = generator ?? new CompiledMapGeneratorFactory();

            this.ProjectionGeneratorFactory = projection ?? new DefaultProjectionGeneratorFactory();

            this.Options = options ?? new MapperOptions();

            this.Data = new MapperDataAccessor(this);
        }
コード例 #20
0
        public void MapReturnsNumber(int number, string expectedResult)
        {
            //arrange
            var mappingStrategies            = new IMappingStrategy[] { };
            IMappingStrategy mappingStrategy = new CompositeMappingStrategy(mappingStrategies);

            //act
            string result = mappingStrategy.Map(number);

            //assert
            Assert.Equal(expectedResult, result);
        }
コード例 #21
0
        public void MapReturnsFizzBuzzForNumberDividableByFifteen(int number, string expectedResult)
        {
            //arrange
            var mappingStrategies            = new IMappingStrategy[] { new DividableByThreeMappingStrategy(), new DividableByFiveMappingStrategy() };
            IMappingStrategy mappingStrategy = new CompositeMappingStrategy(mappingStrategies);

            //act
            string result = mappingStrategy.Map(number);

            //assert
            Assert.Equal(expectedResult, result);
        }
コード例 #22
0
        public object Map(Type type, XElement element, IMappingStrategy strategy = null)
        {
            var instance = _typeFactory.InstanceOf(type);
            // since the type param might be an interface, and we need the concrete type
            var concreteType = instance.GetType();

            strategy = strategy ?? _strategyManager.GetStrategyFor(type);
            var mapping = _mappingFactory.CreateMapping(concreteType, element, strategy);

            mapping.Apply(instance);
            return(instance);
        }
コード例 #23
0
 public AsteriskFastAGI(string ipaddress              = Common.AGI_BIND_ADDRESS,
                        int port                      = Common.AGI_BIND_PORT,
                        int poolSize                  = Common.AGI_POOL_SIZE,
                        bool sc511_CausesException    = false,
                        bool scHangUp_CausesException = false)
 {
     address                   = ipaddress;
     this.port                 = port;
     this.poolSize             = poolSize;
     mappingStrategy           = new ResourceMappingStrategy();
     SC511_CAUSES_EXCEPTION    = sc511_CausesException;
     SCHANGUP_CAUSES_EXCEPTION = scHangUp_CausesException;
 }
コード例 #24
0
        public ITypeMapping CreateMapping(Type type, XElement sectionElement, IMappingStrategy mappingStrategy)
        {
            var typeMapping = new TypeMapping();

            var elementList   = sectionElement.Elements().ToList();
            var attributeList = sectionElement.Attributes().ToList();

            foreach (var property in type.PublicSetters().ToList())
            {
                var propertyStrategy = mappingStrategy.ForProperty(property);

                var xName = propertyStrategy.MapFrom ?? mappingStrategy.ConvertCase(property.Name);

                if (TryAddPropertyFromElement(typeMapping, elementList, property, propertyStrategy, xName))
                {
                    continue;
                }

                if (TryAddPropertyFromAttribute(type, typeMapping, attributeList, property, propertyStrategy, xName))
                {
                    continue;
                }

                if (!propertyStrategy.IsOptional)
                {
                    throw new AutoConfigMappingException(
                              string.Format(
                                  "Could not map property '{0}' for type '{1}' from section '{2}'. Looked for a config element or attribute with name '{3}' but didn't find one, and the property is not marked as optional.",
                                  property.Name, type, sectionElement.Name.LocalName, xName));
                }

                var defaultValue = propertyStrategy.DefaultValue;
                if (defaultValue != null)
                {
                    EnsureDefaultValueType(ref defaultValue, property, type, sectionElement.Name.LocalName);
                    var propertyMapping = new MappingFromFixedValue(property, defaultValue);
                    typeMapping.Include(propertyMapping);
                }
            }

            EnsureEmpty(elementList, element => string.Format(
                            "Could not map type '{0}' from section '{1}'. No matching settable property for config element '{2}' was found.",
                            type, sectionElement.Name.LocalName, element.Name.LocalName));

            EnsureEmpty(attributeList, attribute => string.Format(
                            "Could not map type '{0}' from section '{1}'. No matching settable property for config attribute '{2}' was found.",
                            type, sectionElement.Name.LocalName, attribute.Name.LocalName));

            return(typeMapping);
        }
コード例 #25
0
        static void Main()
        {
            var mappingStrategies = new IMappingStrategy[]
            {
                new DividableByThreeMappingStrategy(),
                new DividableByFiveMappingStrategy()
            };
            IMappingStrategy mappingStrategy = new CompositeMappingStrategy(mappingStrategies);

            const int minimum = 1;
            const int maximum = 100;

            for (var number = minimum; number <= maximum; number++)
            {
                Console.WriteLine(number + " => " + mappingStrategy.Map(number));
            }
        }
コード例 #26
0
        public object Map(object source, Type targetType)
        {
            Check.NotNull(source, nameof(source));
            Check.NotNull(targetType, nameof(targetType));

            IMappingStrategy strategy  = null;
            TargetMap        targetMap = FindMappingStrategy(source.GetType(), targetType);

            // Complete a reverse lookup.
            if (targetMap == null)
            {
                targetMap = FindMappingStrategy(targetType, source.GetType());
            }

            // If mapping strategy found, create an instance using the container.  This allows
            // the strategy to inject any required services required to complete the mappings.
            if (targetMap != null)
            {
                strategy = targetMap.StrategyInstance ?? (IMappingStrategy)_lifetimeScope.Resolve(targetMap.StrategyType);
                return(strategy.Map(this, _autoMapper, source));
            }

            return(null);
        }
コード例 #27
0
        public void Map <TSrc, TDest>(TSrc src, TDest dest,
                                      IPropNamesMatcher propsMatcher             = null,
                                      IPropValueConverter propertyValueConverter = null,
                                      IMappingStrategy mappingStrategy           = null,
                                      Dictionary <string, object> externalData   = null)
        {
            if (src == null)
            {
                throw new ArgumentNullException("src", "Source can not be null, specify valid source for mapping");
            }

            propertyValueConverter = propertyValueConverter ?? new NopPropertyValueConverter();
            externalData           = externalData ?? new Dictionary <string, object>();

            var srcMappingObjectType = _mapperConfiguration.MappingObjects.Get(src);
            var srcMappingObject     = _mapperConfiguration.ObjectFactory.CreateInstance(srcMappingObjectType) as IMappingObject;

            srcMappingObject.UnderlyingObject = src;
            srcMappingObject.ExternalData     = externalData;

            var destMappingObjectType = _mapperConfiguration.MappingObjects.Get(dest);
            var destMappingObject     = _mapperConfiguration.ObjectFactory.CreateInstance(destMappingObjectType) as IMappingObject;

            destMappingObject.UnderlyingObject = dest;
            destMappingObject.ExternalData     = externalData;

            var mappingPair = new MappingPair(srcMappingObject, destMappingObject);

            var strategyType = _mapperConfiguration.MappingStrategies.Get(mappingPair);
            var strategy     = mappingStrategy ?? _mapperConfiguration.ObjectFactory.CreateInstance(strategyType) as IMappingStrategy;

            strategy.MapperConfiguration = _mapperConfiguration;
            strategy.PropValueConverter  = propertyValueConverter;
            strategy.PropsMatcher        = propsMatcher ?? _mapperConfiguration.ObjectFactory.CreateInstance(_mapperConfiguration.PropertyNameConverters.Get(mappingPair)) as IPropNamesMatcher;
            strategy.Map(mappingPair);
        }
コード例 #28
0
ファイル: AsteriskFastAGI.cs プロジェクト: jgowdy/AsterNET
 public AsteriskFastAGI(IMappingStrategy mappingStrategy, string ipaddress, int port, int poolSize)
 {
     this.address = ipaddress;
     this.port = port;
     this.poolSize = poolSize;
     this.mappingStrategy = mappingStrategy;
 }
コード例 #29
0
 public AsteriskFastAGI(string ipaddress = Common.AGI_BIND_ADDRESS,
     int port = Common.AGI_BIND_PORT,
     int poolSize = Common.AGI_POOL_SIZE,
     bool sc511_CausesException = false,
     bool scHangUp_CausesException = false)
 {
     address = ipaddress;
     this.port = port;
     this.poolSize = poolSize;
     mappingStrategy = new ResourceMappingStrategy();
     SC511_CAUSES_EXCEPTION = sc511_CausesException;
     SCHANGUP_CAUSES_EXCEPTION = scHangUp_CausesException;
 }
コード例 #30
0
ファイル: AsteriskFastAGI.cs プロジェクト: jgowdy/AsterNET
 /// <summary>
 /// Creates a new AsteriskFastAGI.
 /// </summary>
 /// <param name="ipaddress">The address to listen on.</param>
 /// <param name="port">The port to listen on.</param>
 /// <param name="poolSize">The number of worker threads in the thread pool.
 /// This equals the maximum number of concurrent requests this AGIServer can serve.</param>
 public AsteriskFastAGI(string ipaddress, int port, int poolSize)
 {
     this.address = ipaddress;
     this.port = port;
     this.poolSize = poolSize;
     this.mappingStrategy = new ResourceMappingStrategy();
 }
コード例 #31
0
ファイル: AsteriskFastAGI.cs プロジェクト: jgowdy/AsterNET
 /// <summary>
 /// Creates a new AsteriskFastAGI.
 /// </summary>
 /// <param name="port">The port to listen on.</param>
 /// <param name="poolSize">The number of worker threads in the thread pool.
 /// This equals the maximum number of concurrent requests this AGIServer can serve.</param>
 public AsteriskFastAGI(int port, int poolSize)
 {
     this.address = Common.AGI_BIND_ADDRESS;
     this.port = port;
     this.poolSize = poolSize;
     this.mappingStrategy = new ResourceMappingStrategy();
 }
コード例 #32
0
        /// <summary>
        /// Read object from the node.
        /// </summary>
        /// <param name="type">The object's type.</param>
        /// <param name="xmlNode">The node.</param>
        /// <returns>The object.</returns>
        public object ReadObject(Type type, XmlNode xmlNode)
        {
            //if (type.Name.ToLower() != xmlNode.Name.ToLower())
            //    throw new InvalidCastException("Cannot convert " + xmlNode.Name + " into the " + type.Name);

            object obj = Activator.CreateInstance(type);

            PropertyInfo[] propertyInfos = type.GetProperties(BindingFlags.Instance | BindingFlags.Public);
            Dictionary <string, PropertyInfo>           attributes       = new Dictionary <string, PropertyInfo>();
            Dictionary <string, ICustomMappingStrategy> customStrategies = new Dictionary <string, ICustomMappingStrategy>();
            List <string> ignoreList = new List <string>();

            IEnumerable <PropertyInfo> props = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(PropertyMappingAttribute)));

            foreach (PropertyInfo propertyInfo in props)
            {
                PropertyMappingAttribute attr = (PropertyMappingAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(PropertyMappingAttribute));
                attributes.Add(attr.Name.ToLower(), propertyInfo);
            }

            props = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(CustomStrategyAttribute)));
            foreach (PropertyInfo propertyInfo in props)
            {
                CustomStrategyAttribute attr     = (CustomStrategyAttribute)Attribute.GetCustomAttribute(propertyInfo, typeof(CustomStrategyAttribute));
                ICustomMappingStrategy  strategy = (ICustomMappingStrategy)Activator.CreateInstance(attr.StrategyType);
                customStrategies.Add(propertyInfo.Name.ToLower(), strategy);
            }

            props = type.GetProperties().Where(prop => Attribute.IsDefined(prop, typeof(IgnorePropertyAttribute)));
            foreach (PropertyInfo propertyInfo in props)
            {
                ignoreList.Add(propertyInfo.Name.ToLower());
            }

            if (xmlNode.Attributes != null)
            {
                for (int i = 0; i < xmlNode.Attributes.Count; i++)
                {
                    XmlAttribute xmlAttribute   = xmlNode.Attributes[i];
                    string       attributeName  = xmlAttribute.Name.ToLower();
                    string       attributeValue = xmlAttribute.Value;

                    if (ignoreList.Contains(attributeName))
                    {
                        continue;
                    }

                    PropertyInfo propertyInfo;
                    if (attributes.TryGetValue(attributeName, out propertyInfo) == false)
                    {
                        propertyInfo = propertyInfos.Single(x => x.Name.ToLower() == attributeName);
                    }

                    object value;
                    if (customStrategies.ContainsKey(propertyInfo.Name.ToLower()))
                    {
                        ICustomMappingStrategy customMappingStrategy = customStrategies[propertyInfo.Name.ToLower()];
                        value = customMappingStrategy.Map(attributeValue, propertyInfo.PropertyType);
                    }
                    else
                    {
                        IPrimitiveMappingStrategy mappingStrategy = mappingStrategyFactory.CreatePrimitiveStrategy(propertyInfo.PropertyType);
                        value = mappingStrategy.Map(attributeValue, propertyInfo.PropertyType);
                    }
                    propertyInfo.SetValue(obj, value, null);
                }
            }

            if (xmlNode.HasChildNodes)
            {
                for (int i = 0; i < xmlNode.ChildNodes.Count; i++)
                {
                    XmlNode child = xmlNode.ChildNodes[i];
                    if (child.NodeType != XmlNodeType.Element)
                    {
                        continue;
                    }

                    string childName = child.Name.ToLower();
                    if (ignoreList.Contains(childName))
                    {
                        continue;
                    }

                    PropertyInfo propertyInfo;
                    if (attributes.TryGetValue(childName, out propertyInfo) == false)
                    {
                        propertyInfo = propertyInfos.Single(x => x.Name.ToLower() == childName);
                    }

                    if (customStrategies.ContainsKey(propertyInfo.Name.ToLower()))
                    {
                        ICustomMappingStrategy customMappingStrategy = customStrategies[propertyInfo.Name.ToLower()];
                        var value = customMappingStrategy.Map(child, propertyInfo.PropertyType);
                        propertyInfo.SetValue(obj, value, null);
                        continue;
                    }

                    Type propertyType = propertyInfo.PropertyType;
                    if (propertyType.IsPrimitive || propertyType == typeof(string) || propertyType.IsEnum)
                    {
                        IPrimitiveMappingStrategy mappingStrategy = mappingStrategyFactory.CreatePrimitiveStrategy(propertyInfo.PropertyType);
                        var value = mappingStrategy.Map(child.InnerText, propertyInfo.PropertyType);
                        propertyInfo.SetValue(obj, value, null);
                    }
                    else
                    {
                        IMappingStrategy mappingStrategy = mappingStrategyFactory.CreateComplexStrategy(propertyInfo.PropertyType);
                        var value = mappingStrategy.Map(child, propertyInfo.PropertyType, this);
                        propertyInfo.SetValue(obj, value, null);
                    }
                }
            }

            return(obj);
        }
コード例 #33
0
        /// <summary>
        /// Convert xml node into the IDictionary<K, itemType>.
        /// </summary>
        /// <param name="node">The node</param>
        /// <param name="collectionType">Collection's type.</param>
        /// <param name="configurationReader">The IConfigurationReader instance.</param>
        /// <returns>The IDictionary<K, itemType>.</returns>
        /// <exception cref="KeyNotFoundException">There is no key in the collection..</exception>
        /// <exception cref="NotSupportedException">Only primitive keys are supported.</exception>
        /// <exception cref="IndexOutOfRangeException">The value section should contain only one inner element.</exception>
        /// <exception cref="TargetInvocationException">The constructor being called throws an exception. </exception>
        /// <exception cref="AmbiguousMatchException">More than one method is found with the specified name. </exception>
        /// <exception cref="TargetException">In the .NET for Windows Store apps or the Portable Class Library, catch <see cref="T:System.Exception" /> instead.The <paramref name="obj" /> parameter is null and the method is not static.-or- The method is not declared or inherited by the class of <paramref name="obj" />. -or-A static constructor is invoked, and <paramref name="obj" /> is neither null nor an instance of the class that declared the constructor.</exception>
        public object Map(XmlNode node, Type collectionType, IConfigurationReader configurationReader)
        {
            object     dictionary;
            Type       keyType  = collectionType.GetGenericArguments()[0];
            Type       itemType = collectionType.GetGenericArguments()[1];
            MethodInfo addMethod;

            if (collectionType.IsInterface)
            {
                var    d1       = typeof(Dictionary <,>);
                Type[] typeArgs = { keyType, itemType };
                var    makeme   = d1.MakeGenericType(typeArgs);
                dictionary = Activator.CreateInstance(makeme);
                addMethod  = makeme.GetMethod("Add");
            }
            else
            {
                dictionary = Activator.CreateInstance(collectionType);
                addMethod  = collectionType.GetMethod("Add");
            }

            for (int i = 0; i < node.ChildNodes.Count; i++)
            {
                XmlNode childNode = node.ChildNodes[i];
                string  keyValue  = childNode.GetNodeValue("key");
                if (string.IsNullOrEmpty(keyValue))
                {
                    string msg = string.Format("There is no 'key' in the {0}.{1}", node.Name, childNode.Name);
                    throw new KeyNotFoundException(msg);
                }

                object key;
                object item;

                if (keyType.IsPrimitive || keyType == typeof(string) || keyType.IsEnum)
                {
                    IPrimitiveMappingStrategy mappingStrategy = mappingStrategyFactory.CreatePrimitiveStrategy(itemType);
                    key = mappingStrategy.Map(keyValue, keyType);
                }
                else
                {
                    string msg = string.Format("{0} as a key not supported.", keyType);
                    throw new NotSupportedException(msg);
                }

                if (itemType.IsPrimitive || itemType == typeof(string) || itemType.IsEnum)
                {
                    IPrimitiveMappingStrategy mappingStrategy = mappingStrategyFactory.CreatePrimitiveStrategy(itemType);
                    string itemValue = childNode.GetNodeValue("value");
                    item = mappingStrategy.Map(itemValue, itemType);
                }
                else
                {
                    XmlNode innerXml = childNode.GetXmlNode("value");

                    if (innerXml.ChildNodes.Count != 1)
                    {
                        string msg = string.Format("The value section should contain only one inner element in the {0}.{1}", childNode.Name, innerXml.Name);
                        throw new IndexOutOfRangeException(msg);
                    }

                    innerXml = innerXml.ChildNodes[0];
                    IMappingStrategy mappingStrategy = mappingStrategyFactory.CreateComplexStrategy(itemType);
                    item = mappingStrategy.Map(innerXml, itemType, configurationReader);
                }

                addMethod.Invoke(dictionary, new[] { key, item });
            }

            return(dictionary);
        }