From b051b233789afccdcfacb93d9964a32f2e8745b0 Mon Sep 17 00:00:00 2001 From: Michael Hallett Date: Tue, 9 Dec 2014 11:05:08 -0800 Subject: [PATCH 1/2] Added support to allow the user to set the parameter encoding on the RestClient for #608; Code cleanup; --- RestSharp/Http.Async.cs | 32 +++---- RestSharp/Http.Sync.cs | 16 ++-- RestSharp/Http.cs | 52 +++++------ RestSharp/IHttp.cs | 3 + RestSharp/IRestClient.cs | 44 +--------- RestSharp/RestClient.cs | 146 +++++++++++++++--------------- RestSharp/RestRequest.cs | 185 +++++++++++++++++++++------------------ 7 files changed, 233 insertions(+), 245 deletions(-) diff --git a/RestSharp/Http.Async.cs b/RestSharp/Http.Async.cs index c04465935..28f09fffd 100644 --- a/RestSharp/Http.Async.cs +++ b/RestSharp/Http.Async.cs @@ -40,7 +40,7 @@ namespace RestSharp /// public partial class Http { - private TimeOutState _timeoutState; + private TimeOutState timeoutState; public HttpWebRequest DeleteAsync(Action action) { @@ -129,11 +129,11 @@ private HttpWebRequest GetStyleMethodInternalAsync(string method, Action ResponseCallback(result, callback), webRequest); - SetTimeout(asyncResult, _timeoutState); + SetTimeout(asyncResult, this.timeoutState); } } catch (Exception ex) @@ -151,7 +151,7 @@ private HttpResponse CreateErrorResponse(Exception ex) if (webException != null && webException.Status == WebExceptionStatus.RequestCanceled) { - response.ResponseStatus = _timeoutState.TimedOut ? ResponseStatus.TimedOut : ResponseStatus.Aborted; + response.ResponseStatus = this.timeoutState.TimedOut ? ResponseStatus.TimedOut : ResponseStatus.Aborted; return response; } @@ -182,7 +182,7 @@ private HttpWebRequest PutPostInternalAsync(string method, Action private void WriteRequestBodyAsync(HttpWebRequest webRequest, Action callback) { IAsyncResult asyncResult; - _timeoutState = new TimeOutState { Request = webRequest }; + this.timeoutState = new TimeOutState { Request = webRequest }; if (HasBody || HasFiles || AlwaysMultipartFormData) { @@ -196,7 +196,7 @@ private void WriteRequestBodyAsync(HttpWebRequest webRequest, Action ResponseCallback(r, callback), webRequest); } - SetTimeout(asyncResult, _timeoutState); + SetTimeout(asyncResult, this.timeoutState); } private long CalculateContentLength() @@ -206,7 +206,7 @@ private long CalculateContentLength() if (!HasFiles && !AlwaysMultipartFormData) { - return _defaultEncoding.GetByteCount(RequestBody); + return encoding.GetByteCount(RequestBody); } // calculate length for multipart form @@ -214,17 +214,17 @@ private long CalculateContentLength() foreach (var file in Files) { - length += _defaultEncoding.GetByteCount(GetMultipartFileHeader(file)); + length += this.Encoding.GetByteCount(GetMultipartFileHeader(file)); length += file.ContentLength; - length += _defaultEncoding.GetByteCount(_lineBreak); + length += this.Encoding.GetByteCount(LINE_BREAK); } foreach (var param in Parameters) { - length += _defaultEncoding.GetByteCount(GetMultipartFormData(param)); + length += this.Encoding.GetByteCount(GetMultipartFormData(param)); } - length += _defaultEncoding.GetByteCount(GetMultipartFooter()); + length += this.Encoding.GetByteCount(GetMultipartFooter()); return length; } @@ -232,7 +232,7 @@ private void RequestStreamCallback(IAsyncResult result, Action cal { var webRequest = (HttpWebRequest)result.AsyncState; - if (_timeoutState.TimedOut) + if (this.timeoutState.TimedOut) { var response = new HttpResponse { ResponseStatus = ResponseStatus.TimedOut }; ExecuteCallback(response, callback); @@ -265,7 +265,7 @@ private void RequestStreamCallback(IAsyncResult result, Action cal } IAsyncResult asyncResult = webRequest.BeginGetResponse(r => ResponseCallback(r, callback), webRequest); - SetTimeout(asyncResult, _timeoutState); + SetTimeout(asyncResult, this.timeoutState); } private void SetTimeout(IAsyncResult asyncResult, TimeOutState timeOutState) @@ -349,7 +349,7 @@ private void ResponseCallback(IAsyncResult result, Action callback try { - if (_timeoutState.TimedOut) + if (this.timeoutState.TimedOut) { response.ResponseStatus = ResponseStatus.TimedOut; ExecuteCallback(response, callback); @@ -376,12 +376,12 @@ private static void ExecuteCallback(HttpResponse response, Action partial void AddAsyncHeaderActions() { #if SILVERLIGHT - _restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v)); + restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v)); #endif #if WINDOWS_PHONE // WP7 doesn't as of Beta doesn't support a way to set Content-Length either directly // or indirectly - _restrictedHeaderActions.Add("Content-Length", (r, v) => { }); + restrictedHeaderActions.Add("Content-Length", (r, v) => { }); #endif } diff --git a/RestSharp/Http.Sync.cs b/RestSharp/Http.Sync.cs index c0198df7e..0f81e7384 100644 --- a/RestSharp/Http.Sync.cs +++ b/RestSharp/Http.Sync.cs @@ -148,13 +148,13 @@ private HttpResponse PostPutInternal(string method) partial void AddSyncHeaderActions() { - _restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v); - _restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v)); - _restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v); - _restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v)); - _restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v); - _restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; }); - _restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v); + restrictedHeaderActions.Add("Connection", (r, v) => r.Connection = v); + restrictedHeaderActions.Add("Content-Length", (r, v) => r.ContentLength = Convert.ToInt64(v)); + restrictedHeaderActions.Add("Expect", (r, v) => r.Expect = v); + restrictedHeaderActions.Add("If-Modified-Since", (r, v) => r.IfModifiedSince = Convert.ToDateTime(v)); + restrictedHeaderActions.Add("Referer", (r, v) => r.Referer = v); + restrictedHeaderActions.Add("Transfer-Encoding", (r, v) => { r.TransferEncoding = v; r.SendChunked = true; }); + restrictedHeaderActions.Add("User-Agent", (r, v) => r.UserAgent = v); } private void ExtractErrorResponse(HttpResponse httpResponse, Exception ex) @@ -234,7 +234,7 @@ private void WriteRequestBody(HttpWebRequest webRequest) if (!HasBody) return; - var bytes = RequestBodyBytes == null ? _defaultEncoding.GetBytes(RequestBody) : RequestBodyBytes; + var bytes = this.RequestBodyBytes ?? this.Encoding.GetBytes(this.RequestBody); webRequest.ContentLength = bytes.Length; diff --git a/RestSharp/Http.cs b/RestSharp/Http.cs index f547f0472..67e7cf4ab 100644 --- a/RestSharp/Http.cs +++ b/RestSharp/Http.cs @@ -34,8 +34,7 @@ namespace RestSharp /// public partial class Http : IHttp, IHttpFactory { - private const string _lineBreak = "\r\n"; - private static readonly Encoding _defaultEncoding = Encoding.UTF8; + private const string LINE_BREAK = "\r\n"; /// /// Creates an IHttp @@ -148,6 +147,9 @@ protected bool HasFiles /// public bool UseDefaultCredentials { get; set; } #endif + private Encoding encoding = Encoding.UTF8; + + public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } } /// /// HTTP headers to be sent with request @@ -201,15 +203,15 @@ protected bool HasFiles /// public Http() { - Headers = new List(); - Files = new List(); - Parameters = new List(); - Cookies = new List(); + this.Headers = new List(); + this.Files = new List(); + this.Parameters = new List(); + this.Cookies = new List(); - _restrictedHeaderActions = new Dictionary>(StringComparer.OrdinalIgnoreCase); + restrictedHeaderActions = new Dictionary>(StringComparer.OrdinalIgnoreCase); - AddSharedHeaderActions(); - AddSyncHeaderActions(); + this.AddSharedHeaderActions(); + this.AddSyncHeaderActions(); } partial void AddSyncHeaderActions(); @@ -218,10 +220,10 @@ public Http() private void AddSharedHeaderActions() { - _restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v); - _restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v); + restrictedHeaderActions.Add("Accept", (r, v) => r.Accept = v); + restrictedHeaderActions.Add("Content-Type", (r, v) => r.ContentType = v); #if NET4 - _restrictedHeaderActions.Add("Date", (r, v) => + restrictedHeaderActions.Add("Date", (r, v) => { DateTime parsed; @@ -231,14 +233,14 @@ private void AddSharedHeaderActions() } }); - _restrictedHeaderActions.Add("Host", (r, v) => r.Host = v); + restrictedHeaderActions.Add("Host", (r, v) => r.Host = v); #else - _restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ }); - _restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ }); + restrictedHeaderActions.Add("Date", (r, v) => { /* Set by system */ }); + restrictedHeaderActions.Add("Host", (r, v) => { /* Set by system */ }); #endif #if FRAMEWORK - _restrictedHeaderActions.Add("Range", (r, v) => { AddRange(r, v); }); + restrictedHeaderActions.Add("Range", (r, v) => { AddRange(r, v); }); #endif } @@ -252,7 +254,7 @@ private static string GetMultipartFormContentType() private static string GetMultipartFileHeader(HttpFile file) { return string.Format("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}", - FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", _lineBreak); + FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", LINE_BREAK); } private string GetMultipartFormData(HttpParameter param) @@ -261,15 +263,15 @@ private string GetMultipartFormData(HttpParameter param) ? "--{0}{3}Content-Type: {1}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}" : "--{0}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}"; - return string.Format(format, FormBoundary, param.Name, param.Value, _lineBreak); + return string.Format(format, FormBoundary, param.Name, param.Value, LINE_BREAK); } private static string GetMultipartFooter() { - return string.Format("--{0}--{1}", FormBoundary, _lineBreak); + return string.Format("--{0}--{1}", FormBoundary, LINE_BREAK); } - private readonly IDictionary> _restrictedHeaderActions; + private readonly IDictionary> restrictedHeaderActions; // handle restricted headers the .NET way - thanks @dimebrain! // http://msdn.microsoft.com/en-us/library/system.net.httpwebrequest.headers.aspx @@ -277,9 +279,9 @@ private void AppendHeaders(HttpWebRequest webRequest) { foreach (var header in Headers) { - if (_restrictedHeaderActions.ContainsKey(header.Name)) + if (restrictedHeaderActions.ContainsKey(header.Name)) { - _restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value); + restrictedHeaderActions[header.Name].Invoke(webRequest, header.Value); } else { @@ -356,9 +358,9 @@ private void PreparePostBody(HttpWebRequest webRequest) } } - private static void WriteStringTo(Stream stream, string toWrite) + private void WriteStringTo(Stream stream, string toWrite) { - var bytes = _defaultEncoding.GetBytes(toWrite); + var bytes = this.Encoding.GetBytes(toWrite); stream.Write(bytes, 0, bytes.Length); } @@ -376,7 +378,7 @@ private void WriteMultipartFormData(Stream requestStream) // Write the file data directly to the Stream, rather than serializing it to a string. file.Writer(requestStream); - WriteStringTo(requestStream, _lineBreak); + WriteStringTo(requestStream, LINE_BREAK); } WriteStringTo(requestStream, GetMultipartFooter()); diff --git a/RestSharp/IHttp.cs b/RestSharp/IHttp.cs index 2cfe7e72d..fc6a80ffe 100644 --- a/RestSharp/IHttp.cs +++ b/RestSharp/IHttp.cs @@ -19,6 +19,7 @@ using System.IO; using System.Net; using System.Security.Cryptography.X509Certificates; +using System.Text; namespace RestSharp { @@ -57,6 +58,8 @@ public interface IHttp bool UseDefaultCredentials { get; set; } #endif + Encoding Encoding { get; set; } + IList Headers { get; } IList Parameters { get; } diff --git a/RestSharp/IRestClient.cs b/RestSharp/IRestClient.cs index d61c70771..429636e64 100644 --- a/RestSharp/IRestClient.cs +++ b/RestSharp/IRestClient.cs @@ -18,6 +18,8 @@ using System.Net; using System.Collections.Generic; using System.Security.Cryptography.X509Certificates; +using System.Text; + #if NET4 || MONODROID || MONOTOUCH || WP8 using System.Threading; using System.Threading.Tasks; @@ -25,69 +27,31 @@ namespace RestSharp { - /// - /// - /// public interface IRestClient { - /// - /// - /// #if !PocketPC CookieContainer CookieContainer { get; set; } #endif - /// - /// - /// string UserAgent { get; set; } - /// - /// - /// int Timeout { get; set; } - /// - /// - /// int ReadWriteTimeout { get; set; } - /// - /// - /// bool UseSynchronizationContext { get; set; } - /// - /// - /// IAuthenticator Authenticator { get; set; } - /// - /// - /// Uri BaseUrl { get; set; } - /// - /// - /// + Encoding Encoding { get; set; } + bool PreAuthenticate { get; set; } - /// - /// - /// IList DefaultParameters { get; } - /// - /// - /// - /// - /// RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action callback); - /// - /// - /// - /// - /// RestRequestAsyncHandle ExecuteAsync(IRestRequest request, Action, RestRequestAsyncHandle> callback); #if FRAMEWORK || PocketPC diff --git a/RestSharp/RestClient.cs b/RestSharp/RestClient.cs index c4ca7c438..eaa84f217 100644 --- a/RestSharp/RestClient.cs +++ b/RestSharp/RestClient.cs @@ -20,6 +20,7 @@ using System.Net; using System.Reflection; using System.Security.Cryptography.X509Certificates; +using System.Text; using RestSharp.Deserializers; using RestSharp.Extensions; @@ -38,6 +39,78 @@ public partial class RestClient : IRestClient #endif public IHttpFactory HttpFactory = new SimpleFactory(); + + /// + /// Maximum number of redirects to follow if FollowRedirects is true + /// + public int? MaxRedirects { get; set; } + +#if FRAMEWORK + /// + /// X509CertificateCollection to be sent with request + /// + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Proxy to use for requests made by this client instance. + /// Passed on to underlying WebRequest if set. + /// + public IWebProxy Proxy { get; set; } +#endif + + /// + /// Default is true. Determine whether or not requests that result in + /// HTTP status codes of 3xx should follow returned redirect + /// + public bool FollowRedirects { get; set; } + +#if !PocketPC + /// + /// The CookieContainer used for requests made by this client instance + /// + public CookieContainer CookieContainer { get; set; } +#endif + + /// + /// UserAgent to use for requests made by this client instance + /// + public string UserAgent { get; set; } + + /// + /// Timeout in milliseconds to use for requests made by this client instance + /// + public int Timeout { get; set; } + + /// + /// The number of milliseconds before the writing or reading times out. + /// + public int ReadWriteTimeout { get; set; } + + /// + /// Whether to invoke async callbacks using the SynchronizationContext.Current captured when invoked + /// + public bool UseSynchronizationContext { get; set; } + + /// + /// Authenticator to use for requests made by this client instance + /// + public IAuthenticator Authenticator { get; set; } + + /// + /// Combined with Request.Resource to construct URL for request + /// Should include scheme and domain without trailing slash. + /// + /// + /// client.BaseUrl = new Uri("http://example.com"); + /// + public virtual Uri BaseUrl { get; set; } + + private Encoding encoding = Encoding.UTF8; + + public Encoding Encoding { get { return this.encoding; } set { this.encoding = value; } } + + public bool PreAuthenticate { get; set; } + /// /// Default constructor that registers default content handlers /// @@ -168,73 +241,6 @@ private IDeserializer GetHandler(string contentType) return handler; } - /// - /// Maximum number of redirects to follow if FollowRedirects is true - /// - public int? MaxRedirects { get; set; } - -#if FRAMEWORK - /// - /// X509CertificateCollection to be sent with request - /// - public X509CertificateCollection ClientCertificates { get; set; } - - /// - /// Proxy to use for requests made by this client instance. - /// Passed on to underlying WebRequest if set. - /// - public IWebProxy Proxy { get; set; } -#endif - - /// - /// Default is true. Determine whether or not requests that result in - /// HTTP status codes of 3xx should follow returned redirect - /// - public bool FollowRedirects { get; set; } - -#if !PocketPC - /// - /// The CookieContainer used for requests made by this client instance - /// - public CookieContainer CookieContainer { get; set; } -#endif - - /// - /// UserAgent to use for requests made by this client instance - /// - public string UserAgent { get; set; } - - /// - /// Timeout in milliseconds to use for requests made by this client instance - /// - public int Timeout { get; set; } - - /// - /// The number of milliseconds before the writing or reading times out. - /// - public int ReadWriteTimeout { get; set; } - - /// - /// Whether to invoke async callbacks using the SynchronizationContext.Current captured when invoked - /// - public bool UseSynchronizationContext { get; set; } - - /// - /// Authenticator to use for requests made by this client instance - /// - public IAuthenticator Authenticator { get; set; } - - /// - /// Combined with Request.Resource to construct URL for request - /// Should include scheme and domain without trailing slash. - /// - /// - /// client.BaseUrl = new Uri("http://example.com"); - /// - public virtual Uri BaseUrl { get; set; } - - public bool PreAuthenticate { get; set; } - private void AuthenticateIfNeeded(RestClient client, IRestRequest request) { if (Authenticator != null) @@ -327,6 +333,7 @@ private static string EncodeParameter(Parameter parameter) private void ConfigureHttp(IRestRequest request, IHttp http) { + http.Encoding = this.Encoding; http.AlwaysMultipartFormData = request.AlwaysMultipartFormData; #if !PocketPC http.UseDefaultCredentials = request.UseDefaultCredentials; @@ -477,7 +484,7 @@ private void ConfigureHttp(IRestRequest request, IHttp http) } } #if FRAMEWORK - ConfigureProxy(http); + this.ConfigureProxy(http); #endif } @@ -491,7 +498,7 @@ private void ConfigureProxy(IHttp http) } #endif - private RestResponse ConvertToRestResponse(IRestRequest request, HttpResponse httpResponse) + private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponse httpResponse) { var restResponse = new RestResponse { @@ -549,6 +556,7 @@ private IRestResponse Deserialize(IRestRequest request, IRestResponse raw) request.OnBeforeDeserialization(raw); IRestResponse response = new RestResponse(); + try { response = raw.toAsyncResponse(); diff --git a/RestSharp/RestRequest.cs b/RestSharp/RestRequest.cs index cd362bc9e..e0e9e781c 100644 --- a/RestSharp/RestRequest.cs +++ b/RestSharp/RestRequest.cs @@ -63,44 +63,40 @@ public class RestRequest : IRestRequest /// public RestRequest() { - Parameters = new List(); - Files = new List(); - XmlSerializer = new XmlSerializer(); - JsonSerializer = new JsonSerializer(); + this.Parameters = new List(); + this.Files = new List(); + this.XmlSerializer = new XmlSerializer(); + this.JsonSerializer = new JsonSerializer(); - OnBeforeDeserialization = r => { }; + this.OnBeforeDeserialization = r => { }; } /// /// Sets Method property to value of method /// /// Method to use for this request - public RestRequest(Method method) - : this() + public RestRequest(Method method) : this() { - Method = method; + this.Method = method; } /// /// Sets Resource property /// /// Resource to use for this request - public RestRequest(string resource) - : this(resource, Method.GET) { } + public RestRequest(string resource) : this(resource, Method.GET) { } /// /// Sets Resource and Method properties /// /// Resource to use for this request /// Method to use for this request - public RestRequest(string resource, Method method) - : this() + public RestRequest(string resource, Method method) : this() { - Resource = resource; - Method = method; + this.Resource = resource; + this.Method = method; } - /// /// Sets Resource property /// @@ -131,18 +127,18 @@ public IRestRequest AddFile(string name, string path) long fileLength = f.Length; return AddFile(new FileParameter - { - Name = name, - FileName = Path.GetFileName(path), - ContentLength = fileLength, - Writer = s => - { - using (var file = new StreamReader(path)) - { - file.BaseStream.CopyTo(s); - } - } - }); + { + Name = name, + FileName = Path.GetFileName(path), + ContentLength = fileLength, + Writer = s => + { + using (var file = new StreamReader(path)) + { + file.BaseStream.CopyTo(s); + } + } + }); } /// @@ -154,7 +150,7 @@ public IRestRequest AddFile(string name, string path) /// This request public IRestRequest AddFile(string name, byte[] bytes, string fileName) { - return AddFile(FileParameter.Create(name, bytes, fileName)); + return this.AddFile(FileParameter.Create(name, bytes, fileName)); } /// @@ -167,7 +163,7 @@ public IRestRequest AddFile(string name, byte[] bytes, string fileName) /// This request public IRestRequest AddFile(string name, byte[] bytes, string fileName, string contentType) { - return AddFile(FileParameter.Create(name, bytes, fileName, contentType)); + return this.AddFile(FileParameter.Create(name, bytes, fileName, contentType)); } /// @@ -179,7 +175,7 @@ public IRestRequest AddFile(string name, byte[] bytes, string fileName, string c /// This request public IRestRequest AddFile(string name, Action writer, string fileName) { - return AddFile(name, writer, fileName, null); + return this.AddFile(name, writer, fileName, null); } /// @@ -192,12 +188,18 @@ public IRestRequest AddFile(string name, Action writer, string fileName) /// This request public IRestRequest AddFile(string name, Action writer, string fileName, string contentType) { - return AddFile(new FileParameter { Name = name, Writer = writer, FileName = fileName, ContentType = contentType }); + return AddFile(new FileParameter + { + Name = name, + Writer = writer, + FileName = fileName, + ContentType = contentType + }); } private IRestRequest AddFile(FileParameter file) { - Files.Add(file); + this.Files.Add(file); return this; } @@ -221,7 +223,7 @@ public IRestRequest AddBody(object obj, string xmlNamespace) break; case DataFormat.Xml: - XmlSerializer.Namespace = xmlNamespace; + this.XmlSerializer.Namespace = xmlNamespace; serialized = XmlSerializer.Serialize(obj); contentType = XmlSerializer.ContentType; break; @@ -235,7 +237,7 @@ public IRestRequest AddBody(object obj, string xmlNamespace) // passing the content type as the parameter name because there can only be // one parameter with ParameterType.RequestBody so name isn't used otherwise // it's a hack, but it works :) - return AddParameter(contentType, serialized, ParameterType.RequestBody); + return this.AddParameter(contentType, serialized, ParameterType.RequestBody); } /// @@ -246,7 +248,7 @@ public IRestRequest AddBody(object obj, string xmlNamespace) /// This request public IRestRequest AddBody(object obj) { - return AddBody(obj, ""); + return this.AddBody(obj, ""); } /// @@ -256,8 +258,8 @@ public IRestRequest AddBody(object obj) /// This request public IRestRequest AddJsonBody(object obj) { - RequestFormat = DataFormat.Json; - return AddBody(obj, ""); + this.RequestFormat = DataFormat.Json; + return this.AddBody(obj, ""); } /// @@ -267,8 +269,8 @@ public IRestRequest AddJsonBody(object obj) /// This request public IRestRequest AddXmlBody(object obj) { - RequestFormat = DataFormat.Xml; - return AddBody(obj, ""); + this.RequestFormat = DataFormat.Xml; + return this.AddBody(obj, ""); } /// @@ -280,8 +282,8 @@ public IRestRequest AddXmlBody(object obj) /// This request public IRestRequest AddXmlBody(object obj, string xmlNamespace) { - RequestFormat = DataFormat.Xml; - return AddBody(obj, xmlNamespace); + this.RequestFormat = DataFormat.Xml; + return this.AddBody(obj, xmlNamespace); } /// @@ -304,35 +306,38 @@ public IRestRequest AddObject(object obj, params string[] includedProperties) bool isAllowed = includedProperties.Length == 0 || (includedProperties.Length > 0 && includedProperties.Contains(prop.Name)); - if (isAllowed) + if (!isAllowed) + continue; + + var propType = prop.PropertyType; + var val = prop.GetValue(obj, null); + + if (val == null) + continue; + + if (propType.IsArray) { - var propType = prop.PropertyType; - var val = prop.GetValue(obj, null); + var elementType = propType.GetElementType(); + + if (((Array)val).Length > 0 && + elementType != null && + (elementType.IsPrimitive|| elementType.IsValueType || elementType == typeof(string))) + { + // convert the array to an array of strings + var values = (from object item in ((Array)val) + select item.ToString()) + .ToArray(); - if (val != null) + val = string.Join(",", values); + } + else { - if (propType.IsArray) - { - var elementType = propType.GetElementType(); - - if (((Array)val).Length > 0 && - (elementType.IsPrimitive || elementType.IsValueType || elementType == typeof(string))) - { - // convert the array to an array of strings - var values = - (from object item in ((Array)val) select item.ToString()).ToArray(); - val = string.Join(",", values); - } - else - { - // try to cast it - val = string.Join(",", (string[])val); - } - } - - AddParameter(prop.Name, val); + // try to cast it + val = string.Join(",", (string[])val); } } + + this.AddParameter(prop.Name, val); } return this; @@ -345,7 +350,7 @@ public IRestRequest AddObject(object obj, params string[] includedProperties) /// This request public IRestRequest AddObject(object obj) { - AddObject(obj, new string[] { }); + this.AddObject(obj, new string[] { }); return this; } @@ -356,7 +361,7 @@ public IRestRequest AddObject(object obj) /// public IRestRequest AddParameter(Parameter p) { - Parameters.Add(p); + this.Parameters.Add(p); return this; } @@ -368,7 +373,12 @@ public IRestRequest AddParameter(Parameter p) /// This request public IRestRequest AddParameter(string name, object value) { - return AddParameter(new Parameter { Name = name, Value = value, Type = ParameterType.GetOrPost }); + return this.AddParameter(new Parameter + { + Name = name, + Value = value, + Type = ParameterType.GetOrPost + }); } /// @@ -384,7 +394,12 @@ public IRestRequest AddParameter(string name, object value) /// This request public IRestRequest AddParameter(string name, object value, ParameterType type) { - return AddParameter(new Parameter { Name = name, Value = value, Type = type }); + return this.AddParameter(new Parameter + { + Name = name, + Value = value, + Type = type + }); } /// @@ -397,14 +412,15 @@ public IRestRequest AddHeader(string name, string value) { #if !SILVERLIGHT const string portSplit = @":\d+"; - Func invalidHost = host => Uri.CheckHostName(Regex.Split(host, portSplit)[0]) == UriHostNameType.Unknown; + Func invalidHost = + host => Uri.CheckHostName(Regex.Split(host, portSplit)[0]) == UriHostNameType.Unknown; if (name == "Host" && invalidHost(value)) { throw new ArgumentException("The specified value is not a valid Host header string.", "value"); } #endif - return AddParameter(name, value, ParameterType.HttpHeader); + return this.AddParameter(name, value, ParameterType.HttpHeader); } /// @@ -415,7 +431,7 @@ public IRestRequest AddHeader(string name, string value) /// public IRestRequest AddCookie(string name, string value) { - return AddParameter(name, value, ParameterType.Cookie); + return this.AddParameter(name, value, ParameterType.Cookie); } /// @@ -426,7 +442,7 @@ public IRestRequest AddCookie(string name, string value) /// public IRestRequest AddUrlSegment(string name, string value) { - return AddParameter(name, value, ParameterType.UrlSegment); + return this.AddParameter(name, value, ParameterType.UrlSegment); } /// @@ -437,7 +453,7 @@ public IRestRequest AddUrlSegment(string name, string value) /// public IRestRequest AddQueryParameter(string name, string value) { - return AddParameter(name, value, ParameterType.QueryString); + return this.AddParameter(name, value, ParameterType.QueryString); } /// @@ -451,7 +467,7 @@ public IRestRequest AddQueryParameter(string name, string value) /// public List Files { get; private set; } - private Method _method = Method.GET; + private Method method = Method.GET; /// /// Determines what HTTP method to use for this request. Supported methods: GET, POST, PUT, DELETE, HEAD, OPTIONS @@ -459,8 +475,8 @@ public IRestRequest AddQueryParameter(string name, string value) /// public Method Method { - get { return _method; } - set { _method = value; } + get { return this.method; } + set { this.method = value; } } /// @@ -477,7 +493,7 @@ public Method Method /// public string Resource { get; set; } - private DataFormat _requestFormat = DataFormat.Xml; + private DataFormat requestFormat = DataFormat.Xml; /// /// Serializer to use when writing XML request bodies. Used if RequestFormat is Xml. @@ -485,8 +501,8 @@ public Method Method /// public DataFormat RequestFormat { - get { return _requestFormat; } - set { _requestFormat = value; } + get { return this.requestFormat; } + set { this.requestFormat = value; } } /// @@ -531,14 +547,12 @@ public DataFormat RequestFormat /// public int ReadWriteTimeout { get; set; } - private int _attempts; - /// /// Internal Method so that RestClient can increase the number of attempts /// public void IncreaseNumAttempts() { - _attempts++; + this.Attempts++; } /// @@ -548,9 +562,6 @@ public void IncreaseNumAttempts() /// This Number is incremented each time the RestClient sends the request. /// Useful when using Asynchronous Execution with Callbacks /// - public int Attempts - { - get { return _attempts; } - } + public int Attempts { get; private set; } } } From 659511fc21b4efdb6eee54555c5e672721714a3a Mon Sep 17 00:00:00 2001 From: Michael Hallett Date: Wed, 10 Dec 2014 14:34:23 -0800 Subject: [PATCH 2/2] Added a condition for CF on Encode Parameters; Code Cleanup; --- RestSharp/Http.Async.cs | 8 +++----- RestSharp/Http.cs | 10 +++++----- RestSharp/RestClient.cs | 4 ++++ 3 files changed, 12 insertions(+), 10 deletions(-) diff --git a/RestSharp/Http.Async.cs b/RestSharp/Http.Async.cs index 28f09fffd..cfc00e14d 100644 --- a/RestSharp/Http.Async.cs +++ b/RestSharp/Http.Async.cs @@ -15,6 +15,7 @@ #endregion using System; +using System.Linq; using System.Net; using System.Threading; using RestSharp.Extensions; @@ -219,10 +220,8 @@ private long CalculateContentLength() length += this.Encoding.GetByteCount(LINE_BREAK); } - foreach (var param in Parameters) - { - length += this.Encoding.GetByteCount(GetMultipartFormData(param)); - } + length = this.Parameters.Aggregate(length, + (current, param) => current + this.Encoding.GetByteCount(this.GetMultipartFormData(param))); length += this.Encoding.GetByteCount(GetMultipartFooter()); return length; @@ -304,7 +303,6 @@ private static void TimeoutCallback(object state, bool timedOut) private static void GetRawResponseAsync(IAsyncResult result, Action callback) { - var response = new HttpResponse { ResponseStatus = ResponseStatus.None }; HttpWebResponse raw; try diff --git a/RestSharp/Http.cs b/RestSharp/Http.cs index 67e7cf4ab..0ea26e621 100644 --- a/RestSharp/Http.cs +++ b/RestSharp/Http.cs @@ -244,17 +244,17 @@ private void AddSharedHeaderActions() #endif } - private const string FormBoundary = "-----------------------------28947758029299"; + private const string FORM_BOUNDARY = "-----------------------------28947758029299"; private static string GetMultipartFormContentType() { - return string.Format("multipart/form-data; boundary={0}", FormBoundary); + return string.Format("multipart/form-data; boundary={0}", FORM_BOUNDARY); } private static string GetMultipartFileHeader(HttpFile file) { return string.Format("--{0}{4}Content-Disposition: form-data; name=\"{1}\"; filename=\"{2}\"{4}Content-Type: {3}{4}{4}", - FormBoundary, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", LINE_BREAK); + FORM_BOUNDARY, file.Name, file.FileName, file.ContentType ?? "application/octet-stream", LINE_BREAK); } private string GetMultipartFormData(HttpParameter param) @@ -263,12 +263,12 @@ private string GetMultipartFormData(HttpParameter param) ? "--{0}{3}Content-Type: {1}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}" : "--{0}{3}Content-Disposition: form-data; name=\"{1}\"{3}{3}{2}{3}"; - return string.Format(format, FormBoundary, param.Name, param.Value, LINE_BREAK); + return string.Format(format, FORM_BOUNDARY, param.Name, param.Value, LINE_BREAK); } private static string GetMultipartFooter() { - return string.Format("--{0}--{1}", FormBoundary, LINE_BREAK); + return string.Format("--{0}--{1}", FORM_BOUNDARY, LINE_BREAK); } private readonly IDictionary> restrictedHeaderActions; diff --git a/RestSharp/RestClient.cs b/RestSharp/RestClient.cs index eaa84f217..1dbc99abb 100644 --- a/RestSharp/RestClient.cs +++ b/RestSharp/RestClient.cs @@ -321,7 +321,11 @@ public Uri BuildUri(IRestRequest request) private static string EncodeParameters(IEnumerable parameters) { +#if !PocketPC return string.Join("&", parameters.Select(EncodeParameter).ToArray()); +#else + return string.Join("&", parameters.Select(x => EncodeParameter(x)).ToArray()); +#endif } private static string EncodeParameter(Parameter parameter)