/// <summary>A callback method which will be called after an individual response was parsed.</summary> /// <param name="content">The content response or <c>null</c> if the request failed.</param> /// <param name="error">Error or <c>null</c> if the request succeeded.</param> /// <param name="index">The request index.</param> /// <param name="message">The HTTP individual response.</param> public virtual void OnResponse(object content, RequestError error, int index, HttpResponseMessage message) { // Set ETag on the response. var eTagValue = message.Headers.ETag != null ? message.Headers.ETag.Tag : null; var eTagContainer = content as IDirectResponseSchema; if (eTagContainer != null && eTagContainer.ETag == null && eTagValue != null) { eTagContainer.ETag = eTagValue; } }
public bool CanHandleErrorResponse(WebException exception, RequestError error) { if (callOrder != 0 && callOrder != 2) { Assert.Fail("IErrorResponseHandler methods called in wrong order."); } // This handler will only handle the first retry, and will fail every additional request. callOrder++; return(!Called); }
public virtual void OnResponse(object content, RequestError error, int index, HttpResponseMessage message) { var str = message.Headers.ETag?.Tag; var directResponseSchema = content as IDirectResponseSchema; if (directResponseSchema == null || directResponseSchema.ETag != null || str == null) { return; } directResponseSchema.ETag = str; }
public static async Task ProcessResults(Lottery sender) { //todo: post results in fusion channel ulong tsNow = DateTimeHelper.TimestampNow(); //save the game in case of dispute or a problem paying out string savedGameName = $"{tsNow}.xml"; new ObjectSerializer().Serialize(sender, savedGameName); var n = sender.Numbers; var wn = sender.WinningNumbers; FusionBotConfig cfg = ((FusionBotConfig)Globals.Bot.Config); //pay minor prizes foreach (var w in wn) { RequestError err = await AccountHelper.PayUser((double)sender.Parameters.MinorPrize, cfg.BotId, n[w]); if (err != null) { await Sender.SendPrivateMessage(Globals.Client.GetUser(n[w]), $"You just won {sender.Parameters.MinorPrize}xnv in the lottery, but there was a problem with the payout. Please contact an admin and quote number `{tsNow}`"); } else { await Sender.SendPrivateMessage(Globals.Client.GetUser(n[w]), $"You just won {sender.Parameters.MinorPrize}xnv in the lottery."); } } float jackpot = sender.JackpotAmount; foreach (var w in wn) { if (sender.JackpotNumber == w) { RequestError err = await AccountHelper.PayUser((double)sender.JackpotAmount, cfg.BotId, n[w]); if (err != null) { await Sender.SendPrivateMessage(Globals.Client.GetUser(n[w]), $"You just won the lottery jackpot of {sender.JackpotAmount}xnv, but there was a problem with the payout. Please contact an admin and quote number `{tsNow}`"); } else { await Sender.SendPrivateMessage(Globals.Client.GetUser(n[w]), $"You just won the lottery jackpot of {sender.JackpotAmount}xnv."); } jackpot = 0; } } Restart(jackpot); }
private static string PickMessage(RequestError error, Exception inner) { if (error != null) { return(error.ToString()); } if (inner != null) { return(inner.Message); } return("An error has ocurred, but no message is available."); }
public VlcApi(LoginCredentials cred) { _cred = cred; _baseUrl = "http://" + _cred.Hostname + ":" + _cred.Port + "/requests/"; _statusRequestWorker.DoWork += (sender, args) => { _statusUpdater.Stop(); while (_statusRequestQueue.Count >= 1) { if (_statusRequestWorker.CancellationPending) { return; } try { Status status = GetStatusSync(_statusRequestQueue[0]); if (_statusRequestQueue[0] == "") { StatusChanged?.Invoke(this, status); } _statusRequestQueue.RemoveAt(0); } catch (ApiRespondException e) { RequestError?.Invoke(this, e); _statusRequestQueue.Clear(); return; } } _statusUpdater.Start(); }; _statusRequestQueue.CollectionChanged += (sender, args) => { if (!_statusRequestWorker.IsBusy) { _statusRequestWorker.RunWorkerAsync(); } StatusRequestCountChanged?.Invoke(sender, _statusRequestQueue.Count); }; _statusUpdater.Elapsed += (sender, args) => { RequestStatus(); }; _statusUpdater.Start(); }
/// <summary> /// Useful method to retry the execution safely. While <see cref="Start"/> throws exceptions, /// this method catches them and marks the <see cref="_parent"/> request as complete, /// making it suitable to be called in a fire and forget manner. /// </summary> private void RetryExecution(bool currentHostRetry, Host host) { try { Start(currentHostRetry); } catch (Exception ex) { //There was an Exception before sending (probably no host is available). //This will mark the Task as faulted. HandleResponse(RequestError.CreateClientError(ex, true), null, host); } }
private void LoadCompletionHandler(RequestError error) { if (error != null) { OnRewardedVideoAdFailedToLoad?.Invoke(_rewardedAd.AdUnitId, new AdMobErrorEventArgs() { Code = (int?)error?.Code, Domain = error?.Domain, Message = error?.LocalizedDescription, FullStacktrace = error?.ToString() }); } else { OnRewardedVideoAdLoaded?.Invoke(_rewardedAd.AdUnitId, null); } }
public void HandleErrorResponse(WebException exception, RequestError error, WebRequest request) { request.ThrowIfNull("request"); if (!(request is HttpWebRequest)) { throw new InvalidCastException( "Expected a HttpWebRequest, but got a " + request.GetType() + " instead."); } // Refresh our access token: tokenProvider.RefreshToken(State, null); // Overwrite the current auth header: ApplyAuthenticationToRequest((HttpWebRequest)request); }
/// <summary> /// Retrieve an item of type <typeparamref name="T"/> from the Blizzard World of Warcraft Game Data or Profile API. /// </summary> /// <typeparam name="T"> /// The return type. /// </typeparam> /// <param name="requestUri"> /// The URI the request is sent to. /// </param> /// <param name="accessToken"> /// The OAuth access token. /// </param> /// <returns> /// The JSON response, deserialized to an object of type <typeparamref name="T"/>. /// </returns> private async Task <RequestResult <T> > GetAsync <T>(string requestUri, string accessToken) { // Add an authentication header with the token. Client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); // Retrieve the response. HttpResponseMessage response = await Client.GetAsync(requestUri).ConfigureAwait(false); if (!response.IsSuccessStatusCode) { // Check if the request was successful and made it to the Blizzard API. // The API will always send back content if successful. if (response.Content != null) { string content = await response.Content.ReadAsStringAsync().ConfigureAwait(false); if (!string.IsNullOrEmpty(content)) { RequestResult <T> requestError = JsonSerializer.Deserialize <RequestError>(content); return(requestError); } } // If not then it is most likely a problem on our end due to an HTTP error. string message = $"Response code {(int)response.StatusCode} ({response.ReasonPhrase}) does not indicate success. Request: {requestUri}"; throw new HttpRequestException(message); } // Deserialize an object of type T from the JSON string. string json = await response.Content.ReadAsStringAsync().ConfigureAwait(false); try { RequestResult <T> requestResult = JsonSerializer.Deserialize <T>(json, s_jsonSerializerOptions); return(requestResult); } catch (JsonException ex) { var requestError = new RequestError { Code = null, Detail = ex.Message, Type = typeof(JsonException).ToString() }; return(new RequestResult <T>(requestError)); } }
public void TestErrorDeserialization( [Values(DiscoveryVersion.Version_0_3, DiscoveryVersion.Version_1_0)] DiscoveryVersion version) { const string ErrorResponse = @"{ ""error"": { ""errors"": [ { ""domain"": ""global"", ""reason"": ""required"", ""message"": ""Required"", ""locationType"": ""parameter"", ""location"": ""resource.longUrl"" } ], ""code"": 400, ""message"": ""Required"" } }"; IService impl = CreateService(version); using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse))) { // Verify that the response is decoded correctly. GoogleApiException ex = Assert.Throws <GoogleApiException>(() => { impl.DeserializeResponse <MockJsonSchema>(new MockResponse() { Stream = stream }); }); // Check that the contents of the error json was translated into the exception object. // We cannot compare the entire exception as it depends on the implementation and might change. Assert.That(ex.ToString(), Contains.Substring("resource.longUrl")); } using (var stream = new MemoryStream(Encoding.Default.GetBytes(ErrorResponse))) { RequestError error = impl.DeserializeError(new MockResponse() { Stream = stream }); Assert.AreEqual(400, error.Code); Assert.AreEqual("Required", error.Message); Assert.AreEqual(1, error.Errors.Count); } }
/// <summary> /// Marks this operation as timed-out, callbacks with the exception /// and sets a handler when the response is received /// </summary> public bool MarkAsTimedOut(OperationTimedOutException ex, Action onReceive, long timestamp) { var previousState = Interlocked.CompareExchange(ref _state, StateTimedout, StateInit); if (previousState != StateInit) { return(false); } //When the data is received, invoke on receive callback var callback = Interlocked.Exchange(ref _callback, (_, __, ___) => onReceive()); Thread.MemoryBarrier(); _timeoutCallbackSet = true; Task.Factory.StartNew(() => callback(RequestError.CreateClientError(ex, false), null, timestamp), CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default); return(true); }
public static Google.GoogleApiException isNotAFolder(string id, DriveService service) { Google.GoogleApiException notAFolder = new Google.GoogleApiException(service.Name, "File is not a folder :" + id); RequestError error = new RequestError(); error.Code = 400; error.Message = "File is not a folder: " + id; error.Errors = new List <SingleError>() { new SingleError() { Domain = "global", Location = "field", LocationType = "parameter", Message = "File is not a folder: " + id, Reason = "notAFolder" } }; notAFolder.Error = error; return(notAFolder); }
private void CallbackEventErrorMessage(Event content, RequestError error, int index, HttpResponseMessage message, List <Appointment> eventList, string errorMessage, Dictionary <int, Appointment> errorAppointments, List <Appointment> deletedEvents) { var phrase = message.ReasonPhrase; if (!message.IsSuccessStatusCode) { var googleEvent = eventList[index]; errorAppointments.Add(index, googleEvent); Logger.ErrorFormat("{0} : {1}{2} - {3}", errorMessage, Environment.NewLine, phrase, googleEvent); } else { deletedEvents.Add(CreateAppointment(content)); } }
public void Download_Error_JsonResponse() { var downloadUri = "http://www.sample.com"; var chunkSize = 100; var error = new RequestError { Code = 12345, Message = "Text", Errors = new[] { new SingleError { Message = "Nested error" } } }; var response = new StandardResponse <object> { Error = error }; var responseText = new NewtonsoftJsonSerializer().Serialize(response); var handler = new MultipleChunksMessageHandler { ErrorResponse = responseText }; handler.StatusCode = HttpStatusCode.BadRequest; handler.ChunkSize = chunkSize; // The media downloader adds the parameter... handler.DownloadUri = new Uri(downloadUri + "?alt=media"); using (var service = CreateMockClientService(handler)) { var downloader = new MediaDownloader(service); downloader.ChunkSize = chunkSize; IList <IDownloadProgress> progressList = new List <IDownloadProgress>(); downloader.ProgressChanged += (p) => { progressList.Add(p); }; var outputStream = new MemoryStream(); downloader.Download(downloadUri, outputStream); var lastProgress = progressList.LastOrDefault(); Assert.That(lastProgress.Status, Is.EqualTo(DownloadStatus.Failed)); GoogleApiException exception = (GoogleApiException)lastProgress.Exception; Assert.That(exception.HttpStatusCode, Is.EqualTo(handler.StatusCode)); // Just a smattering of checks - if these two pass, it's surely okay. Assert.That(exception.Error.Code, Is.EqualTo(error.Code)); Assert.That(exception.Error.Errors[0].Message, Is.EqualTo(error.Errors[0].Message)); } }
private void CallbackEventErrorMessage(Task content, RequestError error, int index, HttpResponseMessage message, List <ReminderTask> reminderTasks, string errorMessage, Dictionary <int, ReminderTask> errorAppointments, List <ReminderTask> addedTasks) { var phrase = message.ReasonPhrase; var googleEvent = reminderTasks[index]; if (!message.IsSuccessStatusCode) { errorAppointments.Add(index, googleEvent); Logger.ErrorFormat("{0} : {1}{2} - {3}", errorMessage, Environment.NewLine, phrase, googleEvent); } else if (content != null) { addedTasks.Add(CreateReminderTask(content)); } }
private async Task HandlePayoutResult(SocketUserMessage msg, bool win, RequestError err) { if (err != null) { await Sender.PrivateReply(msg, $"{msg.Author.Mention} Oops. RPC Error: {err.Code}: {err.Message}", null); } else { if (win) { await Sender.PublicReply(msg, $"{msg.Author.Mention} Winner winner, chicken dinner! :chicken:"); } else { await Sender.PublicReply(msg, $"{msg.Author.Mention} You lose, sucker! :joy:"); } } }
public RequestError completePhoneCall(Guid PhoneCallId, Guid ActionStatusId, Guid?DeclineReasonStatusId, DateTime?NextCallTime) { try { PhoneCallsServiceClient client = new PhoneCallsServiceClient(); client.ClientCredentials.UserName.UserName = Properties.Settings.Default.ActionUser.ToString(); client.ClientCredentials.UserName.Password = Properties.Settings.Default.ActionPassword.ToString(); RequestError result = client.CompletePhoneCall(PhoneCallId, ActionStatusId, DeclineReasonStatusId, NextCallTime); return(result); } catch (Exception e) { Log.add(String.Format("[ERR] Системная ошибка: {0} Stack: {1}", e.Message, e.StackTrace)); return(null); } }
//---------------------------------------------------------------------------- /// <summary> /// Обработчик событий ошибочной работы COM-порта /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void ComPort_ErrorReceived(object sender, SerialErrorReceivedEventArgs e) { switch (e.EventType) { case SerialError.Frame: { _error = RequestError.Frame; break; } case SerialError.Overrun: { _error = RequestError.Overrun; break; } case SerialError.RXOver: { _error = RequestError.RXOver; break; } case SerialError.RXParity: { _error = RequestError.RXParity; break; } case SerialError.TXFull: { _error = RequestError.TXFull; break; } } StopTransaction(); _timeOut.Set(); return; }
public bool CanHandleErrorResponse(WebException exception, RequestError error) { exception.ThrowIfNull("exception"); // If we have an access token, and the response was 401, then the access token // probably expired. We can try to handle this error. if (State == null) { return(false); } var response = exception.Response as HttpWebResponse; if (response == null) { return(false); } return(response.StatusCode == HttpStatusCode.Unauthorized); }
public int Convert(RequestError error) { switch (error) { case RequestError.ApplicationException: return(StatusCodes.Status500InternalServerError); case RequestError.AlreadyExists: return(StatusCodes.Status409Conflict); case RequestError.NotFound: return(StatusCodes.Status404NotFound); case RequestError.ValidationError: case RequestError.OtherError: return(StatusCodes.Status400BadRequest); default: _logger.LogWarning("No StatusCode for {errorType} found"); return(StatusCodes.Status500InternalServerError); } }
public static async Task <RequestError> PayUser(double amount, ulong sender, ulong recipient) { FusionBotConfig cfg = ((FusionBotConfig)Globals.Bot.Config); RequestError error = null; await new Transfer(new TransferRequestData { AccountIndex = cfg.UserWalletCache[sender].Item1, Destinations = new List <TransferDestination> { new TransferDestination { Amount = amount.ToAtomicUnits(), Address = cfg.UserWalletCache[recipient].Item2 } } }, null, (RequestError e) => { error = e; }, cfg.WalletHost, cfg.UserWalletPort).RunAsync(); return(error); }
public void TestErrorDeserialization( [CombinatorialValues(Features.LegacyDataResponse, null)] Features?features) { const string ErrorResponse = @"{ ""error"": { ""errors"": [ { ""domain"": ""global"", ""reason"": ""required"", ""message"": ""Required"", ""locationType"": ""parameter"", ""location"": ""resource.longUrl"", ""customIndividual"": ""Custom individual error info"" } ], ""code"": 400, ""message"": ""Required"", ""custom"": ""Custom error info"" } }"; var client = CreateClientService(features); using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(ErrorResponse))) { var response = new HttpResponseMessage { Content = new StreamContent(stream) }; RequestError error = client.DeserializeError(response).Result; Assert.Equal(400, error.Code); Assert.Equal("Required", error.Message); Assert.Equal(1, error.Errors.Count); Assert.NotNull(error.ErrorResponseContent); Assert.Equal(ErrorResponse, error.ErrorResponseContent); } }
protected virtual void OnRequestError(HyperErrorEventArgs e) { RequestError?.Invoke(this, e); }
private static FirebaseException CreateExceptionFor(RequestError requestError) { return(new FirebaseException(requestError.ToString())); }
/// <summary>Subtest for the execute method.</summary> /// <param name="successful2ndReponse">Indicates if the 2nd individual response is unsuccessful.</param> void SubtestExecuteAsync_Test(bool successful2ndReponse) { var handler = new BatchMessageHandler(successful2ndReponse); var initializer = new BaseClientService.Initializer() { HttpClientFactory = new MockHttpClientFactory(handler) }; using (var service = new MockClientService(initializer, "http://sample.com")) { var responses = new List <Tuple <MockResponse, RequestError, HttpResponseMessage> >(); var batch = new BatchRequest(service); var request1 = new TestClientServiceRequest(service, new MockRequest { ETag = "\"100\"", Name = "Name1" }); var request2 = new TestClientServiceRequest(service, new MockRequest { ETag = "\"200\"", Name = "Name1-1" }); // Adding the content, error and message into the responses list to verify the results later on batch.Queue <MockResponse>(request1, (content, error, index, message) => { responses.Add(new Tuple <MockResponse, RequestError, HttpResponseMessage>( content, error, message)); }); batch.Queue <MockResponse>(request2, (content, error, index, message) => { responses.Add(new Tuple <MockResponse, RequestError, HttpResponseMessage>( content, error, message)); }); batch.ExecuteAsync().Wait(); Assert.That(responses.Count, Is.EqualTo(2)); var tuple = responses[0]; Assert.Null(tuple.Item2); // no error var response = tuple.Item1; // response Assert.That(response.ETag, Is.EqualTo(@"""10011""")); Assert.That(response.Id, Is.EqualTo(1)); var httpMessage = tuple.Item3; // HTTP message Assert.That(httpMessage.Content.Headers.ContentType.MediaType, Is.EqualTo("application/json")); Assert.That(httpMessage.Content.Headers.ContentLength, Is.EqualTo(505)); tuple = responses[1]; if (successful2ndReponse) { Assert.Null(tuple.Item2); // no error response = tuple.Item1; // response Assert.That(response.ETag, Is.EqualTo(@"""234""")); Assert.That(response.Id, Is.EqualTo(2)); } else { Assert.Null(tuple.Item1); // no response RequestError reqError = tuple.Item2; // error Assert.That(reqError.Errors.Count, Is.EqualTo(1)); Assert.That(reqError.Code, Is.EqualTo(404)); Assert.That(reqError.Message, Is.EqualTo("Not Found")); } httpMessage = tuple.Item3; // HTTP message Assert.That(httpMessage.Content.Headers.ContentType.MediaType, Is.EqualTo("application/json")); Assert.That(httpMessage.Content.Headers.ContentLength, Is.EqualTo(202)); } }
public void ProcessRequest(HttpContext context) { try { IHttpRequest httpRequest = new HttpGetPostRequest(context.Request); //context.Request.s //检测是否存在ashx if (string.IsNullOrEmpty(httpRequest.RequestFileName)) { LogWarnInfo(httpRequest, "请求失败:没有指定ashx路径。\n", 0, 0); return; } SPChannelWrapper channel = SPChannelWrapper.GetChannelByPath(Path.GetFileNameWithoutExtension(httpRequest.RequestFileName)); //如果没有找到通道 if (channel == null) { LogWarnInfo(httpRequest, "处理请求失败:无法找到对应的通道。\n", 0, 0); return; } saveLogFailedRequestToDb = channel.LogFailedRequestToDb; //如果通道未能运行 if (channel.CStatus != ChannelStatus.Run) { LogWarnInfo(httpRequest, "请求失败:\n" + "通道“" + channel.Name + "”未运行。\n", channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); return; } //如果通道是监视通道,记录请求。 if (channel.IsMonitoringRequest.HasValue && channel.IsMonitoringRequest.Value) { SPMonitoringRequestWrapper.SaveRequest(httpRequest, channel.Id); } if (channel.Id == 88) { if (httpRequest.RequestParams.ContainsKey("command")) { if (httpRequest.RequestParams["command"].ToString().ToLower().Equals("z6")) { httpRequest.RequestParams["command"] = " 6"; } } if (httpRequest.RequestParams.ContainsKey("command")) { if (httpRequest.RequestParams["command"].ToString().ToLower().Equals("71") && httpRequest.RequestParams["sp_no"].ToString().ToLower().Equals("1066885031")) { httpRequest.RequestParams["command"] = "7"; } } } if (channel.Id == 66) { if (httpRequest.RequestParams.ContainsKey("spnumber") && httpRequest.RequestParams.ContainsKey("momsg")) { if (httpRequest.RequestParams["momsg"].ToString().ToLower().StartsWith("8dm") && httpRequest.RequestParams["spnumber"].ToString().ToLower().Equals("106268001")) { httpRequest.RequestParams["spnumber"] = "106268000"; } } } if (channel.FuzzyCommand.Trim().ToLower().Equals("quantt")) { if (httpRequest.RequestParams.ContainsKey("reportcode")) { if (!string.IsNullOrEmpty(httpRequest.RequestParams["reportcode"].ToString())) { httpRequest.RequestParams.Add("status", httpRequest.RequestParams["reportcode"].ToString().Substring(0, 1)); httpRequest.RequestParams.Add("msg", httpRequest.RequestParams["reportcode"].ToString().Substring(1, httpRequest.RequestParams["reportcode"].ToString().Length - 1)); } } } if (channel.HasConvertRule.HasValue && channel.HasConvertRule.Value) { try { PreProcessRequest(httpRequest.RequestParams, context, channel.FuzzyCommand); } catch (Exception ex) { LogWarnInfo(httpRequest, "数据转换错误:" + ex.Message, channel.Id, 0); } } //如果状态报告通道 if (channel.RecStatReport.HasValue && channel.RecStatReport.Value) { RequestError requestError1 = new RequestError(); bool result1 = false; //分类型请求 if (channel.HasRequestTypeParams.HasValue && channel.HasRequestTypeParams.Value) { //报告状态请求 if (httpRequest.IsRequestContainValues(channel.RequestTypeParamName, channel.RequestReportTypeValue)) { if (httpRequest.IsRequestContainValues(channel.StatParamsName, channel.StatParamsValues)) { result1 = channel.RecState(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString(), out requestError1); } else { //channel.SaveStatReport(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString()); context.Response.Write(channel.GetOkCode(httpRequest)); return; } } //发送数据请求 else if (httpRequest.IsRequestContainValues(channel.RequestTypeParamName, channel.RequestDataTypeValue)) { result1 = channel.ProcessStateRequest(httpRequest, out requestError1); } else { LogWarnInfo(httpRequest, "未知类型请求", channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); return; } } else { if (httpRequest.RequestParams.ContainsKey(channel.StatParamsName.ToLower())) { if (httpRequest.IsRequestContainValues(channel.StatParamsName, channel.StatParamsValues)) { if (channel.StatSendOnce.HasValue && channel.StatSendOnce.Value) { result1 = channel.ProcessRequest(httpRequest, out requestError1); } else { result1 = channel.RecState(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString(), out requestError1); } } else { //channel.SaveStatReport(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString()); context.Response.Write(channel.GetOkCode(httpRequest)); return; } } else { result1 = channel.ProcessStateRequest(httpRequest, out requestError1); } } //正确数据返回OK if (result1) { context.Response.Write(channel.GetOkCode(httpRequest)); return; } //重复数据返回OK if (requestError1.ErrorType == RequestErrorType.RepeatLinkID) { logger.Warn(requestError1.ErrorMessage); context.Response.Write(channel.GetOkCode(httpRequest)); return; } //其他错误类型记录错误请求 LogWarnInfo(httpRequest, requestError1.ErrorMessage, channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); return; } RequestError requestError; bool result = channel.ProcessRequest(httpRequest, out requestError); if (result) { context.Response.Write(channel.GetOkCode(httpRequest)); return; } //重复数据返回OK if (requestError.ErrorType == RequestErrorType.RepeatLinkID) { logger.Warn(requestError.ErrorMessage); context.Response.Write(channel.GetOkCode(httpRequest)); return; } LogWarnInfo(httpRequest, requestError.ErrorMessage, channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); } catch (Exception ex) { try { IHttpRequest failRequest = new HttpGetPostRequest(context.Request); string errorMessage = "处理请求失败:\n错误信息:" + ex.Message; logger.Error(errorMessage + "\n请求信息:\n" + failRequest.RequestData, ex); if (saveLogFailedRequestToDb) { SPFailedRequestWrapper.SaveFailedRequest(failRequest, errorMessage, 0, 0); } } catch (Exception e) { logger.Error("处理请求失败:\n错误信息:" + e.Message); } } }
public void ProcessRequest(HttpContext context) { try { IHttpRequest httpRequest = new HttpGetPostRequest(context.Request); //context.Request.s //检测是否存在ashx if (string.IsNullOrEmpty(httpRequest.RequestFileName)) { LogWarnInfo(httpRequest, "请求失败:没有指定ashx路径。\n", 0, 0); return; } SPChannelWrapper channel = SPChannelWrapper.GetChannelByPath(httpRequest.GetChannelCode()); //如果没有找到通道 if (channel == null) { LogWarnInfo(httpRequest, "处理请求失败:无法找到对应的通道。\n", 0, 0); return; } saveLogFailedRequestToDb = channel.LogFailedRequestToDb; //如果通道未能运行 if (channel.CStatus != ChannelStatus.Run) { LogWarnInfo(httpRequest, "请求失败:\n" + "通道“" + channel.Name + "”未运行。\n", channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); return; } //如果通道是监视通道,记录请求。 if (channel.IsMonitoringRequest.HasValue && channel.IsMonitoringRequest.Value) { SPMonitoringRequestWrapper.SaveRequest(httpRequest, channel.Id); } if (channel.Id == 88) { if (httpRequest.RequestParams.ContainsKey("command")) { if (httpRequest.RequestParams["command"].ToString().ToLower().Equals("z6")) { httpRequest.RequestParams["command"] = " 6"; } } if (httpRequest.RequestParams.ContainsKey("command")) { if (httpRequest.RequestParams["command"].ToString().ToLower().Equals("71") && httpRequest.RequestParams["sp_no"].ToString().ToLower().Equals("1066885031")) { httpRequest.RequestParams["command"] = "7"; } } } if (channel.Id == 66) { if (httpRequest.RequestParams.ContainsKey("spnumber")&&httpRequest.RequestParams.ContainsKey("momsg")) { if (httpRequest.RequestParams["momsg"].ToString().ToLower().StartsWith("8dm") && httpRequest.RequestParams["spnumber"].ToString().ToLower().Equals("106268001")) { httpRequest.RequestParams["spnumber"] = "106268000"; } } } //如果状态报告通道 if (channel.RecStatReport.HasValue && channel.RecStatReport.Value) { RequestError requestError1 = new RequestError(); bool result1 = false; //分类型请求 if (channel.HasRequestTypeParams.HasValue && channel.HasRequestTypeParams.Value) { //报告状态请求 if (httpRequest.IsRequestContainValues(channel.RequestTypeParamName, channel.RequestReportTypeValue)) { if (httpRequest.IsRequestContainValues(channel.StatParamsName, channel.StatParamsValues)) { result1 = channel.RecState(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString(), out requestError1); } else { //channel.SaveStatReport(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString()); context.Response.Write(channel.GetOkCode(httpRequest)); return; } } //发送数据请求 else if (httpRequest.IsRequestContainValues(channel.RequestTypeParamName, channel.RequestDataTypeValue)) { result1 = channel.ProcessStateRequest(httpRequest, out requestError1); } else { LogWarnInfo(httpRequest, "未知类型请求", channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); return; } } else { if (httpRequest.RequestParams.ContainsKey(channel.StatParamsName.ToLower())) { if (httpRequest.IsRequestContainValues(channel.StatParamsName, channel.StatParamsValues)) { if (channel.StatSendOnce.HasValue && channel.StatSendOnce.Value) { result1 = channel.ProcessRequest(httpRequest, out requestError1); } else { result1 = channel.RecState(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString(), out requestError1); } } else { //channel.SaveStatReport(httpRequest, httpRequest.RequestParams[channel.StatParamsName.ToLower()].ToString()); context.Response.Write(channel.GetOkCode(httpRequest)); return; } } else { result1 = channel.ProcessStateRequest(httpRequest, out requestError1); } } //正确数据返回OK if (result1) { context.Response.Write(channel.GetOkCode(httpRequest)); return; } //重复数据返回OK if (requestError1.ErrorType == RequestErrorType.RepeatLinkID) { logger.Warn(requestError1.ErrorMessage); context.Response.Write(channel.GetOkCode(httpRequest)); return; } //其他错误类型记录错误请求 LogWarnInfo(httpRequest, requestError1.ErrorMessage, channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); return; } RequestError requestError; bool result = channel.ProcessRequest(httpRequest, out requestError); if (result) { context.Response.Write(channel.GetOkCode(httpRequest)); return; } //重复数据返回OK if (requestError.ErrorType == RequestErrorType.RepeatLinkID) { logger.Warn(requestError.ErrorMessage); context.Response.Write(channel.GetOkCode(httpRequest)); return; } LogWarnInfo(httpRequest, requestError.ErrorMessage, channel.Id, 0); context.Response.Write(channel.GetFailedCode(httpRequest)); } catch (Exception ex) { try { IHttpRequest failRequest = new HttpGetPostRequest(context.Request); string errorMessage = "处理请求失败:\n错误信息:" + ex.Message ; logger.Error(errorMessage + "\n请求信息:\n" + failRequest.RequestData, ex); if (saveLogFailedRequestToDb) SPFailedRequestWrapper.SaveFailedRequest(failRequest, errorMessage, 0, 0); } catch (Exception e) { logger.Error("处理请求失败:\n错误信息:" + e.Message); } } }
public async Task Process(SocketUserMessage msg) { FusionBotConfig cfg = ((FusionBotConfig)Globals.Bot.Config); if (!cfg.UserWalletCache.ContainsKey(msg.Author.Id)) { await AccountHelper.CreateNewAccount(msg); } else { double betAmount; if (!AccountHelper.ParseDoubleFromMessage(msg, out betAmount)) { await Sender.PublicReply(msg, "Oof. No good. You didn't say how much you want to bet."); return; } ulong totalAmount = betAmount.ToAtomicUnits() + (0.1d).ToAtomicUnits(); //both parties must have the amount + 0.1xnv to cover potential fees uint playerAccountIndex = cfg.UserWalletCache[msg.Author.Id].Item1; string playerAddress = cfg.UserWalletCache[msg.Author.Id].Item2; ulong playerBalance = 0; string fusionAddress = cfg.UserWalletCache[cfg.BotId].Item2; ulong fusionBalance = 0; //get balance of player wallet await new GetBalance(new GetBalanceRequestData { AccountIndex = cfg.UserWalletCache[msg.Author.Id].Item1 }, (GetBalanceResponseData result) => { playerBalance = result.UnlockedBalance; }, (RequestError e) => { Sender.PrivateReply(msg, "Oof. No good. You are going to have to try again later.").Wait(); }, cfg.WalletHost, cfg.UserWalletPort).RunAsync(); //get balance of fusion wallet await new GetBalance(new GetBalanceRequestData { AccountIndex = cfg.UserWalletCache[cfg.BotId].Item1 }, (GetBalanceResponseData result) => { fusionBalance = result.UnlockedBalance; }, (RequestError e) => { Sender.PrivateReply(msg, "Oof. No good. You are going to have to try again later.").Wait(); }, cfg.WalletHost, cfg.UserWalletPort).RunAsync(); if (playerBalance < totalAmount) { await Sender.PublicReply(msg, "You ain't got enough cash. Maybe you need gamblers anonymous? :thinking:"); return; } if (fusionBalance < totalAmount) { await Sender.PublicReply(msg, "Hold on high roller! I can't cover that :whale:"); return; } double d = MathHelper.Random.NextDouble(); if (d > 0.5d) //payout { RequestError err = await AccountHelper.PayUser(betAmount, cfg.BotId, msg.Author.Id); await HandlePayoutResult(msg, true, err); } else //take it { RequestError err = await AccountHelper.PayUser(betAmount, msg.Author.Id, cfg.BotId); await HandlePayoutResult(msg, false, err); } } }
//---------------------------------------------------------------------------- /// <summary> /// Устанавливает режим транзакции запрос-ответ /// </summary> private void StartTransaction( Modbus.OSIModel.Transaction.TransactionType type) { if (_transaction == TransactionType.Undefined) { if ((_MaskOfMessageLog & TypeOfMessageLog.Information) == TypeOfMessageLog.Information) { Trace.TraceInformation("{0}: Поток ID: {1} : Старт транзакции", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId); } //_incomingBuffer.Clear(); _serialPort.DiscardInBuffer(); _serialPort.DiscardOutBuffer(); _transaction = type; _error = RequestError.NoError; } else { if ((_MaskOfMessageLog & TypeOfMessageLog.Information) == TypeOfMessageLog.Information) { Trace.TraceError("{0}: Поток ID: {1} : Попытка начать новую транзакцию во время текущей транзакции", DateTime.Now.ToLongTimeString(), Thread.CurrentThread.ManagedThreadId); } throw new Exception("Попытка начать новую транзакцию во время текущей транзакции"); } return; }
private void OnRequestFail(RequestError error) { // process error UnityEngine.Debug.Log("OnRequestError: " + error.Description); }
private void PrintResponse(Result result, RequestError[] requestErrors) { if(result == Result.REQUEST_SUCCESSFUL) { Console.WriteLine(Result.REQUEST_SUCCESSFUL.ToString()); } else { Console.WriteLine(Result.REQUEST_FAILED.ToString()); Console.WriteLine("Number of Errors: " + requestErrors.Length); foreach(RequestError error in requestErrors) { Console.WriteLine(error.ErrorCode + ":" + error.ErrorMessage); } } }
private RequestResult(bool succeeded, RequestError errorType, IEnumerable <string> errors) : base(succeeded, errorType, errors) { }
public static RequestResult Fail(RequestError errorType, string error) => new RequestResult(false, errorType, new string[] { error });