/// <summary> /// Parse to JSON and send to the server. /// </summary> /// <typeparam name="T">JSON message type.</typeparam> /// <param name="method">Sent JSON object as a string.</param> /// <param name="request">Request to send.</param> /// <param name="data">Async request.</param> /// <returns>Http request that is sent to the server.</returns> private HttpWebRequest Send <T>(string method, object request, GXAsyncData <T> data) { CancelOperation = false; string cmd = null; bool content = method == "POST" || method == "PUT"; //Serialize to string because we want to know length. using (TextWriter writer = new StringWriter()) { Parser.Serialize(request, writer, true, !content, false, false); cmd = writer.ToString(); } HttpWebRequest req; if (content)//If POST or PUT. { req = WebRequest.Create(Address + request.GetType().Name) as HttpWebRequest; } else //If GET or DELETE. { req = WebRequest.Create(Address + request.GetType().Name + "?" + cmd) as HttpWebRequest; } if (Timeout.TotalMilliseconds != 0) { req.ReadWriteTimeout = req.Timeout = (int)this.Timeout.TotalMilliseconds; } req.ContentType = "application/json"; req.Accept = "application/json"; req.Method = method; if (trace != null) { trace(this, new TraceEventArgs(TraceTypes.Sent, content ? cmd : null, req.Address.ToString())); } //Add basic authentication if it is used. if (!string.IsNullOrEmpty(UserName)) { req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName + ":" + Password))); } if (content) { req.ContentLength = cmd.Length; //If data is send as async. if (data != null) { data.Data = cmd; data.Request = req; req.BeginGetRequestStream(delegate(IAsyncResult result) { lock (asyncOperations) { asyncOperations.Add(result.AsyncWaitHandle); } GXAsyncData <T> tmp = (GXAsyncData <T>)result.AsyncState; try { using (Stream stream = tmp.Request.EndGetRequestStream(result)) { using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(tmp.Data); streamWriter.Flush(); } } tmp.Request.BeginGetResponse(AsyncReponse <T>, tmp); } catch (Exception ex) { tmp.OnError(this, ex); } finally { lock (asyncOperations) { asyncOperations.Remove(result.AsyncWaitHandle); } } }, data); } else { using (var streamWriter = new StreamWriter(req.GetRequestStream())) { streamWriter.Write(cmd); streamWriter.Flush(); } } } else if (data != null) { req.BeginGetResponse(delegate(IAsyncResult result) { lock (asyncOperations) { asyncOperations.Add(result.AsyncWaitHandle); } GXAsyncData <T> tmp = (GXAsyncData <T>)result.AsyncState; try { T result2 = GetResponse <T>(req); if (data.OnDone != null) { data.OnDone(this, result2); } } catch (Exception ex) { tmp.OnError(this, ex); } finally { lock (asyncOperations) { asyncOperations.Remove(result.AsyncWaitHandle); } } }, data); } return(req); }
/// <summary> /// Parse to JSON and send to the server. /// </summary> /// <typeparam name="T">JSON message type.</typeparam> /// <param name="route">Additional route.</param> /// <param name="method">Sent JSON object as a string.</param> /// <param name="request">Request to send.</param> /// <param name="data">Async request.</param> /// <returns>Http request that is sent to the server.</returns> private HttpWebRequest Send <T>(string route, string method, object request, GXAsyncData <T> data) { CancelOperation = false; string cmd = null; bool content = method == "POST" || method == "PUT"; //Serialize to string because we want to know length. using (TextWriter writer = new StringWriter()) { Parser.Serialize(request, writer, true, !content, false, false); cmd = writer.ToString(); } if (string.IsNullOrEmpty(route)) { route = request.GetType().Name; } if (route[0] != '/' && Address[Address.Length - 1] != '/') { route = "/" + route; } HttpWebRequest req; if (content)//If POST or PUT. { req = WebRequest.Create(Address + route) as HttpWebRequest; } else //If GET or DELETE. { req = WebRequest.Create(Address + route + "?" + cmd) as HttpWebRequest; } #if !NET35 if (Date != DateTime.MinValue && Date != DateTime.MaxValue) { req.Date = Date.ToUniversalTime(); } #endif //!NET35 req.CachePolicy = new HttpRequestCachePolicy(HttpRequestCacheLevel.BypassCache); req.Headers.Add("Cache-Control", "no-cache"); if (Timeout.TotalMilliseconds != 0) { req.ReadWriteTimeout = req.Timeout = (int)this.Timeout.TotalMilliseconds; } req.ContentType = "application/json"; req.Accept = "application/json"; req.Method = method; if (trace != null) { trace(this, new TraceEventArgs(TraceTypes.Sent, content ? cmd : null, req.Address.ToString())); } //Add basic authentication if it is used. if (!string.IsNullOrEmpty(UserName)) { req.Headers.Add("Authorization", "Basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(UserName + ":" + Password))); } //Data must serialize because data might be non-ASCII. byte[] d; using (MemoryStream ms = new MemoryStream()) { using (var sw = new StreamWriter(ms)) { sw.Write(cmd); sw.Flush(); d = new byte[ms.Position]; ms.Position = 0; ms.Read(d, 0, d.Length); } } if (content) { req.ContentLength = d.Length; //If data is send as async. if (data != null) { data.Data = d; data.Request = req; req.BeginGetRequestStream(delegate(IAsyncResult result) { lock (asyncOperations) { asyncOperations.Add(result.AsyncWaitHandle); } GXAsyncData <T> tmp = (GXAsyncData <T>)result.AsyncState; try { using (Stream stream = tmp.Request.EndGetRequestStream(result)) { using (var streamWriter = new StreamWriter(stream)) { streamWriter.Write(tmp.Data); streamWriter.Flush(); } } tmp.Request.BeginGetResponse(AsyncReponse <T>, tmp); } catch (Exception ex) { tmp.OnError(this, ex); } finally { lock (asyncOperations) { asyncOperations.Remove(result.AsyncWaitHandle); } } }, data); } else { using (BufferedStream bs = new BufferedStream(req.GetRequestStream())) { bs.Write(d, 0, d.Length); bs.Flush(); } } } else if (data != null) { data.Data = d; req.BeginGetResponse(delegate(IAsyncResult result) { lock (asyncOperations) { asyncOperations.Add(result.AsyncWaitHandle); } GXAsyncData <T> tmp = (GXAsyncData <T>)result.AsyncState; try { T result2 = GetResponse <T>(req); if (data.OnDone != null) { data.OnDone(this, result2); } } catch (Exception ex) { tmp.OnError(this, ex); } finally { lock (asyncOperations) { asyncOperations.Remove(result.AsyncWaitHandle); } } }, data); } return(req); }