Esempio n. 1
0
        public static void Snippet2()
        {
            // <Snippet2>
            UriTemplate template    = new UriTemplate("weather/{state}/{city}?forecast=today");
            Uri         baseAddress = new Uri("http://localhost");
            Uri         fullUri     = new Uri("http://localhost/weather/WA/Seattle?forecast=today");

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            // Match a URI to a template
            UriTemplateMatch results = template.Match(baseAddress, fullUri);

            if (results != null)
            {
                // BaseUri
                Console.WriteLine("BaseUri: {0}", results.BaseUri);

                Console.WriteLine("BoundVariables:");
                foreach (string variableName in results.BoundVariables.Keys)
                {
                    Console.WriteLine("    {0}: {1}", variableName, results.BoundVariables[variableName]);
                }
            }
            // Code output:
            // BaseUri: http://localhost/
            // BoundVariables:
            //  state: wa
            //  city: seattleConsole.WriteLine("BaseUri: {0}", results.BaseUri);
            // </Snippet2>
        }
Esempio n. 2
0
        public void PartialResolveNothingTest([Values("#", "+", "")] string exprOp)
        {
            var template        = new UriTemplate("{" + exprOp + "param1,param2}");
            var partialTemplate = template.GetResolver().Bind("unknown", "1").ResolveTemplate();

            Assert.AreEqual(template.ToString(), partialTemplate.ToString());
        }
Esempio n. 3
0
        public static void Snippet4()
        {
            // <Snippet4>
            UriTemplate template    = new UriTemplate("weather/{state}/{city}?forecast=today");
            Uri         baseAddress = new Uri("http://localhost");
            Uri         fullUri     = new Uri("http://localhost/weather/WA/Seattle?forecast=today");

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            // Match a URI to a template
            UriTemplateMatch results = template.Match(baseAddress, fullUri);

            if (results != null)
            {
                Console.WriteLine("QueryParameters:");
                foreach (string queryName in results.QueryParameters.Keys)
                {
                    Console.WriteLine("    {0} : {1}", queryName, results.QueryParameters[queryName]);
                }
                Console.WriteLine();
            }
            // Code output:
            //  QueryParameters:
            //  forecast : today
            // </Snippet4>
        }
Esempio n. 4
0
        public void PartialResolveSimpleTest()
        {
            var template = new UriTemplate("{host}{/path}{?query}{#fragment}");

            template = template.GetResolver().Bind("host", "example.com").ResolveTemplate();
            Assert.AreEqual("example.com{/path}{?query}{#fragment}", template.ToString());

            template = template.GetResolver().Bind("path", "path").ResolveTemplate();
            Assert.AreEqual("example.com/path{?query}{#fragment}", template.ToString());

            template = template.GetResolver().Bind("query", "value").ResolveTemplate();
            Assert.AreEqual("example.com/path?query=value{#fragment}", template.ToString());

            template = template.GetResolver().Bind("fragment", "fragment").ResolveTemplate();
            Assert.AreEqual("example.com/path?query=value#fragment", template.ToString());
        }
Esempio n. 5
0
        public static void Snippet8()
        {
            // <Snippet8>
            UriTemplate template    = new UriTemplate("weather/{state}/*?forecast=today");
            Uri         baseAddress = new Uri("http://localhost");
            Uri         fullUri     = new Uri("http://localhost/weather/WA/Seattle?forecast=today");

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            // Match a URI to a template
            UriTemplateMatch results = template.Match(baseAddress, fullUri);

            if (results != null)
            {
                Console.WriteLine("WildcardPathSegments:");
                foreach (string segment in results.WildcardPathSegments)
                {
                    Console.WriteLine("     {0}", segment);
                }
                Console.WriteLine();
            }
            // Code output:
            // WildcardPathSegments:
            //   seattle
            // </Snippet8>
        }
Esempio n. 6
0
        public static void Snippet8()
        {
            // <Snippet8>
            UriTemplate template = new UriTemplate("weather/{state}/{city}?forecast={day}");

            Console.WriteLine(template.ToString());
            // </Snippet8>
        }
        public static string GetString(string message1, UriTemplate message2)
        {
            string message = GetString(message1);

            if (message2 != null)
            {
                message = message + message2.ToString() + "\n\n";
            }
            return(message);
        }
        public void SelectOperationThrowsWithMatchDifferingByTrailingSlash()
        {
            HttpOperationAssert.Execute <UriTemplateService>(
                (operations) =>
            {
                Uri baseAddress = new Uri("http://localhost/baseAddress");
                UriAndMethodOperationSelector selector = new UriAndMethodOperationSelector(baseAddress, operations, TrailingSlashMode.AutoRedirect);

                foreach (HttpOperationDescription operation in operations)
                {
                    UriTemplate uriTemplate  = operation.GetUriTemplate();
                    HttpMethod method        = operation.GetHttpMethod();
                    string expectedOperation = operation.Name;

                    string[] uriParameters = uriTemplate.PathSegmentVariableNames
                                             .Concat(uriTemplate.QueryValueVariableNames)
                                             .ToArray();
                    Uri requestUri          = uriTemplate.BindByPosition(baseAddress, uriParameters);
                    UriBuilder uriBuilder   = new UriBuilder(requestUri);
                    uriBuilder.Path         = requestUri.AbsolutePath.EndsWith("/") ? uriBuilder.Path.TrimEnd('/') : uriBuilder.Path + "/";
                    Uri backSlashAlteredUri = uriBuilder.Uri;

                    // Because UriTemplate.BindByPosition always adds a backslash for templates "" and "/",
                    //  the original requestUri is actually the correct backSlashAlteredUri in these cases.
                    if (uriTemplate.ToString() == "" || uriTemplate.ToString() == "/")
                    {
                        Uri temp            = requestUri;
                        requestUri          = backSlashAlteredUri;
                        backSlashAlteredUri = temp;
                    }

                    HttpRequestMessage request = new HttpRequestMessage(method, backSlashAlteredUri);

                    ExceptionAssert.Throws <HttpResponseException>(
                        () => selector.SelectOperation(request),
                        (responseException) =>
                    {
                        HttpResponseMessage expectedResponse = StandardHttpResponseMessageBuilder.CreateTemporaryRedirectResponse(request, backSlashAlteredUri, requestUri);
                        HttpAssert.AreEqual(expectedResponse, responseException.Response);
                    });
                }
            });
        }
        private static void CreatePreflightOperation(OperationDescription operation, string originalUriTemplateStr, string originalMethod, ContractDescription contract, out OperationDescription preflightOperation, out PreflightOperationBehavior preflightOperationBehavior)
        {
            var originalUriTemplate = new UriTemplate(originalUriTemplateStr);

            preflightOperation = new OperationDescription(operation.Name + "_preflight", contract);

            //First the input message
            MessageDescription inputMessage = new MessageDescription(operation.Messages[0].Action + "_preflight", MessageDirection.Input);

            preflightOperation.Messages.Add(inputMessage);

            //We need to mirror the input parameters in the URI template
            //First any variables in the path
            if (originalUriTemplate.PathSegmentVariableNames != null && originalUriTemplate.PathSegmentVariableNames.Count > 0)
            {
                foreach (string uriParameter in originalUriTemplate.PathSegmentVariableNames)
                {
                    inputMessage.Body.Parts.Add(new MessagePartDescription(uriParameter, "")
                    {
                        Type = typeof(string)
                    });
                }
            }
            //Next any in the querystring
            if (originalUriTemplate.QueryValueVariableNames != null && originalUriTemplate.QueryValueVariableNames.Count > 0)
            {
                foreach (string uriParameter in originalUriTemplate.QueryValueVariableNames)
                {
                    inputMessage.Body.Parts.Add(new MessagePartDescription(uriParameter, "")
                    {
                        Type = typeof(string)
                    });
                }
            }

            //Now the output message, we only need the CORS headers in reality
            MessageDescription outputMessage = new MessageDescription(operation.Messages[1].Action + "_preflight", MessageDirection.Output);

            //outputMessage.Body.ReturnValue = new MessagePartDescription(preflightOperation.Name + "Return", contract.Namespace) { Type = typeof(Message) };
            preflightOperation.Messages.Add(outputMessage);

            WebInvokeAttribute wia = new WebInvokeAttribute();

            wia.UriTemplate = originalUriTemplate.ToString();
            wia.Method      = "OPTIONS";

            //TODO:TEST
            //wia.BodyStyle = WebMessageBodyStyle.WrappedRequest;

            preflightOperation.Behaviors.Add(wia);
            preflightOperation.Behaviors.Add(new DataContractSerializerOperationBehavior(preflightOperation));
            preflightOperationBehavior = new PreflightOperationBehavior(preflightOperation);
            preflightOperationBehavior.AddAllowedMethod(originalMethod);
            preflightOperation.Behaviors.Add(preflightOperationBehavior);
        }
        private static Dictionary <HttpMethod, UriTemplateTable> GenerateMethodSpecificTables(IEnumerable <HttpOperationDescription> operations, Uri baseAddress, out string catchAllOperationName)
        {
            Fx.Assert(operations != null, "The 'operations' parameter should not be null.");

            catchAllOperationName = string.Empty;
            Dictionary <HttpMethod, UriTemplateTable> methodSpecificTables = new Dictionary <HttpMethod, UriTemplateTable>();

            Dictionary <OperationRoutingKey, string> alreadyHaves = new Dictionary <OperationRoutingKey, string>();

            foreach (HttpOperationDescription operation in operations)
            {
                UriTemplate uriTemplate       = operation.GetUriTemplate();
                string      uriTemplateString = uriTemplate.ToString();
                HttpMethod  httpMethod        = operation.GetHttpMethod();

                if (uriTemplate.IsWildcardPath() && httpMethod.Method == WildcardMethod)
                {
                    if (catchAllOperationName != string.Empty)
                    {
                        throw Fx.Exception.AsError(
                                  new InvalidOperationException(
                                      Http.SR.MultipleOperationsWithSameMethodAndUriTemplate(uriTemplateString, httpMethod.Method)));
                    }

                    catchAllOperationName = operation.Name;
                }

                OperationRoutingKey operationKey = new OperationRoutingKey(uriTemplate, httpMethod);
                if (alreadyHaves.ContainsKey(operationKey))
                {
                    throw Fx.Exception.AsError(
                              new InvalidOperationException(
                                  Http.SR.MultipleOperationsWithSameMethodAndUriTemplate(uriTemplateString, httpMethod.Method)));
                }

                alreadyHaves.Add(operationKey, operation.Name);

                UriTemplateTable methodSpecificTable;
                if (!methodSpecificTables.TryGetValue(httpMethod, out methodSpecificTable))
                {
                    methodSpecificTable = new UriTemplateTable(baseAddress);
                    methodSpecificTables.Add(httpMethod, methodSpecificTable);
                }

                methodSpecificTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, object>(uriTemplate, operation.Name));
            }

            foreach (UriTemplateTable table in methodSpecificTables.Values)
            {
                table.MakeReadOnly(true);
            }

            return(methodSpecificTables);
        }
Esempio n. 11
0
        public void HandleThrowsOnFailedUriTemplateMatch()
        {
            Uri                baseAddress    = new Uri("http://someHost/somePath");
            UriTemplate        template       = new UriTemplate("somePath/{someVariable}/{someVariableWithDefault=default}?query={someQuery}");
            Uri                nonMatchingUri = new Uri("http://someHost/somePath/thisPathDoesNotMatch");
            UriTemplateHandler handler        = new UriTemplateHandler(baseAddress, template);

            ExceptionAssert.Throws <InvalidOperationException>(
                SR.UriTemplateDoesNotMatchUri(nonMatchingUri.ToString(), template.ToString()),
                () => handler.Handle(new object[] { new HttpRequestMessage(HttpMethod.Get, nonMatchingUri) }));
        }
Esempio n. 12
0
        static void Main(string[] args)
        {
            // <Snippet0>
            UriTemplate template    = new UriTemplate("weather/{state}/{city}?forecast=today");
            Uri         baseAddress = new Uri("http://localhost");
            Uri         fullUri     = new Uri("http://localhost/weather/WA/Seattle?forecast=today");

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            // Match a URI to a template
            UriTemplateMatch results = template.Match(baseAddress, fullUri);

            if (results != null)
            {
                // BaseUri
                Console.WriteLine("BaseUri: {0}", results.BaseUri);

                Console.WriteLine("BoundVariables:");
                foreach (string variableName in results.BoundVariables.Keys)
                {
                    Console.WriteLine("    {0}: {1}", variableName, results.BoundVariables[variableName]);
                }

                Console.WriteLine("QueryParameters:");
                foreach (string queryName in results.QueryParameters.Keys)
                {
                    Console.WriteLine("    {0} : {1}", queryName, results.QueryParameters[queryName]);
                }
                Console.WriteLine();

                Console.WriteLine("RelativePathSegments:");
                foreach (string segment in results.RelativePathSegments)
                {
                    Console.WriteLine("     {0}", segment);
                }
                Console.WriteLine();

                Console.WriteLine("RequestUri:");
                Console.WriteLine(results.RequestUri);

                Console.WriteLine("Template:");
                Console.WriteLine(results.Template);

                Console.WriteLine("WildcardPathSegments:");
                foreach (string segment in results.WildcardPathSegments)
                {
                    Console.WriteLine("     {0}", segment);
                }
                Console.WriteLine();
            }
            // </Snippet0>
        }
Esempio n. 13
0
        public static void Main()
        {
            Uri prefix = new Uri("http://localhost/");

            //A UriTemplate is a "URI with holes". It describes a set of URI's that
            //are structurally similar. This UriTemplate might be used for organizing
            //weather reports:
            UriTemplate template = new UriTemplate("weather/{state}/{city}");

            //You can convert a UriTemplate into a Uri by filling
            //the holes in the template with parameters.

            //BindByPosition moves left-to-right across the template
            Uri positionalUri = template.BindByPosition(prefix, "Washington", "Redmond");

            Console.WriteLine("Calling BindByPosition...");
            Console.WriteLine(positionalUri);
            Console.WriteLine();

            //BindByName takes a NameValueCollection of parameters.
            //Each parameter gets substituted into the UriTemplate "hole"
            //that has the same name as the parameter.
            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("state", "Washington");
            parameters.Add("city", "Redmond");

            Uri namedUri = template.BindByName(prefix, parameters);

            Console.WriteLine("Calling BindByName...");
            Console.WriteLine(namedUri);
            Console.WriteLine();


            //The inverse operation of Bind is Match(), which extrudes a URI
            //through the template to produce a set of name/value pairs.
            Uri fullUri = new Uri("http://localhost/weather/Washington/Redmond");
            UriTemplateMatch results = template.Match(prefix, fullUri);

            Console.WriteLine(String.Format("Matching {0} to {1}", template.ToString(), fullUri.ToString()));

            if (results != null)
            {
                foreach (string variableName in results.BoundVariables.Keys)
                {
                    Console.WriteLine(String.Format("   {0}: {1}", variableName, results.BoundVariables[variableName]));
                }
            }

            Console.WriteLine("Press any key to terminate");
            Console.ReadLine();
        }
Esempio n. 14
0
        static void Main(string[] args)
        {
            /*
             * UriTeplate标识统一资源标识符(URI)模版的类,它继承自System.Object
             * 其位于System.ServiceModel程序集中(System.ServiceModel.dll)
             *
             * URI模版,可以定义一组结构相似的URI。模版由两部分组成,即路径和查询。路径由一些列反斜杠(/)分隔的段组成。
             * 每个段可都可以具有文本值,变量值(书写在大括号中({})且被选址为仅与一个段的内容匹配)或必须出现在路径末端的通配符(书写为型号*,与"路径的其余部分"匹配)。
             * 查询表达式可以完全忽略,如果出现表达式,则它指定一组无序的名称/值对,查询表达式的元素可以是文本对(?x=2)
             * 也可以是变量对(?x={val})。不允许使用不成对的值
             */

            UriTemplate template = new UriTemplate("weather/{state}/{city}?forecast={day}");
            Uri         prefix   = new Uri("http://localhost");

            Console.WriteLine("路径片段所有的变量名称:");
            foreach (string name in template.PathSegmentVariableNames)
            {
                Console.WriteLine("     {0}", name);
            }

            Console.WriteLine("查询表达式中的变量名称:");
            foreach (string name in template.QueryValueVariableNames)
            {
                Console.WriteLine("     {0}", name);
            }

            Uri positionaUri = template.BindByPosition(prefix, "Washington", "Redmond", "Today");
            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("state", "Washington");
            parameters.Add("city", "Redmond");
            parameters.Add("day", "Today");
            Uri nameUri = template.BindByName(prefix, parameters);

            Uri fullUri             = new Uri("http://localhost/weather/Washington/Redmond?forecast=today");
            UriTemplateMatch result = template.Match(prefix, fullUri);

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            if (result != null)
            {
                foreach (string variableName in result.BoundVariables.Keys)
                {
                    Console.WriteLine("     {0}:{1}", variableName, result.BoundVariables[variableName]);
                }
            }

            Console.Read();
        }
Esempio n. 15
0
        public static void Snippet0()
        {
            // <Snippet0>
            // <Snippet1>
            UriTemplate template = new UriTemplate("weather/{state}/{city}?forecast={day}");
            // </Snippet1>
            Uri prefix = new Uri("http://localhost");

            Console.WriteLine("PathSegmentVariableNames:");
            foreach (string name in template.PathSegmentVariableNames)
            {
                Console.WriteLine("     {0}", name);
            }
            Console.WriteLine();

            Console.WriteLine("QueryValueVariableNames:");
            foreach (string name in template.QueryValueVariableNames)
            {
                Console.WriteLine("     {0}", name);
            }
            Console.WriteLine();

            Uri positionalUri = template.BindByPosition(prefix, "Washington", "Redmond", "Today");

            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("state", "Washington");
            parameters.Add("city", "Redmond");
            parameters.Add("day", "Today");
            Uri namedUri = template.BindByName(prefix, parameters);

            Uri fullUri = new Uri("http://localhost/weather/Washington/Redmond?forecast=today");
            UriTemplateMatch results = template.Match(prefix, fullUri);

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            if (results != null)
            {
                foreach (string variableName in results.BoundVariables.Keys)
                {
                    Console.WriteLine("   {0}: {1}", variableName, results.BoundVariables[variableName]);
                }
            }
            // </Snippet0>
        }
Esempio n. 16
0
        public static void Snippet3()
        {
            // <Snippet3>
            UriTemplate template    = new UriTemplate("weather/{state}/{city}?forecast=today");
            Uri         baseAddress = new Uri("http://localhost");
            Uri         fullUri     = new Uri("http://localhost/weather/WA/Seattle?forecast=today");

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            // Match a URI to a template
            UriTemplateMatch results = template.Match(baseAddress, fullUri);

            if (results != null)
            {
                Object data = results.Data;
            }
            // </Snippet3>
        }
Esempio n. 17
0
        public static void Snippet7()
        {
            // <Snippet7>
            UriTemplate template = new UriTemplate("weather/{state}/{city}?forecast={day}");
            Uri         prefix   = new Uri("http://localhost");

            Uri fullUri = new Uri("http://localhost/weather/Washington/Redmond?forecast=today");
            UriTemplateMatch results = template.Match(prefix, fullUri);

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            if (results != null)
            {
                foreach (string variableName in results.BoundVariables.Keys)
                {
                    Console.WriteLine("   {0}: {1}", variableName, results.BoundVariables[variableName]);
                }
            }
            // </Snippet7>
        }
Esempio n. 18
0
        public static void Snippet6()
        {
            // <Snippet6>
            UriTemplate template    = new UriTemplate("weather/{state}/{city}?forecast=today");
            Uri         baseAddress = new Uri("http://localhost");
            Uri         fullUri     = new Uri("http://localhost/weather/WA/Seattle?forecast=today");

            Console.WriteLine("Matching {0} to {1}", template.ToString(), fullUri.ToString());

            // Match a URI to a template
            UriTemplateMatch results = template.Match(baseAddress, fullUri);

            if (results != null)
            {
                Console.WriteLine("RequestUri:");
                Console.WriteLine(results.RequestUri);
            }
            // Code output:
            // RequestUri:
            // http://localhost/weather/WA/Seattle?forecast=today
            // </Snippet6>
        }
Esempio n. 19
0
        public void Constructor_sets_UriTemplate()
        {
            var tpl = new UriTemplate("repos/{owner}/{repo}/tags");

            Assert.AreEqual(tpl.ToString(), Query.Template.ToString());
        }
Esempio n. 20
0
 public static bool IsWildcardPath(this UriTemplate template)
 {
     return(IsWildcardPath(template.ToString()));
 }