public void Can_Serialize_Unicode_Query_String()
        {
            Assert.That(QueryStringSerializer.SerializeToString(new D { A = "믬㼼摄䰸蠧蛛㙷뇰믓堐锗멮ᙒ덃", B = "八敁喖䉬ڵẀ똦⌀羭䥀主䧒蚭㾐타" }),
                Is.EqualTo("A=%eb%af%ac%e3%bc%bc%e6%91%84%e4%b0%b8%e8%a0%a7%e8%9b%9b%e3%99%b7%eb%87%b0%eb%af%93%e5%a0" +
                "%90%e9%94%97%eb%a9%ae%e1%99%92%eb%8d%83&B=%e5%85%ab%e6%95%81%e5%96%96%e4%89%ac%da%b5%e1%ba%80%eb%98%a6%e2%8c%80%e7%be%ad%e4" +
                "%a5%80%e4%b8%bb%e4%a7%92%e8%9a%ad%e3%be%90%ed%83%80"));

            Assert.That(QueryStringSerializer.SerializeToString(new D { A = "崑⨹堡ꁀᢖ㤹ì㭡줪銬", B = null }),
                Is.EqualTo("A=%e5%b4%91%e2%a8%b9%e5%a0%a1%ea%81%80%e1%a2%96%e3%a4%b9%c3%ac%e3%ad%a1%ec%a4%aa%e9%8a%ac"));
        }
        private RequestState <TResponse> SendWebRequest <TResponse>(string httpMethod, string absoluteUrl, object request,
                                                                    Action <TResponse> onSuccess, Action <TResponse, Exception> onError)
        {
            if (httpMethod == null)
            {
                throw new ArgumentNullException("httpMethod");
            }

            var requestUri      = absoluteUrl;
            var httpGetOrDelete = (httpMethod == "GET" || httpMethod == "DELETE");
            var hasQueryString  = request != null && httpGetOrDelete;

            if (hasQueryString)
            {
                var queryString = QueryStringSerializer.SerializeToString(request);
                if (!string.IsNullOrEmpty(queryString))
                {
                    requestUri += "?" + queryString;
                }
            }

            var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);

            var requestState = new RequestState <TResponse>
            {
                Url        = requestUri,
                WebRequest = webRequest,
                Request    = request,
                OnSuccess  = onSuccess,
                OnError    = onError,
            };

            requestState.StartTimer(this.Timeout);

            webRequest.Accept = string.Format("{0}, */*", ContentType);
            webRequest.Method = httpMethod;

            if (HttpWebRequestFilter != null)
            {
                HttpWebRequestFilter(webRequest);
            }

            if (!httpGetOrDelete && request != null)
            {
                webRequest.ContentType = ContentType;
                webRequest.BeginGetRequestStream(RequestCallback <TResponse>, requestState);
            }
            else
            {
                var result = requestState.WebRequest.BeginGetResponse(ResponseCallback <TResponse>, requestState);
            }

            return(requestState);
        }
 public void Can_deserialize_with_comma_in_property_in_list_from_QueryStringSerializer()
 {
     var testPocos = new TestPocos
     {
         ListOfA = new List<A> { new A { ListOfB = new List<B> { new B { Property = "Doe, John", Property2 = "Doe", Property3 = "John" } } } }
     };
     var str = QueryStringSerializer.SerializeToString(testPocos);
     var poco = StringToPoco<TestPocos>(str);
     Assert.That(poco.ListOfA[0].ListOfB[0].Property, Is.EqualTo("Doe, John"));
     Assert.That(poco.ListOfA[0].ListOfB[0].Property2, Is.EqualTo("Doe"));
     Assert.That(poco.ListOfA[0].ListOfB[0].Property3, Is.EqualTo("John"));
 }
        public void TestParsingInvalidKey()
        {
            BarCodeType         type        = BarCodeType.Code128;
            string              data        = "123456";
            NameValueCollection querystring = new NameValueCollection();

            querystring.Add(QueryStringSerializer.TYPE_KEY, type.ToString());
            querystring.Add(QueryStringSerializer.DATA_KEY, data);
            querystring.Add("InvalidKey", "whatever");

            IBarCodeSettings settings = QueryStringSerializer.ParseQueryString(querystring);
        }
        public void Can_serialize_query_string()
        {
            Assert.That(QueryStringSerializer.SerializeToString(new C {
                A = 1, B = 2
            }),
                        Is.EqualTo("A=1&B=2"));

            Assert.That(QueryStringSerializer.SerializeToString(new C {
                A = null, B = 2
            }),
                        Is.EqualTo("B=2"));
        }
Exemplo n.º 6
0
        private string ComposePostUrlWithQueryParams <TResponse>(
            string relativeOrAbsoluteUri,
            IReturn <TResponse> requestDto)
        {
            var queryString = QueryStringSerializer.SerializeToString(requestDto);

            var uriBuilder = new UriBuilder(relativeOrAbsoluteUri)
            {
                Query = queryString
            };

            return(uriBuilder.ToString());
        }
Exemplo n.º 7
0
        /// <summary>
        /// Invokes the request without checking for status code.
        /// </summary>
        /// <param name="httpClient">HttpClient instance to be used to invoke the request.</param>
        /// <param name="token">CancellationToken instance to be used to cancel the execution of the request.</param>
        /// <returns>Result instance that contains the HttpStatusCode and the deserialized request response.</returns>
        protected async Task <Result <TResponse> > InvokeUncheckedAsync(HttpClient httpClient, CancellationToken token)
        {
            string query = QueryStringSerializer.ToQueryString(this);

            var pathAndQuery = string.IsNullOrEmpty(query) ? Path : $"{Path}?{query}";

            var httpRequest = new HttpRequestMessage(HttpMethod, new Uri(pathAndQuery, UriKind.Relative));

            var httpResponse = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, token)
                               .ConfigureAwait(false);

            return(await ReadResponseAsync(httpResponse));
        }
        public T Send <T>(IReturn <T> request, string method, bool sendRequestBody = true, string idempotencyKey = null)
        {
            using (new ConfigScope())
            {
                var relativeUrl = request.ToUrl(method);
                var body        = sendRequestBody ? QueryStringSerializer.SerializeToString(request) : null;

                var json = Send(relativeUrl, method, body, idempotencyKey);

                var response = json.FromJson <T>();
                return(response);
            }
        }
        public void TestParseGenerated()
        {
            BarCodeSettings settings = SettingsUtils.CreateTestSettings();

            string queryString = QueryStringSerializer.ToQueryString(settings);

            // re-parse querystring
            NameValueCollection queryStringCollection = MakeCollection(queryString);
            IBarCodeSettings    parsedSettings        = QueryStringSerializer.ParseQueryString(queryStringCollection);

            // compare outcome
            SettingsUtils.AssertSettingsEqual(settings, parsedSettings);
        }
        public void QueryStringSerializer_emits_empty_string_without_quotes()
        {
            var qs = QueryStringSerializer.SerializeToString(new StripeCreateSubscription
            {
                metadata = new Dictionary <string, string>
                {
                    { "foo", string.Empty },
                    { "bar", "qux" }
                }
            });

            Assert.That(qs, Is.EqualTo("metadata[foo]=&metadata[bar]=qux"));
        }
        public void Deos_serialize_QueryStrings()
        {
            var testPocos = new TestPocos { ListOfA = new List<A> { new A { ListOfB = new List<B> { new B { Property = "prop1" }, new B { Property = "prop2" } } } } };

            Assert.That(QueryStringSerializer.SerializeToString(testPocos), Is.EqualTo(
                "ListOfA={ListOfB:[{Property:prop1},{Property:prop2}]}"));

            Assert.That(QueryStringSerializer.SerializeToString(new[] { 1, 2, 3 }), Is.EqualTo(
                "[1,2,3]"));

            Assert.That(QueryStringSerializer.SerializeToString(new[] { "AA", "BB", "CC" }), Is.EqualTo(
                "[AA,BB,CC]"));
        }
Exemplo n.º 12
0
        public void Does_serialize_Poco_and_string_dictionary_with_encoded_data()
        {
            var msg = "Field with comma, to demo. ";

            Assert.That(QueryStringSerializer.SerializeToString(new D {
                A = msg
            }),
                        Is.EqualTo("A=Field+with+comma,+to+demo.+"));

            Assert.That(QueryStringSerializer.SerializeToString(new D {
                A = msg
            }.ToStringDictionary()),
                        Is.EqualTo("A=Field+with+comma,+to+demo.+"));
        }
Exemplo n.º 13
0
        public void TestParsingMinimal()
        {
            BarCodeType         type        = BarCodeType.Code128;
            string              data        = "123456";
            NameValueCollection querystring = new NameValueCollection();

            querystring.Add(QueryStringSerializer.TYPE_KEY, type.ToString());
            querystring.Add(QueryStringSerializer.DATA_KEY, data);

            IBarCodeSettings settings = QueryStringSerializer.ParseQueryString(querystring);

            Assert.AreEqual(type, settings.Type, "Barcode type differs");
            Assert.AreEqual(data, settings.Data, "Barcode data differs");
        }
Exemplo n.º 14
0
        /// <summary>
        /// Parses the query string.
        /// </summary>
        /// <param name="qs">The query string.</param>
        /// <param name="target">The dictionary target.</param>
        private static void ParseQueryString(string qs, IDictionary <string, string> target)
        {
            var fr = qs ?? string.Empty;

            if (fr.StartsWith("?", StringComparison.Ordinal))
            {
                fr = fr.Substring(1);
            }

            foreach (var frag in fr.Split(new char[] { '&' }, StringSplitOptions.RemoveEmptyEntries))
            {
                var parts = frag.Split(new char[] { '=' }, 2, StringSplitOptions.RemoveEmptyEntries);
                target[QueryStringSerializer.UnescapeDataString(parts[0])] = parts.Length == 1 ? null : QueryStringSerializer.UnescapeDataString(parts[1]);
            }
        }
Exemplo n.º 15
0
        public async Task <TResponse> InvokeAsync(HttpClient httpClient, CancellationToken token)
        {
            var query = QueryStringSerializer.ToQueryString(this);

            var pathAndQuery = string.IsNullOrEmpty(query) ? Path : $"{Path}?{query}";

            var httpRequest = new HttpRequestMessage(HttpMethod.Get, new Uri(pathAndQuery, UriKind.Relative));

            var httpResponse = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, token)
                               .ConfigureAwait(false);

            httpResponse.EnsureSuccessStatusCode();

            return(await ReadResponse(httpResponse));
        }
        public void Serializes_Customer_Metadata()
        {
            var dto = new CreateStripeCustomer
            {
                AccountBalance = 100,
                Metadata       = new Dictionary <string, string> {
                    { "order_id", "1234" }
                },
            };

            var qs = QueryStringSerializer.SerializeToString(dto);

            qs.Print();
            Assert.That(qs, Is.EqualTo("account_balance=100&metadata[order_id]=1234"));
        }
        private WebRequest SendRequest(string requestUri, object request)
        {
            var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET";

            if (isHttpGet)
            {
                var queryString = QueryStringSerializer.SerializeToString(request);
                if (!string.IsNullOrEmpty(queryString))
                {
                    requestUri += "?" + queryString;
                }
            }

            return(SendRequest(HttpMethod ?? DefaultHttpMethod, requestUri, request));
        }
Exemplo n.º 18
0
        private string ComposeCamelCaseQueryString(object requestDto)
        {
            var queryString = QueryStringSerializer.SerializeToString(requestDto);

            if (string.IsNullOrWhiteSpace(queryString))
            {
                return(queryString);
            }

            var x = queryString
                    .Split(ParameterSeparators)
                    .Select(SplitPair)
                    .ToList();

            return(string.Join("&", x.Select(p => $"{p.Key.ToCamelCase()}={p.Value}")));
        }
Exemplo n.º 19
0
        public void SendAsync <TResponse>(object request, Action <TResponse> onSuccess, Action <TResponse, Exception> onError)
        {
            var requestUri = this.SyncReplyBaseUri.WithTrailingSlash() + request.GetType().Name;

            var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET";

            if (isHttpGet)
            {
                var queryString = QueryStringSerializer.SerializeToString(request);
                if (!string.IsNullOrEmpty(queryString))
                {
                    requestUri += "?" + queryString;
                }
            }

            var webRequest = (HttpWebRequest)WebRequest.Create(requestUri);

            var requestState = new RequestState <TResponse>
            {
                Url       = requestUri,
                Request   = webRequest,
                OnSuccess = onSuccess,
                OnError   = onError,
            };

            requestState.StartTimer(this.Timeout);

            webRequest.Accept = string.Format("{0}, */*", ContentType);
            webRequest.Method = HttpMethod ?? DefaultHttpMethod;

            if (HttpWebRequestFilter != null)
            {
                HttpWebRequestFilter(webRequest);
            }

            if (!isHttpGet)
            {
                webRequest.ContentType = ContentType;

                //TODO: change to use: webRequest.BeginGetRequestStream()
                using (var requestStream = webRequest.GetRequestStream())
                {
                    SerializeToStream(request, requestStream);
                }
            }
            var result = webRequest.BeginGetResponse(ResponseCallback <TResponse>, requestState);
        }
Exemplo n.º 20
0
        private WebRequest SendRequest(object request, string requestUri)
        {
            var isHttpGet = HttpMethod != null && HttpMethod.ToUpper() == "GET";

            if (isHttpGet)
            {
                var queryString = QueryStringSerializer.SerializeToString(request);
                if (!string.IsNullOrEmpty(queryString))
                {
                    requestUri += "?" + queryString;
                }
            }

            var client = (HttpWebRequest)WebRequest.Create(requestUri);

            try
            {
                if (this.Timeout.HasValue)
                {
                    client.Timeout = (int)this.Timeout.Value.TotalMilliseconds;
                }

                client.Accept = string.Format("{0}, */*", ContentType);
                client.Method = HttpMethod ?? DefaultHttpMethod;

                if (HttpWebRequestFilter != null)
                {
                    HttpWebRequestFilter(client);
                }

                if (!isHttpGet)
                {
                    client.ContentType = ContentType;

                    using (var requestStream = client.GetRequestStream())
                    {
                        SerializeToStream(request, requestStream);
                    }
                }
            }
            catch (AuthenticationException ex)
            {
                throw WebRequestUtils.CreateCustomException(requestUri, ex) ?? ex;
            }
            return(client);
        }
Exemplo n.º 21
0
        public void Can_serialize_with_comma_in_property_in_list()
        {
            var testPocos = new TestPocos
            {
                ListOfA = new List <A> {
                    new A {
                        ListOfB = new List <B> {
                            new B {
                                Property = "Doe, John", Property2 = "Doe", Property3 = "John"
                            }
                        }
                    }
                }
            };

            Assert.That(QueryStringSerializer.SerializeToString(testPocos), Is.EqualTo("ListOfA={ListOfB:[{Property:%22Doe,%20John%22,Property2:Doe,Property3:John}]}"));
        }
Exemplo n.º 22
0
        public async Task <T> SendAsync <T>(IReturn <T> request, string method, bool sendRequestBody = true, string idempotencyKey = null)
        {
            string relativeUrl;
            string body;

            using (new FordereStripeGateway.ConfigScope())
            {
                relativeUrl = ServiceStack.UrlExtensions.ToUrl((IReturn)request, method, (string)null);
                body        = sendRequestBody ? QueryStringSerializer.SerializeToString <IReturn <T> >(request) : (string)null;
            }
            string json = await this.SendAsync(relativeUrl, method, body, idempotencyKey);

            T obj;

            using (new FordereStripeGateway.ConfigScope())
                obj = StringExtensions.FromJson <T>(json);
            return(obj);
        }
Exemplo n.º 23
0
        public void QueryStringSerializer_TestRequest_output()
        {
            var testRequest = new TestRequest {
                ListOfA = new List <A> {
                    new A {
                        ListOfB = new List <B> {
                            new B {
                                Property = "prop1"
                            }, new B {
                                Property = "prop2"
                            }
                        }
                    }
                }
            };
            var str = QueryStringSerializer.SerializeToString(testRequest);

            Assert.That(str, Is.EqualTo("ListOfA={ListOfB:[{Property:prop1},{Property:prop2}]}"));
        }
        /// <summary>
        /// Invokes the request without checking for status code.
        /// </summary>
        /// <param name="httpClient">HttpClient instance to be used to invoke the request.</param>
        /// <param name="token">CancellationToken instance to be used to cancel the execution of the request.</param>
        /// <returns>Result instance that contains the HttpStatusCode and the deserialized request response.</returns>
        protected async Task <Result <TResponse> > InvokeUncheckedAsync(HttpClient httpClient, CancellationToken token)
        {
            Logger.Debug("Sending Http request:");

            string query = QueryStringSerializer.ToQueryString(this);

            var pathAndQuery = string.IsNullOrEmpty(query) ? Path : $"{Path}?{query}";

            var httpRequest = new HttpRequestMessage(HttpMethod, new Uri(pathAndQuery, UriKind.Relative));

            Logger.Debug(httpRequest.ToString());

            var httpResponse = await httpClient.SendAsync(httpRequest, HttpCompletionOption.ResponseHeadersRead, token)
                               .ConfigureAwait(false);

            Logger.Debug($"Response with HTTP status code '{httpResponse.StatusCode}' received.");

            return(await ReadResponseAsync(httpResponse));
        }
Exemplo n.º 25
0
        public async Task <T> SendAsync <T>(IReturn <T> request, string method, bool sendRequestBody = true, string idempotencyKey = null)
        {
            string relativeUrl;
            string body;

            using (new ConfigScope())
            {
                relativeUrl = request.ToUrl(method);
                body        = sendRequestBody ? QueryStringSerializer.SerializeToString(request) : null;
            }

            var json = await SendAsync(relativeUrl, method, body, idempotencyKey);

            using (new ConfigScope())
            {
                var response = json.FromJson <T>();
                return(response);
            }
        }
        public void Can_Write_QueryString()
        {
            var newMovie = new Movie
            {
                Id          = "tt0110912",
                Title       = "Pulp Fiction",
                Rating      = 8.9m,
                Director    = "Quentin Tarantino",
                ReleaseDate = new DateTime(1994, 10, 24),
                TagLine     = "Girls like me don't make invitations like this to just anyone!",
                Genres      = new List <string> {
                    "Crime", "Drama", "Thriller"
                },
            };

            var queryString = QueryStringSerializer.SerializeToString(newMovie);

            Console.WriteLine(queryString);
        }
Exemplo n.º 27
0
        public void Can_write_dictionary_to_QueryString()
        {
            var map = new Dictionary <string, string>
            {
                { "Id", "tt0110912" },
                { "Title", "Pulp Fiction" },
                { "Rating", "8.9" },
                { "Director", "Quentin Tarantino" },
                { "ReleaseDate", "1994-10-24" },
                { "TagLine", "Girls like me don't make invitations like this to just anyone!" },
                { "Genres", "Crime,Drama,Thriller" },
            };

            var queryString = QueryStringSerializer.SerializeToString(map);

            queryString.Print();

            Assert.That(queryString,
                        Is.EqualTo("Id=tt0110912&Title=Pulp+Fiction&Rating=8.9&Director=Quentin+Tarantino&ReleaseDate=1994-10-24&TagLine=Girls+like+me+don%27t+make+invitations+like+this+to+just+anyone%21&Genres=%22Crime,Drama,Thriller%22"));
        }
Exemplo n.º 28
0
        public static void Main(string[] args)
        {
            var serializer = new QueryStringSerializer(
                new QueryStringValueMetadataProvider());

            var albertEinstein =
                new Person
            {
                FirstName = "Albert",
                LastName  = "Einstein",
                BirthDate = new DateTime(1879, 3, 14),
                Height    = 1.75f
            };

            var queryString = serializer.Serialize(albertEinstein);

            Console.WriteLine(queryString);

            Console.ReadLine();
        }
Exemplo n.º 29
0
        public static Status <bool> SendMail <T>(T model, string path)
        {
            var requestUrl = ResolveUrl(path);

            var resSerializer   = new JsonSerializer <Status <bool> >();
            var modelSerializer = new JsonSerializer <T>();

            string data = QueryStringSerializer.SerializeToString <T>(model);

            ASCIIEncoding encoding = new ASCIIEncoding();

            byte[] bytes = encoding.GetBytes(data);

            var req = (HttpWebRequest)HttpWebRequest.Create(requestUrl);

            req.Method        = "POST";
            req.ContentType   = "application/x-www-form-urlencoded";
            req.ContentLength = bytes.Length;

            WebResponse res = null;

            try
            {
                var stream = req.GetRequestStream();
                stream.Write(bytes, 0, bytes.Length);
                stream.Close();

                res = req.GetResponse();
            }
            catch (Exception exc)
            {
                return(Status.Error <bool>(exc.Message, false));
            }

            Status <bool> result = null;

            using (var reader = new StreamReader(res.GetResponseStream()))
                result = resSerializer.DeserializeFromString(reader.ReadToEnd());

            return(result);
        }
Exemplo n.º 30
0
        public void Can_write_AnonymousType_to_QueryString()
        {
            var anonType = new {
                Id          = "tt0110912",
                Title       = "Pulp Fiction",
                Rating      = 8.9m,
                Director    = "Quentin Tarantino",
                ReleaseDate = new DateTime(1994, 10, 24),
                TagLine     = "Girls like me don't make invitations like this to just anyone!",
                Genres      = new List <string> {
                    "Crime", "Drama", "Thriller"
                },
            };

            var queryString = QueryStringSerializer.SerializeToString(anonType);

            queryString.Print();

            Assert.That(queryString,
                        Is.EqualTo("Id=tt0110912&Title=Pulp+Fiction&Rating=8.9&Director=Quentin+Tarantino&ReleaseDate=1994-10-24&TagLine=Girls+like+me+don%27t+make+invitations+like+this+to+just+anyone%21&Genres=Crime,Drama,Thriller"));
        }