Exemplo n.º 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;
 }
Exemplo n.º 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);
 }
        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);
        }
Exemplo n.º 4
0
 public AsteriskFastAGI(IMappingStrategy mappingStrategy, string ipaddress, int port, int poolSize)
 {
     address              = ipaddress;
     this.port            = port;
     this.poolSize        = poolSize;
     this.mappingStrategy = mappingStrategy;
 }
Exemplo n.º 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;
 }
Exemplo n.º 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();
 }
Exemplo n.º 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();
 }
Exemplo n.º 8
0
 /// <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();
 }
Exemplo n.º 9
0
 /// <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);
 }
Exemplo n.º 10
0
 /// <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;
 }
Exemplo n.º 11
0
 public void EntityMapping(IMappingStrategy <string> tableNameMappingStrategy)
 {
     if (tableNameMappingStrategy != null)
     {
         ToTable(tableNameMappingStrategy.To(typeof(TEntity).Name));
     }
 }
Exemplo n.º 12
0
 /// <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();
 }
        /// <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));
        }
Exemplo n.º 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;
 }
Exemplo n.º 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 + "'")));
        }
Exemplo n.º 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;
 }
        /// <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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 19
0
        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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 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;
 }
Exemplo n.º 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);
        }
Exemplo n.º 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));
            }
        }
Exemplo n.º 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);
        }
Exemplo n.º 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);
        }
Exemplo n.º 28
0
 public AsteriskFastAGI(IMappingStrategy mappingStrategy, string ipaddress, int port, int poolSize)
 {
     this.address = ipaddress;
     this.port = port;
     this.poolSize = poolSize;
     this.mappingStrategy = mappingStrategy;
 }
Exemplo n.º 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;
 }
Exemplo n.º 30
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)
 {
     this.address = ipaddress;
     this.port = port;
     this.poolSize = poolSize;
     this.mappingStrategy = new ResourceMappingStrategy();
 }
Exemplo n.º 31
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)
 {
     this.address = Common.AGI_BIND_ADDRESS;
     this.port = port;
     this.poolSize = poolSize;
     this.mappingStrategy = new ResourceMappingStrategy();
 }
Exemplo n.º 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);
        }
Exemplo n.º 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);
        }