public MethodAndUriTemplateOperationSelector(ServiceEndpoint endpoint)
        {
            if (endpoint == null)
            {
                throw new ArgumentNullException("endpoint");
            }

            this.delegates =
                new Dictionary<string, UriTemplateOperationSelector>();

            var operations = endpoint.Contract.Operations.Select(od => new HttpOperationDescription(od));

            foreach (var methodGroup in operations.GroupBy(od => od.GetWebMethod()))
            {
                UriTemplateTable table = new UriTemplateTable(endpoint.ListenUri);
                foreach (var operation in methodGroup)
                {
                    UriTemplate template = new UriTemplate(operation.GetUriTemplateString());
                    table.KeyValuePairs.Add(
                        new KeyValuePair<UriTemplate, object>(template, operation.Name));

                }

                table.MakeReadOnly(false);
                UriTemplateOperationSelector templateSelector =
                    new UriTemplateOperationSelector(table);
                this.delegates.Add(methodGroup.Key, templateSelector);
            }
        }
示例#2
0
		public void MatchSingle ()
		{
			var t = new UriTemplateTable (new Uri ("http://localhost:37564"));
			t.KeyValuePairs.Add (new KeyValuePair<UriTemplate,object> (new UriTemplate ("/jsdebug"), null));
			Assert.IsNull (t.MatchSingle (new Uri ("http://localhost:37564/js")), "#1");
			Assert.IsNotNull (t.MatchSingle (new Uri ("http://localhost:37564/jsdebug")), "#2");
		}
        public UriTemplateOperationSelector(UriTemplateTable uriTemplateTable)
        {
            if (uriTemplateTable == null)
            {
                throw new ArgumentNullException("uriTemplateTable");
            }

            this.uriTemplateTable = uriTemplateTable;
            this.UseMatchSingle = true;
        }
        void InitializeFromConfiguration(MessageAddressConversionConfiguration configuration)
        {
            Contract.Requires(configuration != null);

            this.topicTemplateTable = new UriTemplateTable(
                BaseUri,
                from template in configuration.InboundTemplates select new KeyValuePair<UriTemplate, object>(new UriTemplate(template, false), null));
            this.topicTemplateTable.MakeReadOnly(true);
            this.outboundTemplate = configuration.OutboundTemplates.Select(x => new UriPathTemplate(x)).Single();
        }
        public Routes(UriConfiguration uriConfiguration)
        {
            Check.IsNotNull(uriConfiguration, "uriConfiguration");

            baseAddress = uriConfiguration.BaseAddress;

            uriTemplates = new UriTemplateTable(baseAddress);
            uriTemplates.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(uriConfiguration.RecentFeedTemplate, GetFeedOfRecentEvents));
            uriTemplates.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(uriConfiguration.FeedTemplate, GetFeed));
        }
        void InitializeFromConfiguration(RoutingConfiguration configuration)
        {
            Contract.Requires(configuration != null);

            this.topicTemplateTable = new UriTemplateTable(
                BaseUri,
                (from route in configuration.InboundRoutes
                    from template in route.Templates
                    select new KeyValuePair<UriTemplate, object>(new UriTemplate(template, false), route)));
            this.topicTemplateTable.MakeReadOnly(true);
            this.routeTemplateMap = configuration.OutboundRoutes.ToDictionary(x => x.Type, x => new UriPathTemplate(x.Template));
        }
示例#7
0
        public static void Main()
        {
            Uri prefix = new Uri("http://localhost/");

            //A UriTemplateTable is an associative set of UriTemplates. It lets you match
            //candidate URI's against the templates in the set, and retrieve the data associated
            //with the matching templates.

            //To start, we need some example templates and a table to put them in:
            UriTemplate weatherByCity = new UriTemplate("weather/{state}/{city}");
            UriTemplate weatherByState = new UriTemplate("weather/{state}");
            UriTemplate traffic = new UriTemplate("traffic/*");
            UriTemplate wildcard = new UriTemplate("*");

            UriTemplateTable table = new UriTemplateTable(prefix);

            //Now we associate each template with some data. Here we're just using strings;
            //you can associate anything you want with the template.
            table.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(weatherByCity, "weatherByCity"));
            table.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(weatherByState, "weatherByState"));
            table.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(traffic, "traffic"));

            //Once the table is populated, we can use the MatchSingle function to
            //retrieve some match results:

            UriTemplateMatch results = null;
            Uri weatherInSeattle = new Uri("http://localhost/weather/Washington/Seattle");

            //The Match function will select the best match for the incoming URI 
            //based on the templates in the table. There are two variants of Match --
            //Match() can potentially return multiple results, which MatchSingle() will
            //either return exactly one result or throw an exception.
            
            results = table.MatchSingle(weatherInSeattle);

            //We get back the associated data in the Data member of
            //the UriTemplateMatchResults that are returned.
            if (results != null)
            {
                //Output will be "weatherByCity"
                Console.WriteLine(results.Data);

                //The UriTemplateMatch contains useful data obtained during the
                //matching process.

                Console.WriteLine("State: {0}", results.BoundVariables["state"]);
                Console.WriteLine("City: {0}", results.BoundVariables["city"]);
            }
            
            Console.WriteLine("Press any key to terminate");
            Console.ReadLine();
        }
示例#8
0
 public void Add(params CommandBind[] binds)
 {
     foreach (var b in binds)
     {
         UriTemplateTable t;
         if (!_tables.TryGetValue(b.HttpMethod, out t))
         {
             t = new UriTemplateTable(new Uri(_baseAddress));
             _tables.Add(b.HttpMethod, t);
         }
         t.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(b.UriTemplate, b.Command));
     }
 }
        public void Add(params ICommand[] cmds)
        {
            foreach(var cmd in cmds)
            {
                UriTemplateTable t;
                if(!_tables.TryGetValue(cmd.HttpMethod, out t))
                {
                    t = new UriTemplateTable(new Uri(_baseAddress));
                    _tables.Add(cmd.HttpMethod, t);
                }

                t.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(cmd.UriTemplate, cmd));
            }
        }
		public WebHttpDispatchOperationSelector (ServiceEndpoint endpoint)
		{
			if (endpoint == null)
				throw new ArgumentNullException ("endpoint");
			if (endpoint.Address == null)
				throw new InvalidOperationException ("EndpointAddress must be set in the argument ServiceEndpoint");

			table = new UriTemplateTable (endpoint.Address.Uri);

			foreach (OperationDescription od in endpoint.Contract.Operations) {
				WebAttributeInfo info = od.GetWebAttributeInfo ();
				if (info != null)
					table.KeyValuePairs.Add (new TemplateTablePair (info.BuildUriTemplate (od, null), od));
			}
		}
示例#11
0
        private void ConstructDispatcherTables(Uri prefix)
        {
            this.getDispatcherTable = new UriTemplateTable(prefix);
            this.postDispatcherTable = new UriTemplateTable(prefix);
            this.deleteDispatcherTable = new UriTemplateTable(prefix);

            var commands = this.GetCommands();

            foreach (var command in commands)
            {
                var commandUriTemplate = new UriTemplate(command.Value.ResourcePath);
                var templateTable = this.FindDispatcherTable(command.Value.Method);
                templateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(commandUriTemplate, command.Key));
            }

            this.getDispatcherTable.MakeReadOnly(false);
            this.postDispatcherTable.MakeReadOnly(false);
            this.deleteDispatcherTable.MakeReadOnly(false);
        }
 public WebHttpOperationSelector(ServiceEndpoint endpoint)
 {
     this.UriTemplateTables = new Dictionary<string, UriTemplateTable>();
     Uri baseAddress = endpoint.Address.Uri;
     foreach (var operation in endpoint.Contract.Operations)
     {
     WebGetAttribute webGet = operation.Behaviors.Find<WebGetAttribute>();
     WebInvokeAttribute webInvoke = operation.Behaviors.Find<WebInvokeAttribute>();
     string method = (null != webGet) ? "GET" : webInvoke.Method;
     UriTemplateTable uriTemplateTable;
     if (!this.UriTemplateTables.TryGetValue(method, out uriTemplateTable))
     {
         uriTemplateTable = new UriTemplateTable(baseAddress);
         this.UriTemplateTables.Add(method, uriTemplateTable);
     }
     string template = (null != webGet)?webGet.UriTemplate:webInvoke.UriTemplate;
     uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(template), operation.Name));
     }
 }
        private void ConstructDispatcherTables(Uri prefix)
        {
            this.getDispatcherTable = new UriTemplateTable(prefix);
            this.postDispatcherTable = new UriTemplateTable(prefix);
            this.deleteDispatcherTable = new UriTemplateTable(prefix);

            var fields = typeof(DriverCommand).GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (var field in fields)
            {
                var commandName = field.GetValue(null).ToString();
                var commandInformation = this.commandDictionary[commandName];
                var commandUriTemplate = new UriTemplate(commandInformation.ResourcePath);
                var templateTable = this.FindDispatcherTable(commandInformation.Method);
                templateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(commandUriTemplate, commandName));
            }

            this.getDispatcherTable.MakeReadOnly(false);
            this.postDispatcherTable.MakeReadOnly(false);
            this.deleteDispatcherTable.MakeReadOnly(false);
        }
示例#14
0
        public static void Main()
        {
            Uri prefix = new Uri("http://localhost/");

            //One interesting use for UriTemplateTable is as a dispatching engine.
            //This is accomplished by using the UriTemplateTable to associate
            //a delegate handler with each UriTemplate.

            //To start, we need a UriTemplateTable.
            UriTemplateTable table = new UriTemplateTable(prefix);

            //Now, we add templates to the table and associate them
            //with handler functions, written as anonymous delegates:

            AddHandler(table, new UriTemplate("weather/{state}/{city}"),
                delegate(UriTemplateMatch r)
            {
                Console.WriteLine("Matched the WeatherByCity template");
                Console.WriteLine("State: {0}", r.BoundVariables["state"]);
                Console.WriteLine("City: {0}", r.BoundVariables["city"]);
            });

            AddHandler(table, new UriTemplate("weather/{state}"),
                delegate(UriTemplateMatch r)
            {
                Console.WriteLine("Matched the WeatherByState template");
                Console.WriteLine("State: {0}", r.BoundVariables["state"]);
            });

            AddHandler(table, new UriTemplate("traffic/*"),
                delegate(UriTemplateMatch r)
            {
                Console.WriteLine("Matched the traffic/* template");
                Console.WriteLine("Wildcard segments:");

                foreach (string s in r.WildcardPathSegments)
                {
                    Console.WriteLine("   " + s);
                }
            });

            //MakeReadOnly() freezes the table and prevents further additions.
            //Passing false to this method will disallow duplicate URI's,
            //guaranteeing that at most a single match will be returned. 
            //Calling this method explictly is optional, as the collection
            //will be made read-only during the first call to Match() or MatchSingle()
            table.MakeReadOnly(false);

            Uri request = null;

            //Match WeatherByCity
            request = new Uri("http://localhost/weather/Washington/Seattle");
            Console.WriteLine(request);
            InvokeDelegate(table.MatchSingle(request));

            //Match WeatherByState
            request = new Uri("http://localhost/weather/Washington");
            Console.WriteLine(request);
            InvokeDelegate(table.MatchSingle(request));

            //Wildcard match Traffic
            request = new Uri("http://localhost/Traffic/Washington/Seattle/SR520");
            Console.WriteLine(request);
            InvokeDelegate(table.MatchSingle(request));

            Console.WriteLine("Press any key to terminate");
            Console.ReadLine();
        }
        bool CanUriMatch(UriTemplateTable methodSpecificTable, Uri to, HttpRequestMessageProperty prop, Message message, out string operationName)
        {
            operationName = null;
            UriTemplateMatch result = methodSpecificTable.MatchSingle(to);

            if (result != null)
            {
                operationName = result.Data as string;
                Fx.Assert(operationName != null, "bad result");
                AddUriTemplateMatch(result, prop, message);
                return true;
            }
            return false;
        }
示例#16
0
 private static void AddHandler(UriTemplateTable table, UriTemplate template, Handler handler)
 {
     table.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(template, handler));
 }
示例#17
0
        /// <summary>
        /// Executes if the current request is processed by ASP.NET on the begin of request.
        /// Rewrites the Url if there IIS is configured for extensionless Urls.
        /// </summary>
        /// <param name="sender">The current <see cref="HttpApplication" />.</param>
        /// <param name="e">The EventArgs.</param>
        private void context_BeginRequest(object sender, EventArgs e)
        {
            // Get the current HTTP context.
            var context = ((HttpApplication)sender).Context;

            // Get the navigation service.
            var navigationService =
                this.Container.Resolve<INavigationService>();

            // Get the url from the current request.
            var currentPath = context.Request.Url;

            // Set up the table with the URI templates.
            var uriTemplateTable = new UriTemplateTable();

            // Set the table's base address.
            uriTemplateTable.BaseAddress = new Uri(navigationService.GetApplicationPath());

            // Set the rules.
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetDownloadUriTemplate() + "{data}"), HandlerAction.Download));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetRedirectUriTemplate() + "{data}"), HandlerAction.Redirect));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetSecurityTokenServiceUriTemplate()), HandlerAction.SecurityTokenService));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetSecurityTokenServiceUriTemplate().TrimEnd('/')), HandlerAction.SecurityTokenService));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetSecurityTokenServiceUriTemplate() + "{data}"), HandlerAction.SecurityTokenService));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate().TrimEnd('/')), HandlerAction.UI));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate()), HandlerAction.UI));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate() + "{controller}"), HandlerAction.UI));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate() + "{controller}/"), HandlerAction.UI));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate() + "{controller}/{controllerAction}"), HandlerAction.UI));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate() + "{controller}/{controllerAction}/"), HandlerAction.UI));
            uriTemplateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(navigationService.GetUIUriTemplate() + "{controller}/{controllerAction}/{data}"), HandlerAction.UI));

            // Check whether the current path matches any of these rewrite rules. If not, return.
            UriTemplateMatch uriTemplateMatch = uriTemplateTable.MatchSingle(currentPath);
            if (uriTemplateMatch == null)
            {
                // Before returning, check whether silkveil.net's application handler was called
                // directly. If so, check if SSL is required for silkveil.net, and redirect, if
                // neccessary.
                if (context.Request.Url.GetLeftPart(UriPartial.Path).TrimEnd('/').ToLowerInvariant() ==
                    navigationService.GetApplicationHandlerFactoryPath().TrimEnd('/').ToLowerInvariant())
                {
                    this.Container.Resolve<IProtocolManager>().RedirectIfNeccessary(context.Request);
                }

                // Return to the caller.
                return;
            }

            // Check if SSL is required for silkveil.net, and redirect, if neccessary.
            this.Container.Resolve<IProtocolManager>().RedirectIfNeccessary(context.Request);

            // Otherwise, redirect using the URI match.
            var applicationHandlerFactoryVirtualPath = navigationService.GetApplicationHandlerFactoryVirtualPath();
            switch ((HandlerAction)uriTemplateMatch.Data)
            {
                case HandlerAction.Download:
                    context.RewritePath(string.Format(CultureInfo.InvariantCulture,
                        applicationHandlerFactoryVirtualPath + "?Action={0}&Data={1}", HandlerAction.Download, uriTemplateMatch.BoundVariables["data"]));
                    break;
                case HandlerAction.Redirect:
                    context.RewritePath(string.Format(CultureInfo.InvariantCulture,
                        applicationHandlerFactoryVirtualPath + "?Action={0}&Data={1}", HandlerAction.Redirect, uriTemplateMatch.BoundVariables["data"]));
                    break;
                case HandlerAction.SecurityTokenService:
                    string data = uriTemplateMatch.BoundVariables["data"] ?? "Logon";
                    string wa;
                    switch (data)
                    {
                        case "Logon":
                            wa = WSFederationConstants.Actions.SignIn;
                            break;
                        case "Logoff":
                            wa = WSFederationConstants.Actions.SignOut;
                            break;
                        default:
                            throw new InvalidOperationException(string.Format(CultureInfo.CurrentUICulture,
                                "The data '{0}' is not supported.", data));
                    }
                    var wtrealm = "http://www.silkveil.net/";
                    context.RewritePath(string.Format(CultureInfo.InvariantCulture,
                        applicationHandlerFactoryVirtualPath + "?Action={0}&Data={1}&wa={2}&wtrealm={3}", HandlerAction.SecurityTokenService,
                            data, wa, HttpUtility.UrlEncode(wtrealm)));
                    break;
                case HandlerAction.UI:
                    context.RewritePath(string.Format(CultureInfo.InvariantCulture,
                        applicationHandlerFactoryVirtualPath + "?Action={0}&Controller={1}&ControllerAction={2}&Data={3}", HandlerAction.UI,
                            uriTemplateMatch.BoundVariables["controller"] ?? string.Empty,
                            uriTemplateMatch.BoundVariables["controllerAction"] ?? string.Empty,
                            uriTemplateMatch.BoundVariables["data"] ?? string.Empty));
                    break;
            }
        }
        UriTemplate FindBestMatchingTemplate(UriTemplateTable templates, 
            object resourceKey,
            string uriName,
            NameValueCollection keyValues)
        {
            resourceKey = EnsureIsNotType(resourceKey);
            var matchingTemplates =
                from template in templates.KeyValuePairs
                let descriptor = (UrlDescriptor)template.Value
                where CompatibleKeys(resourceKey, descriptor.ResourceKey)
                where UriNameMatches(uriName, descriptor.UriName)
                let templateParameters =
                    template.Key.PathSegmentVariableNames.Concat(template.Key.QueryValueVariableNames).ToList()
                let hasKeys = keyValues != null && keyValues.HasKeys()
                where (templateParameters.Count == 0) ||
                      (templateParameters.Count > 0
                       && hasKeys
                       && templateParameters.All(x => keyValues.AllKeys.Contains(x, StringComparison.OrdinalIgnoreCase)))
                orderby templateParameters.Count descending
                select template.Key;

            return matchingTemplates.FirstOrDefault();
        }
示例#19
0
        private void ConstructDispatcherTables(string prefix)
        {
            this.getDispatcherTable = new UriTemplateTable(new Uri(prefix.Replace("*", "localhost")));
            this.postDispatcherTable = new UriTemplateTable(new Uri(prefix.Replace("*", "localhost")));
            this.deleteDispatcherTable = new UriTemplateTable(new Uri(prefix.Replace("*", "localhost")));

            // DriverCommand is a static class with static fields containing the command names.
            // Since this is initialization code only, we'll take the perf hit in using reflection.
            FieldInfo[] fields = typeof(DriverCommand).GetFields(BindingFlags.Public | BindingFlags.Static);
            foreach (FieldInfo field in fields)
            {
                string commandName = field.GetValue(null).ToString();
                CommandInfo commandInformation = CommandInfoRepository.Instance.GetCommandInfo(commandName);
                UriTemplate commandUriTemplate = new UriTemplate(commandInformation.ResourcePath);
                if (!this.handlerFactory.CanCreateHandler(commandName))
                {
                    this.serverLogger.Log("No command handler implemented for " + commandName.ToString(), LogLevel.Warning);
                }

                UriTemplateTable templateTable = this.FindDispatcherTable(commandInformation.Method);
                templateTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(commandUriTemplate, commandName));
            }

            this.getDispatcherTable.MakeReadOnly(false);
            this.postDispatcherTable.MakeReadOnly(false);
            this.deleteDispatcherTable.MakeReadOnly(false);
        }
示例#20
0
 public HelpPageOperationSelector(Uri baseUri)
 {
     List<KeyValuePair<UriTemplate, object>> templateList = new List<KeyValuePair<UriTemplate, object>>();
     templateList.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(HelpPageInvoker.AllOperationsTemplate), "GetFeed"));
     templateList.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(HelpPageInvoker.OperationRequestExampleTemplate), "GetRequestExample"));
     templateList.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(HelpPageInvoker.OperationRequestSchemaTemplate), "GetRequestSchema"));
     templateList.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(HelpPageInvoker.OperationResponseExampleTemplate), "GetResponseExample"));
     templateList.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(HelpPageInvoker.OperationResponseSchemaTemplate), "GetResponseSchema"));
     table = new UriTemplateTable(baseUri, templateList);
     table.MakeReadOnly(false);
 }
        public WebHttpDispatchOperationSelector(ServiceEndpoint endpoint)
        {
            if (endpoint == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("endpoint");
            }
            if (endpoint.Address == null)
            {
                throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidOperationException(
                    SR2.GetString(SR2.EndpointAddressCannotBeNull)));
            }
#pragma warning disable 56506 // [....], endpoint.Address.Uri is never null
            Uri baseUri = endpoint.Address.Uri;
            this.methodSpecificTables = new Dictionary<string, UriTemplateTable>();
            this.templates = new Dictionary<string, UriTemplate>();
#pragma warning restore 56506

            WebHttpBehavior webHttpBehavior = endpoint.Behaviors.Find<WebHttpBehavior>();
            if (webHttpBehavior != null && webHttpBehavior.HelpEnabled)
            {
                this.helpUriTable = new UriTemplateTable(endpoint.ListenUri, HelpPage.GetOperationTemplatePairs());
            }

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

#pragma warning disable 56506 // [....], endpoint.Contract is never null
            foreach (OperationDescription od in endpoint.Contract.Operations)
#pragma warning restore 56506
            {
                // ignore callback operations
                if (od.Messages[0].Direction == MessageDirection.Input)
                {
                    string method = WebHttpBehavior.GetWebMethod(od);
                    string path = UriTemplateClientFormatter.GetUTStringOrDefault(od);

                    // 

                    if (UriTemplateHelpers.IsWildcardPath(path) && (method == WebHttpBehavior.WildcardMethod))
                    {
                        if (this.catchAllOperationName != "")
                        {
                            throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                                new InvalidOperationException(
                                SR2.GetString(SR2.MultipleOperationsInContractWithPathMethod,
                                endpoint.Contract.Name, path, method)));
                        }
                        this.catchAllOperationName = od.Name;
                    }
                    UriTemplate ut = new UriTemplate(path);
                    WCFKey wcfKey = new WCFKey(ut, method);
                    if (alreadyHaves.ContainsKey(wcfKey))
                    {
                        throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(
                            new InvalidOperationException(
                            SR2.GetString(SR2.MultipleOperationsInContractWithPathMethod,
                            endpoint.Contract.Name, path, method)));
                    }
                    alreadyHaves.Add(wcfKey, od.Name);

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

                    methodSpecificTable.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(ut, od.Name));
                    this.templates.Add(od.Name, ut);
                }
            }

            if (this.methodSpecificTables.Count == 0)
            {
                this.methodSpecificTables = null;
            }
            else
            {
                // freeze all the tables because they should not be modified after this point
                foreach (UriTemplateTable table in this.methodSpecificTables.Values)
                {
                    table.MakeReadOnly(true /* allowDuplicateEquivalentUriTemplates */);
                }

                if (!methodSpecificTables.TryGetValue(WebHttpBehavior.WildcardMethod, out wildcardTable))
                {
                    wildcardTable = null;
                }
            }
        }
        bool ShouldRedirectToUriWithSlashAtTheEnd(UriTemplateTable methodSpecificTable, Message message, Uri to)
        {
            UriBuilder ub = new UriBuilder(to);
            if (ub.Path.EndsWith("/", StringComparison.Ordinal))
            {
                return false;
            }

            ub.Path = ub.Path + "/";
            Uri originalPlusSlash = ub.Uri;

            bool result = false;
            if (methodSpecificTable != null && methodSpecificTable.MatchSingle(originalPlusSlash) != null)
            {
                // as an optimization, we check the table that matched the request's method
                // first, as it is more probable that a hit happens there
                result = true;
            }
            else
            {
                // back-compat:
                // we will redirect as long as there is any method 
                // - not necessary the one the user is looking for -
                // that matches the uri with a slash at the end

                foreach (KeyValuePair<string, UriTemplateTable> pair in methodSpecificTables)
                {
                    UriTemplateTable table = pair.Value;
                    if (table != methodSpecificTable && table.MatchSingle(originalPlusSlash) != null)
                    {
                        result = true;
                        break;
                    }
                }
            }

            if (result)
            {
                string hostAndPort = GetAuthority(message);
                originalPlusSlash = UriTemplate.RewriteUri(ub.Uri, hostAndPort);
                message.Properties.Add(RedirectPropertyName, originalPlusSlash);
            }
            return result;
        }
 public void Clear()
 {
     _templates = new UriTemplateTable();
 }
示例#24
0
		public void MatchSingleNoPair ()
		{
			var t = new UriTemplateTable (new Uri ("http://localhost:37564"));
			// at least one UriTemplate must exist in the table.
			t.MatchSingle (new Uri ("http://localhost:37564"));
		}
 /// <summary>
 /// Create UriTemplate collection that universally accepts all query operations.
 /// </summary>
 /// <param name="baseUri">Base endpoint URI.</param>
 /// <returns>Table that contains a universal matcher.</returns>
 private static UriTemplateTable CreateAstoriaTemplate(Uri baseUri)
 {
     UriTemplateTable table = new UriTemplateTable();
     table.BaseAddress = baseUri;
     table.KeyValuePairs.Add(new KeyValuePair<UriTemplate, object>(new UriTemplate(ServiceUtils.MatchAllWildCard), null));
     return table;
 }
        /// <summary>
        /// The locate http receive activities.
        /// </summary>
        /// <param name="activity">
        /// The activity.
        /// </param>
        /// <param name="uriTemplateTable">
        /// The uri template table.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// The activity is null
        /// </exception>
        private void LocateHttpReceiveActivities(Activity activity, UriTemplateTable uriTemplateTable)
        {
            if (activity == null)
            {
                throw new ArgumentNullException("activity");
            }

            if (activity is HttpReceive)
            {
                var receive = (HttpReceive)activity;

                uriTemplateTable.KeyValuePairs.Add(
                    new KeyValuePair<UriTemplate, object>(new UriTemplate(receive.UriTemplate), receive));
            }

            foreach (var childActivity in WorkflowInspectionServices.GetActivities(activity))
            {
                this.LocateHttpReceiveActivities(childActivity, uriTemplateTable);
            }
        }