public void Can_serialize_quoted_strings() { Assert.That(QueryStringSerializer.SerializeToString(new B { Property = "\"quoted content\"" }), Is.EqualTo("Property=%22quoted+content%22")); Assert.That(QueryStringSerializer.SerializeToString(new B { Property = "\"quoted content, and with a comma\"" }), Is.EqualTo("Property=%22quoted+content,+and+with+a+comma%22")); }
public void Can_serialize_Poco_with_comma_in_string() { var dto = new B { Property = "Foo,Bar" }; var qs = QueryStringSerializer.SerializeToString(dto); Assert.That(qs, Is.EqualTo("Property=Foo,Bar")); }
public void Does_urlencode_Poco_with_escape_char() { var dto = new B { Property = "Foo&Bar" }; var qs = QueryStringSerializer.SerializeToString(dto); Assert.That(qs, Is.EqualTo("Property=Foo%26Bar")); }
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_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")); }
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 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]")); }
private string ComposePostUrlWithQueryParams <TResponse>( string relativeOrAbsoluteUri, IReturn <TResponse> requestDto) { var queryString = QueryStringSerializer.SerializeToString(requestDto); var uriBuilder = new UriBuilder(relativeOrAbsoluteUri) { Query = queryString }; return(uriBuilder.ToString()); }
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 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 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.+")); }
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)); }
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}"))); }
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); }
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}]}")); }
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); }
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); }
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); }
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}]}")); }
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")); }
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); }
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")); }
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> { HttpMethod = httpMethod, Url = requestUri, WebRequest = webRequest, Request = request, OnSuccess = onSuccess, OnError = onError, }; requestState.StartTimer(this.Timeout); SendWebRequestAsync(httpMethod, request, requestState, webRequest); return(requestState); }
public void Can_Write_QueryString() { Movie 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); queryString.Print(); Assert.That(queryString, Is.EqualTo("Id=tt0110912&Title=Pulp%20Fiction&Rating=8.9&Director=Quentin%20Tarantino&ReleaseDate=1994-10-24&TagLine=Girls%20like%20me%20don%27t%20make%20invitations%20like%20this%20to%20just%20anyone%21&Genres=Crime,Drama,Thriller")); }
public void Can_serialize_newline() { Assert.That(QueryStringSerializer.SerializeToString(new { newline = "\r\n" }), Is.EqualTo("newline=%0d%0a")); }
public async Task <TResponse> SendAsync <TResponse>(string httpMethod, string absoluteUrl, object request, CancellationToken token = default) { var client = GetHttpClient(); if (!HttpUtils.HasRequestBody(httpMethod) && request != null) { var queryString = QueryStringSerializer.SerializeToString(request); if (!string.IsNullOrEmpty(queryString)) { absoluteUrl += "?" + queryString; } } try { absoluteUrl = new Uri(absoluteUrl).ToString(); } catch (Exception ex) { if (log.IsDebugEnabled) { log.Debug("Could not parse URL: " + absoluteUrl, ex); } } var filterResponse = ResultsFilter?.Invoke(typeof(TResponse), httpMethod, absoluteUrl, request); if (filterResponse is TResponse typedResponse) { return(typedResponse); } var httpReq = CreateRequest(httpMethod, absoluteUrl, request); try { var httpRes = await client.SendAsync(httpReq, token).ConfigAwait(); if (typeof(TResponse) == typeof(HttpResponseMessage)) { return((TResponse)(object)httpRes); } if (httpRes.StatusCode == HttpStatusCode.Unauthorized) { var hasRefreshToken = RefreshToken != null; if (EnableAutoRefreshToken && hasRefreshToken) { var refreshDto = new GetAccessToken { RefreshToken = RefreshToken, }; var uri = this.RefreshTokenUri ?? this.BaseUri.CombineWith(refreshDto.ToPostUrl()); this.BearerToken = null; this.CookieContainer?.DeleteCookie(new Uri(BaseUri), "ss-tok"); try { var accessTokenResponse = await this.PostAsync <GetAccessTokenResponse>(uri, refreshDto, token).ConfigAwait(); var accessToken = accessTokenResponse?.AccessToken; var tokenCookie = this.GetTokenCookie(); var refreshRequest = CreateRequest(httpMethod, absoluteUrl, request); if (!string.IsNullOrEmpty(accessToken)) { refreshRequest.AddBearerToken(this.BearerToken = accessToken); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); } else if (tokenCookie != null) { this.SetTokenCookie(tokenCookie); } else { throw new RefreshTokenException("Could not retrieve new AccessToken from: " + uri); } var refreshTokenResponse = await client.SendAsync(refreshRequest, token).ConfigAwait(); return(await ConvertToResponse <TResponse>(refreshTokenResponse, httpMethod, absoluteUrl, refreshRequest, token).ConfigAwait()); } catch (Exception e) { if (e.UnwrapIfSingleException() is WebServiceException refreshEx) { throw new RefreshTokenException(refreshEx); } throw; } } if (UserName != null && Password != null && client.DefaultRequestHeaders.Authorization == null) { AddBasicAuth(client); httpReq = CreateRequest(httpMethod, absoluteUrl, request); var response = await client.SendAsync(httpReq, token).ConfigAwait(); return(await ConvertToResponse <TResponse>(response, httpMethod, absoluteUrl, request, token).ConfigAwait()); } } return(await ConvertToResponse <TResponse>(httpRes, httpMethod, absoluteUrl, request, token).ConfigAwait()); } catch (Exception e) { log.Error(e, "HttpClient Exception: " + e.Message); throw; } }
public void Can_serialize_tab() { Assert.That(QueryStringSerializer.SerializeToString(new { tab = "\t" }), Is.EqualTo("tab=%09")); }