Ejemplo n.º 1
0
        public async Task<HttpResponseMessage> Post(string fileName, string fileExtension, string contentType)
        {
            try
            {
                Check.IsNotEmptyOrWhiteSpace(fileName, "fileName");
                Check.IsNotEmptyOrWhiteSpace(fileExtension, "fileExtension");
                Check.IsNotEmptyOrWhiteSpace(contentType, "contentType");

                byte[] fileContent = default(byte[]);
                if (Request.Content.IsMimeMultipartContent("form-data"))
                {
                    string root = Path.GetTempPath();
                    MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(root);
                    await Request.Content.ReadAsMultipartAsync(streamProvider);
                    MultipartFileData multipartFileData = streamProvider.FileData.First();

                    /*********************************************************
                     * This API under stress can cause IO exception, for File read
                     * or Delete operation. More details @https://aspnetwebstack.codeplex.com/workitem/176 
                     * Following logic retries file operations at most 3 times
                     * inducing the recommended delay in case of failure. 
                     */ 
                    int executionDelay = 50, 
                        readRetryCount = 3,
                        deleteRetryCount = 3;

                    // Retry mechanics for file read operation
                    while (readRetryCount-- > 0) 
                    {
                        try
                        {
                            using (FileStream fileSource = new FileStream(multipartFileData.LocalFileName, FileMode.Open, FileAccess.Read))
                            {
                                fileContent = await fileSource.GetBytesAsync();
                            }
                            break;
                        }
                        catch (IOException ioe)
                        {
                            diagnostics.WriteErrorTrace(TraceEventId.Exception, ioe.ToString());
                        }
                        await Task.Delay(executionDelay);
                    }

                    // Retry mechanics for file delete operation
                    while (deleteRetryCount-- > 0)
                    {
                        try
                        {
                            await Task.Factory.StartNew(() => System.IO.File.Delete(multipartFileData.LocalFileName));
                            break;
                        }
                        catch (IOException ioe)
                        {
                            diagnostics.WriteErrorTrace(TraceEventId.Exception, ioe.ToString());
                        }
                        await Task.Delay(executionDelay);
                    }

                }
                else
                {
                    var bufferlessInputStream = HttpContext.Current.Request.GetBufferlessInputStream();
                    Check.IsNotNull(bufferlessInputStream, "HttpContext.Current.Request.GetBufferlessInputStream()");
                    fileContent = await bufferlessInputStream.GetBytesAsync();
                }

                this.fileService.ValidateForUpload(fileName, this.user.UserId);

                DataFile dataFile = new DataFile
                {
                    FileContent = fileContent,
                    ContentType = contentType,
                    FileName = fileName,
                    CreatedBy = this.user.UserId,
                    FileExtentsion = fileExtension
                };

                IFileHandler fileHandler = this.fileHandlerFactory.GetFileHandler(contentType, this.user.UserId);
                diagnostics.WriteInformationTrace(Utilities.Enums.TraceEventId.Flow, "blob-before file upload");
                var uploadedDataDetails = fileHandler.Upload(dataFile);
                diagnostics.WriteInformationTrace(Utilities.Enums.TraceEventId.Flow, "blob-after file upload");
                if (!uploadedDataDetails.Any() || uploadedDataDetails.Any(dd => dd.FileDetail.FileId == 0))
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, MessageStrings.UploadFailed);
                }

                return Request.CreateResponse<IEnumerable<DataDetail>>(HttpStatusCode.OK, uploadedDataDetails);
            }
            catch (ValidationException validationException)
            {
                HttpError error = validationException.GetHttpError(string.Format(MessageStrings.Upload_Validation_Error_Template, validationException.FileName));
                return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, error);
            }
            catch (ArgumentException ex)
            {
                message = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ex.ParamName);
                status = HttpStatusCode.BadRequest;
            }

            return Request.CreateErrorResponse(status, message);
        }
Ejemplo n.º 2
0
        public async Task<HttpResponseMessage> Post(string nameIdentifier)
        {
            try
            {
                Check.IsNotEmptyOrWhiteSpace(nameIdentifier, "nameIdentifier");
                if (!Request.Content.IsMimeMultipartContent("form-data"))
                {
                    throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType);
                }

                string root = Path.GetTempPath();
                MultipartFormDataStreamProvider streamProvider = new MultipartFormDataStreamProvider(root);
                await Request.Content.ReadAsMultipartAsync(streamProvider);
                MultipartFileData multipartFileData = streamProvider.FileData.First();
                byte[] fileContent;
                using (FileStream fileSource = new FileStream(multipartFileData.LocalFileName, FileMode.Open, FileAccess.Read))
                {
                    fileContent = await fileSource.GetBytesAsync();
                }

                string fileName = multipartFileData.Headers.ContentDisposition.FileName.Trim(new char[] { '\"' });
                string fileExtension = Path.GetExtension(fileName);
                string contentType = MimeMapping.GetMimeMapping(fileName);
                Task.Factory.StartNew(() => System.IO.File.Delete(multipartFileData.LocalFileName));
                User impersonatedUser = IdentityHelper.GetUser(this.userService, nameIdentifier);

                this.fileService.ValidateForUpload(fileName, impersonatedUser.UserId);

                DataFile dataFile = new DataFile
                {
                    FileContent = fileContent,
                    ContentType = contentType,
                    FileName = fileName,
                    CreatedBy = impersonatedUser.UserId,
                    FileExtentsion = fileExtension
                };

                IFileHandler fileHandler = this.fileHandlerFactory.GetFileHandler(contentType, impersonatedUser.UserId);
                var uploadedDataDetails = fileHandler.Upload(dataFile);
                if (!uploadedDataDetails.Any() || uploadedDataDetails.Any(dd => dd.FileDetail.FileId == 0))
                {
                    return Request.CreateErrorResponse(HttpStatusCode.BadRequest, MessageStrings.UploadFailed);
                }

                return Request.CreateResponse<IEnumerable<DataDetail>>(HttpStatusCode.OK, uploadedDataDetails);
            }
            catch (ArgumentException ex)
            {
                message = string.Format(CultureInfo.CurrentCulture, MessageStrings.Argument_Error_Message_Template, ex.ParamName);
                status = HttpStatusCode.BadRequest;
            }

            return Request.CreateErrorResponse(status, message);
        }