private void GeneralFailureCallback(FailureResponse response) { if (!IsStarted) { return; } LogFailureDetails(response, "general"); if (response.Message.Contains("(403) Forbidden")) { if ((DateTime.Now - _prevSessionBreak).TotalMinutes >= 1) { _prevSessionBreak = DateTime.Now; OnSessionDisconnected(); } } }
public virtual async Task <IHttpActionResult> Put(int CustomerId, string FirstName, string LastName, string EmailAddress, long MobileNumber, string Address) { try { var updateUser = await _userServices.updateUserAsync(CustomerId, FirstName, LastName, EmailAddress, MobileNumber, Address); return(Ok(ResponseUtil.GetResponse(true, updateUser, null))); } catch (Exception ex) { var response = new FailureResponse() { Message = Messages.FAILURE_MESSAGE_CREATEUSER, StatusCode = 400 }; return(Content(HttpStatusCode.BadRequest, ResponseUtil.GetResponse(false, null, response))); } }
public virtual async Task <IHttpActionResult> Post(OrderStatusModel orderStatusModel) { try { var createUser = await _orderStatusServices.createOrderAsync(orderStatusModel); return(Ok(ResponseUtil.GetResponse(true, createUser, null))); } catch (Exception ex) { var response = new FailureResponse() { Message = Messages.FAILURE_MESSAGE_CREATESALESUSER, StatusCode = 400 }; return(Content(HttpStatusCode.BadRequest, ResponseUtil.GetResponse(false, null, response))); } }
private async Task <Response> SafeProcessRequestAsync(GetRequestDelegate getRequestDelegate, UpdateRequestDelegate updateRequestDelegate, CreateRequestDelegate createRequestDelegate, Request request, BrokeredMessage message) { Response responseSent = null; try { Log.Verbose("{0} processing {1}", request.ClientName, request); var successResponse = ProcessRequest( getRequestDelegate, updateRequestDelegate, createRequestDelegate, request); await SendResponseAsync(successResponse); responseSent = successResponse; } catch (MovedException exception) { Log.Information(exception.Message); var failureResponse = new FailureResponse(request, exception.ErrorType) { Value = exception.NewKeyValue, Message = exception.Message, }; SendResponseAsync(failureResponse).Wait(); responseSent = failureResponse; } catch (ClientDataHasBeenUpdated exception) { Log.Information(exception.Message); if (exception.NewClientData != null) { exception.NewClientData.CalculateCheckSum(request.KeyValue); } var failureResponse = new FailureResponse(request, exception.ErrorType) { Value = exception.NewCheckSum, Data = exception.NewClientData, Message = exception.Message, }; SendResponseAsync(failureResponse).Wait(); responseSent = failureResponse; } catch (InternalServerErrorException exception) { Log.Critical(exception, "An internal server error has occured."); var failureResponse = new FailureResponse(request, FailureResponse.ErrorTypeEnum.InternalServerError) { Message = exception.ToString() }; SendResponseAsync(failureResponse).Wait(); responseSent = failureResponse; } catch (MatchException exception) { Log.Error(exception, "An error has occured"); var failureResponse = new FailureResponse(request, exception.ErrorType) { Message = exception.Message }; SendResponseAsync(failureResponse).Wait(); responseSent = failureResponse; } catch (SilentFailOnlyForTestingException) { #if DEBUG Log.Warning("Silent fail. This exception should only occur when running test cases."); #else Log.Critical("Silent fail. This exception should only occur when running test cases."); #endif } catch (Exception exception) { Log.Critical(exception, "An error not handled by the adapter has occured"); var failureResponse = new FailureResponse(request, FailureResponse.ErrorTypeEnum.AdapterDidNotHandleException) { Message = exception.ToString() }; SendResponseAsync(failureResponse).Wait(); responseSent = failureResponse; } // Try to complete this message since we should have sent a response, either success or failure at // this point. SafeCompleteAsync(message, request).Wait(); return(responseSent); }
private void OnLogoutFailure(FailureResponse failureResponse) { SendError <DisconnectMessage>(ToException(failureResponse, "Logout")); }
private void OnLoginFailure(FailureResponse failureResponse) { SendError <ConnectMessage>(ToException(failureResponse, "Login")); }
public bool Accept(FailureResponse failure) => Accept(failure as ResponseModel);
private static void FailureLoginCallback(FailureResponse args) => throw new InvalidCredentialException(args.Message, args.Exception);
/// <summary> /// Listen on the port for receiving incoming connections from clients /// </summary> public void Listen() { this.socket.Bind(new IPEndPoint(IPAddress.Any, servicePort)); this.socket.Listen(30); this.socket.ReceiveTimeout = 30000; this.socket.SendTimeout = 30000; var alive = true; while (alive) { var connection = this.socket.Accept(); // Start a new thread for the connection var thread = new Thread((o) => { var logger = Program.Logger; try { var recv = new byte[2048]; connection.Receive(recv); var received = Encoding.UTF8.GetString(recv); var request = ExecuteServiceServerRequest.FromMessage(received); logger.Write("Receiving service request : "); foreach (var line in Response.CleanContents(received).Split(Request.NewRow.ToCharArray())) { logger.Write(" >> {0}", line); } logger.Write("---"); // Check if client has security privileges, will throw exception otherwise var query = registryConnection.QueryTeam(request.Call.CallerTeamName, request.Call.CallerTeamId, tagName); var args = request.Call.Args; var provinceCode = args.Where(a => a.Name == ProvinceCode).Select(a => a.Value).FirstOrDefault(); var subtotal = double.Parse(args.Where(a => a.Name == SubTotal).Select(a => a.Value).FirstOrDefault()); var serviceResponse = new PurchaseTotallerResponse(provinceCode, subtotal); logger.Write("Responding to service request : "); foreach (var line in Response.CleanContents(serviceResponse.ToString()) .Split(Request.NewRow.ToCharArray())) { logger.Write(" >> {0}", line); } logger.Write("---"); var responseBytes = Encoding.UTF8.GetBytes(serviceResponse.ToHl7()); connection.Send(responseBytes); } catch (FailureResponseException ex) { // Send the client a failure response var response = new FailureResponse(ex.ErrorCode, ex.Message); logger.Write("Responding to service request : "); foreach (var line in Response.CleanContents(response.ToString()) .Split(Request.NewRow.ToCharArray())) { logger.Write(" >> {0}", line); } logger.Write("---"); var responseBytes = Encoding.UTF8.GetBytes(response.ToHl7()); connection.Send(responseBytes); } catch (Exception ex) { Program.Logger.Write(ex); // Send the client a failure response var response = new FailureResponse("-6", ex.Message); logger.Write("Responding to service request : "); foreach (var line in Response.CleanContents(response.ToString()) .Split(Request.NewRow.ToCharArray())) { logger.Write(" >> {0}", line); } logger.Write("---"); var responseBytes = Encoding.UTF8.GetBytes(response.ToHl7()); connection.Send(responseBytes); } finally { if (connection != null && connection.Connected) { connection.Disconnect(false); connection.Close(); } } }); thread.Start(connection); } }
private void LogFailureDetails(FailureResponse response, string failedAction) { var msg = $"{Name} {failedAction} failure: {response.Message} ({response.Description}). Exception details: {response.Exception?.Message}"; Logger.Warning(msg); }
private void LoginFailureCallback(FailureResponse response) { LogFailureDetails(response, "login"); throw new InvalidCredentialException($"Login failed for {AccountInfo.UserName} ({Name} broker)", response.Exception); }
private void ReconnectFailureCallback(FailureResponse response) { LogFailureDetails(response, "reconnection"); ThreadPool.QueueUserWorkItem(_ => Reconnect(30)); }
/// <summary> /// Gets application level statistics for all missing symbol groups /// </summary> /// <remarks> /// Gets application level statistics for all missing symbol groups /// </remarks> /// <param name='ownerName'> /// The name of the owner /// </param> /// <param name='appName'> /// The name of the application /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="FailureResponseException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task <HttpOperationResponse <MissingSymbolCrashGroupsInfoResponse> > InfoWithHttpMessagesAsync(string ownerName, string appName, Dictionary <string, List <string> > customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (ownerName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "ownerName"); } if (appName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "appName"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary <string, object> tracingParameters = new Dictionary <string, object>(); tracingParameters.Add("ownerName", ownerName); tracingParameters.Add("appName", appName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Info", tracingParameters); } // Construct URL var _baseUrl = Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "v0.1/apps/{owner_name}/{app_name}/symbol_groups_info").ToString(); _url = _url.Replace("{owner_name}", System.Uri.EscapeDataString(ownerName)); _url = _url.Replace("{app_name}", System.Uri.EscapeDataString(appName)); // Create HTTP transport objects var _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach (var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new FailureResponseException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); FailureResponse _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <FailureResponse>(_responseContent, Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new HttpOperationResponse <MissingSymbolCrashGroupsInfoResponse>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject <MissingSymbolCrashGroupsInfoResponse>(_responseContent, Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return(_result); }
public void Start() { InitializeResultsCache(); try { RestoreProgram(); Logging.Log("Restoring completed"); } catch (Exception e) { Logging.Log(e.Message); } ////////////////////////// if (myClient == null) { var currentTime = DateTime.Now; //SaveProgram(); //TODO: Analysis Console.WriteLine( $"Analysis completed in {DateTime.Now.Subtract(currentTime).TotalMilliseconds} milliseconds"); Console.ReadLine(); return; } /////////////////////////// myIsProcessing = true; var stream = myClient.GetStream(); var reader = new StreamReader(stream); var requestsSerializer = new DataContractSerializer(typeof(Request)); var responsesSerializer = new DataContractSerializer(typeof(Response)); //TODO: Errors processing while (myIsProcessing) { Response response = null; try { var rawMessage = reader.ReadLine(); Logging.LogXML(rawMessage); if (rawMessage == null) { myIsProcessing = false; continue; } Request request; using (var stringReader = new StringReader(rawMessage)) using (var xmlReader = XmlReader.Create(stringReader)) { request = (Request)requestsSerializer.ReadObject(xmlReader); } response = ProcessMessage(request); } catch (Exception e) { Console.WriteLine(e); response = new FailureResponse(); } try { using (var stringWriter = new StringWriter()) using (var xmlWriter = XmlWriter.Create(stringWriter)) { responsesSerializer.WriteObject(xmlWriter, response); xmlWriter.Flush(); var serialized = stringWriter.ToString(); Logging.LogXML(serialized); //TODO: Make new line sending more accurate responsesSerializer.WriteObject(stream, response); stream.Write(new[] { (byte)'\n' }, 0, 1); stream.Flush(); } } catch (Exception e) { Console.WriteLine(e); } } }