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);
            }
        }
Ejemplo n.º 2
0
        public static void Snippet7()
        {
            // <Snippet7>
            Uri prefix = new Uri("http://localhost/");

            //Create a series of templates
            UriTemplate weatherByCity    = new UriTemplate("weather/ state}/ city}");
            UriTemplate weatherByCountry = new UriTemplate("weather/ country}/ village}");
            UriTemplate weatherByState   = new UriTemplate("weather/ state}");
            UriTemplate traffic          = new UriTemplate("traffic/*");
            UriTemplate wildcard         = new UriTemplate("*");

            //Create a template table
            UriTemplateTable table = new UriTemplateTable(prefix);

            //Add each template to the table with some associated data
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCity, "weatherByCity"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCountry, "weatherByCountry"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByState, "weatherByState"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(traffic, "traffic"));

            table.MakeReadOnly(true);

            Console.WriteLine("KeyValuePairs:");
            foreach (KeyValuePair <UriTemplate, Object> keyPair in table.KeyValuePairs)
            {
                Console.WriteLine("     0},  1}", keyPair.Key, keyPair.Value);
            }

            Console.WriteLine();
            // </Snippet7>
        }
Ejemplo n.º 3
0
        public static void Snippet4()
        {
            // <Snippet6>
            // <Snippet4>
            Uri baseAddress = new Uri("http://localhost/");
            //Create a series of templates
            UriTemplate weatherByCity    = new UriTemplate("weather/{state}/{city}");
            UriTemplate weatherByCountry = new UriTemplate("weather/{country}/{village}");
            UriTemplate weatherByState   = new UriTemplate("weather/{state}");
            UriTemplate traffic          = new UriTemplate("traffic/*");
            UriTemplate wildcard         = new UriTemplate("*");

            //Add each template to the table with some associated data
            List <KeyValuePair <UriTemplate, Object> > list = new List <KeyValuePair <UriTemplate, object> >();

            list.Add(new KeyValuePair <UriTemplate, Object>(weatherByCity, "weatherByCity"));
            list.Add(new KeyValuePair <UriTemplate, Object>(weatherByCountry, "weatherByCountry"));
            list.Add(new KeyValuePair <UriTemplate, Object>(weatherByState, "weatherByState"));
            list.Add(new KeyValuePair <UriTemplate, Object>(traffic, "traffic"));

            //Create a template table
            UriTemplateTable table = new UriTemplateTable(baseAddress, list);

            table.MakeReadOnly(true);
            // </Snippet4>
            if (table.IsReadOnly)
            {
                Console.WriteLine("UriTemplateTable is read only");
            }
            else
            {
                Console.WriteLine("UriTemplateTable is not read only");
            }
            // </Snippet6>
        }
Ejemplo n.º 4
0
        public static void Snippet10()
        {
            // <Snippet10>
            Uri prefix = new Uri("http://localhost/");

            //Create a series of templates
            UriTemplate weatherByCity    = new UriTemplate("weather/ state}/ city}");
            UriTemplate weatherByCountry = new UriTemplate("weather/ country}/ village}");
            UriTemplate weatherByState   = new UriTemplate("weather/ state}");
            UriTemplate traffic          = new UriTemplate("traffic/*");
            UriTemplate wildcard         = new UriTemplate("*");

            //Create a template table
            UriTemplateTable table = new UriTemplateTable(prefix);

            //Add each template to the table with some associated data
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCity, "weatherByCity"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCountry, "weatherByCountry"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByState, "weatherByState"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(traffic, "traffic"));

            table.MakeReadOnly(true);

            //Call MatchSingle to retrieve some match results:
            Uri weatherInSeattle   = new Uri("http://localhost/weather/Washington/Seattle");
            UriTemplateMatch match = table.MatchSingle(weatherInSeattle);

            Console.WriteLine("Matching template: {0}", match.Template.ToString());
            // </Snippet10>
        }
Ejemplo n.º 5
0
        public static void Snippet2()
        {
            // <Snippet2>
            // <Snippet5>
            //Create a series of templates
            UriTemplate weatherByCity    = new UriTemplate("weather/{state}/{city}");
            UriTemplate weatherByCountry = new UriTemplate("weather/{country}/{village}");
            UriTemplate weatherByState   = new UriTemplate("weather/{state}");
            UriTemplate traffic          = new UriTemplate("traffic/*");
            UriTemplate wildcard         = new UriTemplate("*");

            //Add each template to the table with some associated data
            List <KeyValuePair <UriTemplate, Object> > list = new List <KeyValuePair <UriTemplate, object> >();

            list.Add(new KeyValuePair <UriTemplate, Object>(weatherByCity, "weatherByCity"));
            list.Add(new KeyValuePair <UriTemplate, Object>(weatherByCountry, "weatherByCountry"));
            list.Add(new KeyValuePair <UriTemplate, Object>(weatherByState, "weatherByState"));
            list.Add(new KeyValuePair <UriTemplate, Object>(traffic, "traffic"));

            //Create a template table
            UriTemplateTable table = new UriTemplateTable(list);

            table.BaseAddress = new Uri("http://localhost/");
            table.MakeReadOnly(true);
            // </Snippet5>
            // </Snippet2>
        }
        /// <summary>
        /// Creates a new instance of the HttpTransportListener class.
        /// </summary>
        /// <param name="port">The port for listening.</param>
        /// <param name="hostName">Name of the host for binding.</param>
        /// <param name="useHttps">if set to <c>true</c> the listener endpoint will use HTTPS.</param>
        /// <param name="requestTimeout">The request timeout.</param>
        /// <param name="writeExceptionsToOutput">if set to <c>true</c> the exceptions details will be written in the response body.</param>
        /// <param name="httpServer">The HTTP server instance.</param>
        /// <param name="httpTransportProvider">The HTTP transport provider instance.</param>
        /// <param name="serializer">The serializer instance.</param>
        /// <param name="messageStorage">The message storage instance.</param>
        /// <param name="notificationStorage">The notification storage instance.</param>
        /// <param name="processors">The processors.</param>
        /// <param name="traceWriter">The trace writer.</param>
        public HttpTransportListener(int port, string hostName  = "*", bool useHttps        = false, TimeSpan requestTimeout = default(TimeSpan), TimeSpan transportExpirationInactivityInterval = default(TimeSpan), bool writeExceptionsToOutput = true,
                                     int maxDegreeOfParallelism = 1, IHttpServer httpServer = null, IHttpTransportProvider httpTransportProvider = null, IDocumentSerializer serializer          = null, IEnvelopeStorage <Message> messageStorage = null,
                                     IEnvelopeStorage <Notification> notificationStorage = null, IHttpProcessor[] processors = null, ITraceWriter traceWriter = null)
        {
            _useHttps = useHttps;
            var scheme = _useHttps ? Uri.UriSchemeHttps : Uri.UriSchemeHttp;

            _writeExceptionsToOutput = writeExceptionsToOutput;
            _maxDegreeOfParallelism  = maxDegreeOfParallelism;
            _requestTimeout          = requestTimeout != default(TimeSpan) ? requestTimeout : TimeSpan.FromSeconds(Constants.DEFAULT_REQUEST_TIMEOUT);

            var basePath = string.Format("{0}://{1}:{2}", scheme, hostName, port);
            var prefixes = new string[]
            {
                Constants.ROOT + Constants.MESSAGES_PATH + Constants.ROOT,
                Constants.ROOT + Constants.COMMANDS_PATH + Constants.ROOT,
                Constants.ROOT + Constants.NOTIFICATIONS_PATH + Constants.ROOT
            };

            var fullPrefixes = prefixes.Select(p => basePath + p).ToArray();

            var safeHostName = hostName;

            if (hostName.Equals("*") || hostName.Equals("+"))
            {
                safeHostName = "localhost";
            }

            var baseUri = new Uri(string.Format("{0}://{1}:{2}", scheme, safeHostName, port));

            ListenerUris = prefixes
                           .Select(p => new Uri(baseUri, p))
                           .ToArray();

            _httpServer          = httpServer ?? new HttpServer(fullPrefixes, AuthenticationSchemes.Basic);
            _serializer          = serializer ?? new DocumentSerializer();
            _messageStorage      = messageStorage ?? new DictionaryEnvelopeStorage <Message>();
            _notificationStorage = notificationStorage ?? new DictionaryEnvelopeStorage <Notification>();
            _traceWriter         = traceWriter;

            transportExpirationInactivityInterval = transportExpirationInactivityInterval != default(TimeSpan) ? transportExpirationInactivityInterval : TimeSpan.FromSeconds(Constants.DEFAULT_TRANSPORT_EXPIRATION_INACTIVITY_INTERVAL);
            _httpTransportProvider = httpTransportProvider ?? new HttpTransportProvider(_useHttps, _messageStorage, _notificationStorage, transportExpirationInactivityInterval);
            _httpTransportProvider.TransportCreated += async(sender, e) => await _transportBufferBlock.SendAsync(e.Transport, _listenerCancellationTokenSource.Token).ConfigureAwait(false);

            // Context processors
            _uriTemplateTable = new UriTemplateTable(baseUri);
            if (processors == null)
            {
                processors = CreateProcessors();
            }
            foreach (var processor in processors)
            {
                _uriTemplateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, object>(processor.Template, processor));
            }
            _uriTemplateTable.MakeReadOnly(true);
        }
Ejemplo n.º 7
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);
            }
Ejemplo n.º 8
0
        static void Main(string[] args)
        {
            Snippets.Snippet2();
            // <Snippet0>
            // <Snippet1>
            // <Snippet3>
            Uri prefix = new Uri("http://localhost/");

            //Create a series of templates
            UriTemplate weatherByCity    = new UriTemplate("weather/{state}/{city}");
            UriTemplate weatherByCountry = new UriTemplate("weather/{country}/{village}");
            UriTemplate weatherByState   = new UriTemplate("weather/{state}");
            UriTemplate traffic          = new UriTemplate("traffic/*");
            UriTemplate wildcard         = new UriTemplate("*");

            //Create a template table
            UriTemplateTable table = new UriTemplateTable(prefix);

            //Add each template to the table with some associated data
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCity, "weatherByCity"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCountry, "weatherByCountry"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByState, "weatherByState"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(traffic, "traffic"));

            table.MakeReadOnly(true);
            // </Snippet3>
            // </Snippet1>
            Console.WriteLine("KeyValuePairs:");
            foreach (KeyValuePair <UriTemplate, Object> keyPair in table.KeyValuePairs)
            {
                Console.WriteLine($"{keyPair.Key}, {keyPair.Value}");
            }

            Console.WriteLine();

            //Call MatchSingle to retrieve some match results:
            ICollection <UriTemplateMatch> results = null;
            Uri weatherInSeattle = new Uri("http://localhost/weather/Washington/Seattle");

            results = table.Match(weatherInSeattle);
            if (results != null)
            {
                Console.WriteLine("Matching templates:");
                foreach (UriTemplateMatch match in results)
                {
                    Console.WriteLine(match.Template);
                }
            }
            // </Snippet0>
        }
Ejemplo n.º 9
0
        static ThemeService()
        {
#if NETCOREAPP
            _templateTable = new UriTemplateTable();
            _templateTable.Add("theme", new UriTemplate(_baseUrl + _themeUrl));
            _templateTable.Add("accent", new UriTemplate(_baseUrl + _accentUrl));
            _templateTable.Add("uwptheme", new UriTemplate(_baseUrl + _uwpThemeUrl));
            _templateTable.Add("uwpaccent", new UriTemplate(_baseUrl + _uwpAccentUrl));
            _templateTable.Add("style", new UriTemplate(_baseUrl + _styleUrl));
#else
            _templateTable = new UriTemplateTable(_templateBaseUri);
            _templateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(_themeTemplate, "theme"));
            _templateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(_accentTemplate, "accent"));
            _templateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(_uwpThemeTemplate, "uwptheme"));
            _templateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(_uwpAccentTemplate, "uwpaccent"));
            _templateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(_styleTemplate, "style"));
            _templateTable.MakeReadOnly(false);
#endif
        }
Ejemplo n.º 10
0
        public static void Snippet9()
        {
            // <Snippet9>
            Uri prefix = new Uri("http://localhost/");

            //Create a series of templates
            UriTemplate weatherByCity    = new UriTemplate("weather/ state}/ city}");
            UriTemplate weatherByCountry = new UriTemplate("weather/ country}/ village}");
            UriTemplate weatherByState   = new UriTemplate("weather/ state}");
            UriTemplate traffic          = new UriTemplate("traffic/*");
            UriTemplate wildcard         = new UriTemplate("*");

            //Create a template table
            UriTemplateTable table = new UriTemplateTable(prefix);

            //Add each template to the table with some associated data
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCity, "weatherByCity"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByCountry, "weatherByCountry"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(weatherByState, "weatherByState"));
            table.KeyValuePairs.Add(new KeyValuePair <UriTemplate, Object>(traffic, "traffic"));

            table.MakeReadOnly(true);

            //Call Match to retrieve some match results:
            ICollection <UriTemplateMatch> results = null;
            Uri weatherInSeattle = new Uri("http://localhost/weather/Washington/Seattle");

            results = table.Match(weatherInSeattle);
            if (results != null)
            {
                Console.WriteLine("Matching templates:");
                foreach (UriTemplateMatch match in results)
                {
                    Console.WriteLine("    0}", match.Template);
                }
            }
            // </Snippet9>
        }
Ejemplo n.º 11
0
        private void ConstructDispatcherTables(Uri prefix)
        {
            _getDispatcherTable    = new UriTemplateTable(prefix);
            _postDispatcherTable   = new UriTemplateTable(prefix);
            _deleteDispatcherTable = new UriTemplateTable(prefix);

            var fields = typeof(DriverCommand).GetFields(BindingFlags.Public | BindingFlags.Static);

            foreach (var field in fields)
            {
                // Console.WriteLine(commandName);
                var commandName = field.GetValue(null).ToString();
                Console.WriteLine(commandName);
                var commandInformation = _commandDictionary[commandName];
                var commandUriTemplate = new UriTemplate(commandInformation.ResourcePath);
                var templateTable      = FindDispatcherTable(commandInformation.Method);
                templateTable.KeyValuePairs.Add(new KeyValuePair <UriTemplate, object>(commandUriTemplate, commandName));
            }

            _getDispatcherTable.MakeReadOnly(false);
            _postDispatcherTable.MakeReadOnly(false);
            _deleteDispatcherTable.MakeReadOnly(false);
        }
Ejemplo n.º 12
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();
        }
        public static long Run()
        {
            long      ran        = 0;
            const int Iterations = 1000000; // 100 * 1000 * 1000;

            var baseUri = new Uri("http://x");
            var table   = new UriTemplateTable(
                baseUri,
                new[] { "devices/{deviceId}/messages/events/{*subTopic}", "devices/{deviceId}/messages/log/{level=info}/{subject=n%2Fa}" }.Select(x => new KeyValuePair <UriTemplate, object>(new UriTemplate(x, false), x)));

            table.MakeReadOnly(true);
            Regex[] regexes = new[] { "^devices/(?<deviceId>[^/]*)/messages/events/(?<subTopic>.*)$", "^devices/(?<deviceId>[^/]*)/messages/log(/(?<level>[^/]*)(/(?<level>[^/]*))?)?$" }.Select(x => new Regex(x, RegexOptions.Compiled | RegexOptions.Singleline | RegexOptions.CultureInvariant)).ToArray();

            var values = new[] { "devices/WAUCB28D7XA451194/messages/events/some/other/segments", "devices/WAUCB28D7XA451194/messages/log/warning/oilPressureAlert" };

            CodeTimer.Time(true, "table", Iterations, () =>
            {
                foreach (string value in values)
                {
                    Collection <UriTemplateMatch> matches = table.Match(new Uri(baseUri, value));
                    if (matches.Count == 0)
                    {
                        continue;
                    }
                    if (matches.Count > 1)
                    {
                        //
                    }
                    UriTemplateMatch match = matches[0];
                    string deviceId        = match.BoundVariables["deviceId"];
                    if (deviceId[0] == 'W')
                    {
                        unchecked
                        {
                            ran++;
                        }
                    }
                }
            });

            CodeTimer.Time(true, "regex", Iterations, () =>
            {
                foreach (string value in values)
                {
                    foreach (Regex regex in regexes)
                    {
                        Match match = regex.Match(value);
                        if (!match.Success)
                        {
                            continue;
                        }
                        string deviceId = match.Groups["deviceId"].Value;
                        if (deviceId[0] == 'W')
                        {
                            unchecked
                            {
                                ran++;
                            }
                        }
                        break;
                    }
                }
            });

            return(ran);
        }