示例#1
0
        private void RunTest(
            string template,
            RouteValueDictionary defaults,
            RouteValueDictionary ambientValues,
            RouteValueDictionary values,
            string expected,
            UrlEncoder encoder = null)
        {
            // Arrange
            var binderFactory = encoder == null ? BinderFactory : new RoutePatternBinderFactory(encoder, new DefaultObjectPoolProvider());
            var binder        = new TemplateBinder(binderFactory.Create(template, defaults ?? new RouteValueDictionary()));

            // Act & Assert
            var result = binder.GetValues(ambientValues, values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);

                // We want to chop off the query string and compare that using an unordered comparison
                var expectedParts = new PathAndQuery(expected);
                var actualParts   = new PathAndQuery(boundTemplate);

                Assert.Equal(expectedParts.Path, actualParts.Path);

                if (expectedParts.Parameters == null)
                {
                    Assert.Null(actualParts.Parameters);
                }
                else
                {
                    Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count);

                    foreach (var kvp in expectedParts.Parameters)
                    {
                        string value;
                        Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value));
                        Assert.Equal(kvp.Value, value);
                    }
                }
            }
        }
        public void TemplateBinder_KeepsExplicitlySuppliedRouteValues_OnFailedRouetMatch()
        {
            // Arrange
            var template = "{area?}/{controller=Home}/{action=Index}/{id?}";
            var binder   = new TemplateBinder(
                UrlEncoder.Default,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()),
                TemplateParser.Parse(template),
                defaults: null);
            var ambientValues = new RouteValueDictionary();
            var routeValues   = new RouteValueDictionary(new { controller = "Test", action = "Index" });

            // Act
            var templateValuesResult = binder.GetValues(ambientValues, routeValues);
            var boundTemplate        = binder.BindValues(templateValuesResult.AcceptedValues);

            // Assert
            Assert.Null(boundTemplate);
            Assert.Equal(2, templateValuesResult.CombinedValues.Count);
            object routeValue;

            Assert.True(templateValuesResult.CombinedValues.TryGetValue("controller", out routeValue));
            Assert.Equal("Test", routeValue?.ToString());
            Assert.True(templateValuesResult.CombinedValues.TryGetValue("action", out routeValue));
            Assert.Equal("Index", routeValue?.ToString());
        }
示例#3
0
        public void GetValues_SuccessfullyMatchesRouteValues_ForExplicitNullValue_AndEmptyStringDefault()
        {
            // Arrange
            var expected       = "/Home/Index";
            var template       = "Home/Index";
            var defaults       = new RouteValueDictionary(new { controller = "Home", action = "Index", area = "" });
            var ambientValues  = new RouteValueDictionary(new { controller = "Rail", action = "Schedule", area = "Travel" });
            var explicitValues = new RouteValueDictionary(new { controller = "Home", action = "Index", area = (string)null });
            var binder         = new TemplateBinder(
                UrlEncoder.Default,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()),
                TemplateParser.Parse(template),
                defaults);

            // Act1
            var result = binder.GetValues(ambientValues, explicitValues);

            // Assert1
            Assert.NotNull(result);

            // Act2
            var boundTemplate = binder.BindValues(result.AcceptedValues);

            // Assert2
            Assert.NotNull(boundTemplate);
            Assert.Equal(expected, boundTemplate);
        }
示例#4
0
        private string GetLink(MatcherEndpoint endpoint, LinkGeneratorContext context)
        {
            var templateBinder = new TemplateBinder(
                UrlEncoder.Default,
                _uriBuildingContextPool,
                new RouteTemplate(endpoint.RoutePattern),
                new RouteValueDictionary(endpoint.RoutePattern.Defaults));

            var templateValuesResult = templateBinder.GetValues(
                ambientValues: context.AmbientValues,
                explicitValues: context.ExplicitValues,
                endpoint.RequiredValues.Keys);

            if (templateValuesResult == null)
            {
                // We're missing one of the required values for this route.
                return(null);
            }

            if (!MatchesConstraints(context.HttpContext, endpoint, templateValuesResult.CombinedValues))
            {
                return(null);
            }

            var url = templateBinder.BindValues(templateValuesResult.AcceptedValues);

            return(Normalize(context, url));
        }
示例#5
0
        internal string MakeLink(
            HttpContext httpContext,
            RouteEndpoint endpoint,
            RouteValueDictionary ambientValues,
            RouteValueDictionary explicitValues,
            LinkOptions options)
        {
            var templateBinder = new TemplateBinder(
                UrlEncoder.Default,
                _uriBuildingContextPool,
                endpoint.RoutePattern,
                new RouteValueDictionary(endpoint.RoutePattern.Defaults));

            var routeValuesAddressMetadata = endpoint.Metadata.GetMetadata <IRouteValuesAddressMetadata>();
            var templateValuesResult       = templateBinder.GetValues(
                ambientValues: ambientValues,
                explicitValues: explicitValues,
                requiredKeys: routeValuesAddressMetadata?.RequiredValues.Keys);

            if (templateValuesResult == null)
            {
                // We're missing one of the required values for this route.
                return(null);
            }

            if (!MatchesConstraints(httpContext, endpoint, templateValuesResult.CombinedValues))
            {
                return(null);
            }

            var url = templateBinder.BindValues(templateValuesResult.AcceptedValues);

            return(Normalize(url, options));
        }
示例#6
0
 private void EnsureBinder(HttpContext context)
 {
     if (_binder == null)
     {
         var binderFactory = context.RequestServices.GetRequiredService <RoutePatternBinderFactory>();
         _binder = new TemplateBinder(binderFactory.Create(ParsedTemplate.ToRoutePattern(), Defaults));
     }
 }
示例#7
0
 private void EnsureBinder(HttpContext context)
 {
     if (_binder == null)
     {
         var binderFactory = context.RequestServices.GetRequiredService <TemplateBinderFactory>();
         _binder = binderFactory.Create(ParsedTemplate, Defaults);
     }
 }
 private void EnsureBinder(HttpContext context)
 {
     if (_binder == null)
     {
         var pool = context.RequestServices.GetRequiredService <ObjectPool <UriBuildingContext> >();
         _binder = new TemplateBinder(UrlEncoder.Default, pool, ParsedTemplate, Defaults);
     }
 }
示例#9
0
        private static void RunTest(
            string template,
            IReadOnlyDictionary <string, object> defaults,
            IDictionary <string, object> ambientValues,
            IDictionary <string, object> values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(TemplateParser.Parse(template), defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues, values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);

                // We want to chop off the query string and compare that using an unordered comparison
                var expectedParts = new PathAndQuery(expected);
                var actualParts   = new PathAndQuery(boundTemplate);

                Assert.Equal(expectedParts.Path, actualParts.Path);

                if (expectedParts.Parameters == null)
                {
                    Assert.Null(actualParts.Parameters);
                }
                else
                {
                    Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count);

                    foreach (var kvp in expectedParts.Parameters)
                    {
                        string value;
                        Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value));
                        Assert.Equal(kvp.Value, value);
                    }
                }
            }
        }
示例#10
0
 public void RoutePartsEqualTest(object left, object right, bool expected)
 {
     // Arrange & Act & Assert
     if (expected)
     {
         Assert.True(TemplateBinder.RoutePartsEqual(left, right));
     }
     else
     {
         Assert.False(TemplateBinder.RoutePartsEqual(left, right));
     }
 }
示例#11
0
        /// <summary>
        /// 使用mvc路由模版绑定参数
        /// </summary>
        /// <param name="template">路由模版</param>
        /// <param name="values">参数</param>
        /// <returns></returns>
        private string BoundTemplate(string template, RouteValueDictionary values)
        {
            var binder = new TemplateBinder(
                UrlEncoder.Default,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy(UrlEncoder.Default)),
                TemplateParser.Parse(template),
                null
                );

            // Act & Assert
            var result = binder.GetValues(new RouteValueDictionary(), values);

            return(binder.BindValues(result.AcceptedValues));
        }
示例#12
0
        /// <summary>
        /// 使用mvc路由模版绑定参数
        /// </summary>
        /// <param name="template">路由模版</param>
        /// <param name="values">参数</param>
        /// <returns></returns>
        private string BoundTemplate(string template, RouteValueDictionary values)
        {
            var binder = new TemplateBinder(
                UrlEncoder.Default,
                null,
                TemplateParser.Parse(template),
                null
                );

            // Act & Assert
            var result = binder.GetValues(new RouteValueDictionary(), values);

            return(binder.BindValues(result.AcceptedValues));
        }
示例#13
0
        public PathRouteValuesTransform(string pattern, TemplateBinderFactory binderFactory)
        {
            if (pattern is null)
            {
                throw new System.ArgumentNullException(nameof(pattern));
            }

            if (binderFactory is null)
            {
                throw new System.ArgumentNullException(nameof(binderFactory));
            }

            _binder = binderFactory.Create(RoutePatternFactory.Parse(pattern));
        }
示例#14
0
        public List <DBColumn> ExecuteQuery(SqlQuery aQuery)
        {
            TemplateBinder <DBColumn> _binder = new TemplateBinder <DBColumn>();
            List <DBColumn>           _r      = new List <DBColumn>();

            _binder.OnBind = delegate(DBColumn aT)
            {
                _r.Add(aT);
            };
            DBHelper.Execute(delegate(DbSession aDBSession)
            {
                aDBSession.Execute(aQuery, _binder);
            });
            return(_r);
        }
示例#15
0
        public void FakeCall(
            TemplateBinder binder,
            RouteValueDictionary ambientValues,
            RouteValueDictionary values)
        {
            var par = GetType().GetMethod(nameof(GetValues)).GetParameters();
            var ot  = new object[par.Length];

            for (int i = 0; i < par.Length - 2; i++)
            {
                ot[i] = typeof(TemplateBinder).GetField(par[i].Name, BindingFlags.NonPublic | BindingFlags.Instance).GetValue(binder);
            }
            ot[par.Length - 2] = ambientValues;
            ot[par.Length - 1] = values;
            GetType().GetMethod(nameof(GetValues)).Invoke(null, ot);
        }
示例#16
0
        public void Should_Handle_Space_After_NewLine()
        {
            var testData =
                " Id | StringField | \r\n " +
                " 1  | test        | \r\n " +
                "";

            var binder = new TemplateBinder()
                         .SetPropertyNameSpaceDelimiter("_");

            var faker = new AutoFaker <Parent>(binder);

            var result = faker.GenerateWithTemplate(testData);

            result.Should().HaveCount(1);
            result[0].StringField.Should().Be("test");
        }
        public List <DBStoredProcedureParamater> GetStoredProcedureParamaters()
        {
            var q = NativeQuery.SimpleQueryHelper("select r.SPECIFIC_SCHEMA, r.SPECIFIC_NAME, r.SPECIFIC_CATALOG, p.PARAMETER_NAME, p.DATA_TYPE from  DataBank.INFORMATION_SCHEMA.ROUTINES as r inner JOIN information_schema.PARAMETERS as p ON p.SPECIFIC_NAME = r.SPECIFIC_NAME where routine_type = @p0", "PROCEDURE");

            TemplateBinder <DBStoredProcedureParamater> _binder = new TemplateBinder <DBStoredProcedureParamater>();
            List <DBStoredProcedureParamater>           _r      = new List <DBStoredProcedureParamater>();

            _binder.OnBind = delegate(DBStoredProcedureParamater aT)
            {
                _r.Add(aT);
            };
            DBHelper.Execute(delegate(DbSession aDBSession)
            {
                aDBSession.Execute(q, _binder);
            });
            return(_r);
        }
示例#18
0
        public void Should_Treat_Missing_As_Empty_If_Specified()
        {
            var testData =
                " StringField  \r\n" +
                "        \r\n" +
                "";

            var binder = new TemplateBinder()
                         .TreatMissingAsEmpty()
                         .SetTypeConverter(ChildConverter());

            var faker = new AutoFaker <Parent>(binder);

            var result = faker.GenerateWithTemplate(testData);

            result.Should().HaveCount(1);
            result[0].StringField.Should().BeEmpty();
        }
示例#19
0
        private bool ContextHasSameValue(VirtualPathContext context, string key, object value)
        {
            object providedValue;

            if (!context.Values.TryGetValue(key, out providedValue))
            {
                // If the required value is an 'empty' route value, then ignore ambient values.
                // This handles a case where we're generating a link to an action like:
                // { area = "", controller = "Home", action = "Index" }
                //
                // and the ambient values has a value for area.
                if (value != null)
                {
                    context.AmbientValues.TryGetValue(key, out providedValue);
                }
            }

            return(TemplateBinder.RoutePartsEqual(providedValue, value));
        }
示例#20
0
        public void GetVirtualPathWithMultiSegmentWithOptionalParam(
            string template,
            RouteValueDictionary defaults,
            RouteValueDictionary ambientValues,
            RouteValueDictionary values,
            string expected)
        {
            // Arrange
            var encoder = new UrlTestEncoder();
            var binder  = new TemplateBinder(
                encoder,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy(encoder)),
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: ambientValues, values: values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#21
0
        public void Should_Translate_Space_In_Field_If_Specified()
        {
            var testData =
                " Space Field  | Date Space Field\r\n" +
                " test |  \r\n" +
                "   | 2002-09-08\r\n" +
                "";

            var binder = new TemplateBinder()
                         .SetPropertyNameSpaceDelimiter("_");

            var faker = new AutoFaker <Parent>(binder);

            var result = faker.GenerateWithTemplate(testData);

            result.Should().HaveCount(2);
            result[0].Space_Field.Should().Be("test");
            result[0].Date_Space_Field.Should().BeNull();
            result[1].Space_Field.Should().BeNull();
            result[1].Date_Space_Field.Should().Be(DateTime.Parse("2002-09-08"));
        }
        public void Binding_WithEmptyAndNull_DefaultValues(
            string template,
            RouteValueDictionary defaults,
            RouteValueDictionary values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(
                UrlEncoder.Default,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy()),
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: null, values: values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#23
0
        public void GetVirtualPathWithMultiSegmentWithOptionalParam(
            string template,
            IReadOnlyDictionary <string, object> defaults,
            IDictionary <string, object> ambientValues,
            IDictionary <string, object> values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: ambientValues, values: values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#24
0
        public void Should_Use_Type_Converter_If_Specified()
        {
            var testData =
                " Child  \r\n" +
                " Child1 \r\n" +
                " Child2 \r\n" +
                "        \r\n" +
                "";

            var binder = new TemplateBinder()
                         .SetTypeConverter(ChildConverter());

            var faker = new AutoFaker <Parent>(binder);

            var result = faker.GenerateWithTemplate(testData);

            result.Should().HaveCount(3);
            result[0].Child.Name.Should().Be("child1");
            result[1].Child.Name.Should().NotBe("child1"); //noting that in the converted for child2 we'd use a new faker instance
            result[1].Child.Name.Should().NotBeNull();
            result[2].Child.Should().BeNull();
        }
示例#25
0
        public void Binding_WithEmptyAndNull_DefaultValues(
            string template,
            IReadOnlyDictionary <string, object> defaults,
            IDictionary <string, object> values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: null, values: values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#26
0
        public void TestAutoFaker()
        {
            var binder  = new TemplateBinder();
            var persons = new AutoFaker <Person>(binder)
                          .GenerateWithTemplate(@"
          Id | FirstName | LastName
	        0  | John      | Smith
	        1  | Jane      | Jones
	        2  | Bob       | Clark
        ");

            persons.Should().BeEquivalentTo(
                new[]
            {
                new { Id = 0, FirstName = "John", LastName = "Smith", Status = default(string) },
                new { Id = 1, FirstName = "Jane", LastName = "Jones", Status = default(string) },
                new { Id = 2, FirstName = "Bob", LastName = "Clark", Status = default(string) }
            },
                options => options
                .Using <string>(context => context.Subject.Should().NotBeNull())
                .When(info => info.SelectedMemberPath == "Status")
                );
        }
示例#27
0
        public void TemplateBinder_KeepsExplicitlySuppliedRouteValues_OnFailedRouetMatch()
        {
            // Arrange
            var template = "{area?}/{controller=Home}/{action=Index}/{id?}";
            var binder   = new TemplateBinder(BinderFactory.Create(template));

            var ambientValues = new RouteValueDictionary();
            var routeValues   = new RouteValueDictionary(new { controller = "Test", action = "Index" });

            // Act
            var templateValuesResult = binder.GetValues(ambientValues, routeValues);
            var boundTemplate        = binder.BindValues(templateValuesResult.AcceptedValues);

            // Assert
            Assert.Null(boundTemplate);
            Assert.Equal(2, templateValuesResult.CombinedValues.Count);
            object routeValue;

            Assert.True(templateValuesResult.CombinedValues.TryGetValue("controller", out routeValue));
            Assert.Equal("Test", routeValue?.ToString());
            Assert.True(templateValuesResult.CombinedValues.TryGetValue("action", out routeValue));
            Assert.Equal("Index", routeValue?.ToString());
        }
示例#28
0
        public void GetVirtualPathWithMultiSegmentWithOptionalParam(
            string template,
            RouteValueDictionary defaults,
            RouteValueDictionary ambientValues,
            RouteValueDictionary values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(BinderFactory.Create(template, defaults));

            // Act & Assert
            var result = binder.GetValues(ambientValues: ambientValues, values: values);

            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);

            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#29
0
        private static bool TryProcessPrefixTemplate(HttpRequest request, RoutePattern routePattern, out string path)
        {
            // TODO: Do you have a better way to process the prefix template?
            Contract.Assert(request != null);
            Contract.Assert(routePattern != null);

            HttpContext           httpContext    = request.HttpContext;
            TemplateBinderFactory factory        = request.HttpContext.RequestServices.GetRequiredService <TemplateBinderFactory>();
            TemplateBinder        templateBinder = factory.Create(routePattern);

            RouteValueDictionary ambientValues = GetAmbientValues(httpContext);

            var templateValuesResult = templateBinder.GetValues(ambientValues, request.RouteValues);

            if (templateValuesResult == null)
            {
                // We're missing one of the required values for this route.
                path = default;
                return(false);
            }

            if (!templateBinder.TryProcessConstraints(httpContext, templateValuesResult.CombinedValues, out var _, out var _))
            {
                path = default;
                return(false);
            }

            path = templateBinder.BindValues(templateValuesResult.AcceptedValues);
            int index = path.IndexOf("?", StringComparison.Ordinal); // remove the query string

            if (index >= 0)
            {
                path = path.Substring(0, index);
            }

            return(true);
        }
示例#30
0
        public async Task Execute(HttpContext context)
        {
            RouteData routeData = context.GetRouteData();

            var tasks = _appenders.Select((a, i) =>
            {
                // Create binder for the tempalte
                var templateBinder = new TemplateBinder(
                    context.RequestServices.GetRequiredService <UrlEncoder>(),
                    context.RequestServices.GetRequiredService <ObjectPool <UriBuildingContext> >(),
                    _routeTemplates[i].Item2,
                    null);

                // Transform the uri
                Uri fullUri = _routeTemplates[i].Item1 ?? context.Request.GetUri();
                string url  = templateBinder.BindValues(new RouteValueDictionary(routeData.Values));

                var ub  = new UriBuilder(fullUri);
                ub.Path = url;

                // Make the request
                return(a.GetAsync(ub.ToString(), context.RequestAborted));
            });

            // Wait for answer from all requests
            IAppenderResult[] results = await Task.WhenAll(tasks);

            // Merge reults
            object result = MergeResults(results);

            // Write output using formatters
            var actionContext = new ActionContext {
                HttpContext = context, RouteData = routeData
            };
            var objectResult = new OkObjectResult(result);
            await objectResult.ExecuteResultAsync(actionContext);
        }
示例#31
0
        public void Binding_WithEmptyAndNull_DefaultValues(
            string template,
            IReadOnlyDictionary<string, object> defaults,
            IDictionary<string, object> values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: null, values: values);
            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);
            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#32
0
        public void GetVirtualPathWithMultiSegmentWithOptionalParam(
            string template,
            IReadOnlyDictionary<string, object> defaults,
            IDictionary<string, object> ambientValues,
            IDictionary<string, object> values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: ambientValues, values: values);
            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);
            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
示例#33
0
        private static void RunTest(
            string template,
            RouteValueDictionary defaults,
            RouteValueDictionary ambientValues,
            RouteValueDictionary values,
            string expected,
            UrlEncoder encoder = null)
        {
            // Arrange
            encoder = encoder ?? new UrlTestEncoder();

            var binder = new TemplateBinder(
                encoder,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy(encoder)),
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues, values);
            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);
            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);

                // We want to chop off the query string and compare that using an unordered comparison
                var expectedParts = new PathAndQuery(expected);
                var actualParts = new PathAndQuery(boundTemplate);

                Assert.Equal(expectedParts.Path, actualParts.Path);

                if (expectedParts.Parameters == null)
                {
                    Assert.Null(actualParts.Parameters);
                }
                else
                {
                    Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count);

                    foreach (var kvp in expectedParts.Parameters)
                    {
                        string value;
                        Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value));
                        Assert.Equal(kvp.Value, value);
                    }
                }
            }
        }
示例#34
0
        private static void RunTest(
            string template,
            IReadOnlyDictionary<string, object> defaults,
            IDictionary<string, object> ambientValues,
            IDictionary<string, object> values,
            string expected)
        {
            // Arrange
            var binder = new TemplateBinder(TemplateParser.Parse(template), defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues, values);
            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);
            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);

                // We want to chop off the query string and compare that using an unordered comparison
                var expectedParts = new PathAndQuery(expected);
                var actualParts = new PathAndQuery(boundTemplate);

                Assert.Equal(expectedParts.Path, actualParts.Path);

                if (expectedParts.Parameters == null)
                {
                    Assert.Null(actualParts.Parameters);
                }
                else
                {
                    Assert.Equal(expectedParts.Parameters.Count, actualParts.Parameters.Count);

                    foreach (var kvp in expectedParts.Parameters)
                    {
                        string value;
                        Assert.True(actualParts.Parameters.TryGetValue(kvp.Key, out value));
                        Assert.Equal(kvp.Value, value);
                    }
                }
            }
        }
示例#35
0
        public void GetVirtualPathWithMultiSegmentWithOptionalParam(
            string template,
            RouteValueDictionary defaults,
            RouteValueDictionary ambientValues,
            RouteValueDictionary values,
            string expected)
        {
            // Arrange
            var encoder = new UrlTestEncoder();
            var binder = new TemplateBinder(
                encoder,
                new DefaultObjectPoolProvider().Create(new UriBuilderContextPooledObjectPolicy(encoder)),
                TemplateParser.Parse(template),
                defaults);

            // Act & Assert
            var result = binder.GetValues(ambientValues: ambientValues, values: values);
            if (result == null)
            {
                if (expected == null)
                {
                    return;
                }
                else
                {
                    Assert.NotNull(result);
                }
            }

            var boundTemplate = binder.BindValues(result.AcceptedValues);
            if (expected == null)
            {
                Assert.Null(boundTemplate);
            }
            else
            {
                Assert.NotNull(boundTemplate);
                Assert.Equal(expected, boundTemplate);
            }
        }
 public void When_adding_a_value_with_an_element_name_a_source_property_and_target_property_then_binder_is_constructed()
 {
     var templateBinder = new TemplateBinder<OrderViewModel>("Order");
     var definition = templateBinder.Value("FirstName", TextBox.TextProperty, p => p.FirstName);
     Assert.IsNotNull(definition);
 }
 public void When_adding_a_value_with_property_expression_then_binder_definition_is_constructed()
 {
     var templateBinder = new TemplateBinder<OrderViewModel>("Order");
     var definition = templateBinder.Value(p => p.FirstName);
     Assert.IsNotNull(definition);
 }