Ejemplo n.º 1
0
            public async void Must_map_to_properties_whose_return_values_implement_iconvertible(Type type, string propertyName, object expectedValue)
            {
                MapResult result = await _mapper.MapAsync(_request, type, type.GetProperty(propertyName));

                Assert.That(result.ResultType, Is.EqualTo(MapResultType.ValueMapped));
                Assert.That(result.Value, Is.EqualTo(expectedValue));
            }
Ejemplo n.º 2
0
        public async Task Should_not_use_a_mapper_that_doesnt_apply_at_runtime()
        {
            var requestGraph = RequestGraph
                               .CreateFor <MappingHandler>(h => h.Action(null, null, null))
                               .AddAllActionParameters()
                               .Configure(x => x.BindRequestInfo())
                               .AddValueMapper1(x => MapResult.Success(x.Values.First() + "mapper1"),
                                                instanceAppliesTo: x => false)
                               .AddValueMapper2(x => MapResult.Success(x.Values.First() + "mapper2"));

            var properties = new Dictionary <string, object>
            {
                ["param2"] = "value2",
                ["param3"] = "value3"
            };

            var binder = CreateBinder(requestGraph, properties);

            await binder.Bind(requestGraph.GetRequestBinderContext());

            requestGraph.ActionArguments.ShouldOnlyContain(null, "value2mapper2", "value3mapper2");

            requestGraph.ValueMapper1.AppliesToCalled.ShouldBeTrue();
            requestGraph.ValueMapper1.MapCalled.ShouldBeFalse();

            requestGraph.ValueMapper2.AppliesToCalled.ShouldBeTrue();
            requestGraph.ValueMapper2.MapCalled.ShouldBeTrue();
        }
Ejemplo n.º 3
0
            public async void Must_map_default_value(Type type, string propertyName, object expectedValue)
            {
                MapResult result = await _mapper.MapAsync(_request, type, type.GetProperty(propertyName));

                Assert.That(result.ResultType, Is.EqualTo(MapResultType.ValueMapped));
                Assert.That(result.Value, Is.EqualTo(expectedValue));
            }
Ejemplo n.º 4
0
        public void Should_bind_values_to_properties()
        {
            var requestGraph = RequestGraph
                               .CreateFor <Handler>(h => h.Params(null, null, null, 0))
                               .WithUrl("http://fark.com?param1=value1&param2=value2")
                               .AddModelParameters("model", "param1", "param2")
                               .AddValueMapper1(x => MapResult.Success(x.Values.First()));

            var result = Bind(requestGraph);

            result.Status.ShouldEqual(BindingStatus.Success);

            var model = requestGraph.ActionArguments[0] as Model;

            model.ShouldNotBeNull();
            model.Param1.ShouldEqual("value1");
            model.Param2.ShouldEqual("value2");

            requestGraph.ActionArguments[1].ShouldBeNull();
            requestGraph.ActionArguments[2].ShouldBeNull();

            requestGraph.ValueMapper1.AppliesToContext.Parameter.ShouldNotBeNull();
            requestGraph.ValueMapper1.AppliesToContext.Values.ShouldNotBeNull();

            requestGraph.ValueMapper1.MapContext.Parameter.ShouldNotBeNull();
            requestGraph.ValueMapper1.MapContext.Values.ShouldNotBeNull();
        }
Ejemplo n.º 5
0
        public Startup(IConfiguration configuration)
        {
            Configuration = configuration;

            DeltaConfig.Init(cfg =>
            {
                cfg.AddEntity <Person>();

                cfg.AddMapping((propertyType, newValue) =>
                {
                    var result = new MapResult <object>();

                    if (propertyType != typeof(DateTime?) || newValue.GetType() != typeof(string))
                    {
                        return(result.SkipMap());
                    }

                    if (DateTime.TryParseExact((string)newValue, "dd/MM/yyyy", new CultureInfo("it-IT"), DateTimeStyles.None, out var date))
                    {
                        result.Value = date;
                    }
                    else
                    {
                        result.Value = null;
                    }

                    return(result);
                });
            });
        }
Ejemplo n.º 6
0
        public async Task Should_not_bind_with_reader_instance_that_does_not_apply()
        {
            var requestGraph = RequestGraph
                               .CreateFor <Handler>(h => h.Get(null))
                               .WithRequestParameter("request")
                               .WithRequestData("fark")
                               .AddRequestReader1(() => ReadResult.Success("reader1").ToTaskResult(),
                                                  instanceAppliesTo: () => false)
                               .AddRequestReader2(() => ReadResult.Success("reader2").ToTaskResult())
                               .AddValueMapper1(x => MapResult.Success(x.Values.First()));

            var binder = CreateBinder(requestGraph);

            var result = await binder.Bind(requestGraph.GetRequestBinderContext());

            result.Status.ShouldEqual(BindingStatus.Success);

            requestGraph.ActionArguments.ShouldOnlyContain("reader2");

            requestGraph.RequestReader1.AppliesCalled.ShouldBeTrue();
            requestGraph.RequestReader1.ReadCalled.ShouldBeFalse();

            requestGraph.RequestReader2.AppliesCalled.ShouldBeTrue();
            requestGraph.RequestReader2.ReadCalled.ShouldBeTrue();
        }
Ejemplo n.º 7
0
        private void Map(string input)
        {
            var mapResult = new MapResult();

            using (var reader = new StringReader(input))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    if (!String.IsNullOrWhiteSpace(line))
                    {
                        var key = line.Split(new [] { '|' }).Last().Trim();

                        mapResult.Counts.Add(new KeyCount(key));
                    }
                }
            }

            Console.WriteLine("Mapper [{0}/{1}]: {2}",
                              Self.Path.Name, Thread.CurrentThread.ManagedThreadId, mapResult);

            // simulate some runtime...
            Thread.Sleep(50);

            Sender.Tell(mapResult);
        }
Ejemplo n.º 8
0
        /// <summary>
        /// 将json数据反序列化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public override MapResult  JsonToEntity(string json)
        {
            //反序列化
            var map = JsonConvert.DeserializeObject <GaodeMapResult>(json);

            //转换为通用结果
            var result = new MapResult();

            result.count   = map.count;
            result.status  = map.status == "1"?"0":"1";//百度地图api接口成功判断与高德地图相反
            result.message = map.info;
            var list = new List <Result>();

            foreach (var item in map.tips)
            {
                //搜索结果
                var i = new Result();
                i.name     = item.name;
                i.location = item.location == null? new Location()
                {
                    lat = "0", lng = "0"
                } : new Location()
                {
                    lat = item.location.Split(',')[1], lng = item.location.Split(',')[0]
                };
                i.uid      = item.id.ToString();
                i.address  = item.address.ToString().Replace("[]", "暂无地址详情");
                i.province = item.district;
                list.Add(i);
            }
            result.list = list;
            return(result);
        }
Ejemplo n.º 9
0
        public void ResolveMap()
        {
            MapResult expectedResult = new MapResult()
            {
                Letters = "BEEFCAKE", PathChars = "@---+B||E--+|E|+--F--+|C|||A--|-----K|||+--E--Ex"
            };

            char[][] testArray = new char[9][]
            {
                new char[] { ' ', ' ', '@', '-', '-', '-', '+' },
                new char[] { ' ', ' ', ' ', ' ', ' ', ' ', 'B' },
                new char[] { 'K', '-', '-', '-', '-', '-', '|', '-', '-', 'A' },
                new char[] { '|', ' ', ' ', ' ', ' ', ' ', '|', ' ', ' ', '|' },
                new char[] { '|', ' ', ' ', '+', '-', '-', 'E', ' ', ' ', '|' },
                new char[] { '|', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|' },
                new char[] { '+', '-', '-', 'E', '-', '-', 'E', 'x', ' ', 'C' },
                new char[] { ' ', ' ', ' ', '|', ' ', ' ', ' ', ' ', ' ', '|' },
                new char[] { ' ', ' ', ' ', '+', '-', '-', 'F', '-', '-', '+' },
            };

            var result = AsciiMapService.ResolveMap(testArray);

            Assert.AreEqual(expectedResult.Letters, result.Letters);
            Assert.AreEqual(expectedResult.PathChars, result.PathChars);
        }
Ejemplo n.º 10
0
        public async Task Should_not_use_a_mapper_that_doesnt_apply_at_runtime()
        {
            var requestGraph = RequestGraph
                               .CreateFor <Handler>(h => h.Post(null, null))
                               .WithRequestData("param1=value1")
                               .WithRequestParameter("request")
                               .AddValueMapper1(x => MapResult.Success(x.Values.First() + "mapper1"), instanceAppliesTo: x => false)
                               .AddValueMapper2(x => MapResult.Success(x.Values.First() + "mapper2"));

            var reader = CreateReader(requestGraph);

            var result = await reader
                         .Read(CreateReaderContext(requestGraph));

            result.Status.ShouldEqual(ReadStatus.Success);
            result.Value.ShouldNotBeNull();
            result.Value.ShouldBeType <InputModel>();
            var inputModel = result.Value.CastTo <InputModel>();

            inputModel.Param1.ShouldEqual("value1mapper2");
            inputModel.Param2.ShouldEqual(0);

            requestGraph.ValueMapper1.AppliesToCalled.ShouldBeTrue();
            requestGraph.ValueMapper1.MapCalled.ShouldBeFalse();

            requestGraph.ValueMapper2.AppliesToCalled.ShouldBeTrue();
            requestGraph.ValueMapper2.MapCalled.ShouldBeTrue();
        }
Ejemplo n.º 11
0
        protected override Task <MapResult> OnMapAsync(HttpContextBase context, string value, Type propertyType)
        {
            context.ThrowIfNull("context");
            value.ThrowIfNull("value");
            propertyType.ThrowIfNull("propertyType");

            return(MapResult.ValueMapped(_format != null ? Guid.ParseExact(value, _format) : Guid.Parse(value)).AsCompletedTask());
        }
            public async void Must_map_to_default_value_of_property_type(Type type, string propertyName, object expectedValue)
            {
                PropertyInfo propertyInfo = type.GetProperty(propertyName);
                MapResult    result       = await _mapper.MapAsync(_request, type, propertyInfo);

                Assert.That(result.ResultType, Is.EqualTo(MapResultType.ValueMapped));
                Assert.That(result.Value, Is.EqualTo(propertyInfo.PropertyType.GetDefaultValue()));
            }
Ejemplo n.º 13
0
        protected override Task <MapResult> OnMapAsync(HttpContextBase context, string value, Type parameterType)
        {
            context.ThrowIfNull("context");
            value.ThrowIfNull("value");
            parameterType.ThrowIfNull("parameterType");

            return(MapResult.ValueMapped(((IConvertible)value).ToType(parameterType, CultureInfo.InvariantCulture)).AsCompletedTask());
        }
Ejemplo n.º 14
0
        public Task <MapResult> MapAsync(HttpContextBase context, Type modelType, PropertyInfo property)
        {
            context.ThrowIfNull("context");
            modelType.ThrowIfNull("modelType");
            property.ThrowIfNull("property");

            return(MapResult.ValueMapped(property.PropertyType.GetDefaultValue()).AsCompletedTask());
        }
Ejemplo n.º 15
0
        public async Task <IEnumerable <object> > GetParameterValuesAsync(HttpContextBase context, Type type, MethodInfo method)
        {
            context.ThrowIfNull("context");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");

            ParameterInfo[] parameterInfos  = method.GetParameters();
            var             parameterValues = new List <object>();

            foreach (ParameterInfo parameterInfo in parameterInfos)
            {
                Type   parameterType        = parameterInfo.ParameterType;
                string parameterName        = parameterInfo.Name;
                Type   currentParameterType = parameterType;

                do
                {
                    bool mapped = false;

                    foreach (IParameterMapper parameterMapper in _parameterMappers)
                    {
                        if (!await parameterMapper.CanMapTypeAsync(context, parameterType))
                        {
                            continue;
                        }
                        MapResult mapResult = await parameterMapper.MapAsync(context, type, method, parameterInfo);

                        if (mapResult.ResultType == MapResultType.ValueNotMapped)
                        {
                            continue;
                        }

                        parameterValues.Add(mapResult.Value);
                        mapped = true;
                        break;
                    }
                    if (mapped)
                    {
                        break;
                    }

                    currentParameterType = currentParameterType.BaseType;
                } while (currentParameterType != null);

                if (currentParameterType == null)
                {
                    throw new ApplicationException(
                              String.Format(
                                  "No request parameter mapper was found for parameter '{0} {1}' of {2}.{3}.",
                                  parameterType.FullName,
                                  parameterName,
                                  type.FullName,
                                  method.Name));
                }
            }

            return(parameterValues);
        }
Ejemplo n.º 16
0
        public void MappingFunction()
        {
            DeltaConfig.Init(cfg =>
            {
                cfg

                /* When the target property type is int and the input is string,
                *  then the assigned value will be the length of the input string*/
                .AddMapping((propType, newValue) =>
                {
                    var result = new MapResult <object>();

                    if (propType != typeof(int))
                    {
                        return(result.SkipMap());
                    }
                    if (newValue.GetType() != typeof(string))
                    {
                        return(result.SkipMap());
                    }

                    result.Value = newValue.ToString().Length;

                    return(result);
                })

                /* When the target property is double and the input is string,
                 * then the assigned value will be the length of the string + 0.5*/
                .AddMapping((propType, newValue) =>
                {
                    var result = new MapResult <object>();

                    if (propType != typeof(double))
                    {
                        return(result.SkipMap());
                    }

                    if (newValue.GetType() != typeof(string))
                    {
                        return(result.SkipMap());
                    }

                    result.Value = newValue.ToString().Length + 0.5;

                    return(result);
                })
                .AddEntity <Person>();
            });

            // First mapping function will be executed here, Age type is int
            CreateDelta <Person, int>(x => x.Age, "abc").Patch(John);
            Assert.AreEqual("abc".Length, John.Age);

            // Second mapping function will be executed here, Height type is double
            CreateDelta <Person, double>(x => x.Height, "abcdef").Patch(John);
            Assert.AreEqual("abcdef".Length + 0.5, John.Height);
        }
Ejemplo n.º 17
0
            public async void Must_map_default_value(Type type, string methodName, string parameterName, object expectedValue)
            {
                MethodInfo    methodInfo    = type.GetMethod(methodName);
                ParameterInfo parameterInfo = methodInfo.GetParameters().Single(arg => arg.Name == parameterName);
                MapResult     result        = await _mapper.MapAsync(_context, type, methodInfo, parameterInfo);

                Assert.That(result.ResultType, Is.EqualTo(MapResultType.ValueMapped));
                Assert.That(result.Value, Is.EqualTo(expectedValue));
            }
Ejemplo n.º 18
0
        public void ConstructorArgumentsGetAssigned()
        {
            var startPos = new GridCoordinate(2, 4);
            var endPos   = new GridCoordinate(4, 6);

            var result = new MapResult(startPos, endPos);

            Assert.Equal(startPos, result.StartPosition);
            Assert.Equal(endPos, result.EndPosition);
        }
Ejemplo n.º 19
0
 public MapResultModel Translate(MapResult mapResult)
 {
     return(new MapResultModel
     {
         StartPosition = mapResult.StartPosition.ToString(),
         EndPosition = mapResult.EndPosition.ToString(),
         BlocksToTravel = mapResult.AbsolutePositionDelta.DistanceTraveledFromOrigin(DistanceCalculationMode.XComponentPlusYComponent),
         AsTheCrowFliesDistance = mapResult.AbsolutePositionDelta.DistanceTraveledFromOrigin(DistanceCalculationMode.ShortestPath)
     });
 }
Ejemplo n.º 20
0
        public Task <MapResult> MapAsync(HttpContextBase context, Type type, MethodInfo method, ParameterInfo parameter)
        {
            context.ThrowIfNull("context");
            type.ThrowIfNull("type");
            method.ThrowIfNull("method");
            parameter.ThrowIfNull("parameter");

            Type   parameterType = parameter.ParameterType;
            string parameterName = parameter.Name;
            NameValueCollection nameValueCollection;

            switch (_source)
            {
            case NameValueCollectionSource.Form:
                nameValueCollection = context.Request.Form;
                break;

            case NameValueCollectionSource.QueryString:
                nameValueCollection = context.Request.QueryString;
                break;

            default:
                throw new InvalidOperationException(String.Format("Unexpected name-value collection source {0}.", _source));
            }
            string field = nameValueCollection.AllKeys.LastOrDefault(arg => String.Equals(arg, parameterName, _caseSensitive ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase));

            if (field == null)
            {
                return(MapResult.ValueNotMapped().AsCompletedTask());
            }

            string value = nameValueCollection[field];

            try
            {
                return(OnMapAsync(context, value, parameterType));
            }
            catch (Exception exception)
            {
                if (_errorHandling == DataConversionErrorHandling.ThrowException)
                {
                    throw new ApplicationException(
                              String.Format(
                                  "Value for form field '{0}' could not be converted to parameter '{1} {2}' of {3}.{4}.",
                                  field,
                                  parameterType.FullName,
                                  parameterName,
                                  type.FullName,
                                  method.Name),
                              exception);
                }

                return(MapResult.ValueMapped(parameterType.GetDefaultValue()).AsCompletedTask());
            }
        }
Ejemplo n.º 21
0
 public static MapResult <T, R> To <T, R>(this MapResult <T, R> mr, R result, Func <T, bool> func)
 {
     if (mr.Success)
     {
         return(mr);
     }
     if (func != null && func(mr.Value))
     {
         mr.Result = result;
     }
     return(mr);
 }
Ejemplo n.º 22
0
        public void TestAbsolutePositionValue()
        {
            var startPos = new GridCoordinate();
            var endPos   = new GridCoordinate(-10, -10);

            // Absolute should be 10, 10.
            var expected = new GridCoordinate(10, 10);

            var result = new MapResult(startPos, endPos);

            Assert.Equal(expected, result.AbsolutePositionDelta);
        }
Ejemplo n.º 23
0
        /// <summary>
        /// 将json数据反序列化
        /// </summary>
        /// <param name="json"></param>
        /// <returns></returns>
        public override MapResult JsonToEntity(string json)
        {
            var map = JsonConvert.DeserializeObject <BaiduMapResult>(json);

            //转换为通用结果
            var result = new MapResult();

            result.count   = map.results.Count.ToString();
            result.status  = map.status.ToString();
            result.message = map.message;
            result.list    = map.results;
            return(result);
        }
Ejemplo n.º 24
0
        public async Task Should_not_map_parameters_that_dont_match_any_action_parameters()
        {
            var requestGraph = RequestGraph
                               .CreateFor <Handler>(h => h.Params(null, null, null))
                               .WithUrl("http://fark.com?param1=value1")
                               .AddParameters("param1")
                               .AddValueMapper1(x => MapResult.Success(x.Values.First()));

            var binder = CreateBinder(requestGraph);

            await binder.Bind(requestGraph.GetRequestBinderContext());

            requestGraph.ActionArguments.ShouldOnlyContain(null, "value1", null);
        }
Ejemplo n.º 25
0
        public void Should_set_properties_on_an_existing_object()
        {
            var instance = new TypeCache().GetTypeDescriptor(typeof(HydratedObject))
                           .CreateAndBind(new List <string, object>
            {
                { "value0", "farker" },
                { "value1", "fark" },
                { "value2", "valueA" },
                { "value2", "valueB" }
            }.ToLookup(), (p, o) => MapResult.WasMapped(o)) as HydratedObject;

            instance.Value1.ShouldOnlyContain("fark");
            instance.Value2.ShouldOnlyContain("valueA", "valueB");
        }
Ejemplo n.º 26
0
        public void Should_not_map_parameters_that_dont_match_any_action_parameters()
        {
            var requestGraph = RequestGraph
                               .CreateFor <Handler>(h => h.Params(null, null, null, 0))
                               .WithUrl("http://fark.com?param1=value1&param3=value3")
                               .AddParameters("param1", "param2")
                               .AddValueMapper1(x => MapResult.Success(x.Values.First()));

            var result = Bind(requestGraph);

            result.Status.ShouldEqual(BindingStatus.Success);

            requestGraph.ActionArguments.ShouldOnlyContain(null, "value1", null, null);
        }
            public async void Must_deserialize_model(Type type, string methodName, string parameterName)
            {
                MethodInfo    methodInfo    = type.GetMethod(methodName);
                ParameterInfo parameterInfo = methodInfo.GetParameters().Single(arg => arg.Name == parameterName);
                MapResult     result        = await _mapper.MapAsync(_context, type, methodInfo, parameterInfo);

                Assert.That(result.ResultType, Is.EqualTo(MapResultType.ValueMapped));
                Assert.That(result.Value, Is.TypeOf <Model>());

                var value = (Model)result.Value;

                Assert.That(value.I, Is.EqualTo(1));
                Assert.That(value.S, Is.EqualTo("value"));
            }
Ejemplo n.º 28
0
        public async Task Should_map_multiple_parameters_with_the_same_name_as_an_array()
        {
            var requestGraph = RequestGraph
                               .CreateFor <Handler>(h => h.MultiParams(null))
                               .WithUrl("http://fark.com?param1=value1&param1=value2")
                               .AddParameters("param1")
                               .AddValueMapper1(x => MapResult.Success(x.Values));

            var binder = CreateBinder(requestGraph);

            await binder.Bind(requestGraph.GetRequestBinderContext());

            requestGraph.ActionArguments[0].CastTo <object[]>()
            .ShouldOnlyContain("value1", "value2");
        }
Ejemplo n.º 29
0
        public void Should_conditionally_set_properties()
        {
            var instance = new TypeCache().GetTypeDescriptor(typeof(HydratedObject))
                           .CreateAndBind(new List <string, object>
            {
                { "value0", "farker" },
                { "value1", "fark" },
                { "value2", "valueA" },
                { "value2", "valueB" }
            }.ToLookup(), (p, o) => p.Name == "Value2" ?
                                          MapResult.WasMapped(o) : MapResult.NotMapped()) as HydratedObject;

            instance.Value1.ShouldBeNull();
            instance.Value2.ShouldOnlyContain("valueA", "valueB");
        }
Ejemplo n.º 30
0
        public static MapResult <T, R> To <T, R>(this MapResult <T, R> mr, R result, params T[] vals)
        {
            if (mr.Success)
            {
                return(mr);
            }

            var comparer = EqualityComparer <T> .Default;

            if (vals != null && Array.Exists(vals, v => comparer.Equals(v, mr.Value)))
            {
                mr.Result = result;
            }
            return(mr);
        }