internal static async Task <IResponse> PutResponseAsync <TInput>(this HttpClient client, string path, TInput value, MediaFormat mediaFormat) { try { using (var request = Helpers.HttpRequestHelper.CreateRequest(HttpMethod.Put, path)) { request.AttachObjectContent(value, mediaFormat); using (var response = await client.ExecuteRequestAsync(request, CancellationToken.None)) { return(await response.PrepareResponseAsync()); } } } catch (Exception ex) { if (ex is OperationCanceledException) { return(ResponseFactory.Exception(ex)); } return(ResponseFactory.Exception(ex, new List <string> { StaticResources.ExecutionFailureMessage, ex.Message })); } }
internal static async Task <IResponse <TOutput> > DeleteResponseAsync <TOutput>(this HttpClient client, string path) { try { using (var request = Helpers.HttpRequestHelper.CreateRequest(HttpMethod.Delete, path)) { using (var response = await client.ExecuteRequestAsync(request, CancellationToken.None)) { return(await response.PrepareResponseAsync <TOutput>()); } } } catch (Exception ex) { if (ex is OperationCanceledException) { return(ResponseFactory <TOutput> .Exception(ex)); } return(ResponseFactory <TOutput> .Exception(ex, new List <string> { StaticResources.ExecutionFailureMessage, ex.Message })); } }
internal static async Task <IResponse <TOutput> > ExecuteFuncOutputAsync <TOutput>( Func <TOutput> func) { try { if (func == null) { return(ResponseFactory <TOutput> .Error("The provided func is null", ErrorResponseStatus.BadRequest)); } var result = await Task.Run(func); var taskDetail = result as Task; if (taskDetail != null && taskDetail.Status == TaskStatus.Canceled) { throw new OperationCanceledException(); } return(ResponseFactory <TOutput> .Ok(result)); } catch (Exception ex) { return(ResponseFactory <TOutput> .Exception(ex)); } }
/// <summary> /// <para>Submits all changes in the context and returns IResponse</para> /// </summary> public IResponse <int> SaveChangesResponse() { try { var readonlyValidationResponse = ValidateReadonlyModels(); if (!readonlyValidationResponse.Success) { return(ResponseFactory <int> .Convert(readonlyValidationResponse)); } var save = Context.SaveChanges(); return(ResponseFactory <int> .Ok(save)); } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); return(ResponseFactory <int> .Exception(ex, errorMessages.ToList())); } catch (Exception ex) { return(ResponseFactory <int> .Exception(ex)); } }
/// <summary> /// <para>Submits all changes in the context and returns IResponse</para> /// </summary> public async Task <IResponse <int> > SaveChangesResponseAsync(CancellationToken cancellationToken) { try { //Check if any readonly entities are modified var readonlyValidationResponse = ValidateReadonlyModels(); if (!readonlyValidationResponse.Success) { return(ResponseFactory <int> .Convert(readonlyValidationResponse)); } var save = await Context.SaveChangesAsync(cancellationToken); return(ResponseFactory <int> .Ok(save)); } catch (DbEntityValidationException ex) { var errorMessages = ex.EntityValidationErrors .SelectMany(x => x.ValidationErrors) .Select(x => x.ErrorMessage); return(ResponseFactory <int> .Exception(ex, errorMessages.ToList())); } catch (Exception ex) { return(ResponseFactory <int> .Exception(ex)); } }
/// <summary> /// <para>Submits all changes in the context and returns IResponse</para> /// </summary> public IResponse <int> SaveChangesResponse() { try { var readonlyValidationResponse = ValidateReadonlyModels(); if (!readonlyValidationResponse.Success) { return(ResponseFactory <int> .Convert(readonlyValidationResponse)); } var save = Context.SaveChanges(); return(ResponseFactory <int> .Ok(save)); } //TODO: Replace this a proper exception to extract error detail //catch (DbEntityValidationException ex) //{ // var errorMessages = ex.EntityValidationErrors // .SelectMany(x => x.ValidationErrors) // .Select(x => x.ErrorMessage); // return ResponseFactory<int>.Exception(ex, errorMessages.ToList()); //} catch (Exception ex) { return(ResponseFactory <int> .Exception(ex)); } }
/// <summary> /// <para>Submits all changes in the context and returns IResponse</para> /// </summary> public async Task <IResponse <int> > SaveChangesResponseAsync(CancellationToken cancellationToken = default) { try { //Check if any readonly entities are modified var readonlyValidationResponse = ValidateReadonlyModels(); if (!readonlyValidationResponse.Success) { return(ResponseFactory <int> .Convert(readonlyValidationResponse)); } var save = await Context.SaveChangesAsync(cancellationToken); return(ResponseFactory <int> .Ok(save)); } //TODO: Replace this a proper exception to extract error detail //catch (DbEntityValidationException ex) //{ // var errorMessages = ex.EntityValidationErrors // .SelectMany(x => x.ValidationErrors) // .Select(x => x.ErrorMessage); // return ResponseFactory<int>.Exception(ex, errorMessages.ToList()); //} catch (Exception ex) { return(ResponseFactory <int> .Exception(ex)); } }
/// <summary> /// Executes a <see cref="Func{Task}"/> which returns a <see cref="Task{TOutput}"/> /// </summary> /// <param name="processor"><see cref="Processor"/></param> /// <param name="func">The function to execute</param> /// <returns><see cref="IResponse"/></returns> public static IResponse <TOutput> Process <TOutput>(this Processor processor, Func <Task <TOutput> > func) { if (processor == null) { var processNullMessage = $"The provided {nameof(processor)} is null."; SweetAlerts.Alert(string.Empty, processNullMessage, AlertButtons.Ok, AlertType.Error); return(ResponseFactory <TOutput> .Error(processNullMessage, ErrorResponseStatus.BadRequest)); } try { using (var form = new FuncOutputExecutorTask <TOutput> { ParentControl = processor.ParentControl, FormTitle = processor.OperationTitle, CanRetry = processor.CanRetry, ShowSuccessMessage = processor.ReportSuccess, IgnoreResponseMessage = processor.IgnoreResponseMessage, SuccessMessage = processor.SuccessMessage, Func = func, CancellationTokenSource = processor.CancellationTokenSource, FormImage = Properties.Resources.rolling, ProgressObject = processor.ProgressObject }) { form.ShowDialog(); return(form.Response as IResponse <TOutput>); } } catch (Exception ex) { return(ResponseFactory <TOutput> .Exception(ex)); } }
/// <summary> /// Executes a function /// </summary> /// <param name="processor">The <see cref="Processor"/></param> /// <param name="func">The function to execute</param> /// <returns><see cref="IResponse"/></returns> public static IResponse Process(this Processor processor, Func <IResponse> func) { if (processor == null) { var processNullMessage = $"The provided {nameof(processor)} is null."; SweetAlerts.Alert(HelperMethods.GetCurrentlyActiveForm(), string.Empty, processNullMessage, AlertButtons.Ok, AlertType.Error); return(ResponseFactory.Error(processNullMessage, ErrorResponseStatus.BadRequest)); } try { using (var form = new FuncOutputResponseExecutor { ParentControl = HelperMethods.GetCurrentlyActiveForm(processor.ParentControl), FormTitle = processor.OperationTitle, CanRetry = processor.CanRetry, ShowSuccessMessage = processor.ReportSuccess, IgnoreResponseMessage = processor.IgnoreResponseMessage, SuccessMessage = processor.SuccessMessage, Func = func, CancellationTokenSource = processor.CancellationTokenSource, FormImage = Properties.Resources.rolling, ProgressObject = processor.ProgressObject }) { form.ShowDialog(HelperMethods.GetCurrentlyActiveForm(processor.ParentControl)); return(form.Response); } } catch (Exception ex) { return(ResponseFactory.Exception(ex)); } }
public void Response_Operation_Cancelled() { var cancelledResponse = ResponseFactory.Exception(new OperationCanceledException("Operation has been cancelled")); Assert.IsFalse(cancelledResponse.Success); Assert.IsTrue(cancelledResponse.Cancelled); Assert.AreEqual(ResponseStatus.BadRequest, cancelledResponse.Status); }
internal static async Task <IResponse <Stream> > GetStreamResponseAsync(this HttpClient client, string path, MediaFormat mediaFormat) { try { using (var request = Helpers.HttpRequestHelper.CreateRequest(HttpMethod.Get, path)) { using (var response = await client.ExecuteRequestAsync(request, CancellationToken.None)) { var status = response.StatusCode; var reasonPhrase = response.ReasonPhrase; var contentType = response.Content.Headers.ContentType; if (contentType != null && response.IsInResponsibleFormat()) { var resultObjectFromMultiPart = await response.Content.ReadAsMultipartAsync(); var messagesFromMultiPart = await resultObjectFromMultiPart.Contents[0].ReadAsAsync <List <ServiceMessage> >(); Stream streamResult = null; if (resultObjectFromMultiPart.Contents.Count > 1) { streamResult = await resultObjectFromMultiPart.Contents[1].ReadAsStreamAsync(); } return(ResponseFactory <Stream> .Custom((ResponseStatus)status, messagesFromMultiPart.Select(m => m.Message).ToList(), streamResult)); } if (response.IsSuccessStatusCode) { var resultObject = await response.Content.ReadAsStreamAsync(); return(ResponseFactory <Stream> .Custom((ResponseStatus)status, resultObject)); } return(ResponseFactory <Stream> .Custom((ResponseStatus)status, $"Status: {status} - ReasonPhrase: {reasonPhrase}")); } } } catch (Exception ex) { if (ex is OperationCanceledException) { return(ResponseFactory <Stream> .Exception(ex)); } return(ResponseFactory <Stream> .Exception(ex, new List <string> { StaticResources.ExecutionFailureMessage, ex.Message })); } }
public static IResponse <List <Customer> > Find(string name) { try { var result = new CustomersData().Find(name); return(ResponseFactory <List <Customer> > .Ok(result, $"{result.Count} records found.")); } catch (Exception ex) { return(ResponseFactory <List <Customer> > .Exception(ex)); } }
public void Response_Operation_Exception_DetaildError() { var cancelledResponse = ResponseFactory.Exception(new InvalidOperationException("Invalid Operation Exception")); Assert.IsFalse(cancelledResponse.Success); Assert.IsFalse(cancelledResponse.Cancelled); Assert.AreEqual(ResponseStatus.InternalServerError, cancelledResponse.Status); Assert.AreEqual("Invalid Operation Exception", cancelledResponse.Messages.ToList()[0], "Message is not the same"); var detailedMessage = $"Error Detail:{Environment.NewLine}{cancelledResponse.SingleMessage}StackTrace:{Environment.NewLine}{cancelledResponse.Exception.StackTrace}"; Assert.AreEqual(detailedMessage, cancelledResponse.DetailedError, "Detailed Message is not the same"); }
internal static async Task <IResponse> PrepareResponseAsync(this HttpResponseMessage response) { try { if (response == null) { return(ResponseFactory.Error( $"Specified {nameof(HttpResponseMessage)} is null, could not create {nameof(IResponse)}.", ErrorResponseStatus.BadRequest)); } var status = response.StatusCode; var reasonPhrase = response.ReasonPhrase; var contentType = response.Content.Headers.ContentType; if (contentType != null && response.IsInResponsibleFormat()) { var multiContent = await response.Content.ReadAsMultipartAsync(); var multiMessages = await multiContent.Contents[0].ReadAsAsync <List <ServiceMessage> >(); return(ResponseFactory.Custom((ResponseStatus)status, multiMessages.Select(m => m.Message).ToList())); } var responseContent = await TryToCastResponseToAString(response); if (!string.IsNullOrWhiteSpace(responseContent)) { return(ResponseFactory.Custom((ResponseStatus)status, new List <string> { $"Status: {status} - ReasonPhrase: {reasonPhrase}", $"{responseContent}" })); } return(ResponseFactory.Custom((ResponseStatus)status, $"Status: {status} - ReasonPhrase: {reasonPhrase}")); } catch (Exception ex) { if (ex is OperationCanceledException) { return(ResponseFactory.Exception(ex)); } return(ResponseFactory.Exception(ex, new List <string> { StaticResources.ExecutionFailureMessage, ex.Message })); } }
public static IResponse <int> Add(Customer customer) { try { if (customer == null) { return(ResponseFactory <int> .Error("Invalid customer data.", ErrorResponseStatus.BadRequest)); } var customerId = new CustomersData().Add(customer); return(ResponseFactory <int> .Ok(customerId, "Customer has been added.")); } catch (Exception ex) { return(ResponseFactory <int> .Exception(ex)); } }
public static IResponse <Customer> Get(int id) { try { var result = new CustomersData().Get(id); if (result == null) { return(ResponseFactory <Customer> .Error($"Could not find a record with Id: {id}", ErrorResponseStatus.NotFound)); } return(ResponseFactory <Customer> .Ok(result)); } catch (Exception ex) { return(ResponseFactory <Customer> .Exception(ex)); } }
internal static async Task <IResponse> ExecuteActionAsync(Action action) { try { if (action == null) { return(ResponseFactory.Error("The provided action is null", ErrorResponseStatus.BadRequest)); } await Task.Run(() => action.Invoke()); return(ResponseFactory.Ok()); } catch (Exception ex) { return(ResponseFactory.Exception(ex)); } }
internal static async Task <IResponse <TOutput> > ExecuteFuncOutputResponseAsync <TOutput>( Func <IResponse <TOutput> > func) { try { if (func == null) { return(ResponseFactory <TOutput> .Error("The provided func is null", ErrorResponseStatus.BadRequest)); } var result = await Task.Run(func); return(result); } catch (Exception ex) { return(ResponseFactory <TOutput> .Exception(ex)); } }
/// <summary> /// Creates an <see cref="HttpResponseMessage"/> with <see cref="HttpStatusCode.InternalServerError"/> /// and the message <see cref="DefaultErrorMessage"/> /// </summary> /// <param name="actionExecutedContext"></param> protected virtual void CreateErrorResponse(HttpActionExecutedContext actionExecutedContext) { var exceptionResponse = ResponseFactory.Exception(DefaultErrorMessage); actionExecutedContext.Response = ResponseGenerator.CreateResponse(actionExecutedContext.Request, exceptionResponse); }
internal static async Task <IResponse <T> > PrepareResponseAsync <T>(this HttpResponseMessage response) { try { if (response == null) { return(ResponseFactory <T> .Error( $"Specified {nameof(HttpResponseMessage)} is null, could not create {nameof(IResponse<T>)}.", ErrorResponseStatus.BadRequest)); } var status = response.StatusCode; var reasonPhrase = response.ReasonPhrase; var contentType = response.Content.Headers.ContentType; if (contentType != null && response.IsInResponsibleFormat()) { var resultObjectFromMultiPart = await response.Content.ReadAsMultipartAsync(); var messagesFromMultiPart = await resultObjectFromMultiPart.Contents[0].ReadAsAsync <List <ServiceMessage> >(); var value = default(T); if (resultObjectFromMultiPart.Contents.Count > 1) { value = await resultObjectFromMultiPart.Contents[1].ReadAsAsync <T>(); } return(ResponseFactory <T> .Custom((ResponseStatus)status, messagesFromMultiPart.Select(m => m.Message).ToList(), value)); } if (response.IsSuccessStatusCode) { var resultObject = await response.Content.ReadAsAsync <T>(); return(ResponseFactory <T> .Custom((ResponseStatus)status, resultObject)); } var responseContent = await TryToCastResponseToAString(response); if (!string.IsNullOrWhiteSpace(responseContent)) { return(ResponseFactory <T> .Custom((ResponseStatus)status, new List <string> { $"Status: {status} - ReasonPhrase: {reasonPhrase}", $"{responseContent}" })); } return(ResponseFactory <T> .Custom((ResponseStatus)status, $"Status: {status} - ReasonPhrase: {reasonPhrase}")); } catch (Exception ex) { return(ResponseFactory <T> .Exception(ex, new List <string> { StaticResources.ExecutionFailureMessage, ex.Message })); } }