using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; using iiie.Logs.DataAccess; using iiie.Logs.DBO; using iiie.WebApiUtils.DBO; namespace iiie.WebApiUtils.BusinessManager { /// /// Handle business manager results /// public class BMRHandler : ApiController { /// /// Converts ResultStatus codes to HttpStatusCodes codes /// /// The status code /// The http code public static HttpStatusCode ResultStatusToHttp(ResultStatus status) { if (status == ResultStatus.LoginError) return HttpStatusCode.Unauthorized; if (status == ResultStatus.PermissionError) return HttpStatusCode.Forbidden; if (status == ResultStatus.InputError) return HttpStatusCode.BadRequest; if (status == ResultStatus.NotFound) return HttpStatusCode.NotFound; return HttpStatusCode.InternalServerError; } /// /// Returns a string corresponding to the error /// /// The result of the operation /// The error string public static string OpResultToString(OpResult result) { if (result.PublicDetails != null) return result.PublicDetails; if (result.Status == ResultStatus.LoginError) return "Bad username/password"; if (result.Status == ResultStatus.PermissionError) return "You don\'t have the permission to do this action"; if (result.Status == ResultStatus.InputError) return "Invalid data was provided"; if (result.Status == ResultStatus.NotFound) return "Ressource not found"; return "Internal error"; } /// /// Handle business manager results /// /// The result to handle /// The data to return to the user [NonAction] public T Handle(OpResult result) { if (result.Status == ResultStatus.Success) return result.Data; result.Log(); var msg = Request.CreateErrorResponse(ResultStatusToHttp(result.Status), OpResultToString(result)); throw new HttpResponseException(msg); } /// /// Handle business manager results /// /// The result to handle /// The data to return to the user [NonAction] public DboGetSingle HandleSingle(OpResult result) { return new DboGetSingle { Value = Handle(result) }; } /// /// Save the uploaded file to the temp dir /// /// The file path [NonAction] public async Task> SaveFileToTemp(string name = null) { IEnumerable parts = null; try { Task.Factory.StartNew(() => parts = Request.Content.ReadAsMultipartAsync().Result.Contents, CancellationToken.None, TaskCreationOptions.LongRunning, TaskScheduler.Default).Wait(); } catch (Exception e) { return OpResult.Error(ResultStatus.InputError, e, "Failed to read post parts (maximum size exceeded?)"); } HttpContent file = parts.FirstOrDefault(x => name == null || (x.Headers.ContentDisposition != null && x.Headers.ContentDisposition.Name.Trim('"') == name)); if (file == null) { return OpResult.Error(ResultStatus.InputError, "No uploaded file", ""); } try { DboUploadFile dbo = new DboUploadFile(); if (file.Headers.ContentDisposition != null) { dbo.OriginalFilename = Uri.UnescapeDataString(file.Headers.ContentDisposition.FileName.Trim('"')); } dbo.TempFilePath = Path.GetTempFileName(); using (var memoryStream = new MemoryStream(await file.ReadAsByteArrayAsync())) { using (var streamWriter = new FileStream(dbo.TempFilePath, FileMode.OpenOrCreate)) { memoryStream.WriteTo(streamWriter); memoryStream.Close(); streamWriter.Close(); } } return OpResult.Ok(dbo); } catch (Exception e) { return OpResult.Error(ResultStatus.InputError, e, "Failed to write uploaded file"); } } } }