public void ExtendedSamplesTest(string template, string[] results, TestSet.TestCase testCase)
        {
            var uriTemplate = new UriTemplate(template);

            foreach (var variable in testCase.TestSet.Variables)
            {
                uriTemplate.SetParameter(variable.Key, variable.Value);
            }

            string result = null;
            ArgumentException aex = null;

            try
            {
                result = uriTemplate.Resolve();

            }
            catch (ArgumentException ex)
            {
                aex = ex;
            }

            if (results[0] == "False")
            {
                Assert.NotNull(aex);
            }
            else
            {
                Assert.True(results.Contains(result));
            }

        }
Example #2
0
 public void LabelExpansionWithDotPrefixAndEmptyKeys()
 {
     var template = new UriTemplate("X{.empty_keys}");
     template.SetParameter("empty_keys", new Dictionary<string, string>());
     var uriString = template.Resolve();
     Assert.Equal("X", uriString);
 }
 public void ShouldAllowUriTemplateWithPathSegmentParameter()
 {
     var template = new UriTemplate("http://example.org/foo/{bar}/baz");
     template.SetParameter("bar", "yo");
     var uriString = template.Resolve();
     Assert.Equal("http://example.org/foo/yo/baz", uriString);
 }
        // Disabled for the moment. [Theory, PropertyData("FailureSamples")]
        public void FailureSamplesTest(string template, string[] results, TestSet.TestCase testCase)
        {
            var uriTemplate = new UriTemplate(template);

            foreach (var variable in testCase.TestSet.Variables)
            {
                uriTemplate.SetParameter(variable.Key, variable.Value);
            }

            string result = null;
            ArgumentException aex = null;

            try
            {
                result = uriTemplate.Resolve();

            }
            catch (ArgumentException ex)
            {
                aex = ex;
            }

            Assert.NotNull(aex);


        }
 public void FactMethodName()
 {
     UriTemplate template = new UriTemplate("https://api.github.com/search/code?q={query}{&page,per_page,sort,order}");
     template.SetParameter("query", "1234");
     template.SetParameter("per_page", "19");
     var result = template.Resolve();
 }
        public void UpdatePathParameter()
        {
            var url = new UriTemplate("http://example.org/{tenant}/customers")
                .AddParameter("tenant", "acmé")
                .Resolve();

            Assert.Equal("http://example.org/acm%C3%A9/customers", url);
        }
        public void QueryParametersTheNewWay()
        {
            var url = new UriTemplate("http://example.org/customers{?active}")
                .AddParameter("active", "true")
                .Resolve();

            Assert.Equal("http://example.org/customers?active=true", url);
        }
        public void ShouldResolveUriTemplateWithNonStringParameter()
        {
            var url = new UriTemplate("http://example.org/location{?lat,lng}")
                .AddParameters(new { lat = 31.464, lng = 74.386 })
                .Resolve();

            Assert.Equal("http://example.org/location?lat=31.464&lng=74.386", url);
        }
        private static Uri ResolveDocumentationUri(ILinkObject link, string rel)
        {
            var template = new UriTemplate(link.Href.ToString());

            template.SetParameter("rel", rel);

            return new Uri(template.Resolve());
        }
 public void ShouldAllowUriTemplateWithQueryParamsButNoValues()
 {
     var template = new UriTemplate("http://example.org/foo{?bar,baz}");
     //template.SetParameter("bar", "yo");
     //template.SetParameter("blar", "yuck");
     var uriString = template.Resolve();
     Assert.Equal("http://example.org/foo", uriString);
 }
        public void ShouldAllowUriTemplateWithQueryParamsWithOneValue()
        {
            var template = new UriTemplate("http://example.org/foo{?bar,baz}");
            template.SetParameter("baz", "yo");

            var uriString = template.Resolve();
            Assert.Equal("http://example.org/foo?baz=yo", uriString);
        }
        public void SpecTest(TestCase testCase)
        {
            Assume.That(!testCase.IsInvalid);

            var uriTemplate = new UriTemplate(testCase.Template);
            var uri = uriTemplate.Resolve(testCase.Suite.Variables);
            Assert.Contains(uri, testCase.Expecteds);
        }
Example #13
0
 public void ShouldAllowListAndSingleValueInQueryParam()
 {
     var template = new UriTemplate("http://example.org{/id*}{?fields,token}");
     template.SetParameter("id", new List<string>() { "person", "albums" });
     template.SetParameter("fields", new List<string>() { "id", "name", "picture" });
     template.SetParameter("token", "12345");
     var uriString = template.Resolve();
     Assert.Equal("http://example.org/person/albums?fields=id,name,picture&token=12345", uriString);
 }
        public UriTemplateBuilder(UriTemplate uriTemplate)
        {
            if (uriTemplate == null)
            {
                throw new ArgumentNullException("uriTemplate");
            }

            this.components = new List<IUriTemplateComponent>(uriTemplate.Components);
        }
        public void QueryParametersTheNewWayWithoutValue()
        {

            var url = new UriTemplate("http://example.org/customers{?active}")
                .AddParameters(null)
                .Resolve();

            Assert.Equal("http://example.org/customers", url);
        }
        private static string ResolveTemplateUrl(string href, Dictionary<string, string> values)
        {
            var template = new UriTemplate(href);

            foreach (var templateValue in values)
                template.SetParameter(templateValue.Key, templateValue.Value);

            return template.Resolve();
        }
Example #17
0
        public async Task<ContentResponse> GetProfile(string artistId)
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("apikey", _apikey);
            parameters.Add("artistid", artistId);

            var template = new UriTemplate("artist/profile?api_key={apikey}&id=songkick:artist:{artistid}&bucket=id:spotify&format=json");

            return await GetWithRetryAsync(baseUri, template, parameters);
        }
Example #18
0
        public async Task<ContentResponse> GetBiographies(string artistId)
        {
            var parameters = new Dictionary<string, string>();
            parameters.Add("apikey", _apikey);
            parameters.Add("artistid", artistId);

            var template = new UriTemplate("artist/biographies?api_key={apikey}&id=songkick:artist:{artistid}&format=json&results=20&start=0&license=cc-by-sa");

            return await GetWithRetryAsync(baseUri, template, parameters);
        }
        public void ShouldAllowUriTemplateToRemoveParameter()
        {
            var template = new UriTemplate("http://example.org/foo{?bar,baz}");
            template.SetParameter("bar", "yo");
            template.SetParameter("baz", "yuck");
            template.ClearParameter("bar");

            var uriString = template.Resolve();
            Assert.Equal("http://example.org/foo?baz=yuck", uriString);
        }
        public static UriTemplate MakeTemplate(this Uri uri, IDictionary<string, object> parameters)
        {
            var target = uri.GetComponents(UriComponents.AbsoluteUri
                                                     & ~UriComponents.Query
                                                     & ~UriComponents.Fragment, UriFormat.Unescaped);
            var template = new UriTemplate(target + "{?" + string.Join(",", parameters.Keys.ToArray()) + "}");
            template.AddParameters(parameters);

            return template;
        }
Example #21
0
        public void Query_param_with_list_array()
        {
            UriTemplate template = new UriTemplate("/foo/{foo}/baz{?haz}");
            template.SetParameter("foo", "1234");
            template.SetParameter("haz", new string[] { "foo", "bar" });

            string uri = template.Resolve();

            Assert.Equal("/foo/1234/baz?haz=foo,bar", uri);
        }
        public void ShouldResolveMatrixParameter()
        {
            var template = new UriTemplate("http://example.org/foo{;lat,lng}");

            double lat = 31.464, lng = 74.386;

            template.SetParameter("lat", lat);
            template.SetParameter("lng", lng);

            var uriString = template.Resolve();
            Assert.Equal("http://example.org/foo;lat=31.464;lng=74.386", uriString);
        }
        public void GetParametersWithOperators()
        {
            var uri = new Uri("http://example.com/foo/bar");

            var template = new UriTemplate("http://example.com/{+p1}/{p2*}");

            var parameters = template.GetParameters(uri);

            Assert.Equal(2, parameters.Count);
            Assert.Equal("foo", parameters["p1"]);
            Assert.Equal("bar", parameters["p2"]);
        }
Example #24
0
        public void PreserveReservedCharacterExpansion()
        {
            UriTemplate template = new UriTemplate("https://foo.com/?format={+format}");
            template.SetParameter("format", "application/vnd.foo+xml");

            var result = template.Resolve();

            Assert.Equal("https://foo.com/?format=application/vnd.foo+xml", result);

            var httpClient = new HttpClient();

            var response = httpClient.GetAsync("http://yahoo.com/foo%2Fbar").Result;
        }
        public void ShouldResolveUriTemplateWithNonStringParameter()
        {
            var template = new UriTemplate("http://example.org/foo/{bar}/baz{?lat,lng}");

            double lat = 31.464, lng = 74.386;

            template.SetParameter("bar", "yo");
            template.SetParameter("lat", lat);
            template.SetParameter("lng", lng);
            
            var uriString = template.Resolve();
            Assert.Equal("http://example.org/foo/yo/baz?lat=31.464&lng=74.386", uriString);
        }
        public void ParametersFromAnObject()
        {
            var url = new UriTemplate("http://example.org/{environment}/{version}/customers{?active,country}")
                .AddParameters(new
                {
                    environment = "dev",
                    version = "v2",
                    active = "true",
                    country = "CA"
                })
                .Resolve();

            Assert.Equal("http://example.org/dev/v2/customers?active=true&country=CA", url);
        }
        public void GetParametersFromMultipleQueryString()
        {
            var uri = new Uri("http://example.com/foo/bar?blur=45");

            var template = new UriTemplate("http://example.com/{+p1}/{p2*}{?blur,blob}");

            var parameters = template.GetParameters(uri);

            Assert.Equal(3, parameters.Count);
            Assert.Equal("foo", parameters["p1"]);
            Assert.Equal("bar", parameters["p2"]);
            Assert.Equal("45", parameters["blur"]);

        }
        public void SpecSamplesTest(string template, string[] results, TestSet.TestCase testCase)
        {
            var uriTemplate = new UriTemplate(template);

            foreach (var variable in testCase.TestSet.Variables)
            {
                uriTemplate.SetParameter(variable.Key, variable.Value);
            }

            string result = null;
            result = uriTemplate.Resolve();

            Assert.True(results.Contains(result));
        }
Example #29
0
        public static string SubstituteParams(this string uriTemplateString, IDictionary<string, object> parameters)
        {
            var uriTemplate = new UriTemplate(uriTemplateString);

            foreach(var parameter in parameters) {
                var name = parameter.Key;
                var value = parameter.Value;

                var substituionValue = value == null ? null : value.ToString();
                uriTemplate.SetParameter(name, substituionValue);
            }

            return uriTemplate.Resolve();
        }
Example #30
0
        public HalLink ResolveFor(object Dto, IHalModelConfig config, JsonSerializer serializer, object memberValue = null)
        {
            var clone = MemberwiseClone() as HalLink;
            var dtoType = Dto?.GetType();

            UriTemplate template;
            if (string.IsNullOrEmpty(Href))
            {
                template = new UriTemplate(memberValue as string, true, false);
            }
            else
            {
                template = new UriTemplate(Href, true, false);

                foreach (string param in template.GetParameterNames())
                {
                    object value;
                    if (param == "value")
                        value = memberValue;
                    else
                        value = dtoType?.GetProperty(param)?.GetValue(Dto);

                    if (value != null)
                    {
                        if (value is string == false)
                        {
                            var token = JToken.FromObject(value, serializer);
                            value = token.Type == JTokenType.String ?
                                token.Value<string>() : value;
                        }

                        template.SetParameter(param, value);
                    }
                }
            }

            var linkUri = new Uri(template.Resolve(), UriKind.RelativeOrAbsolute);

            if (!linkUri.IsAbsoluteUri)
            {
                var baseUri = new Uri(config.RequestPathBase);
                string basePath = baseUri.GetLeftPart(UriPartial.Authority) +
                    VirtualPathUtility.ToAbsolute(config.RelativePathBase, baseUri.AbsolutePath);
                linkUri = new Uri(new Uri(basePath), linkUri);
            }

            clone.Href = linkUri.ToString();

            return clone;
        }
        public void Example07()
        {
            Func <object, string> func = x =>
            {
                switch (x)
                {
                case Vector2 y:
                    return($"({y.X},{y.Y})");

                default:
                    return(x?.ToString());
                }
            };
            Vector2 u         = new Vector2(3, 4);
            string  uriString = UriTemplate.For("http://example.org{/vector}")
                                .WithParameter("vector", u)
                                .WithValueFormatter(func)
                                .ExpandToString();

            uriString.ShouldBeEquivalentTo("http://example.org/%283%2C4%29");
        }
Example #32
0
        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);
        }
Example #33
0
        public IEnumerable<Uri> GetValidPaths(IAsset asset, CloudMediaContext _context)
        {
            IEnumerable<Uri> ValidURIs;

            var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin && l.ExpirationDateTime > DateTime.UtcNow).OrderByDescending(l => l.ExpirationDateTime);

            var se = _context.StreamingEndpoints.AsEnumerable().Where(o => (o.State == StreamingEndpointState.Running) && (CanDoDynPackaging(o))).OrderByDescending(o => o.CdnEnabled);

            if (se.Count() == 0) // No running which can do dynpackaging SE. Let's use the default one to get URL
            {
                se = _context.StreamingEndpoints.AsEnumerable().Where(o => o.Name == "default").OrderByDescending(o => o.CdnEnabled);
            }

            var template = new UriTemplate("{contentAccessComponent}/");
            ValidURIs = locators.SelectMany(l => se.Select(
                        o =>
                            template.BindByPosition(new Uri("http://" + o.HostName), l.ContentAccessComponent)))
                .ToArray();

            return ValidURIs;
        }
Example #34
0
        public void EncodingTest3()
        {
            // There are different ways that lists can be included in query params
            // Just as a comma delimited list
            var url = new UriTemplate("/docs/salary.csv{?columns}")
                      .AddParameter("columns", new List <int> {
                1, 2
            })
                      .Resolve();

            Assert.Equal("/docs/salary.csv?columns=1,2", url);

            // or as a multiple parameter instances
            var url2 = new UriTemplate("/docs/salary.csv{?columns*}")
                       .AddParameter("columns", new List <int> {
                1, 2
            })
                       .Resolve();

            Assert.Equal("/docs/salary.csv?columns=1&columns=2", url2);
        }
Example #35
0
 // Invokes the subtraction RESTful service to subtract the amount from the balance.
 // Returns the new balance.
 private string subtractionRest(string balance, string amount)
 {
     try
     {
         // Create the base address
         Uri baseUri = new Uri("http://localhost:54118/Service.svc");
         // Create the from tree root to the child node
         UriTemplate myTemplate = new UriTemplate("sub2/{operand1}/{operand2}");
         // Assign values to variables to complete Uri
         Uri       completeUri      = myTemplate.BindByPosition(baseUri, balance, amount);
         WebClient proxy            = new WebClient();
         byte[]    abc              = proxy.DownloadData(completeUri);
         Stream    strm             = new MemoryStream(abc);
         DataContractSerializer obj = new DataContractSerializer(typeof(string));
         return(obj.ReadObject(strm).ToString());
     }
     catch (Exception ex)
     {
         return(ex.Message);
     }
 }
        public void TestFragmentExpansionMultipleVariables()
        {
            string      template    = "{#x,hello,y}";
            UriTemplate uriTemplate = new UriTemplate(template);
            Uri         uri         = uriTemplate.BindByName(Variables);

            Assert.AreEqual("#1024,Hello%20World!,768", uri.OriginalString);

            UriTemplateMatch match = uriTemplate.Match(uri);

            Assert.IsNotNull(match);
            Assert.AreEqual(Variables["x"], match.Bindings["x"].Value);
            Assert.AreEqual(Variables["hello"], match.Bindings["hello"].Value);
            Assert.AreEqual(Variables["y"], match.Bindings["y"].Value);

            match = uriTemplate.Match(uri, RequiredVariables);
            Assert.IsNotNull(match);
            Assert.AreEqual(Variables["x"], match.Bindings["x"].Value);
            Assert.AreEqual(Variables["hello"], match.Bindings["hello"].Value);
            Assert.AreEqual(Variables["y"], match.Bindings["y"].Value);
        }
Example #37
0
        void ApplyWebAttribute()
        {
            MethodInfo mi = operation.SyncMethod ?? operation.BeginMethod;

            object [] atts = mi.GetCustomAttributes(typeof(WebGetAttribute), false);
            if (atts.Length > 0)
            {
                info = ((WebGetAttribute)atts [0]).Info;
            }
            atts = mi.GetCustomAttributes(typeof(WebInvokeAttribute), false);
            if (atts.Length > 0)
            {
                info = ((WebInvokeAttribute)atts [0]).Info;
            }
            if (info == null)
            {
                info = new WebAttributeInfo();
            }

            template = info.BuildUriTemplate(Operation, GetMessageDescription(MessageDirection.Input));
        }
Example #38
0
 // Hashes the userName (salt) & the password. Returns the hashed password.
 // Invokes the Hashing RESTful service.
 protected void hash(object sender, EventArgs e)
 {
     try
     {
         // Create the base address
         Uri baseUri = new Uri("http://localhost:54193/Service.svc");
         // Create the path from tree root to the child node
         UriTemplate myTemplate = new UriTemplate("hash/{password}/{salt}");
         // Assign values to variables to complete Uri
         Uri       completeUri      = myTemplate.BindByPosition(baseUri, Password.Text, Salt.Text);
         WebClient proxy            = new WebClient();
         byte[]    abc              = proxy.DownloadData(completeUri);
         Stream    strm             = new MemoryStream(abc);
         DataContractSerializer obj = new DataContractSerializer(typeof(string));
         Result.Text = obj.ReadObject(strm).ToString();
     }
     catch (Exception ex)
     {
         Result.Text = ex.Message;
     }
 }
Example #39
0
        /// <summary>
        /// Returns the type of the service e.g. AtomPub, Sword or ORE.
        /// </summary>
        /// <param name="contextUrl">The context URL.</param>
        /// <returns>The service type.</returns>
        private static string GetServiceType(Uri contextUrl)
        {
            const string ServiceType    = "serviceType";
            const string SubServiceType = "subServiceType";
            Uri          baseUri        = new Uri(PlatformConstants.GetServiceHostName());

            UriTemplate doubleArgTemplate = new UriTemplate(string.Format(CultureInfo.InvariantCulture,
                                                                          DoubleArgsURI, ServiceType, SubServiceType));

            UriTemplateMatch doubleArgMatches = doubleArgTemplate.Match(baseUri, contextUrl);

            if (doubleArgMatches != null) // Url matches with double template
            {
                string requestedService    = doubleArgMatches.BoundVariables[ServiceType].ToUpperInvariant();
                string subRequestedService = doubleArgMatches.BoundVariables[SubServiceType].ToUpperInvariant();

                if ((Sword == subRequestedService && AtomPub == requestedService) || //is this required?
                    Ore == subRequestedService)
                {
                    return(subRequestedService);
                }
                else
                {
                    return(doubleArgMatches.BoundVariables[ServiceType].ToUpperInvariant());
                }
            }
            else // If Url doesn't match with double template, check for single template.
            {
                UriTemplate singleArgTemplate = new UriTemplate(string.Format(CultureInfo.InvariantCulture,
                                                                              SingleArgURI, ServiceType));
                UriTemplateMatch singleArgMatch = singleArgTemplate.Match(baseUri, contextUrl);
                //Single argument match for ATOM PUB
                if (null != singleArgMatch)
                {
                    return(singleArgMatch.BoundVariables[ServiceType].ToUpperInvariant());
                }
            }

            return(null);
        }
Example #40
0
        private static Uri ArrangeURI(string latLon)
        {
            Uri         prefix            = new Uri(ConfigurationManager.AppSettings.Get("FoursquareAPI"));
            UriTemplate getVenuesTamplate = new UriTemplate("venues/search?client_id={clientId}&client_secret={clientSecret}&v={version}&ll={latLon}&intent={intent}&radius={radius}&limit={limit}");
            string      intent            = "browse";
            string      radius            = "500";
            string      limit             = "5000";

            NameValueCollection parameters = new NameValueCollection();

            parameters.Add("clientId", ConfigurationManager.AppSettings.Get("FoursquareClientId"));
            parameters.Add("clientSecret", ConfigurationManager.AppSettings.Get("FoursquareClientSecret"));
            parameters.Add("version", ConfigurationManager.AppSettings.Get("FoursquareVersion"));
            parameters.Add("latLon", latLon);
            parameters.Add("intent", intent);
            parameters.Add("radius", radius);
            parameters.Add("limit", limit);

            Uri uri = getVenuesTamplate.BindByName(prefix, parameters);

            return(uri);
        }
        /// <summary>
        /// Tries to match the path with the templateString
        /// </summary>
        /// <param name="templateString">The template string.</param>
        /// <param name="pathString">The path string.</param>
        /// <param name="match">The match.</param>
        /// <returns>True if successful.</returns>
        protected bool TryMatchPath(string templateString, string pathString,
                                    out UriTemplateMatch match)
        {
            var uriTemplate = new UriTemplate(templateString);
            var pathUri     = new Uri(UriBaseAddress, pathString);

            try {
                match = uriTemplate.Match(UriBaseAddress, pathUri);
            } catch (Exception ex) {
                Logger.WriteLineIf(LogLevel.Error, _log_props, string.Format(
                                       "Failed to match path. Exception: {0}", ex));
                match = null;
            }
            if (match == null)
            {
                return(false);
            }
            else
            {
                return(true);
            }
        }
Example #42
0
        private HttpRequestMessage BuildHttpRequestMessage(IInvocation invocation)
        {
            var httpAttribute = invocation.Method.GetCustomAttribute <HttpAttribute>();

            var uriTemplate = new Uri(new Uri(_baseUri, invocation.Method.DeclaringType.GetTypeInfo().GetCustomAttribute <RouteAttribute>()?.Value ?? string.Empty), httpAttribute.Route);

            var template = new UriTemplate(uriTemplate.ToString(), false, true);

            AddUriParameters(invocation.Method, template, invocation.Arguments);
            var uri = template.Resolve();

            var httpRequestMessage = new HttpRequestMessage(httpAttribute.Method, uri);

            var body = GetBodyParameter(invocation.Method, invocation.Arguments);

            if (body != null)
            {
                httpRequestMessage.Content = new StringContent(JsonConvert.SerializeObject(body), Encoding.UTF8, "application/json");
            }

            return(httpRequestMessage);
        }
Example #43
0
        public async Task <ConnectionKey> GetConnectionKeyAsync(ConnectionId connection)
        {
            // POST https://management.azure.com/subscriptions/83e6374a-dfa5-428b-82ef-eab6c6bdd383/resourceGroups/AzureFunctions/providers/Microsoft.Web/connections/1aab7e02-73cd-408c-ba1a-cd273ae48105/listConnectionKeys?api-version=2015-08-01-preview"

            UriTemplate connectionsUrl = new UriTemplate("{armId}/listConnectionKeys?api-version={apiVersion}");
            var         parameters     = new Dictionary <string, string>();

            parameters["armId"]      = connection.Id;
            parameters["apiVersion"] = ApiVersion;
            Uri url = connectionsUrl.BindByName(_managementEndpointUri, parameters);

            var result = await SendAsync <JObject>(HttpMethod.Post, url);

            string connectonKey = result["connectionKey"].ToString();
            string runtimeUrl   = result["runtimeUrls"].ToObject <string[]>()[0];

            return(new ConnectionKey
            {
                Key = connectonKey,
                RuntimeUri = new Uri(runtimeUrl)
            });
        }
Example #44
0
        /// <inheritdoc/>
        public Task <MessagesEnqueued> PostMessagesAsync <T>(QueueName queueName, CancellationToken cancellationToken, params Message <T>[] messages)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }
            if (messages == null)
            {
                throw new ArgumentNullException("messages");
            }
            if (messages.Contains(null))
            {
                throw new ArgumentException("messages cannot contain any null values");
            }

            if (messages.Length == 0)
            {
                return(QueueExistsAsync(queueName, cancellationToken)
                       .Select(_ => MessagesEnqueued.Empty));
            }

            UriTemplate template = new UriTemplate("/queues/{queue_name}/messages");

            var parameters =
                new Dictionary <string, string>()
            {
                { "queue_name", queueName.Value },
            };

            Func <Task <Tuple <IdentityToken, Uri> >, Task <HttpWebRequest> > prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.POST, template, parameters, messages);

            Func <Task <HttpWebRequest>, Task <MessagesEnqueued> > requestResource =
                GetResponseAsyncFunc <MessagesEnqueued>(cancellationToken);

            return(AuthenticateServiceAsync(cancellationToken)
                   .Then(prepareRequest)
                   .Then(requestResource));
        }
Example #45
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);
                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);
        }
Example #46
0
        public Customer AddCustomer(Customer customer)
        {
            Snippets.Snippet2();
            lock (writeLock)
            {
                // <Snippet0>
                counter++;

                UriTemplateMatch match = WebOperationContext.Current.IncomingRequest.UriTemplateMatch;

                UriTemplate template = new UriTemplate("{id}");
                customer.Uri = template.BindByPosition(match.BaseUri, counter.ToString());

                customers[counter.ToString()] = customer;

                WebOperationContext.Current.OutgoingResponse.SetStatusAsCreated(customer.Uri);

                // </Snippet0>
            }

            return(customer);
        }
        public static IEnumerable <Uri> GetValidURIs(CloudMediaContext context, IAsset asset, string preferredSE = null)
        {
            IEnumerable <Uri> ValidURIs;
            var ismFile = asset.AssetFiles.AsEnumerable().Where(f => f.Name.EndsWith(".ism")).OrderByDescending(f => f.IsPrimary).FirstOrDefault();

            if (ismFile != null)
            {
                var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin && l.ExpirationDateTime > DateTime.UtcNow).OrderByDescending(l => l.ExpirationDateTime);

                var se = context.StreamingEndpoints.AsEnumerable().Where(o =>

                                                                         (string.IsNullOrEmpty(preferredSE) || (o.Name == preferredSE))
                                                                         &&
                                                                         (!string.IsNullOrEmpty(preferredSE) || ((o.State == StreamingEndpointState.Running) && (CanDoDynPackaging(o)))
                                                                         ))
                         .OrderByDescending(o => o.CdnEnabled);


                if (se.Count() == 0) // No running which can do dynpackaging SE and if not preferredSE. Let's use the default one to get URL
                {
                    se = context.StreamingEndpoints.AsEnumerable().Where(o => o.Name == "default").OrderByDescending(o => o.CdnEnabled);
                }

                var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");

                ValidURIs = locators.SelectMany(l =>
                                                se.Select(
                                                    o =>
                                                    template.BindByPosition(new Uri("https://" + o.HostName), l.ContentAccessComponent,
                                                                            ismFile.Name)))
                            .ToArray();

                return(ValidURIs);
            }
            else
            {
                return(null);
            }
        }
Example #48
0
        public static string CreateUriQueryForTs(string uriText, ParameterDescription[] parameterDescriptions)
        {
            var template       = new UriTemplate(uriText);
            var parameterNames = template.GetParameterNames().ToArray();

            if (parameterNames.Length == 0)
            {
                return(null);
            }

            string newUriText = uriText;

            for (int i = 0; i < parameterNames.Length; i++)
            {
                var name = parameterNames[i];                //PathSegmentVariableNames[i] always give uppercase
                var d    = parameterDescriptions.FirstOrDefault(r => r.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
                Debug.Assert(d != null);
                newUriText = UriTemplateTransform.TransformForTs(newUriText, d);
            }

            return(newUriText);
        }
Example #49
0
        public static string Build(string template, NameValueCollection parameters)
        {
            var uriTemplate = new UriTemplate(template);

            // Base URI is set in the HttpClient, this one is just needed for binding
            var prefix = new Uri("http://localhost");

            var noEmptyParametersCollection = new NameValueCollection();

            foreach (string name in parameters)
            {
                var value = parameters[name];
                if (!string.IsNullOrEmpty(value))
                {
                    noEmptyParametersCollection.Add(name, value);
                }
            }

            var uri = uriTemplate.BindByName(prefix, noEmptyParametersCollection);

            return(uri.PathAndQuery);
        }
Example #50
0
        public static void GetLocatorsInAllStreamingEndpoints(IAsset asset)
        {
            var locators = asset.Locators.Where(l => l.Type == LocatorType.OnDemandOrigin);
            var ismFile  = asset.AssetFiles.AsEnumerable().FirstOrDefault(a => a.Name.EndsWith(".ism"));
            var template = new UriTemplate("{contentAccessComponent}/{ismFileName}/manifest");
            var urls     = locators.SelectMany(l =>
                                               _context
                                               .StreamingEndpoints
                                               .AsEnumerable()
                                               .Where(se => se.State == StreamingEndpointState.Running)
                                               .Select(
                                                   se =>
                                                   template.BindByPosition(new Uri("http://" + se.HostName),
                                                                           l.ContentAccessComponent,
                                                                           ismFile.Name)))
                           .ToArray();

            foreach (var url in urls)
            {
                Console.WriteLine(url);
            }
        }
        /// <inheritdoc/>
        public Task <QueueStatistics> GetQueueStatisticsAsync(QueueName queueName, CancellationToken cancellationToken)
        {
            if (queueName == null)
            {
                throw new ArgumentNullException("queueName");
            }

            UriTemplate template   = new UriTemplate("/queues/{queue_name}/stats");
            var         parameters = new Dictionary <string, string>()
            {
                { "queue_name", queueName.Value }
            };
            Func <Task <Tuple <IdentityToken, Uri> >, HttpWebRequest> prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.GET, template, parameters);

            Func <Task <HttpWebRequest>, Task <QueueStatistics> > requestResource =
                GetResponseAsyncFunc <QueueStatistics>(cancellationToken);

            return(AuthenticateServiceAsync(cancellationToken)
                   .Select(prepareRequest)
                   .Then(requestResource));
        }
        /// <inheritdoc/>
        public Task ResumeGroupAsync(ScalingGroupId groupId, CancellationToken cancellationToken)
        {
            if (groupId == null)
            {
                throw new ArgumentNullException("groupId");
            }

            UriTemplate template   = new UriTemplate("/groups/{groupId}/resume");
            var         parameters = new Dictionary <string, string> {
                { "groupId", groupId.Value }
            };

            Func <Task <Tuple <IdentityToken, Uri> >, HttpWebRequest> prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.POST, template, parameters);

            Func <Task <HttpWebRequest>, Task <string> > requestResource =
                GetResponseAsyncFunc(cancellationToken);

            return(AuthenticateServiceAsync(cancellationToken)
                   .Select(prepareRequest)
                   .Then(requestResource));
        }
Example #53
0
        public async Task <ApiId[]> GetManagedApis()
        {
            // https://management.azure.com/subscriptions/83e6374a-dfa5-428b-82ef-eab6c6bdd383/providers/Microsoft.Web/locations/brazilsouth/managedApis?api-version=2015-08-01-preview"

            UriTemplate apisUrl    = new UriTemplate("/subscriptions/{subscriptionId}/providers/Microsoft.Web/locations/{location}/managedApis/?api-version={apiVersion}");
            var         parameters = new Dictionary <string, string>();

            parameters["subscriptionId"] = this.subscriptionId;
            parameters["location"]       = this.location;
            parameters["apiVersion"]     = ApiVersion;
            Uri url = apisUrl.BindByName(_managementEndpointUri, parameters);

            var json = await SendAsync <JObject>(HttpMethod.Get, url);

            var apis = json["value"].ToObject <ArmEnvelope <JToken>[]>();

            return(Array.ConvertAll(apis, x => new ApiId
            {
                Id = x.Id,
                Name = x.Name
            }));
        }
Example #54
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>
        }
        /// <inheritdoc/>
        public Task <ScalingGroup> CreateGroupAsync(ScalingGroupConfiguration configuration, CancellationToken cancellationToken)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            UriTemplate template   = new UriTemplate("/groups");
            var         parameters = new Dictionary <string, string>();

            Func <Task <Tuple <IdentityToken, Uri> >, Task <HttpWebRequest> > prepareRequest =
                PrepareRequestAsyncFunc(HttpMethod.POST, template, parameters, configuration);

            Func <Task <HttpWebRequest>, Task <JObject> > requestResource =
                GetResponseAsyncFunc <JObject>(cancellationToken);

            Func <Task <JObject>, ScalingGroup> resultSelector =
                task =>
            {
                JObject result = task.Result;
                if (result == null)
                {
                    return(null);
                }

                JToken valueToken = result["group"];
                if (valueToken == null)
                {
                    return(null);
                }

                return(valueToken.ToObject <ScalingGroup>());
            };

            return(AuthenticateServiceAsync(cancellationToken)
                   .Then(prepareRequest)
                   .Then(requestResource)
                   .Select(resultSelector));
        }
Example #56
0
        private static void OnUriAndMethodHandler(
            RequestContext ctx,
            string method,
            UriTemplate uriTemplate,
            IObserver <RequestContext> obs)
        {
            if (!string.IsNullOrEmpty(method) && ctx.Request.HttpMethod != method)
            {
                return;
            }

            var serverPath       = ctx.Request.Url.GetServerBaseUri();
            var uriTemplateMatch = uriTemplate.Match(new Uri(serverPath), ctx.Request.Url);

            if (uriTemplateMatch == null)
            {
                return;
            }

            ctx.Request.LoadArguments(uriTemplateMatch.BoundVariables);
            obs.OnNext(ctx);
        }
        /// <summary>
        ///     Open a WebSocket connection using the <see cref="K8sChannelProtocol.V1"/> sub-protocol.
        /// </summary>
        /// <param name="client">
        ///     The Kubernetes API client.
        /// </param>
        /// <param name="targetUri">
        ///     The template used to generate the target URI.
        /// </param>
        /// <param name="templateParameters">
        ///     A <see cref="Dictionary{TKey, TValue}"/> containing the template parameters.
        /// </param>
        /// <param name="cancellationToken">
        ///     An optional cancellation token that can be used to cancel the request.
        /// </param>
        /// <returns>
        ///     The configured <see cref="WebSocket"/>.
        /// </returns>
        public static Task <WebSocket> ConnectWebSocket(this KubeApiClient client, UriTemplate targetUri, Dictionary <string, string> templateParameters, CancellationToken cancellationToken = default)
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }

            if (targetUri == null)
            {
                throw new ArgumentNullException(nameof(targetUri));
            }

            if (templateParameters == null)
            {
                throw new ArgumentNullException(nameof(templateParameters));
            }

            return(client.ConnectWebSocket(
                       targetUri.Populate(client.ApiEndPoint, templateParameters),
                       cancellationToken
                       ));
        }
Example #58
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>
        }
Example #59
0
        // Disabled for the moment. [Theory, PropertyData("FailureSamples")]
        public void FailureSamplesTest(string template, string[] results, TestSet.TestCase testCase)
        {
            var uriTemplate = new UriTemplate(template);

            foreach (var variable in testCase.TestSet.Variables)
            {
                uriTemplate.SetParameter(variable.Key, variable.Value);
            }

            string            result = null;
            ArgumentException aex    = null;

            try
            {
                result = uriTemplate.Resolve();
            }
            catch (ArgumentException ex)
            {
                aex = ex;
            }

            Assert.NotNull(aex);
        }
        /// <summary>
        /// Normalizes the specified date to a <see cref="DateInfo"/>.
        /// </summary>
        /// <param name="date">The date to be normalized.</param>
        /// <param name="options">The options to apply before executing the REST API call.</param>
        /// <returns></returns>
        public DateInfo NormalizeDate(String date, params IStateTransitionOption[] options)
        {
            Link normalizedDateLink = GetLink(Rel.NORMALIZED_DATE);

            if (normalizedDateLink == null || normalizedDateLink.Template == null)
            {
                return(null);
            }
            String template = normalizedDateLink.Template;
            String uri      = new UriTemplate(template).AddParameter("date", date).Resolve();

            IRestRequest  request   = CreateRequest().Accept(MediaTypes.TEXT_PLAIN).Build(uri, Method.GET);
            IRestResponse response  = Invoke(request, options);
            DateInfo      dateValue = new DateInfo();

            dateValue.Original = date;
            dateValue.AddNormalizedExtension(new TextValue(response.ToIRestResponse <String>().Data));
            if (response.Headers != null)
            {
                dateValue.Formal = response.Headers.Where(x => x.Name == "Location").Select(x => x.Value as string).FirstOrDefault();
            }
            return(dateValue);
        }