public IFuture ExecuteByteBufferList(AsyncHttpRequest req, Action <Exception, IAsyncHttpResponse, ByteBufferList> onCompleted, Action <IAsyncHttpResponse> onConnect = null, Action <IAsyncHttpResponse, long, long> onProgress = null) { return(ExecuteByteBufferList(req, new ActionDownloadCallback(onConnect, onProgress, onCompleted))); }
private Hashtable HandleHttpCloseSession(Hashtable request) { DoExpire(); Hashtable post = DecodePostString(request["body"].ToString()); Hashtable reply = new Hashtable(); reply["str_response_string"] = ""; reply["int_response_code"] = 404; reply["content_type"] = "text/plain"; if (post["ID"] == null) { return(reply); } UUID id; if (!UUID.TryParse(post["ID"].ToString(), out id)) { return(reply); } lock (m_Connections) { if (m_Connections.ContainsKey(id)) { ConsoleConnection connection = m_Connections[id]; m_Connections.Remove(id); CloseConnection(id); if (connection.request != null) { AsyncHttpRequest req = connection.request; connection.request = null; req.SendResponse(ProcessEvents(req)); } } } XmlDocument xmldoc = new XmlDocument(); XmlNode xmlnode = xmldoc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); xmldoc.AppendChild(xmlnode); XmlElement rootElement = xmldoc.CreateElement("", "ConsoleSession", ""); xmldoc.AppendChild(rootElement); XmlElement res = xmldoc.CreateElement("", "Result", ""); res.AppendChild(xmldoc.CreateTextNode("OK")); rootElement.AppendChild(res); reply["str_response_string"] = xmldoc.InnerXml; reply["int_response_code"] = 200; reply["content_type"] = "text/xml"; reply = CheckOrigin(reply); return(reply); }
public void Get(string remotename, System.IO.Stream stream) { AsyncHttpRequest req; if (m_filecache == null || !m_filecache.ContainsKey(remotename)) List(); if (m_filecache != null && m_filecache.ContainsKey(remotename)) req = new AsyncHttpRequest(m_helper.CreateRequest(string.Format("{0}/b2api/v1/b2_download_file_by_id?fileId={1}", m_helper.DownloadUrl, Library.Utility.Uri.UrlEncode(GetFileID(remotename))))); else req = new AsyncHttpRequest(m_helper.CreateRequest(string.Format("{0}/{1}{2}", m_helper.DownloadUrl, m_urlencodedprefix, Library.Utility.Uri.UrlPathEncode(remotename)))); try { using(var resp = req.GetResponse()) using(var rs = req.GetResponseStream()) Library.Utility.Utility.CopyStream(rs, stream); } catch (Exception ex) { if (B2AuthHelper.GetExceptionStatusCode(ex) == HttpStatusCode.NotFound) throw new FileMissingException(); B2AuthHelper.AttemptParseAndThrowException(ex); throw; } }
public void Enqueue(OSD ev, bool highPriority) { AsyncHttpRequest pendingRequest = null; Hashtable responseToSend = null; lock (m_eqLock) { if (isQueueValid == false) { m_log.ErrorFormat("[EVENTQUEUE]: Unable to enqueue new event. isQueueValid == false"); return; } if (highPriority) { m_highPriorityItems.Enqueue(ev); } else { m_Items.Enqueue(ev); } if (m_Request != null) { pendingRequest = m_Request; m_Request = null; responseToSend = GetEvents(pendingRequest); } } if (responseToSend != null) { pendingRequest.SendResponse(responseToSend); } }
public void CreateFolder() { if (string.IsNullOrEmpty(m_project)) { throw new UserInformationException(Strings.GoogleCloudStorage.ProjectIDMissingError(PROJECT_OPTION), "GoogleCloudStorageMissingProjectID"); } var data = System.Text.Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new CreateBucketRequest { name = m_bucket, location = m_location, storageClass = m_storage_class })); var req = m_oauth.CreateRequest(WebApi.GoogleCloudStorage.CreateFolderUrl(m_project)); req.Method = "POST"; req.ContentLength = data.Length; req.ContentType = "application/json; charset=UTF-8"; var areq = new AsyncHttpRequest(req); using (var rs = areq.GetRequestStream()) rs.Write(data, 0, data.Length); m_oauth.ReadJSONResponse <BucketResourceItem>(areq); }
public void DumpQueue() { AsyncHttpRequest pendingRequest = null; Hashtable responseToSend = null; lock (m_eqLock) { if (isQueueValid == true) { m_highPriorityItems.Clear(); m_highPriorityItems = null; m_Items.Clear(); m_Items = null; } // If a request is pending signal it. The response handler will send a 404 if (m_Request != null) { pendingRequest = m_Request; m_Request = null; responseToSend = GetEvents(pendingRequest); } } if (responseToSend != null) { pendingRequest.SendResponse(responseToSend); } }
public void Handle(IHttpServer server, string path, OSHttpRequest httpRequest, OSHttpResponse httpResponse) { AsyncHttpRequest pendingRequest = null; AsyncHttpRequest eventQueueRequest = new AsyncHttpRequest(server, httpRequest, httpResponse, m_agentID, TimeoutHandler, m_timeout); Hashtable responseToSend = null; lock (m_eqLock) { if (!isQueueValid) { m_log.ErrorFormat("[EVENTQUEUE]: HandleRequest for {0} failed, isQueueValid == false", m_agentID); m_Request = null; return; } pendingRequest = m_Request; m_Request = eventQueueRequest; if ((pendingRequest == null) && (m_highPriorityItems.Count > 0 || m_Items.Count > 0)) { pendingRequest = m_Request; m_Request = null; responseToSend = GetEvents(pendingRequest); } } if (responseToSend != null) { pendingRequest.SendResponse(responseToSend); } }
public HttpWebResponse GetResponse(AsyncHttpRequest req, object requestdata = null) { if (requestdata != null) { if (requestdata is System.IO.Stream) { var stream = requestdata as System.IO.Stream; req.Request.ContentLength = stream.Length; if (string.IsNullOrEmpty(req.Request.ContentType)) { req.Request.ContentType = "application/octet-stream"; } using (var rs = req.GetRequestStream()) Library.Utility.Utility.CopyStream(stream, rs); } else { var data = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(requestdata)); req.Request.ContentLength = data.Length; req.Request.ContentType = "application/json; charset=UTF-8"; using (var rs = req.GetRequestStream()) rs.Write(data, 0, data.Length); } } return((HttpWebResponse)req.GetResponse()); }
public IFuture ExecuteJSONObject(AsyncHttpRequest req, Action <Exception, IAsyncHttpResponse, JSONObject> onCompleted, Action <IAsyncHttpResponse> onConnect = null, Action <IAsyncHttpResponse, long, long> onProgress = null) { return(ExecuteJSONObject(req, new ActionJSONObjectCallback(onConnect, onProgress, onCompleted))); }
public IFuture ExecuteFile(AsyncHttpRequest req, string filename, Action <Exception, IAsyncHttpResponse, File> onCompleted, Action <IAsyncHttpResponse> onConnect = null, Action <IAsyncHttpResponse, long, long> onProgress = null) { return(ExecuteFile(req, filename, new ActionFileCallback(onConnect, onProgress, onCompleted))); }
public SimpleFuture Execute <T> (AsyncHttpRequest req, IAsyncParser parser, Action <Exception, IAsyncHttpResponse, T> onCompleted, Action <IAsyncHttpResponse> onConnect = null, Action <IAsyncHttpResponse, long, long> onProgress = null) where T : class, IJavaObject { return(Execute(req, parser, new RequestCallback <T> (onConnect, onProgress, onCompleted))); }
public Route Get(AsyncHttpRequest handler, Func <object, int> statusCodeGenerator = null) { return(Handle("GET", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NotFound : (int)HttpStatusCode.OK))); }
public Route Delete(AsyncHttpRequest handler, Func <object, int> statusCodeGenerator = null) { return(Handle("DELETE", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NoContent : (int)HttpStatusCode.OK))); }
public Route Post(AsyncHttpRequest handler, Func <object, int> statusCodeGenerator = null) { return(Handle("POST", handler, statusCodeGenerator ?? (r => r == null ? (int)HttpStatusCode.NoContent : (int)HttpStatusCode.Created))); }
/// <summary> /// GET数据 /// </summary> /// <param name="requestUrl"></param> /// <param name="parameters"></param> /// <param name="callback"></param> protected virtual void GetData(string requestUrl, Parameters parameters, Action <string> callback) { this.LastError = null; var request = new AsyncHttpRequest(requestUrl, Charset) { Parameters = parameters }; request.Get(EndGetResponseData, callback); }
private Hashtable ProcessEvents(AsyncHttpRequest pRequest, bool timedOut) { UUID requestID = pRequest.RequestID; UrlData urlData = null; RequestData requestData = null; Hashtable response = new Hashtable(); response["content_type"] = "text/plain"; lock (m_RequestMap) { if (m_RequestMap.TryGetValue(requestID, out requestData)) { m_RequestMap.Remove(requestID); } } if (requestData != null) { string url = URLFromURI(requestData.uri); lock (m_UrlMap) { if (m_UrlMap.TryGetValue(url, out urlData)) { urlData.requests.Remove(requestID); } } } if ((requestData == null) || (urlData == null)) { response["int_response_code"] = 404; response["str_response_string"] = "Request not found"; return(response); } if ((timedOut == true) || ((requestData != null) && (requestData.requestDone == false))) { response["int_response_code"] = 500; response["str_response_string"] = "Script timeout"; } else { //put response response["int_response_code"] = requestData.responseCode; response["str_response_string"] = requestData.responseBody; response["content_type"] = requestData.contentType; } return(response); }
private Hashtable ProcessEvents(AsyncHttpRequest pRequest) { var sessionID = pRequest.AgentID; // Is there data to send back? Then send it. if (HasEvents(pRequest.RequestID, sessionID)) { return(GetEvents(pRequest.RequestID, sessionID)); } return(NoEvents(pRequest.RequestID, sessionID)); }
/// <summary> /// Performs a multipart post /// </summary> /// <returns>The response.</returns> /// <param name="url">The url to post to.</param> /// <param name="parts">The multipart items.</param> /// <param name="setup">The optional setup callback method.</param> public virtual HttpWebResponse PostMultipart(string url, Action <HttpWebRequest> setup = null, params MultipartItem[] parts) { var boundary = "----DuplicatiFormBoundary" + Guid.NewGuid().ToString("N"); var bodyterminator = System.Text.Encoding.UTF8.GetBytes("--" + boundary + "--"); var crlf = System.Text.Encoding.UTF8.GetBytes("\r\n"); var headers = (from p in parts select new { Header = System.Text.Encoding.UTF8.GetBytes( "--" + boundary + "\r\n" + string.Join("", from n in p.Headers select string.Format("{0}: {1}\r\n", n.Key, n.Value) ) + "\r\n"), Part = p }).ToArray(); var envelopesize = headers.Sum(x => x.Header.Length + crlf.Length) + bodyterminator.Length; var datasize = parts.Sum(x => x.ContentData.Length); var req = CreateRequest(url); req.Method = "POST"; req.ContentType = "multipart/form-data; boundary=" + boundary; req.ContentLength = envelopesize + datasize; if (setup != null) { setup(req); } var areq = new AsyncHttpRequest(req); using (var rs = areq.GetRequestStream()) { foreach (var p in headers) { rs.Write(p.Header, 0, p.Header.Length); Utility.Utility.CopyStream(p.Part.ContentData, rs); rs.Write(crlf, 0, crlf.Length); } rs.Write(bodyterminator, 0, bodyterminator.Length); } return(GetResponse(areq)); }
/// <summary> /// Helper method that queries a resumeable upload uri for progress /// </summary> /// <returns>The upload range.</returns> /// <param name="oauth">The Oauth instance</param> /// <param name="uploaduri">The resumeable uploaduri</param> /// <param name="streamlength">The length of the entire stream</param> private static long QueryUploadRange <T>(OAuthHelper oauth, string uploaduri, long streamlength, out T response) where T : class { response = null; var req = oauth.CreateRequest(uploaduri); req.Method = "PUT"; req.ContentLength = 0; req.Headers["Content-Range"] = string.Format("bytes */{0}", streamlength); var areq = new AsyncHttpRequest(req); using (var resp = oauth.GetResponseWithoutException(areq)) { var code = (int)resp.StatusCode; // If the upload is completed, we get 201 or 200 if (code >= 200 && code <= 299) { response = oauth.ReadJSONResponse <T>(resp); if (response == null) { throw new Exception(string.Format("Upload succeeded, but no data was returned, status code: {0}", code)); } return(streamlength); } if (code == 308) { // A lack of a Range header is undocumented, // but seems to occur when no data has reached the server: // https://code.google.com/a/google.com/p/apps-api-issues/issues/detail?id=3884 if (resp.Headers["Range"] == null) { return(0); } else { return(long.Parse(resp.Headers["Range"].Split(new char[] { '-' })[1]) + 1); } } else { throw new WebException(string.Format("Unexpected status code: {0}", code), null, WebExceptionStatus.ServerProtocolViolation, resp); } } }
/// <summary> /// Executes a web request and json-deserializes the results as the specified type /// </summary> /// <returns>The deserialized JSON data.</returns> /// <param name="url">The remote URL</param> /// <param name="cancelToken">Token to cancel the operation.</param> /// <param name="setup">A callback method that can be used to customize the request, e.g. by setting the method, content-type and headers.</param> /// <param name="setupbodyreq">A callback method that can be used to submit data into the body of the request.</param> /// <typeparam name="T">The type of data to return.</typeparam> public virtual async Task <T> GetJSONDataAsync <T>(string url, CancellationToken cancelToken, Action <HttpWebRequest> setup = null, Func <AsyncHttpRequest, CancellationToken, Task> setupbodyreq = null) { var req = CreateRequest(url); setup?.Invoke(req); var areq = new AsyncHttpRequest(req); if (setupbodyreq != null) { await setupbodyreq(areq, cancelToken).ConfigureAwait(false); } return(await ReadJSONResponseAsync <T>(areq, cancelToken).ConfigureAwait(false)); }
public async Task <HttpWebResponse> GetResponseAsync(string url, CancellationToken cancelToken, object requestdata = null, string method = null) { if (requestdata is string) { throw new ArgumentException("Cannot send string object as data"); } if (method == null && requestdata != null) { method = "POST"; } var areq = new AsyncHttpRequest(CreateRequest(url, method)); return(await GetResponseAsync(areq, cancelToken, requestdata).ConfigureAwait(false)); }
public void Get(string remotename, Stream stream) { var url = JoinUrls(SimpleStorageEndPoint, m_container, Utility.Uri.UrlPathEncode(m_prefix + remotename)); try { using (var resp = m_helper.GetResponse(url)) using (var rs = AsyncHttpRequest.TrySetTimeout(resp.GetResponseStream())) Library.Utility.Utility.CopyStream(rs, stream); } catch (WebException wex) { if (wex.Response is HttpWebResponse response && response.StatusCode == HttpStatusCode.NotFound) { throw new FileMissingException(); }
public HttpWebResponse GetResponseWithoutException(AsyncHttpRequest req) { try { return((HttpWebResponse)req.GetResponse()); } catch (WebException wex) { if (wex.Response is HttpWebResponse) { return((HttpWebResponse)wex.Response); } throw; } }
private void ResponseCallBack(HttpRequestQueueResultCode result, AsyncHttpRequest response, object state) { Interlocked.Increment(ref this.responseCount); var requestState = state as RequestState; if (requestState != null) { requestState.Result = result; requestState.Response = response; requestState.State = state; requestState.ResetEvent.Set(); } this.resetEvent.Set(); }
public void Get(string remotename, System.IO.Stream stream) { // Prevent repeated download url lookups if (m_filecache.Count == 0) { List(); } var fileid = GetFileId(remotename); var req = m_oauth.CreateRequest(string.Format("{0}/files/{1}?alt=media", DRIVE_API_URL, fileid)); var areq = new AsyncHttpRequest(req); using (var resp = (HttpWebResponse)areq.GetResponse()) using (var rs = resp.GetResponseStream()) Duplicati.Library.Utility.Utility.CopyStream(rs, stream); }
public void Get(string remotename, System.IO.Stream stream) { // Prevent repeated download url lookups if (m_filecache.Count == 0) { foreach (var file in List()) /* Enumerate the full listing */ } { } var fileId = GetFileEntries(remotename).OrderByDescending(x => x.createdDate).First().id; var req = m_oauth.CreateRequest(WebApi.GoogleDrive.GetUrl(fileId)); var areq = new AsyncHttpRequest(req); using (var resp = (HttpWebResponse)areq.GetResponse()) using (var rs = areq.GetResponseStream()) Duplicati.Library.Utility.Utility.CopyStream(rs, stream); }
public void Get(string remotename, System.IO.Stream stream) { // Prevent repeated download url lookups if (m_filecache.Count == 0) { foreach (var file in List()) /* Enumerate the full listing */ } { } var fileid = GetFileEntries(remotename).OrderByDescending(x => x.createdDate).First().id; var req = m_oauth.CreateRequest(string.Format("{0}/files/{1}?alt=media{2}", DRIVE_API_URL, fileid, m_useTeamDrive ? "&supportsTeamDrives=true" : string.Empty)); var areq = new AsyncHttpRequest(req); using (var resp = (HttpWebResponse)areq.GetResponse()) using (var rs = areq.GetResponseStream()) Duplicati.Library.Utility.Utility.CopyStream(rs, stream); }
/// <summary> /// POST数据 /// </summary> /// <param name="requestUrl"></param> /// <param name="parameters"></param> /// <param name="files"></param> /// <param name="callback"></param> protected virtual void PostData(string requestUrl, Parameters parameters, Files files, Action <string> callback) { this.LastError = null; var request = new AsyncHttpRequest(requestUrl, Charset) { Parameters = parameters }; if (files != null) { request.PostFile(EndGetResponseData, files, callback); } else { request.Post(EndGetResponseData, callback); } }
/// <summary> /// Executes a web request and json-deserializes the results as the specified type /// </summary> /// <returns>The deserialized JSON data.</returns> /// <param name="url">The remote URL</param> /// <param name="setup">A callback method that can be used to customize the request, e.g. by setting the method, content-type and headers.</param> /// <param name="setupreq">A callback method that can be used to submit data into the body of the request.</param> /// <typeparam name="T">The type of data to return.</typeparam> public virtual T GetJSONData <T>(string url, Action <HttpWebRequest> setup = null, Action <AsyncHttpRequest> setupreq = null) { var req = CreateRequest(url); if (setup != null) { setup(req); } var areq = new AsyncHttpRequest(req); if (setupreq != null) { setupreq(areq); } return(ReadJSONResponse <T>(areq)); }
/// <summary> /// POST数据 /// </summary> /// <param name="requestUrl"></param> /// <param name="parameters"></param> /// <param name="files"></param> /// <param name="callback"></param> protected virtual void PostData(string requestUrl, Parameters parameters, Files files, Action <string> callback) { this.LastError = null; this.AddOAuthParameter("POST", requestUrl, parameters); var request = new AsyncHttpRequest(requestUrl, this.OAuth.Charset) { Parameters = parameters, AuthHeader = AuthHeaderStr }; if (files != null) { request.PostFile(EndGetResponseData, files, callback); } else { request.Post(EndGetResponseData, callback); } }
private void HttpRequestHttpCallback(HttpRequest request, HttpRequestQueueResultCode result, AsyncHttpRequest httpRequest, object state) { var statusCode = -1; string statusDescription; byte[] responseData = null; try { switch (result) { case HttpRequestQueueResultCode.Success: statusCode = (int)httpRequest.WebResponse.StatusCode; statusDescription = httpRequest.WebResponse.StatusDescription; responseData = httpRequest.Response; break; case HttpRequestQueueResultCode.Error: if (httpRequest.WebResponse != null) { statusCode = (int)httpRequest.WebResponse.StatusCode; statusDescription = httpRequest.WebResponse.StatusDescription; } else { statusDescription = httpRequest.Exception.Message; } break; default: statusCode = -1; statusDescription = string.Empty; break; } } catch (Exception ex) { // we should never get her statusDescription = ex.Message; } var response = new HttpResponseImpl( request, responseData, responseData == null ? null : Encoding.UTF8.GetString(responseData, 0, responseData.Length), result, statusCode, statusDescription, httpRequest == null ? -1 : (int)httpRequest.WebStatus); Log.Debug("Got HttpResoonse - executing callback."); // Sync request triggers an event to release the waiting Request thread to continue try { request.Callback(response, state); } catch (Exception ex) { Log.Error(ex); if (request.Async) { this.Plugin.ReportError(ErrorCodes.AsyncCallbackException, ex, state); } else { throw; } } }
private void OnCallback(HttpRequestQueueResultCode resultCode, AsyncHttpRequest result, object userState, Action<AsyncHttpResponse, ClientAuthenticationQueue> userCallback) { try { var url = result.WebRequest.RequestUri; byte[] responseData = null; var status = result.Status; var exception = result.Exception; this.RequestTimeCounter.AddValue((int)result.Elapsedtime.TotalMilliseconds); if (result.Response != null) { responseData = result.Response; } byte[] resultResponseData = null; switch (resultCode) { case HttpRequestQueueResultCode.Success: { if (log.IsDebugEnabled) { var responseString = string.Empty; if (responseData != null) { responseString = Encoding.UTF8.GetString(responseData); } log.DebugFormat( "Custom authentication result: uri={0}, status={1}, msg={2}, data={3}", url, status, exception != null ? exception.Message : string.Empty, responseString); } this.timeoutCounter.AddValue(0); resultResponseData = responseData; } break; case HttpRequestQueueResultCode.RequestTimeout: { if (log.IsDebugEnabled) { log.DebugFormat("Custom authentication timed out: uri={0}, status={1}, msg={2}", url, status, exception != null ? exception.Message : string.Empty); } this.timeoutCounter.AddValue(1); } break; case HttpRequestQueueResultCode.QueueFull: { if (log.IsDebugEnabled) { log.DebugFormat( "Custom authentication error: queue is full. Requests count {0}, url:{1}, msg:{2}", this.httpRequestQueue.QueuedRequestCount, url, exception != null ? exception.Message : string.Empty); } } break; case HttpRequestQueueResultCode.QueueTimeout: if (log.IsDebugEnabled) { log.DebugFormat("Custom authentication error: Queue timedout. uri={0}, status={1}, msg={2}", url, status, exception != null ? exception.Message : string.Empty); } break; case HttpRequestQueueResultCode.Error: { if (log.IsDebugEnabled) { log.DebugFormat("Custom authentication error: uri={0}, status={1}, msg={2}", url, status, exception != null ? exception.Message : string.Empty); } } break; case HttpRequestQueueResultCode.Offline: { if (log.IsDebugEnabled) { log.DebugFormat("Custom auth error. Queue is offline. url:{0}, status{1}, msg:{2}", url, status, exception != null ? exception.Message : string.Empty); } } break; } var response = new AsyncHttpResponse(resultCode, this.RejectIfUnavailable, userState) { ResponseData = resultResponseData }; ThreadPool.QueueUserWorkItem(delegate { userCallback(response, this); }); return; } catch (Exception e) { log.ErrorFormat("Exception happened:{0}", e); } ThreadPool.QueueUserWorkItem(delegate { userCallback(new AsyncHttpResponse(HttpRequestQueueResultCode.Error, this.RejectIfUnavailable, userState), this); }); }
private void HandleHttpResponse(PeerBase peer, byte operationCode, HttpRequestQueueResultCode result, WebRpcRequest rpcRequest, AsyncHttpRequest request, string requestUri) { if (result == HttpRequestQueueResultCode.Success) { this.HandleSuccessHttpResponse(peer, operationCode, rpcRequest, request); } else { this.HandleErrorHttpRespone(peer, operationCode, result, request, requestUri); } }
private void HandleErrorHttpRespone(PeerBase peer, byte operationCode, HttpRequestQueueResultCode result, AsyncHttpRequest request, string requestUri) { string msg; if (request != null) { msg = string.Format( "webRpc request to address '{0}' failed. HttpQueueResult:{3}, WebStatus:{1}, Exception :{2}", requestUri, request.WebStatus, request.Exception == null ? "(null)" : request.Exception.ToString(), result); } else { msg = string.Format("webRpc request to address '{0}' failed. HttpQueueResult:{1}", requestUri, result); } this.SendErrorResponse(peer, operationCode, new SendParameters(), msg: msg); if (result == HttpRequestQueueResultCode.QueueFull) { Log.Debug(msg); } else { Log.Error(msg); } }
private void HandleSuccessHttpResponse(PeerBase peer, byte operationCode, WebRpcRequest rpcRequest, AsyncHttpRequest request) { try { var serializer = new JavaScriptSerializer(); var responseAsText = Encoding.UTF8.GetString(request.Response); if (string.IsNullOrEmpty(responseAsText)) { var msg = string.Format("WebRpc response for request to address {0} is empty", request.WebRequest.RequestUri); if (Log.IsDebugEnabled) { Log.DebugFormat(msg); } this.SendErrorResponse(peer, operationCode, new SendParameters(), msg: msg); return; } WebRpcResponse rpcResponse; try { rpcResponse = serializer.Deserialize<WebRpcResponse>(responseAsText); } catch (Exception ex) { if (Log.IsDebugEnabled) { Log.DebugFormat("WebRpc failed to deserialize resonse. Uri={0} response={1} error={2}", request.WebRequest.RequestUri, responseAsText, ex.Message); } var msg = string.Format("WebRpc failed to deserialize resonse. Uri={0} response={1} error={2}", request.WebRequest.RequestUri, responseAsText.Substring(0, Math.Min(200, responseAsText.Length)), ex.Message); this.SendErrorResponse(peer, operationCode, new SendParameters(), msg: msg); return; } if (rpcResponse == null) { if (Log.IsDebugEnabled) { Log.DebugFormat("WebRpc response for request to address {0} has wrong format: {1}", request.WebRequest.RequestUri, responseAsText); } var msg = string.Format("WebRpc response for request to address {0} has wrong format: {1}", request.WebRequest.RequestUri, responseAsText.Substring(0, Math.Min(200, responseAsText.Length))); this.SendErrorResponse(peer, operationCode, new SendParameters(), msg: msg); return; } var data = rpcResponse.Data as IEnumerable; var hasData = data != null && data.GetEnumerator().MoveNext(); if (Log.IsDebugEnabled) { Log.DebugFormat("WebRpc response {0} for request to address {1}: {2}", rpcResponse, request.WebRequest.RequestUri, responseAsText); } var path = rpcRequest.UriPath.Contains("?") ? rpcRequest.UriPath.Substring(0, rpcRequest.UriPath.IndexOf("?")) : rpcRequest.UriPath; var response = new OperationResponse { OperationCode = operationCode, ReturnCode = 0, DebugMessage = hasData ? Newtonsoft.Json.JsonConvert.SerializeObject(rpcResponse.Data) : "", Parameters = hasData ? new Dictionary<byte, object> { { (byte)ParameterKey.RpcCallRetCode, rpcResponse.ResultCode }, { (byte)ParameterKey.RpcCallRetMessage, rpcResponse.Message }, { (byte)ParameterKey.UriPath, path }, { (byte)ParameterKey.RpcCallParams, rpcResponse.Data }, } : new Dictionary<byte, object> { { (byte)ParameterKey.RpcCallRetCode, rpcResponse.ResultCode }, { (byte)ParameterKey.RpcCallRetMessage, rpcResponse.Message }, { (byte)ParameterKey.UriPath, path }, } }; peer.SendOperationResponse(response, new SendParameters()); } catch (Exception e) { var msg = string.Format("Handling of successfull response failed with exception {0}", e); this.SendErrorResponse(peer, operationCode, new SendParameters(), msg: msg); Log.Error(msg); } }