Exemple #1
0
 public void InvalidTemplate_InvalidParameterNameWithCloseBracketThrows()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("{a}/{aa}a}/{z}"),
         "There is an incomplete parameter in the route template. Check that each '{' character has a " +
         "matching '}' character.");
 }
        public UdpServiceEntry CreateServiceEntry(Type service)
        {
            UdpServiceEntry result        = null;
            var             routeTemplate = service.GetCustomAttribute <ServiceBundleAttribute>();
            var             objInstance   = _serviceProvider.GetInstances(service);
            var             behavior      = objInstance as UdpBehavior;
            var             path          = RoutePatternParser.Parse(routeTemplate.RouteTemplate, service.Name);

            if (path.Length > 0 && path[0] != '/')
            {
                path = $"/{path}";
            }
            if (behavior != null)
            {
                result = new UdpServiceEntry
                {
                    Behavior = behavior,
                    Type     = behavior.GetType(),
                    Path     = path,
                }
            }
            ;
            return(result);
        }

        #endregion
    }
Exemple #3
0
        private static void RunTest(
            string template,
            string path,
            RouteValueDictionary defaults,
            IDictionary <string, object> expected)
        {
            // Arrange
            var matcher = new RoutePatternMatcher(
                RoutePatternParser.Parse(template),
                defaults ?? new RouteValueDictionary());

            var values = new RouteValueDictionary();

            // Act
            var match = matcher.TryMatch(new PathString(path), values);

            // Assert
            if (expected == null)
            {
                Assert.False(match);
            }
            else
            {
                Assert.True(match);
                Assert.Equal(expected.Count, values.Count);
                foreach (string key in values.Keys)
                {
                    Assert.Equal(expected[key], values[key]);
                }
            }
        }
        public WSServiceEntry CreateServiceEntry(Type service)
        {
            WSServiceEntry result           = null;
            var            routeTemplate    = service.GetCustomAttribute <ServiceBundleAttribute>();
            var            behaviorContract = service.GetCustomAttribute <BehaviorContractAttribute>();
            var            objInstance      = _serviceProvider.GetInstances(service);
            var            behavior         = objInstance as WSBehavior;
            var            path             = RoutePatternParser.Parse(routeTemplate.RouteTemplate, service.Name);

            if (path.Length > 0 && path[0] != '/')
            {
                path = $"/{path}";
            }
            if (behavior != null)
            {
                behavior.Protocol = behaviorContract?.Protocol;
                result            = new WSServiceEntry
                {
                    Behavior = behavior,
                    Type     = behavior.GetType(),
                    Path     = path,
                };
            }
            return(result);
        }
Exemple #5
0
 public void InvalidTemplate_RepeatedParametersThrows()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("foo/aa{p1}{p2}"),
         "A path segment cannot contain two consecutive parameters. They must be separated by a '/' or by " +
         "a literal string.");
 }
Exemple #6
0
 public void InvalidTemplate_CannotHaveConsecutiveCloseBrace()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("foo/{p1}}"),
         "There is an incomplete parameter in the route template. Check that each '{' character has a " +
         "matching '}' character.");
 }
Exemple #7
0
 public void InvalidTemplate_ConsecutiveSeparatorsSlashSlashThrows()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("{a}//{z}"),
         "The route template separator character '/' cannot appear consecutively. It must be separated by " +
         "either a parameter or a literal value.");
 }
Exemple #8
0
 public void InvalidTemplate_WithMismatchedBraces(string template)
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse(template),
         @"There is an incomplete parameter in the route template. Check that each '{' character has a " +
         "matching '}' character.");
 }
        public WSServiceEntry CreateServiceEntry(Type service)
        {
            WSServiceEntry result           = null;
            var            routeTemplate    = service.GetCustomAttribute <ServiceBundleAttribute>();
            var            behaviorContract = service.GetCustomAttribute <BehaviorContractAttribute>();
            var            objInstance      = _serviceProvider.GetInstances(service);
            var            behavior         = objInstance as WebSocketBehavior;
            var            path             = RoutePatternParser.Parse(routeTemplate.RouteTemplate, service.Name);

            if (path.Length > 0 && path[0] != '/')
            {
                path = $"/{path}";
            }
            if (behavior != null)
            {
                result = new WSServiceEntry
                {
                    Behavior     = behavior,
                    Type         = behavior.GetType(),
                    Path         = path,
                    FuncBehavior = () =>
                    {
                        return(GetWebSocketBehavior(service, _options?.Behavior, behaviorContract));
                    }
                }
            }
            ;
            return(result);
        }
Exemple #10
0
 public void InvalidTemplate_CannotHaveMoreThanOneCatchAllInMultiSegment()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("{*p1}abc{*p2}"),
         "A path segment that contains more than one section, such as a literal section or a parameter, " +
         "cannot contain a catch-all parameter.");
 }
Exemple #11
0
 [InlineData(@"{p1:regex(^\d{{3}}-\d{{3}}-\d{4}}$)}")]   // Not escaped {
 public void Parse_RegularExpressions_Unescaped(string template)
 {
     // Act and Assert
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse(template),
         "In a route parameter, '{' and '}' must be escaped with '{{' and '}}'.");
 }
Exemple #12
0
        private ServiceEntry Create(MethodInfo method, string serviceName, string routeTemplate)
        {
            var serviceId         = _serviceIdGenerator.GenerateServiceId(method);
            var attributes        = method.GetCustomAttributes().ToList();
            var serviceDescriptor = new ServiceDescriptor
            {
                Id        = serviceId,
                RoutePath = RoutePatternParser.Parse(routeTemplate, serviceName, method.Name)
            };

            var descriptorAttributes = method.GetCustomAttributes <ServiceDescriptorAttribute>();

            foreach (var descriptorAttribute in descriptorAttributes)
            {
                descriptorAttribute.Apply(serviceDescriptor);
            }
            var authorization = attributes.Where(p => p is AuthorizationFilterAttribute).FirstOrDefault();

            if (authorization != null)
            {
                serviceDescriptor.EnableAuthorization(true);
            }
            if (authorization != null)
            {
                serviceDescriptor.AuthType(((authorization as AuthorizationAttribute)?.AuthType)
                                           ?? AuthorizationType.AppSecret);
            }
            var fastInvoker = GetHandler(serviceId, method);

            return(new ServiceEntry
            {
                Descriptor = serviceDescriptor,
                RoutePath = serviceDescriptor.RoutePath,
                MethodName = method.Name,
                Type = method.DeclaringType,
                Attributes = attributes,
                Func = (key, parameters) =>
                {
                    var instance = _serviceProvider.GetInstances(key, method.DeclaringType);
                    var list = new List <object>();

                    foreach (var parameterInfo in method.GetParameters())
                    {
                        //加入是否有默认值的判断,有默认值,并且用户没传,取默认值
                        if (parameterInfo.HasDefaultValue && !parameters.ContainsKey(parameterInfo.Name))
                        {
                            list.Add(parameterInfo.DefaultValue);
                            continue;
                        }
                        var value = parameters[parameterInfo.Name];
                        var parameterType = parameterInfo.ParameterType;
                        var parameter = _typeConvertibleService.Convert(value, parameterType);
                        list.Add(parameter);
                    }
                    var result = fastInvoker(instance, list.ToArray());
                    return Task.FromResult(result);
                }
            });
        }
Exemple #13
0
    public void ValidTemplate_CanStartWithSlashOrTildeSlash(string routePattern)
    {
        // Arrange & Act
        var pattern = RoutePatternParser.Parse(routePattern);

        // Assert
        Assert.Equal(routePattern, pattern.RawText);
    }
Exemple #14
0
 public void Parse_ComplexSegment_OptionalParametersSeparatedByPeriod_Invalid(string template, string parameter)
 {
     // Act and Assert
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse(template),
         "In the segment '" + template + "', the optional parameter 'p2' is preceded by an invalid " +
         "segment '" + parameter + "'. Only a period (.) can precede an optional parameter.");
 }
Exemple #15
0
 public void Parse_RegularExpressions_Invalid(string template)
 {
     // Act and Assert
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse(template),
         "There is an incomplete parameter in the route template. Check that each '{' character has a matching " +
         "'}' character.");
 }
Exemple #16
0
 public void InvalidTemplate_InvalidParameterNameWithQuestionThrows()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("{Controller}.mvc/{?}"),
         "The route parameter name '' is invalid. Route parameter names must be non-empty and cannot" +
         " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional, and" +
         " can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," +
         " and can occur only at the start of the parameter.");
 }
Exemple #17
0
 public void InvalidTemplate_ParameterCannotContainQuestionMark_UnlessAtEnd()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("{foor?b}"),
         "The route parameter name 'foor?b' is invalid. Route parameter names must be non-empty and cannot" +
         " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional, and" +
         " can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," +
         " and can occur only at the start of the parameter.");
 }
Exemple #18
0
 public void InvalidTemplate_CannotHaveCatchAllWithNoName()
 {
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse("foo/{*}"),
         "The route parameter name '' is invalid. Route parameter names must be non-empty and cannot" +
         " contain these characters: '{', '}', '/'. The '?' character marks a parameter as optional," +
         " and can occur only at the end of the parameter. The '*' character marks a parameter as catch-all," +
         " and can occur only at the start of the parameter.");
 }
Exemple #19
0
    /// <summary>
    /// Creates a <see cref="RoutePattern"/> from its string representation.
    /// </summary>
    /// <param name="pattern">The route pattern string to parse.</param>
    /// <returns>The <see cref="RoutePattern"/>.</returns>
    public static RoutePattern Parse(string pattern)
    {
        if (pattern == null)
        {
            throw new ArgumentNullException(nameof(pattern));
        }

        return(RoutePatternParser.Parse(pattern));
    }
Exemple #20
0
 public RtmpRemoteInvokeService(IServiceRouteProvider serviceRotueProvider, ILogger <RtmpRemoteInvokeService> logger,
                                IHealthCheckService healthCheckService,
                                ITransportClientFactory transportClientFactory)
 {
     _serviceRotueProvider = serviceRotueProvider;
     _logger                 = logger;
     _healthCheckService     = healthCheckService;
     _transportClientFactory = transportClientFactory;
     _routePath              = RoutePatternParser.Parse(AppConfig.Option.RouteTemplate, "ILiveRomtePublishService", "Publish");
 }
Exemple #21
0
    /// <summary>
    /// Creates a <see cref="RoutePattern"/> from its string representation along
    /// with provided default values and parameter policies.
    /// </summary>
    /// <param name="pattern">The route pattern string to parse.</param>
    /// <param name="defaults">
    /// Additional default values to associated with the route pattern. May be null.
    /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/>
    /// and then merged into the parsed route pattern.
    /// </param>
    /// <param name="parameterPolicies">
    /// Additional parameter policies to associated with the route pattern. May be null.
    /// The provided object will be converted to key-value pairs using <see cref="RouteValueDictionary"/>
    /// and then merged into the parsed route pattern.
    /// Multiple policies can be specified for a key by providing a collection as the value.
    /// </param>
    /// <param name="requiredValues">
    /// Route values that can be substituted for parameters in the route pattern. See remarks on <see cref="RoutePattern.RequiredValues"/>.
    /// </param>
    /// <returns>The <see cref="RoutePattern"/>.</returns>
    public static RoutePattern Parse(string pattern, object?defaults, object?parameterPolicies, object?requiredValues)
    {
        if (pattern == null)
        {
            throw new ArgumentNullException(nameof(pattern));
        }

        var original = RoutePatternParser.Parse(pattern);

        return(PatternCore(original.RawText, Wrap(defaults), Wrap(parameterPolicies), Wrap(requiredValues), original.PathSegments));
    }
Exemple #22
0
 public void Parse_ComplexSegment_OptionalParameter_NotTheLastPart(
     string template,
     string parameter,
     string invalid)
 {
     // Act and Assert
     ExceptionAssert.Throws <RoutePatternException>(
         () => RoutePatternParser.Parse(template),
         "An optional parameter must be at the end of the segment. In the segment '" + template +
         "', optional parameter '" + parameter + "' is followed by '" + invalid + "'.");
 }
Exemple #23
0
    public void Parse_SingleParameter()
    {
        // Arrange
        var template = "{p}";

        var expected = Pattern(template, Segment(ParameterPart("p")));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }
Exemple #24
0
    public void Parse_OptionalParameter()
    {
        // Arrange
        var template = "{p?}";

        var expected = Pattern(template, Segment(ParameterPart("p", null, RoutePatternParameterKind.Optional)));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }
Exemple #25
0
    public void ParseRouteParameter_ThrowsIf_ParameterContainsSpecialCharacters(
        string template,
        string parameterName)
    {
        // Arrange
        var expectedMessage = "The route parameter name '" + parameterName + "' is invalid. Route parameter " +
                              "names must be non-empty and cannot contain these characters: '{', '}', '/'. The '?' character " +
                              "marks a parameter as optional, and can occur only at the end of the parameter. The '*' character " +
                              "marks a parameter as catch-all, and can occur only at the start of the parameter.";

        // Act & Assert
        ExceptionAssert.Throws <RoutePatternException>(() => RoutePatternParser.Parse(template), expectedMessage);
    }
Exemple #26
0
    public void Parse_ComplexSegment_LP()
    {
        // Arrange
        var template = "cool-{p1}";

        var expected = Pattern(
            template,
            Segment(
                LiteralPart("cool-"),
                ParameterPart("p1")));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }
Exemple #27
0
    public void Parse_MultipleParameters()
    {
        // Arrange
        var template = "{p1}/{p2}/{*p3}";

        var expected = Pattern(
            template,
            Segment(ParameterPart("p1")),
            Segment(ParameterPart("p2")),
            Segment(ParameterPart("p3", null, RoutePatternParameterKind.CatchAll)));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }
Exemple #28
0
    public void Parse_MultipleLiterals()
    {
        // Arrange
        var template = "cool/awesome/super";

        var expected = Pattern(
            template,
            Segment(LiteralPart("cool")),
            Segment(LiteralPart("awesome")),
            Segment(LiteralPart("super")));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }
Exemple #29
0
    [InlineData(@"{p1:regex(([{{(])\w+)}", @"regex(([{(])\w+)")]                                      // Not balanced {
    public void Parse_RegularExpressions(string template, string constraint)
    {
        // Arrange
        var expected = Pattern(
            template,
            Segment(
                ParameterPart(
                    "p1",
                    null,
                    RoutePatternParameterKind.Standard,
                    Constraint(constraint))));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }
Exemple #30
0
    public void Parse_ComplexSegment_OptionalParameterFollowingPeriod_PeriodAfterSlash()
    {
        // Arrange
        var template = "{p2}/.{p3?}";

        var expected = Pattern(
            template,
            Segment(ParameterPart("p2")),
            Segment(
                SeparatorPart("."),
                ParameterPart("p3", null, RoutePatternParameterKind.Optional)));

        // Act
        var actual = RoutePatternParser.Parse(template);

        // Assert
        Assert.Equal <RoutePattern>(expected, actual, new RoutePatternEqualityComparer());
    }