private void BtnEncrypt_Click(object sender, EventArgs e) { string userName = txtUserName.Text, password = txtPassword.Text; if (string.IsNullOrWhiteSpace(userName) || string.IsNullOrWhiteSpace(password)) { MessageBox.Show("Type both fields", "Information", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } try { Cursor.Current = Cursors.WaitCursor; ToggleControls(); var encryptDecrypt = _service.EncryptAndDecrypt(userName, password); txtAES.Text = encryptDecrypt.EncryptedUserName; txtRSA.Text = encryptDecrypt.EncryptedPassword; ToggleControls(); Cursor.Current = Cursors.Default; } catch (Exception ex) { ExceptionHandlerHelper.ExceptionHandler(ex); } }
async void HandleCompletedAcceptAsync(Task <IConnection> antecendant) { IConnection connection = null; using (await ThisLock.TakeLockAsync()) { bool success = false; Exception unexpectedException = null; try { if (!isDisposed) { connection = await antecendant; if (connection != null) { connections++; } } success = true; } catch (CommunicationException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } if ((errorCallback == null) && !ExceptionHandlerHelper.HandleTransportExceptionHelper(exception)) { throw; } unexpectedException = exception; } finally { if (!success) { connection = null; } pendingAccepts--; } if ((unexpectedException != null) && (errorCallback != null)) { errorCallback(unexpectedException); } } AcceptIfNecessaryAsync(false); if (connection != null) { callback(connection, onConnectionDequeued); } }
public void SetUp() { _defaultHttpContext = new DefaultHttpContext(); _defaultHttpContext.Response.Body = new MemoryStream(); _mockExceptionHandlerFeature = new Mock <IExceptionHandlerFeature>(); _defaultHttpContext.Features.Set(_mockExceptionHandlerFeature.Object); _mockLogger = new Mock <ILogger <Startup> >(); _exceptionHandlerHelper = new ExceptionHandlerHelper(); }
async void AcceptIfNecessaryAsync(bool startAccepting) { if (IsAcceptNecessary) { using (await ThisLock.TakeLockAsync()) { while (IsAcceptNecessary) { Exception unexpectedException = null; try { var acceptTask = listener.AcceptAsync(); // Assigning task to variable to supress warning about not awaiting the task var continuation = acceptTask.ContinueWith( handleCompletedAcceptAsync, CancellationToken.None, TaskContinuationOptions.RunContinuationsAsynchronously, // don't block our accept processing loop ActionItem.IOTaskScheduler); // Run the continuation on the IO Thread Scheduler. Protects against thread starvation pendingAccepts++; } catch (CommunicationException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } catch (Exception exception) { if (Fx.IsFatal(exception)) { throw; } if (startAccepting) { // Since we're under a call to StartAccepting(), just throw the exception up the stack. throw; } if ((errorCallback == null) && !ExceptionHandlerHelper.HandleTransportExceptionHelper(exception)) { throw; } unexpectedException = exception; } if ((unexpectedException != null) && (errorCallback != null)) { errorCallback(unexpectedException); } } } } }
public async Task <PasswordOAuthContext> Login(IAuthRequestData <PasswordAuthData> authRequest) { var factory = new GameClientFactory(_baseUri); var request = factory.CreateRequest("/token"); request.AddHeader("Content-Type", "application/x-www-form-urlencoded"); request.AddParameter("grant_type", "password"); request.AddParameter("username", authRequest.RequestData.Usename); request.AddParameter("password", authRequest.RequestData.Password); var client = new GameClientFactory(_baseUri).CreateClient(); client.AddHandler("application/json", CustomJsonDeserializer.Default); client.AddHandler("text/javascript", CustomJsonDeserializer.Default); IRestResponse <OAuthPasswordResponseData> stringToken = null; try { stringToken = await client.ExecutePostTaskAsync <OAuthPasswordResponseData>(request); } catch (Exception exception) { _logger.Error(exception); } if (stringToken.ErrorException != null) { ExceptionHandlerHelper.HandleHttpRequestException(stringToken.ErrorException); } if ( new HttpStatusCode[] { HttpStatusCode.BadRequest, HttpStatusCode.Forbidden, HttpStatusCode.Unauthorized, HttpStatusCode.BadGateway, HttpStatusCode.InternalServerError }.Contains(stringToken.StatusCode)) { HandleNotSuccessRequest(authRequest.RequestData, stringToken); } return(new PasswordOAuthContext() { Context = new OAuth2AuthorizationRequestHeaderAuthenticator(stringToken.Data.AccessToken, stringToken.Data.TokenType), OAuthToken = stringToken.Data.AccessToken, BaseUri = _baseUri }); }
public static JsonResult HandleExceptions(this HttpResponse response, BaseException e) { var className = e.GetType().Name; switch (className) { case "UnprocessableException": return(response.UnprocessableEntity(ExceptionHandlerHelper.ExceptionMessage(e))); case "BadRequestException": return(response.BadRequest(ExceptionHandlerHelper.ExceptionMessage(e))); case "NotFoundException": return(response.NotFound(ExceptionHandlerHelper.ExceptionMessage(e))); default: return(response.InternalServerError()); } }
public async Task <ActionResult> LogInUser(string user, string password) { try { LogInDto objUser = await _clientesService.LogInUser(user, password); return(Response.Ok(objUser)); } catch (BaseException e) { _logger.LogInformation(ExceptionHandlerHelper.ExceptionMessageStringToLogger(e)); return(Response.HandleExceptions(e)); } catch (Exception e) { _logger.LogError(e, GetType().Name + "." + MethodBase.GetCurrentMethod().Name); return(Response.InternalServerError()); } }
public async Task <ActionResult> GetGarageById(int garageId) { try { GarageDto garageDto = await _garageService.GetGarageById(garageId); return(Response.Ok(garageDto)); } catch (BaseException e) { _logger.LogInformation(ExceptionHandlerHelper.ExceptionMessageStringToLogger(e)); return(Response.HandleExceptions(e)); } catch (Exception e) { _logger.LogError(e, GetType().Name + "." + MethodBase.GetCurrentMethod().Name); return(Response.InternalServerError()); } }
public async Task <ActionResult> Localidades() { try { List <LocalidadesDto> listaLocalidades = await _garageService.Localidades(); return(Response.Ok(listaLocalidades)); } catch (BaseException e) { _logger.LogInformation(ExceptionHandlerHelper.ExceptionMessageStringToLogger(e)); return(Response.HandleExceptions(e)); } catch (Exception e) { _logger.LogError(e, GetType().Name + "." + MethodBase.GetCurrentMethod().Name); return(Response.InternalServerError()); } }
public async Task <ActionResult> GetGarages([FromQuery] string vehiculo, [FromQuery] int?localidad) { try { List <GarageDto> garageList = await _garageService.GetGarages(vehiculo, localidad); return(Response.Ok(garageList)); } catch (BaseException e) { _logger.LogInformation(ExceptionHandlerHelper.ExceptionMessageStringToLogger(e)); return(Response.HandleExceptions(e)); } catch (Exception e) { _logger.LogError(e, GetType().Name + "." + MethodBase.GetCurrentMethod().Name); return(Response.InternalServerError()); } }
public async Task <ActionResult> SaveUser(UserDto userDto) { try { await _clientesService.SaveUser(userDto); return(Response.Ok()); } catch (BaseException e) { _logger.LogInformation(ExceptionHandlerHelper.ExceptionMessageStringToLogger(e)); return(Response.HandleExceptions(e)); } catch (Exception e) { _logger.LogError(e, GetType().Name + "." + MethodBase.GetCurrentMethod().Name); return(Response.InternalServerError()); } }
async Task ReadAndDispatchAsync() { bool success = false; try { while ((size > 0 || !isReadPending) && !IsClosed) { if (size == 0) { isReadPending = true; size = await Connection.ReadAsync(0, connectionBuffer.Length, GetRemainingTimeout()); offset = 0; isReadPending = false; if (size == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException()); } } int bytesRead = decoder.Decode(connectionBuffer, offset, size); if (bytesRead > 0) { offset += bytesRead; size -= bytesRead; } if (decoder.CurrentState == ServerSingletonDecoder.State.PreUpgradeStart) { via = decoder.Via; var validated = await Connection.ValidateAsync(via); if (!ContinuePostValidationProcessing()) { // This goes through the failure path (Abort) even though it doesn't throw. return; } break; //exit loop, set success=true; } } success = true; } catch (CommunicationException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } catch (TimeoutException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ExceptionHandlerHelper.HandleTransportExceptionHelper(e)) { throw; } // containment -- we abort ourselves for any error, no extra containment needed } finally { if (!success) { Abort(); } } }
void OnConnectionModeKnownCore(ConnectionModeReader modeReader, bool isCached) { lock (ThisLock) { if (isDisposed) { return; } connectionReaders.Remove(modeReader); } bool closeReader = true; try { FramingMode framingMode; try { framingMode = modeReader.GetConnectionMode(); } catch (CommunicationException exception) { TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } catch (TimeoutException exception) { if (!isCached) { exception = new TimeoutException(SR.Format(SR.ChannelInitializationTimeout, channelInitializationTimeout), exception); ErrorBehaviorHelper.ThrowAndCatch(exception); } TraceEventType eventType = modeReader.Connection.ExceptionEventType; DiagnosticUtility.TraceHandledException(exception, eventType); return; } switch (framingMode) { case FramingMode.Duplex: OnDuplexConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; case FramingMode.Singleton: OnSingletonConnection(modeReader.Connection, modeReader.ConnectionDequeuedCallback, modeReader.StreamPosition, modeReader.BufferOffset, modeReader.BufferSize, modeReader.GetRemainingTimeout()); break; default: { Exception inner = new InvalidDataException(SR.Format( SR.FramingModeNotSupported, framingMode)); Exception exception = new ProtocolException(inner.Message, inner); FramingEncodingString.AddFaultString(exception, FramingEncodingString.UnsupportedModeFault); ErrorBehaviorHelper.ThrowAndCatch(exception); return; } } closeReader = false; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ExceptionHandlerHelper.HandleTransportExceptionHelper(e)) { throw; } // containment -- the reader is aborted, no need for additional containment } finally { if (closeReader) { modeReader.Dispose(); } } }
async void ContinueReadingAsync() { bool success = false; try { for (;;) { if (size == 0) { offset = 0; size = await Connection.ReadAsync(0, connectionBuffer.Length, GetRemainingTimeout()); if (size == 0) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(decoder.CreatePrematureEOFException()); } } int bytesDecoded = decoder.Decode(connectionBuffer, offset, size); if (bytesDecoded > 0) { offset += bytesDecoded; size -= bytesDecoded; } if (decoder.CurrentState == ServerSessionDecoder.State.PreUpgradeStart) { via = decoder.Via; if (await Connection.ValidateAsync(via)) { settings = transportSettingsCallback(via); if (settings == null) { EndpointNotFoundException e = new EndpointNotFoundException(SR.Format(SR.EndpointNotFound, decoder.Via)); DiagnosticUtility.TraceHandledException(e, TraceEventType.Information); SendFault(FramingEncodingString.EndpointNotFoundFault); // This goes through the failure path (Abort) even though it doesn't throw. return; } // we have enough information to hand off to a channel. Our job is done callback(this); } break; //exit loop, set success=true; } } success = true; } catch (CommunicationException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } catch (TimeoutException exception) { DiagnosticUtility.TraceHandledException(exception, TraceEventType.Information); } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } if (!ExceptionHandlerHelper.HandleTransportExceptionHelper(e)) { throw; } // containment -- all exceptions abort the reader, no additional containment action necessary } finally { if (!success) { Abort(); } } }