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));
        }
Exemple #3
0
        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));
        }
Exemple #4
0
        public static void UploadPdfIfChanged(this FileManagerClient _fileManagerClient, ILogger _logger, string entityName, string entityId, string folderName, string documentType, byte[] data, string hash)
        {
            Contract.Requires(_fileManagerClient != null);
            Contract.Requires(documentType != null);

            // SharePoint can truncate file names that are too long. Make sure we account for that.
            var fileName = FileSystemItemExtensions.CombineNameDocumentType($"{hash}.pdf", documentType);

            fileName = _fileManagerClient.GetTruncatedFilename(_logger, entityName, folderName, fileName);

            var notChanged = _fileManagerClient.FileExists(_logger, entityName, entityId, folderName, documentType, fileName);

            if (notChanged)
            {
                // Do not save full file names to the logs (for privacy)
                var logFolderName = WordSanitizer.Sanitize(folderName);
                var logFileName   = WordSanitizer.Sanitize(fileName);
                _logger.LogInformation($"PDF file {logFileName} in folder {logFolderName} hasn't changed. Will NOT UPLOAD again.");

                // Abort early if PDF hasn't changed...
                return;
            }
            _fileManagerClient.UploadPdf(_logger, entityName, entityId, folderName, fileName, data);
        }
        /// <summary>
        /// Internal implementation of upload attachment
        /// </summary>
        /// <param name="entityId"></param>
        /// <param name="entityName"></param>
        /// <param name="file"></param>
        /// <param name="documentType"></param>
        /// <param name="checkUser"></param>
        /// <returns></returns>
        private async Task <IActionResult> UploadAttachmentInternal(string entityId, string entityName,
                                                                    IFormFile file, string documentType, bool checkUser)
        {
            FileSystemItem result = null;

            if (string.IsNullOrEmpty(entityId) || string.IsNullOrEmpty(entityName) || string.IsNullOrEmpty(documentType))
            {
                return(BadRequest());
            }

            var hasAccess = true;

            if (checkUser)
            {
                ValidateSession();
                hasAccess = await CanAccessEntity(entityName, entityId).ConfigureAwait(true);
            }

            if (!hasAccess)
            {
                return(new NotFoundResult());
            }

            // Sanitize file name
            var illegalInFileName = new Regex(@"[#%*<>?{}~¿""]");
            var fileName          = illegalInFileName.Replace(file.FileName, "");

            illegalInFileName = new Regex(@"[&:/\\|]");
            fileName          = illegalInFileName.Replace(fileName, "-");

            fileName = FileSystemItemExtensions.CombineNameDocumentType(fileName, documentType);

            var folderName = await _dynamicsClient.GetFolderName(entityName, entityId).ConfigureAwait(true);

            _dynamicsClient.CreateEntitySharePointDocumentLocation(entityName, entityId, folderName, folderName);

            var ms = new MemoryStream();

            file.OpenReadStream().CopyTo(ms);
            var data = ms.ToArray();

            // call the web service
            var uploadRequest = new UploadFileRequest
            {
                ContentType = file.ContentType,
                Data        = ByteString.CopyFrom(data),
                EntityName  = entityName,
                FileName    = fileName,
                FolderName  = folderName
            };

            var uploadResult = _fileManagerClient.UploadFile(uploadRequest);

            var logFolderName = WordSanitizer.Sanitize(folderName);
            var logFileName   = WordSanitizer.Sanitize(fileName);

            if (uploadResult.ResultStatus == ResultStatus.Success)
            {
                // Update modifiedon to current time
                UpdateEntityModifiedOnDate(entityName, entityId, true);
                _logger.LogInformation($"SUCCESS in uploading file {logFileName} to folder {logFolderName}");
            }
            else
            {
                _logger.LogError($"ERROR in uploading file {logFileName} to folder {logFolderName}");
                throw new Exception($"ERROR in uploading file {logFileName} to folder {logFolderName}");
            }

            return(new JsonResult(result));
        }
Exemple #6
0
        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());
            }
            var hasAccess = await CanAccessEntity(entityName, entityId);

            if (!hasAccess)
            {
                return(new NotFoundResult());
            }

            // 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);
            }

            MemoryStream ms = new MemoryStream();

            file.OpenReadStream().CopyTo(ms);
            byte[] data = ms.ToArray();

            // call the web service
            var uploadRequest = new UploadFileRequest()
            {
                ContentType = file.ContentType,
                Data        = ByteString.CopyFrom(data),
                EntityName  = entityName,
                FileName    = fileName,
                FolderName  = folderName
            };

            var uploadResult = _fileManagerClient.UploadFile(uploadRequest);

            if (uploadResult.ResultStatus == ResultStatus.Success)
            {
                // Update modifiedon to current time
                UpdateEntityModifiedOnDate(entityName, entityId, true);
                _logger.LogInformation($"SUCCESS in uploading file {fileName} to folder {folderName}");
            }
            else
            {
                _logger.LogError($"ERROR in uploading file {fileName} to folder {folderName}");
                throw new Exception($"ERROR in uploading file {fileName} to folder {folderName}");
            }

            return(new JsonResult(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));
        }