private static void AddBodyFileName(RestRequest request, PostFileModel file) { if (file.ContentType != null) { request.AddHeader("Content-Type", file.ContentType); } request.AddHeader("Content-Disposition", string.Format("file; filename=\"{0}\";", Path.GetFileName(file.FilePath))); request.AddParameter("", File.ReadAllBytes(file.FilePath), ParameterType.RequestBody); }
private static void TestArticles(int goodsOwnerId, ArticlesClient articlesClient) { Console.WriteLine("Running article examples..."); Console.WriteLine(""); // Define a new article. var article = new PostArticleModel() { GoodsOwnerId = goodsOwnerId, ArticleNumber = "12345", ArticleName = "Test article", Weight = 1.7m, // Unit is kilograms. BarCodeInfo = new PostArticleBarCodeInfo() { BarCode = "733123" } }; // Send the new article to the warehouse, thus creating it. var createResponse = articlesClient.Put3(article); // Update the barcode to something else. article.BarCodeInfo.BarCode = "507543"; var updateResponse = articlesClient.Put3(article); // You may query for articles using various ways. The response will include various article data (including stock balances). var getArticleByArticleSystemId = articlesClient.Get(createResponse.ArticleSystemId.Value); var getArticleByArticleNumber = articlesClient.GetAll(goodsOwnerId, "12345", null, null); // If you have a file (such as an image), you may attach it to the article. var imagePath = @"C:\WMS\12345.png"; if (System.IO.File.Exists(imagePath)) { var fileBase64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(imagePath)); var file = new PostFileModel() { FileName = "12345.png", FileDataBase64 = fileBase64, MimeType = "image/png" }; articlesClient.Post(createResponse.ArticleSystemId.Value, file); } }
public async Task <IActionResult> Post(PostFileModel model) { var file = new File(); foreach (var dataFile in model.Files) { file.Name = model.Name ?? System.IO.Path.GetFileNameWithoutExtension(dataFile.FileName); file.FileName = string.Concat(this.seoHelper.GenerateFriendlyName(file.Name), System.IO.Path.GetExtension(dataFile.FileName)); file.MimeType = this.filesHelper.GetContentTypeByFileName(file.FileName); using (var streamFile = dataFile.OpenReadStream()) { var fileBinary = new byte[streamFile.Length]; streamFile.Read(fileBinary, 0, fileBinary.Length); await this.fileService.Insert(file, fileBinary); } } var thumbnail = this.pictureService.GetPicturePath(file, 200, 200, true); return(this.Ok(new { Id = file.Id, Thumbnail = thumbnail })); }
public async Task <IActionResult> Upload([FromRoute] string uploadName, [FromQuery(Name = "k")] string apiKeyQuery) { var apiKeys = HttpContext.Request.Headers["ApiKey"]; var apiKey = apiKeys.Count == 1 ? apiKeys[0] : apiKeyQuery; var uploader = _options.Uploader.FirstOrDefault( s => s.WebBasePath.Equals(uploadName, StringComparison.OrdinalIgnoreCase) && (s.ApiKey.Equals(apiKey) || string.IsNullOrEmpty(s.ApiKey))); if (uploader == null) { return(BadRequest("Uploader not found, invalid upload path or invalid API key.")); } // Used to accumulate all the form url encoded key value pairs in the // request. var formAccumulator = new KeyValueAccumulator(); string targetFilePath = null; var boundary = MultipartRequestHelper.GetBoundary( MediaTypeHeaderValue.Parse(Request.ContentType), _defaultFormOptions.MultipartBoundaryLengthLimit); var reader = new MultipartReader(boundary, HttpContext.Request.Body); var section = await reader.ReadNextSectionAsync(); string fileExtension = null; while (section != null) { var hasContentDispositionHeader = ContentDispositionHeaderValue.TryParse(section.ContentDisposition, out var contentDisposition); if (hasContentDispositionHeader) { if (MultipartRequestHelper.HasFileContentDisposition(contentDisposition)) { fileExtension = Path.GetExtension(contentDisposition.FileName.Value).ToLower(); targetFilePath = Path.GetTempFileName(); if (!uploader.FileExtensions.Contains(fileExtension) && !uploader.FileExtensions.Contains("*")) { return(BadRequest( $"File does not meet the requirements. Invalid extension ({fileExtension}), allowed extensions: [{string.Join(", ", uploader.FileExtensions)}]")); } try { using (var targetStream = System.IO.File.Create(targetFilePath)) { await section.Body.CopyToAsync(targetStream); _logger.LogInformation($"Copied the uploaded file '{targetFilePath}'"); } } catch (Exception) { _logger.LogError("An error occured while streaming the File. Did the client cancel?"); DeleteFileIfExists(targetFilePath); } } else if (MultipartRequestHelper.HasFormDataContentDisposition(contentDisposition)) { // Content-Disposition: form-data; name="key" // // value // Do not limit the key name length here because the // multipart headers length limit is already in effect. var key = HeaderUtilities.RemoveQuotes(contentDisposition.Name); var encoding = GetEncoding(section); using (var streamReader = new StreamReader( section.Body, encoding, detectEncodingFromByteOrderMarks: true, bufferSize: 1024, leaveOpen: true)) { // The value length limit is enforced by MultipartBodyLengthLimit var value = await streamReader.ReadToEndAsync(); if (string.Equals(value, "undefined", StringComparison.OrdinalIgnoreCase)) { value = string.Empty; } formAccumulator.Append(key.Value, value); if (formAccumulator.ValueCount > _defaultFormOptions.ValueCountLimit) { throw new InvalidDataException($"Form key count limit {_defaultFormOptions.ValueCountLimit} exceeded."); } } } } // Drains any remaining section body that has not been consumed and // reads the headers for the next section. section = await reader.ReadNextSectionAsync(); } // Bind form data to a model var model = new PostFileModel(); var formValueProvider = new FormValueProvider( BindingSource.Form, new FormCollection(formAccumulator.GetResults()), CultureInfo.CurrentCulture); var bindingSuccessful = await TryUpdateModelAsync(model, prefix : "", valueProvider : formValueProvider); if (!bindingSuccessful && !ModelState.IsValid) { return(BadRequest(ModelState)); } var file = new FileInfo(targetFilePath ?? throw new InvalidOperationException()); if (!ValidateFileSize(uploader.MaxFileSize, file.Length)) { file.Delete(); return(BadRequest($"File does not meet the Requirements. Maximum size {uploader.MaxFileSize}MB.")); } Directory.CreateDirectory(uploader.LocalBasePath); var fileName = GetRandomFileName(fileExtension); var filePath = Path.Combine(uploader.LocalBasePath, fileName); var fileSize = file.Length; if (uploader.MaxFolderSize > 0) { if (fileSize > uploader.MaxFolderSize * 1024 * 1024) { file.Delete(); return(BadRequest("File bigger than max foldersize")); } while (GetDirectorySize(uploader.LocalBasePath) + fileSize > uploader.MaxFolderSize * 1024 * 1024) { DeleteOldestFile(uploader.LocalBasePath); } } while (System.IO.File.Exists(filePath)) { fileName = GetRandomFileName(fileExtension); filePath = Path.Combine(uploader.LocalBasePath, fileName); } file.MoveTo(filePath); if (uploader.ResponseType == ApiResponseType.Redirect) { return(LocalRedirect($"/{uploader.WebBasePath}/{fileName}")); } return(Ok(new ResultModel { FileUrl = ToAbsoluteUrl(Url.Content(uploader.WebBasePath + "/" + fileName)), DeleteUrl = ToAbsoluteUrl(Url.Action("Delete", "Uploader", new { uploadName = uploader.WebBasePath, fileName })) })); }
public async Task <IActionResult> Post([FromRoute] string uploadName, [FromForm] PostFileModel model) { var file = model.File; var apiKey = model.ApiKey; if (file == null) { return(BadRequest("No file given")); } var uploaders = _options.Uploader.Where( s => s.WebBasePath.Equals(uploadName, StringComparison.OrdinalIgnoreCase)); if (uploaders == null) { return(BadRequest( $"Uploader not Found - Wrong path?")); } if (!uploaders.Any(s => s.ApiKey == apiKey && !string.IsNullOrEmpty(s.ApiKey))) { return(new UnauthorizedResult()); } var uploader = _options.Uploader.FirstOrDefault( s => s.WebBasePath.Equals(uploadName, StringComparison.OrdinalIgnoreCase) && s.ApiKey == apiKey); var fileExtension = Path.GetExtension(file.FileName).ToLower(); if (!uploader.FileExtensions.Contains(fileExtension) && !uploader.FileExtensions.Contains("*") || file.Length > (1024 * 1024) * uploader.MaxFileSize) { return(BadRequest( $"File does not meet the Requirements. Maximum size {uploader.MaxFileSize}MB, Allowed Extensions [{string.Join(", ", uploader.FileExtensions)}]")); } Directory.CreateDirectory(uploader.LocalBasePath); var fileName = GetRandomFileName(fileExtension); var filePath = Path.Combine(uploader.LocalBasePath, fileName); var fileSize = file.Length; if (uploader.MaxFolderSize > 0) { if (fileSize > uploader.MaxFolderSize * 1024 * 1024) { return(BadRequest("File bigger than max foldersize")); } while (GetDirectorySize(uploader.LocalBasePath) + fileSize > uploader.MaxFolderSize * 1024 * 1024) { DeleteOldestFile(uploader.LocalBasePath); } } while (System.IO.File.Exists(filePath)) { fileName = GetRandomFileName(fileExtension); filePath = Path.Combine(uploader.LocalBasePath, fileName); } using (var fs = System.IO.File.Create(filePath)) { await file.CopyToAsync(fs); } if (uploader.ResponseType == ApiResponseType.Redirect) { return(LocalRedirect($"/{uploader.WebBasePath}/{fileName}")); } return(Ok(new ResultModel { FileUrl = ToAbsoluteUrl(Url.Content(uploader.WebBasePath + "/" + fileName)), DeleteUrl = ToAbsoluteUrl(Url.Action("Delete", "Uploader", new { uploadName = uploader.WebBasePath, fileName })) })); }
private static void TestOrders(int goodsOwnerId, OrdersClient ordersClient) { Console.WriteLine("Running order examples..."); Console.WriteLine(""); var orderNumber = "PR78912"; // A unique order number. // Define a new order. var order = new PostOrderModel() { GoodsOwnerId = goodsOwnerId, Consignee = new PostOrderConsignee() { Name = "Test Testsson", Address1 = "Test Street 1", City = "Test City", PostCode = "111111", CountryCode = "SE" }, OrderNumber = orderNumber, OrderLines = new List <PostOrderLine>() { new PostOrderLine() { RowNumber = "OrderRow1", ArticleNumber = "1234", NumberOfItems = 2 }, // Each order line must have a unique row number. new PostOrderLine() { RowNumber = "OrderRow2", ArticleNumber = "7879", NumberOfItems = 4 }, } }; // Send the new order to the warehouse, thus creating it. var createResponse = ordersClient.PutOrder(order); // If we send in the same order number again, the system will try to update the order. // It is possible to update an order as long as the warehouse has not started working on it. order.OrderLines.Add(new PostOrderLine() { RowNumber = "OrderRow3", ArticleNumber = "5943", NumberOfItems = 9 }); var updateResponse = ordersClient.PutOrder(order); // You may upload files (documents, labels, etc) to orders. var pdfPath = @"C:\WMS\Invoice-PR78912.pdf"; if (System.IO.File.Exists(pdfPath)) { var fileBase64 = Convert.ToBase64String(System.IO.File.ReadAllBytes(pdfPath)); var file = new PostFileModel() { FileName = "Invoice-PR78912.pdf", FileDataBase64 = fileBase64, MimeType = "application/pdf" }; ordersClient.Post(createResponse.OrderId.Value, file); } // You may query for orders using various ways. // For instance using orderId: var getOrderByOrderId = ordersClient.Get(createResponse.OrderId.Value); // Or by order number: var getOrderByOrderNumber = ordersClient.GetAll(goodsOwnerId, orderNumber, null, null, null, null, null, null, null); // Or get all orders which have been shipped during a particular period: var from = new DateTimeOffset(new DateTime(2019, 11, 1, 12, 0, 0)); var to = new DateTimeOffset(new DateTime(2019, 11, 1, 13, 0, 0)); var getOrdersByShippedTime = ordersClient.GetAll(goodsOwnerId, null, from, to, null, null, null, null, null); foreach (var shippedOrder in getOrdersByShippedTime) { // Handle "shippedOrder" somehow. } }
public HttpResponseMessage Publish() { string message = string.Empty; HttpStatusCode status = HttpStatusCode.OK; PostFileModel dataDetail = new PostFileModel(); try { diagnostics.WriteInformationTrace(TraceEventId.Flow, "Into publish"); if (HttpContext.Current.Request["PostFileData"] != null) { var postFileString = HttpContext.Current.Request["PostFileData"]; if (postFileString != null) { //diagnostics.WriteInformationTrace(TraceEventId.Flow, "Into publishing3"); /**************************************************** * TODO: Try catch block below is required to handle the case where the * clients send post request with JSON payload as plain text. * The API needs to be refactored to take the model as input * and have the MVC framework resolve/deserialize the payload * into model object. * **************************************************/ PostFileModel postFileData = default(PostFileModel); try { postFileData = Helper.DeSerializeObject <PostFileModel>(postFileString.DecodeFrom64(), "postFile"); } catch (Exception) { // If the data is not base 64 encoded using (MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(postFileString))) { DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(PostFileModel)); postFileData = (PostFileModel)jsonSerializer.ReadObject(stream); } } DM.Repository repository = repositoryService.GetRepositoryById(postFileData.SelectedRepositoryId); this.fileService = this.fileServiceFactory.GetFileService(repository.BaseRepository.Name); // Get the AuthToken from the request. TODO need to move below code to SkyDriveFileController. AuthToken userAuthToken = postFileData.UserAuthToken; userAuthToken.UserId = this.user.UserId; userAuthToken.RespositoryId = repository.RepositoryId; // Save the file details to db and publish logic this.fileService.SaveFile(postFileData); return(Request.CreateResponse <OperationStatus>(HttpStatusCode.OK, OperationStatus.CreateSuccessStatus())); } } } catch (ArgumentNullException ane) { diagnostics.WriteErrorTrace(TraceEventId.Exception, ane); status = HttpStatusCode.BadRequest; if (ane.ParamName.Equals("fileService")) { message = MessageStrings.File_Service_Is_Null; } else { message = ane.Message + ane.StackTrace + ane.GetType().ToString(); } } catch (Exception ex) { diagnostics.WriteErrorTrace(TraceEventId.Exception, ex); message = ex.Message + ex.StackTrace + ex.GetType().ToString(); if (null != ex.InnerException) { message += ex.InnerException.Message + ex.InnerException.StackTrace + ex.InnerException.GetType().ToString(); } status = HttpStatusCode.InternalServerError; } return(Request.CreateErrorResponse(status, message)); }