public async void AddRemoveListFilesTest() { // set file and folder settings Random rnd = new Random(Guid.NewGuid().GetHashCode()); string documentType = "Document Type"; string fileName = documentType + "__" + "test-file-name" + rnd.Next() + ".txt"; string folderName = "test-folder-name" + rnd.Next(); string path = "/"; if (!string.IsNullOrEmpty(sharePointFileManager.WebName)) { path += $"{sharePointFileManager.WebName}/"; } path += SharePointFileManager.DefaultDocumentListTitle + "/" + folderName + "/" + fileName; string contentType = "text/plain"; string testData = "This is just a test."; MemoryStream fileData = new MemoryStream(System.Text.Encoding.ASCII.GetBytes(testData)); // add file to SP await sharePointFileManager.AddFile(folderName, fileName, fileData, contentType); // get file details list in SP folder List <Gov.Lclb.Cllb.Interfaces.SharePointFileManager.FileDetailsList> fileDetailsList = await sharePointFileManager.GetFileDetailsListInFolder(SharePointFileManager.DefaultDocumentListTitle, folderName, documentType); //only one file should be returned Assert.Single(fileDetailsList); // validate that file name uploaded and listed are the same string serverRelativeUrl = null; foreach (var fileDetails in fileDetailsList) { Assert.Equal(fileName, fileDetails.Name); serverRelativeUrl = fileDetails.ServerRelativeUrl; } // verify that we can download the same file. byte[] data = await sharePointFileManager.DownloadFile(path); string stringData = System.Text.Encoding.ASCII.GetString(data); Assert.Equal(stringData, testData); // delete file from SP await sharePointFileManager.DeleteFile(SharePointFileManager.DefaultDocumentUrlTitle, folderName, fileName); // delete folder from SP await sharePointFileManager.DeleteFolder(SharePointFileManager.DefaultDocumentUrlTitle, folderName); }
public override Task <UploadFileReply> UploadFile(UploadFileRequest request, ServerCallContext context) { var result = new UploadFileReply(); string logFileName = WordSanitizer.Sanitize(request.FileName); string logFolderName = WordSanitizer.Sanitize(request.FolderName); SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration); CreateDocumentLibraryIfMissing(GetDocumentListTitle(request.EntityName), GetDocumentTemplateUrlPart(request.EntityName)); try { string fileName = _sharePointFileManager.AddFile(GetDocumentTemplateUrlPart(request.EntityName), request.FolderName, request.FileName, request.Data.ToByteArray(), request.ContentType).GetAwaiter().GetResult(); result.FileName = fileName; result.ResultStatus = ResultStatus.Success; } catch (SharePointRestException ex) { result.ResultStatus = ResultStatus.Fail; result.ErrorDetail = $"ERROR in uploading file {logFileName} to folder {logFolderName}"; _logger.LogError(ex, result.ErrorDetail); } catch (Exception e) { result.ResultStatus = ResultStatus.Fail; result.ErrorDetail = $"ERROR in uploading file {logFileName} to folder {logFolderName}"; _logger.LogError(e, result.ErrorDetail); } return(Task.FromResult(result)); }
public async Task <ActionResult> FileUpload([FromForm] IFormFile file) { _logger.LogError("Testing File Upload"); bool documentLibraryExists = await _sharePointFileManager.DocumentLibraryExists(DocumentListTitle); if (!documentLibraryExists) { await _sharePointFileManager.CreateDocumentLibrary(DocumentListTitle, DocumentUrlTitle); _logger.LogInformation($"Successfully created document library {DocumentListTitle} on SharePoint"); } else { _logger.LogInformation($"Successfully retrieved document library {DocumentListTitle} on SharePoint"); } // format file name string fileName = SanitizeFileName(file.FileName); // upload to SharePoint // in this example we are passing null for the folder name, which results in the file being stored directly in the document library. // Normally in a situation where you have Dynamics document management setup, you would construct a folder name using the same pattern as // used in the configuration of Dynamics Document Management. await _sharePointFileManager.AddFile(DocumentListTitle, null, fileName, file.OpenReadStream(), file.ContentType); _logger.LogInformation("Successfully uploaded file {FileName} to SharePoint", fileName); return(Ok("File uploaded.")); }
public async Task <IActionResult> UploadFile([FromRoute] string id, [FromRoute] string entityName, [FromForm] IFormFile file, [FromForm] string documentType) { if (!string.IsNullOrEmpty(id) && Guid.TryParse(id, out Guid entityId) && !string.IsNullOrEmpty(entityName) && !string.IsNullOrEmpty(documentType)) { ViewModels.FileSystemItem result = null; ValidateSession(); CreateDocumentLibraryIfMissing(GetDocumentListTitle(entityName), GetDocumentTemplateUrlPart(entityName)); if (string.IsNullOrEmpty(entityId.ToString()) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType)) { return(BadRequest()); } var hasAccess = await CanAccessEntity(entityName, entityId.ToString()); if (!hasAccess) { return(new NotFoundResult()); } // Update modifiedon to current time UpdateEntityModifiedOnDate(entityName, entityId.ToString()); string fileName = FileSystemItemExtensions.CombineNameDocumentType(file.FileName, documentType); string folderName = await GetFolderName(entityName, entityId.ToString(), documentType); try { await _sharePointFileManager.AddFile(GetDocumentTemplateUrlPart(entityName), folderName, fileName, file.OpenReadStream(), file.ContentType); } catch (SharePointRestException ex) { _logger.LogError("Error uploading file to SharePoint"); _logger.LogError(ex.Response.Content); _logger.LogError(ex.Message); return(new NotFoundResult()); } return(Json(result)); } else { return(BadRequest()); } }
public async Task <IActionResult> UploadFile([FromRoute] string entityId, [FromRoute] string entityName, [FromForm] IFormFile file, [FromForm] string documentType) { ViewModels.FileSystemItem result = null; ValidateSession(); if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType)) { return(BadRequest()); } await CreateDocumentLibraryIfMissing(GetDocumentListTitle(entityName), GetDocumentTemplateUrlPart(entityName)); var hasAccess = await CanAccessEntity(entityName, entityId); if (!hasAccess) { return(new NotFoundResult()); } // Update modifiedon to current time UpdateEntityModifiedOnDate(entityName, entityId, true); // Sanitize file name Regex illegalInFileName = new Regex(@"[#%*<>?{}~¿""]"); string fileName = illegalInFileName.Replace(file.FileName, ""); illegalInFileName = new Regex(@"[&:/\\|]"); fileName = illegalInFileName.Replace(fileName, "-"); fileName = FileSystemItemExtensions.CombineNameDocumentType(fileName, documentType); string folderName = await GetFolderName(entityName, entityId, _dynamicsClient); try { await _sharePointFileManager.AddFile(GetDocumentTemplateUrlPart(entityName), folderName, fileName, file.OpenReadStream(), file.ContentType); } catch (SharePointRestException ex) { _logger.LogError("Error uploading file to SharePoint"); _logger.LogError(ex.Response.Content); _logger.LogError(ex.Message); return(new NotFoundResult()); } return(Json(result)); }
public async Task <IActionResult> UploadFile([FromRoute] string id, [FromForm] IFormFile file, [FromForm] string documentType) { ViewModels.FileSystemItem result = null; // get the LegalEntity. // Adoxio_legalentity legalEntity = null; // get the current user. string temp = _httpContextAccessor.HttpContext.Session.GetString("UserSettings"); UserSettings userSettings = JsonConvert.DeserializeObject <UserSettings>(temp); // check that the session is setup correctly. userSettings.Validate(); if (id != null) { var applicationId = Guid.Parse(id); var application = await _dynamicsClient.GetApplicationById(applicationId); if (application == null) { return(new NotFoundResult()); } string fileName = FileSystemItemExtensions.CombineNameDocumentType(file.FileName, documentType); var applicationIdCleaned = application.AdoxioApplicationid.ToString().ToUpper().Replace("-", ""); // Dynamics code for the name is {Code(Licence Type (Licence Type))} - {Business Type(Application)} - {Job Number(Application)} string folderName = $"{application.AdoxioLicenceType.AdoxioCode} - {application.AdoxioApplicant.AdoxioBusinesstype}_{applicationIdCleaned}"; try { await _sharePointFileManager.AddFile(folderName, fileName, file.OpenReadStream(), file.ContentType); } catch (Exception ex) { _logger.LogError(ex.Message); _logger.LogError(ex.StackTrace); return(new NotFoundResult()); } } return(Json(result)); }
public async Task <IActionResult> UploadFile([FromRoute] string entityId, [FromRoute] string entityName, [FromForm] IFormFile file, [FromForm] string documentType) { ViewModels.FileSystemItem result = null; ValidateSession(); if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType)) { return(BadRequest()); } await CreateDocumentLibraryIfMissing(GetDocumentListTitle(entityName), GetDocumentTemplateUrlPart(entityName)); var hasAccess = await CanAccessEntity(entityName, entityId); if (!hasAccess) { return(new NotFoundResult()); } // Update modifiedon to current time UpdateEntityModifiedOnDate(entityName, entityId, true); // Sanitize file name Regex illegalInFileName = new Regex(@"[#%*<>?{}~¿""]"); string fileName = illegalInFileName.Replace(file.FileName, ""); illegalInFileName = new Regex(@"[&:/\\|]"); fileName = illegalInFileName.Replace(fileName, "-"); fileName = FileSystemItemExtensions.CombineNameDocumentType(fileName, documentType); string folderName = null; folderName = await GetEntitySharePointDocumentationLocation(entityName, entityId); if (folderName == null) { folderName = await GetFolderName(entityName, entityId, _dynamicsClient); } SharePointFileManager _sharePointFileManager = new SharePointFileManager(_configuration); string headers = LoggingEvents.GetHeaders(Request); try { fileName = await _sharePointFileManager.AddFile(GetDocumentTemplateUrlPart(entityName), folderName, fileName, file.OpenReadStream(), file.ContentType); result = new ViewModels.FileSystemItem() { name = fileName }; _logger.LogInformation($"SUCCESS in uploading file {fileName} to folder {folderName} Headers: {headers} "); } catch (SharePointRestException ex) { _logger.LogError($"ERROR in uploading file {fileName} to folder {folderName} Headers: {headers} - SharePointRestException - {ex.Message} {ex.Response.Content}"); return(new NotFoundResult()); } catch (Exception e) { _logger.LogError($"ERROR in uploading file {fileName} to folder {folderName} Headers: {headers} Unexpected Exception {e.ToString()} {e.Message} {e.StackTrace.ToString()}"); } return(new JsonResult(result)); }