public async void Returns_NotFoundObjectResult_when_ParentDirectoryNotExistsOrNotBelongsToUser() { StatusCode <List <FileUploadResult> > status = new StatusCode <List <FileUploadResult> >(StatusCodes.Status404NotFound); Mock <IFileService> fileService = new Mock <IFileService>(); fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>())) .Returns(Task.FromResult(status)); string username = "******"; FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username)); filesController.Authenticate(username); FilePost filePost = new FilePost { ParentDirectoryID = Guid.NewGuid(), Files = new FormFileCollection { new FormFile(null, 0, 0, "", "") } }; IActionResult result = await filesController.Post(filePost); Assert.IsType <NotFoundObjectResult>(result); }
public async void Returns_ListFileUploadResult() { List <FileUploadResult> fileUploadResults = new List <FileUploadResult>(); Mock <IFileService> fileService = new Mock <IFileService>(); fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>())) .Returns(Task.FromResult(new StatusCode <List <FileUploadResult> >(StatusCodes.Status200OK, fileUploadResults))); string username = "******"; FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username)); filesController.Authenticate(username); FilePost filePost = new FilePost { ParentDirectoryID = null, Files = new FormFileCollection { new FormFile(new MemoryStream(Encoding.UTF8.GetBytes("Some content")), 0, 12, "file", "file.txt") } }; IActionResult result = await filesController.Post(filePost); OkObjectResult okObjectResult = result as OkObjectResult; Assert.NotNull(okObjectResult); Assert.IsType <List <FileUploadResult> >(okObjectResult.Value); }
public async void Returns_Status404NotFound_when_ParentDirectoryNotBelongsToUser() { IDatabaseContext databaseContext = DatabaseTestHelper.GetContext(); IFileService fileService = new FileService(databaseContext, null); string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id; Directory directory = new Directory { ResourceType = ResourceType.DIRECTORY, OwnerID = userId, Name = "Directory" }; await databaseContext.Directories.AddAsync(directory); FilePost filePost = new FilePost { ParentDirectoryID = directory.ID, Files = new FormFileCollection { new FormFile( new System.IO.MemoryStream(Encoding.UTF8.GetBytes("text")), 0, 4, "Data", "file1.txt") } }; StatusCode <List <FileUploadResult> > status = await fileService.PostByUser(filePost, "*****@*****.**"); Assert.NotNull(status); Assert.True(status.Code == StatusCodes.Status404NotFound); }
public IActionResult Upload(FilePost model) { if (ModelState.IsValid) { using (var client = new HttpClient()) { client.BaseAddress = new Uri("https://localhost:44315/"); client.DefaultRequestHeaders.Accept.Clear(); client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); var formData = new MultipartFormDataContent(); formData.Add(new StreamContent(model.MyFile.OpenReadStream()), "formFile", model.MyFile.FileName); var response = client.PostAsync("api/transaction/upload", formData); response.Wait(); var result = response.Result; if (result.IsSuccessStatusCode) { ViewBag.Msg = $"Upload Success {result.StatusCode}"; } else { var responseBody = result.Content.ReadAsStringAsync().Result; ViewBag.Msg = $"Upload Not Success {result.StatusCode}"; } } } return(View(model)); }
public async void Returns_ListOfFileUploadResultAndStatus200OK_when_ParentDirectoryIsNull() { IDatabaseContext databaseContext = DatabaseTestHelper.GetContext(); IFileService fileService = new FileService(databaseContext, null); string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id; FilePost filePost = new FilePost { Files = new FormFileCollection { new FormFile( new System.IO.MemoryStream(Encoding.UTF8.GetBytes("text")), 0, 4, "Data", "file1.txt") } }; StatusCode <List <FileUploadResult> > status = await fileService.PostByUser(filePost, "*****@*****.**"); Assert.NotNull(status); Assert.True(status.Code == StatusCodes.Status200OK); Assert.NotNull(status.Body); Assert.Equal(filePost.Files.Count(), status.Body.Count()); Assert.True(databaseContext.Files .Any(_ => _.ParentDirectoryID == null && _.Name == "file1.txt")); }
public ActionResult Edit(Post model, HttpPostedFileBase upload, int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } Post post = db.Posts.Find(id); if (post == null) { return(HttpNotFound()); } if (ModelState.IsValid) { if (upload != null && upload.ContentLength > 0) { if (post.FilesPost.Any(f => f.FileType == FileType.Avatar)) { db.FilesPost.Remove(post.FilesPost.First(f => f.FileType == FileType.Avatar)); } var avatar = new FilePost { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } post.FilesPost = new List <FilePost> { avatar }; } post.Title = model.Title; post.Body = model.Body; post.PublishDate = model.PublishDate; post.SubCategoryID = model.SubCategoryID; db.Entry(post).State = EntityState.Modified; /* * SubCategory subcateg = db.SubCategories.FirstOrDefault(s => s.ID == post.SubCategoryID); * var postdb = db.Posts.FirstOrDefault(p => p.ID == post.ID); * postdb.SubCategory.Clear(); * subcateg.Post.Add(postdb); */ db.SaveChanges(); return(RedirectToAction("Index", "Categories")); } ViewBag.SubCategoryID = new SelectList(db.SubCategories, "ID", "Name", post.SubCategoryID); return(View(post)); }
public async void Returns_ListOfFileUploadResultAndStatus200OK_when_UploadedMultipleFile() { IDatabaseContext databaseContext = DatabaseTestHelper.GetContext(); IFileService fileService = new FileService(databaseContext, null); string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id; Directory directory = new Directory { ResourceType = ResourceType.DIRECTORY, OwnerID = userId, Name = "Directory" }; await databaseContext.Directories.AddAsync(directory); await databaseContext.SaveChangesAsync(); FilePost filePost = new FilePost { ParentDirectoryID = directory.ID, Files = new FormFileCollection { new FormFile( new System.IO.MemoryStream(Encoding.UTF8.GetBytes("text")), 0, 4, "Data", "file1.txt"), new FormFile( new System.IO.MemoryStream(Encoding.UTF8.GetBytes("Loooong text")), 0, 12, "Data", "file2.txt") } }; StatusCode <List <FileUploadResult> > status = await fileService.PostByUser(filePost, "*****@*****.**"); Assert.NotNull(status); Assert.True(status.Code == StatusCodes.Status200OK); Assert.NotNull(status.Body); Assert.Equal(filePost.Files.Count(), status.Body.Count()); Assert.True(databaseContext.Files .Any(_ => _.ParentDirectoryID == directory.ID && _.Name == "file1.txt")); Assert.True(databaseContext.Files .Any(_ => _.ParentDirectoryID == directory.ID && _.Name == "file2.txt")); }
public async Task <IActionResult> UploadContractDocument([FromBody] FilePost model, string contractId) { // return null because this needs to be handled as files. try { string endpointUrl = endpointUrl = "vsd_contracts(" + contractId + ")/Microsoft.Dynamics.CRM.vsd_UploadCPUContractDocuments"; // make options for the json serializer JsonSerializerOptions options = new JsonSerializerOptions(); options.IgnoreNullValues = true; // turn the model into a string string modelString = System.Text.Json.JsonSerializer.Serialize(model, options); DynamicsResult result = await _dynamicsResultService.Post(endpointUrl, modelString); return(StatusCode((int)result.statusCode, result.result.ToString())); } finally { } }
public ActionResult Create([Bind(Include = "ID,Title,Body,PublishDate,Image,SubCategoryID,TagId")] Post post, HttpPostedFileBase upload) { if (ModelState.IsValid) { //GET ID string currentUserID = User.Identity.GetUserId(); //Search in db for username with this id ApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserID); //post.User = currentUser; var subcateg = db.SubCategories.FirstOrDefault(s => s.ID == post.SubCategoryID); // var posttag = db.Tags.FirstOrDefault(s => s.ID == post.TagId); if (upload != null && upload.ContentLength > 0) { var avatar = new FilePost { FileName = System.IO.Path.GetFileName(upload.FileName), FileType = FileType.Avatar, ContentType = upload.ContentType }; using (var reader = new System.IO.BinaryReader(upload.InputStream)) { avatar.Content = reader.ReadBytes(upload.ContentLength); } post.FilesPost = new List <FilePost> { avatar }; } db.Posts.Add(post); // posttag.Post.Add(post); subcateg.Post.Add(post); currentUser.Posts.Add(post); db.SaveChanges(); return(RedirectToAction("Index")); } ViewBag.Tag = new SelectList(db.Tags, "ID", "Nome", post.TagId); ViewBag.SubCategoryID = new SelectList(db.SubCategories, "ID", "Name", post.SubCategoryID); return(View(post)); }
public async Task <OperationResult <FileDTO> > Upload(FilePost file) { var googleService = await GoogleHelper.AuthGoogle(_configuration); using (var stream = file.File.OpenReadStream()) { var uploadResponse = await GoogleHelper.Upload(_configuration, googleService, stream, file.File); var result = new OperationResult <FileDTO> { Type = uploadResponse.Type, Errors = uploadResponse.Errors }; if (uploadResponse.IsSuccess) { var reportResponse = await _clientUpload.GetResponse <OperationResult <FileReportUploadResponse> >(new FileReportUploadRequest { Description = file.Description, Name = file.File.FileName, GoogleId = uploadResponse.Data.Id, Mime = file.File.ContentType, ReportId = file.ReportId }); result.Type = reportResponse.Message.Type; result.Errors.AddRange(reportResponse.Message.Errors); if (reportResponse.Message.IsSuccess) { result.Data = new FileDTO { FileId = reportResponse.Message.Data.FileId }; } } return(result); } }
public async Task <IActionResult> Post([FromForm] FilePost filePost) { if (filePost.Files == null && Request.HasFormContentType) { filePost.Files = Request.Form.Files; } if (filePost.Files == null || filePost.Files.Count < 1) { return(BadRequest("Something went wrong")); } StatusCode <List <FileUploadResult> > status = await _fileService.PostByUser(filePost, _userManager .GetUserName(User)); if (status.Code == StatusCodes.Status404NotFound) { return(NotFound($"Directory {filePost.ParentDirectoryID} not found")); } return(Ok(status.Body)); }
public async void Returns_BadRequestObjectResult_when_FilePostFilesEmpty() { StatusCode <List <FileUploadResult> > fileUploadResults = new StatusCode <List <FileUploadResult> >(StatusCodes.Status200OK); Mock <IFileService> fileService = new Mock <IFileService>(); fileService.Setup(_ => _.PostByUser(It.IsAny <FilePost>(), It.IsAny <string>())) .Returns(Task.FromResult(fileUploadResults)); string username = "******"; FilesController filesController = new FilesController(fileService.Object, UserManagerHelper.GetUserManager(username)); filesController.Authenticate(username); FilePost filePost = new FilePost { ParentDirectoryID = Guid.NewGuid(), Files = new FormFileCollection() }; IActionResult result = await filesController.Post(filePost); Assert.IsType <BadRequestObjectResult>(result); }
public async void Returns_Status404NotFound_when_ParentDirectoryNotExist() { IDatabaseContext databaseContext = DatabaseTestHelper.GetContext(); IFileService fileService = new FileService(databaseContext, null); string userId = (await databaseContext.Users.FirstOrDefaultAsync(_ => _.UserName == "*****@*****.**")).Id; FilePost filePost = new FilePost { ParentDirectoryID = Guid.NewGuid(), Files = new FormFileCollection { new FormFile( new System.IO.MemoryStream(Encoding.UTF8.GetBytes("text")), 0, 4, "Data", "file1.txt") } }; StatusCode <List <FileUploadResult> > status = await fileService.PostByUser(filePost, "*****@*****.**"); Assert.NotNull(status); Assert.True(status.Code == StatusCodes.Status404NotFound); }
public async Task <StatusCode <List <FileUploadResult> > > PostByUser(FilePost filePost, string username) { ApplicationUser user = await _databaseContext.Users .FirstOrDefaultAsync(_ => _.UserName == username); string userId = user?.Id; Directory directory = await _databaseContext.Directories .FirstOrDefaultAsync(_ => _.ID == filePost.ParentDirectoryID && _.OwnerID == userId); if (directory == null && filePost.ParentDirectoryID != null) { return(new StatusCode <List <FileUploadResult> >(StatusCodes.Status404NotFound, StatusMessages.PARENT_DIRECTORY_NOT_FOUND)); } try { List <FileUploadResult> result = new List <FileUploadResult>(); string pathToWwwroot = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot"); if (!System.IO.Directory.Exists(pathToWwwroot)) { System.IO.Directory.CreateDirectory(pathToWwwroot); } string pathToUploadDirectory = System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), "wwwroot", "uploads"); if (!System.IO.Directory.Exists(pathToUploadDirectory)) { System.IO.Directory.CreateDirectory(pathToUploadDirectory); } foreach (IFormFile file in filePost.Files) { if (user.FreeDiskSpace < (ulong)file.Length) { result.Add(new FileUploadResult { Name = file.FileName, Length = file.Length, Message = "NOT_ENOUGHT_SPACE" }); continue; } DateTime actualTime = DateTime.Now; string fileName = actualTime.Year + actualTime.Month + actualTime.Day + "_" + actualTime.Hour + actualTime.Minute + actualTime.Second + "_" + Guid.NewGuid().ToString(); string pathToNewFile = System.IO.Path.Combine(pathToUploadDirectory, fileName); System.IO.FileStream fileStream = new System.IO.FileStream(pathToNewFile, System.IO.FileMode.Create); Task fileUploadInProgres = file.CopyToAsync(fileStream); File newFile = new File { CreatedDateTime = DateTime.Now, ResourceType = ResourceType.FILE, Name = file.FileName, OwnerID = userId, ParentDirectoryID = filePost.ParentDirectoryID, Path = pathToNewFile, FileSizeBytes = (ulong)file.Length }; await _databaseContext.Files.AddAsync(newFile); user.UsedDiskSpace += (ulong)file.Length; await _databaseContext.SaveChangesAsync(); result.Add(new FileUploadResult { Name = file.FileName, Length = file.Length, Message = "UPLOADED" }); fileStream.Close(); } return(new StatusCode <List <FileUploadResult> >(StatusCodes.Status200OK, result)); } catch { return(new StatusCode <List <FileUploadResult> >(StatusCodes.Status500InternalServerError, StatusMessages.FAILED_TO_SAVE_FILES)); } }