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;
        }
예제 #2
0
        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);
        }
        public void AddMultipleParametersToLink()
        {
            var template = new UriTemplate("http://localhost/api/{dataset}/customer{?foo,bar,baz}");

            template.AddParameters(new Dictionary <string, object>
            {
                { "foo", "bar" },
                { "baz", "99" },
                { "dataset", "bob" }
            });

            var uri = template.Resolve();

            Assert.Equal("http://localhost/api/bob/customer?foo=bar&baz=99", uri);
        }
예제 #4
0
        private static string Construct(ILink link, object parameters)
        {
            if (!link.Templated)
            {
                return(link.Href);
            }

            if (parameters == null)
            {
                throw new TemplateParametersAreRequired(link);
            }

            var template = new UriTemplate(link.Href, caseInsensitiveParameterNames: true);

            template.AddParameters(parameters);
            return(template.Resolve());
        }
예제 #5
0
        public void Can_generate_a_path_with_anonymous_complex_route_properties()
        {
            string       expected      = _baseUrl + "foo/1?bar.abc=abc&bar.def=def";
            const string routeName     = "foo.show";
            const string routeTemplate = "foo/{id}";

            string template = TestHelper.CreateATemplateGenerator(_baseUrl, routeName, routeTemplate)
                              .Generate(routeName, new { Id = 1, Bar = new { Abc = "abc", Def = "def" } });
            var uriTemplate = new UriTemplate(template);

            uriTemplate.AddParameters(new { id = 1 });
            uriTemplate.AddParameter("bar.abc", "abc");
            uriTemplate.AddParameter("bar.def", "def");

            string actual = uriTemplate.Resolve();

            Assert.Equal(expected, actual);
        }
예제 #6
0
        static Uri CreateUwpAccentResourceUri(Accent.SpecifiedColor accent)
        {
#if NETCOREAPP
            var url = _uwpAccentTemplate
                      .AddParameters(new
            {
                accent = accent.ToString()
            })
                      .Resolve();
            return(new Uri(_templateBaseUri, url));
#else
            var param = new Dictionary <string, string>
            {
                { "accent", accent.ToString() },
            };
            return(_uwpAccentTemplate.BindByName(_templateBaseUri, param));
#endif
        }
예제 #7
0
        static Uri CreateUwpThemeResourceUri(Theme.SpecifiedColor theme)
        {
#if NETCOREAPP
            var url = _uwpThemeTemplate
                      .AddParameters(new
            {
                theme = theme.ToString()
            })
                      .Resolve();
            return(new Uri(_templateBaseUri, url));
#else
            var param = new Dictionary <string, string>
            {
                { "theme", theme.ToString() },
            };
            return(_uwpThemeTemplate.BindByName(_templateBaseUri, param));
#endif
        }
예제 #8
0
        /// <summary>
        /// Utility method to build Uri by templating
        /// </summary>
        /// <param name="template">The uri string template</param>
        /// <param name="pathParameters">A dictionary containing respectively as key the string value of the parameter and as value the value to insert in the uri</param>
        /// <param name="queryParameters">An object containing the queries parameters to provide</param>
        /// <example>
        /// How to use it:
        /// <code>
        ///     BuildUri("/template/uri", new Dictionary&lt;string, object&gt;(), new object());
        ///     // Use named arguments to reverse params order
        ///     BuildUri("/template/uri", queryParameters: new object(), pathParameters: new Dictionary&lt;string, object&gt;());
        ///     // with only one optionnal param
        ///     BuildUri("/template/uri"), new Dictionary&lt;string, object&gt;());
        ///     // with only one optionnal param reversed order
        ///     BuildUri("/template/uri"), queryParameters: new object());
        /// </code>
        /// </example>
        /// <returns>Uri formatted</returns>
        private protected static Uri BuildUri(string template, Dictionary <string, object> pathParameters = null, object queryParameters = null)
        {
            if (template == null)
            {
                throw new ArgumentNullException(nameof(template), "The parameter cannot be null");
            }

            string uri;

            if (pathParameters != null)
            {
                UriTemplate templateBuilder = new UriTemplate(template);
                templateBuilder.AddParameters(pathParameters);
                uri = templateBuilder.Resolve();
            }
            else
            {
                uri = template;
            }

            if (queryParameters != null)
            {
                var query = HttpUtility.ParseQueryString(string.Empty);

                foreach (PropertyInfo property in queryParameters.GetType().GetProperties())
                {
                    if (property.GetValue(queryParameters) != null)
                    {
                        query[property.Name] = property.GetValue(queryParameters).ToString();
                    }
                }
                Console.WriteLine(query.ToString());
                uri = $"{uri}?{query.ToString()}";
            }

            if (Uri.IsWellFormedUriString(uri, UriKind.Relative))
            {
                return(new Uri(uri, UriKind.Relative));
            }
            else
            {
                throw new UriFormatException("The template parameter is not a well formed Uri string");
            }
        }
        public static string Construct(Uri baseAddress, ILink link, object parameters)
        {
            if (!link.Templated)
            {
                return(new Uri(baseAddress, link.Href).ToString());
            }

            if (parameters == null)
            {
                throw new TemplateParametersAreRequired(link);
            }

            var template = new UriTemplate(
                new Uri(baseAddress, link.Href).ToString(),
                caseInsensitiveParameterNames: true);

            template.AddParameters(parameters);
            return(template.Resolve());
        }
예제 #10
0
        private string BuildUrl()
        {
            var uriPath    = new UriTemplate(UriTemplate);
            var pathParams = GetUriPathParameters();

            foreach (var param in pathParams)
            {
                uriPath.AddParameterFromKeyValuePair(param.Key, param.Value);
            }

            if (ExtendedInfo != null && ExtendedInfo.HasAnySet)
            {
                uriPath.AddParameters(new { extended = ExtendedInfo.Resolve() });
            }

            if (Filter != null && Filter.HasValues)
            {
                uriPath.AddParametersFromDictionary(Filter.GetParameters());
            }

            if (SupportsPagination || SupportsPaginationParameters)
            {
                if (PaginationOptions.Page != null)
                {
                    uriPath.AddParameterFromKeyValuePair("page", PaginationOptions.Page.ToString());
                }

                if (PaginationOptions.Limit != null)
                {
                    uriPath.AddParameterFromKeyValuePair("limit", PaginationOptions.Limit.ToString());
                }
            }

            var uri = uriPath.Resolve();

            return($"{Client.Configuration.BaseUrl}{uri}");
        }
예제 #11
0
 public static string ResolveWith(this UriTemplate uriTemplate, IDictionary <string, object> parameters)
 {
     uriTemplate.AddParameters(parameters);
     return(uriTemplate.Resolve());
 }
        public void AddMultipleParametersToLink()
        {
            var template = new UriTemplate("http://localhost/api/{dataset}/customer{?foo,bar,baz}");

            template.AddParameters(new Dictionary<string, object>
            {
                {"foo", "bar"},
                {"baz", "99"},
                {"dataset", "bob"}
            });

            var uri = template.Resolve();

            Assert.Equal("http://localhost/api/bob/customer?foo=bar&baz=99", uri);
        }
예제 #13
0
        static async Task MainAsync()
        {
            Console.WriteLine("Reading data from data.json...");

            var serialized = File.ReadAllText("data.json");

            Console.WriteLine("Parsing data...");

            var data = JsonConvert.DeserializeObject <DataInput>(serialized);

            Console.WriteLine("Loading common HTML and Text files...");

            var commonHtml = data.common.htmlFile != null?File.ReadAllText(data.common.htmlFile) : null;

            var commonText = data.common.textFile != null?File.ReadAllText(data.common.textFile) : null;

            var template = new UriTemplate(data.server.sendMessageUrlTemplate);

            template.AddParameters(new
            {
                accountId   = data.server.accountId,
                accountName = data.server.accountName
            });
            var client = new FlurlClient(template.Resolve()).WithOAuthBearerToken(data.server.apikey);

            foreach (var item in data.items)
            {
                Console.WriteLine("Processing " + item.toEmail);

                try
                {
                    Console.WriteLine("Loading files...");

                    var htmlBody = item.htmlFile != null?File.ReadAllText(item.htmlFile) : commonHtml;

                    var textBody = item.textFile != null?File.ReadAllText(item.textFile) : commonText;

                    var fileNames   = data.common.attachments.Union(item.attachments);
                    var attachments = fileNames.Select(x => new
                    {
                        filename       = x,
                        base64_content = Convert.ToBase64String(File.ReadAllBytes(x)),
                        type           = GetContentTypeByExtension(x)
                    })
                                      .ToArray();

                    Console.WriteLine("Preparing data and client...");


                    var request = client.Request();

                    var requestBody = new
                    {
                        from_name  = item.fromName ?? data.common.fromName,
                        from_email = item.fromEmail ?? data.common.fromEmail,
                        recipients = new[]
                        {
                            new
                            {
                                email = item.toEmail ?? data.common.toEmail,
                                name  = item.toName ?? data.common.toName,
                                type  = "to"
                            }
                        },
                        subject     = item.subject ?? data.common.subject,
                        html        = htmlBody,
                        text        = textBody,
                        attachments = attachments
                    };

                    Console.WriteLine("Sending...");

                    var stopwatch = Stopwatch.StartNew();

                    await request.PostJsonAsync(requestBody);

                    Console.WriteLine($"Sent! in {stopwatch.ElapsedMilliseconds} ms");
                }
                catch (FlurlHttpException e)
                {
                    Console.WriteLine("HTTP ERROR");
                    Console.WriteLine(e.GetResponseStringAsync());
                    Console.WriteLine();
                }
                catch (Exception e)
                {
                    Console.WriteLine("ERROR");
                    Console.WriteLine(e);
                    Console.WriteLine();
                }
                System.Threading.Thread.Sleep(20);
            }

            Console.WriteLine("Press ENTER to continue . . .");
            Console.ReadLine();
        }