public async Task<FileDownloadResponse> DownloadZipFile(IEnumerable<Upload> uploads) { try { var fileDownloadResponse = new FileDownloadResponse(); string currentFormattedTime = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss"); string inputZipFileName = "AssignmentSolution_" + currentFormattedTime; string inputZipFileNameWithExtension = inputZipFileName + ".zip"; string rootPath = _hostingEnvironment.WebRootPath; string fullPath = Path.Combine(rootPath, inputZipFileName); string zipPath = Path.Combine(rootPath, inputZipFileNameWithExtension); if (!Directory.Exists(fullPath)) { Directory.CreateDirectory(fullPath); } int count = 0; foreach (var file in uploads) { var blobFileStream = await _blobHelper.DownloadBlobAsync("assignments", file.FileName.Trim()); if (blobFileStream != null) { string localFilePath = Path.Combine(fullPath, file.FileName); using (var localFileStream = new FileStream(localFilePath, FileMode.OpenOrCreate)) { blobFileStream.Position = 0; blobFileStream.CopyTo(localFileStream); } count++; } } if(count > 0) { ZipFile.CreateFromDirectory(fullPath, zipPath); var fileStream = File.OpenRead(zipPath); var blobFileUrl = await _blobHelper.UploadFileToBlobAsync("zipped-files", inputZipFileNameWithExtension,fileStream); if(blobFileUrl != null) { fileDownloadResponse.IsSuccess = true; fileDownloadResponse.Message = "File Downloaded Successfully"; fileDownloadResponse.FileUrl = blobFileUrl; } else { fileDownloadResponse = new FileDownloadResponse { Message = "No File Available to Download." }; } } else { fileDownloadResponse = new FileDownloadResponse { Message = "No Files Available to Download." }; } Directory.Delete(fullPath, true); return fileDownloadResponse; } catch (Exception ex) { return null; } }
public async Task <FileDownloadResponse> DownloadAssignment(IEnumerable <Guid> requestIds) { FileDownloadResponse fileDownloadResponse; var listFileIds = await _requestRepository.GetAssignmentAttemptsDetails(requestIds); if (listFileIds != null && listFileIds.Any()) { var fileDetails = await _requestRepository.GetUploadsDetails(listFileIds); if (fileDetails != null) { if (fileDetails.Count() == 1) { fileDownloadResponse = await _fileOperationsManager.DownloadFile(fileDetails); } else { fileDownloadResponse = await _fileOperationsManager.DownloadZipFile(fileDetails); } } else { fileDownloadResponse = new FileDownloadResponse { Message = "No files to download." }; } } else { fileDownloadResponse = new FileDownloadResponse { Message = "No files to download." }; } return(fileDownloadResponse); }
public async Task DownloadAssignment_Test_UploadsCount1Plus() { var requestIds = new List <Guid> { Guid.Parse("6F5A7376-2D21-46C2-A459-E5E612238512"), Guid.Parse("6F5A7376-2D21-46C2-A459-E5E612238512") }; var uploads = new List <Upload> { new Upload { Id = Guid.Parse("6F5A7376-2D21-46C2-A459-E5E612238512") }, new Upload { Id = Guid.Parse("6F5A7376-2D21-46C2-A459-E5E612238512") } }; var fileDetails = new FileDownloadResponse { IsSuccess = true }; _mockRequestRepository.Setup(x => x.GetAssignmentAttemptsDetails(It.IsAny <IEnumerable <Guid> >())).ReturnsAsync(requestIds); _mockRequestRepository.Setup(x => x.GetUploadsDetails(It.IsAny <IEnumerable <Guid> >())).ReturnsAsync(uploads); fileOperationsManager.Setup(x => x.DownloadZipFile(uploads)).ReturnsAsync(fileDetails); var result = await requestManager.DownloadAssignment(requestIds); Assert.IsNotNull(result); var status = (result as FileDownloadResponse).IsSuccess; Assert.AreEqual(status, true); }
public Result <FileDownloadResponse> Export(int typiconVersionId) { var found = _dbContext.Set <TypiconVersion>().FirstOrDefault(c => c.Id == typiconVersionId); if (found != null) { var projection = _projector.Project(found); if (projection.Success) { XmlSerializer serializer = new XmlSerializer(typeof(TypiconVersionProjection)); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, projection.Value); var response = new FileDownloadResponse(stream.ToArray() , "application/xml" , GetFileName(projection.Value.Name.ToString(), found.VersionNumber)); return(Result.Ok(response)); } } } return(Result.Fail <FileDownloadResponse>($"Устав с Id={typiconVersionId} не был найден.")); }
public void Execute() { var request = new FileDownloadRequest(_fileHeader.Guid); FileDownloadResponse response = _serverConnection.SendFileDownloadRequest(request); _eventAggregator.Publish(new FileDownloaded(response.File)); }
public async Task <FileDownloadResponse> DownloadAsync(FileDownloadRequest filedownloadRequest) { CloudBlobContainer cloudBlobContainer = GetBlobContainerConfig(filedownloadRequest.UserId); bool isContainerExists = await cloudBlobContainer.ExistsAsync(); if (!isContainerExists) { throw new ResourceNotExistsException($"userId: {filedownloadRequest.FileName} does not exists"); } //Get blob reference var blobReference = cloudBlobContainer.GetBlockBlobReference(filedownloadRequest.FileName); bool isExists = await blobReference.ExistsAsync(); if (!isExists) { throw new ResourceNotExistsException($"Provided File {filedownloadRequest.FileName} does not exists"); } var stream = new MemoryStream(); await blobReference.DownloadToStreamAsync(stream); stream.Position = 0; FileDownloadResponse response = new FileDownloadResponse { ContentType = ContentTypeHelper.GetContentType(blobReference.Name), MemoryStream = stream }; return(response); }
public async Task <IActionResult> PostAssignment(Guid id) { var response = new FileDownloadResponse(); var file = HttpContext.Request.Form.Files.FirstOrDefault(); if (id == Guid.Empty) { return(BadRequest(new Response { IsSuccess = false, Message = "Invalid Input Type" })); } if (file == null) { response.IsSuccess = false; response.Message = "No File Found"; return(StatusCode(200, response)); } if (file.Length < 1024) { bool isZipCheck = await _fileOperationsManager.IsZipFileEmpty(file); if (isZipCheck) { response.IsSuccess = false; response.Message = "No Files are found inside the Zip File."; return(StatusCode(200, response)); } } if (file.Length > 104857600) { response.IsSuccess = false; response.Message = "File of the zip file is too large."; return(StatusCode(200, response)); } if (file.FileName.EndsWith(".zip")) { response = await _courseManager.UpdateAssigmentAsync(id, file); if (response.IsSuccess) { return(StatusCode(201, response)); } else { return(StatusCode(200, response)); } } else { return(BadRequest(new Response { IsSuccess = false, Message = "Invalid file Format" })); } }
public async Task <IActionResult> GetFile(string source, string share, string folder, string filename) { if (string.IsNullOrEmpty(source) || string.IsNullOrEmpty(share) || string.IsNullOrEmpty(folder) || string.IsNullOrEmpty(filename)) { return(BadRequest()); } FileDownloadResponse response = await _service.DownloadFile(source, share, folder, filename); return(Ok(response)); }
/// <summary> /// Update the Assignment in the Course Repository /// </summary> /// <param name="courseId"></param> /// <param name="file"></param> /// <returns></returns> public async Task <FileDownloadResponse> UpdateAssigmentAsync(Guid courseId, IFormFile file) { var response = new FileDownloadResponse(); var courseDetails = await _courseRepository.GetCourseDetails(courseId); var fileName = (courseDetails.YorbitCourseId + "_" + courseDetails.CourseName + ".zip").Replace(" ", ""); var upload = await _uploadHelper.UploadFileAsync(file, fileName); if (upload != null) { var result = await _courseRepository.UpdateCourseAsync(courseId, upload.Id); response.IsSuccess = result.IsSuccess; response.FileUrl = upload.FilePath; } response.Message = response.IsSuccess ? "Assignment uploaded successfully" : "Error uploading assignment."; return(response); }
/// <summary> /// Updating AssignmentAttempt with ErrorFile and comment /// </summary> /// <param name="file"></param> /// <param name="comment"></param> /// <param name="requestId"></param> /// <returns></returns> public async Task <FileDownloadResponse> UploadErrorAsync(IFormFile file, string comment, Guid requestId) { var response = new FileDownloadResponse(); try { var currentAssignmentAttempt = await _requestRepository.GetCurrentAssignmentAttemptsAsync(requestId); if (currentAssignmentAttempt.ResultId == RequestResultCodes.Result_Awaited) { string fileName = currentAssignmentAttempt.YorbitRequestId + "_" + currentAssignmentAttempt.Mid + "_ErrorFile_" + DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss") + ".zip"; var upload = await UploadFileAsync(file, fileName); //Update comment and errorfileid in AssignmentAttempt var updateResponse = await _requestRepository.UpdateAssignmenAttemptForErrorFileUpload( currentAssignmentAttempt.Id, comment, upload.Id); if (updateResponse > 0) { _emailManager.SendMail(NotificationType.EvaluatorErrorFileUpload, new EmailDetails { RequestIds = new List <Guid> { requestId } }); } response.FileUrl = upload.FilePath; response.Message = "Succesfully Uploaded"; response.IsSuccess = true; } else { response.IsSuccess = false; response.Message = "Assignment not in 'Yet to Evaluate ' status"; } } catch (Exception ex) { Logging.Logger.LogException(ex); response.Message = "Cannot upload error file"; } return(response); }
private void FileDownloadHandler(IRequest request) { var fileDownloadRequest = (FileDownloadRequest)request; GuidedFile fileToDownload = null; foreach (var file in _filesToDownload) { if (file.Guid.Equals(fileDownloadRequest.FileGuid)) { fileToDownload = file; } break; } _filesToDownload.Remove(fileToDownload); var response = new FileDownloadResponse(fileToDownload.File); SendReponse(response); }
public async Task<FileDownloadResponse> DownloadFile(IEnumerable<Upload> uploads) { try { var fileDownloadResponse = new FileDownloadResponse(); var fileDetails = uploads.FirstOrDefault(); var blobFileUrl = await _blobHelper.GetBlobUriAsync("assignments", fileDetails.FileName.Trim()); if(blobFileUrl != null) { fileDownloadResponse.IsSuccess = true; fileDownloadResponse.Message = "File Downloaded Successfully"; fileDownloadResponse.FileUrl = blobFileUrl; } else { fileDownloadResponse = new FileDownloadResponse { Message = "No File Available to Download." }; } return fileDownloadResponse; } catch(Exception ex) { return null; } }
public Result <FileDownloadResponse> Export() { try { var container = _booksProjector.Project(); XmlSerializer serializer = new XmlSerializer(typeof(BooksContainer)); using (MemoryStream stream = new MemoryStream()) { serializer.Serialize(stream, container); var response = new FileDownloadResponse(stream.ToArray() , "application/xml" , GetFileName()); return(Result.Ok(response)); } } catch (Exception ex) { return(Result.Fail <FileDownloadResponse>($"При экспорте произошла ошибка: {ex.Message}.")); } }
private void ExecuteCommandAndLoadResultToViewData(ICommand commandToExecute) { if (commandToExecute.GetType().BaseType.IsGenericType) // This means the command needs a model to be loaded from the view before executing { LoadModelToCommand(commandToExecute); } result = commandToExecute.Execute(); try { if (result != null) { if (typeof(IError).IsAssignableFrom(result.GetType())) { Log<CommandController>.Debug("Adding an error to the TempData collection"); LoadErrorDataToTempDataAndRedirect(); } else { if (typeof(ISuccess).IsAssignableFrom(result.GetType())) { Log<CommandController>.Debug("Adding a success message to the TempData collection"); LoadObjectToTempData(typeof(ISuccess).FullName, result); var successResult = result as ISuccess; if (!string.IsNullOrEmpty(successResult.RedirectUrl)) { Log<CommandController>.Debug("Success result redirecting to " + successResult.RedirectUrl); redirectPath = successResult.RedirectUrl; } } else if (typeof(IRedirect).IsAssignableFrom(result.GetType())) { var redirect = result as IRedirect; redirectPath = redirect.PathToRedirectTo; } else if (typeof(FileStreamResponse).IsAssignableFrom(result.GetType())) { Log<CommandController>.Debug("FileStreamResponse returned"); fileStreamResponse = result as FileStreamResponse; } else if (typeof(FileDownloadResponse).IsAssignableFrom(result.GetType())) { Log<CommandController>.Debug("FileDownloadResponse returned"); fileDownloadResponse = result as FileDownloadResponse; } else { ViewData.Add(result.GetType().FullName, result); } } } } catch (ArgumentException ex) { Log<CommandController>.Error("Error attempting to execute command", ex); throw new ArgumentException(string.Format("The type: {0} has already been added to the ViewData collection", result.GetType().Name)); } finally { DisposeCommand(commandToExecute); } }