Exemplo n.º 1
0
        public void AttachFilesToRequests(List <Request> requests, NiisWebContextMigration niisWebContext,
                                          ref int migratedFilesCount)
        {
            var documentFiles =
                _oldNiisDocumentDataService.GetDdDocumentDatas(requests.Select(r => r.Barcode).ToList());

            if (documentFiles.Any() == false)
            {
                return;
            }

            foreach (var request in requests)
            {
                var documentData = documentFiles.SingleOrDefault(d => d.Id == request.Barcode);
                if (documentData == null)
                {
                    continue;
                }
                if (string.IsNullOrWhiteSpace(documentData.FileName))
                {
                    documentData.FileName = $"{request.Barcode}.{FileTypes.Pdf}";
                }
                var attachment = new Attachment
                {
                    AuthorId     = request.UserId ?? _appConfiguration.AuthorAttachmentDocumentId,
                    ContentType  = FileTypeHelper.GetContentType(documentData.FileName),
                    BucketName   = $"old-request-{request.Barcode}",
                    IsMain       = true,
                    CopyCount    = request.CopyCount,
                    PageCount    = request.PageCount,
                    DateCreate   = documentData.DateCreate,
                    DateUpdate   = documentData.DateUpdate,
                    OriginalName = documentData.FileName,
                    Length       = documentData.File.Length,
                    ValidName    = documentData.FileName.MakeValidFileName(),
                    Hash         = _generateHash.GenerateFileHash(documentData.File)
                };

                _newNiisAttachmentFileService = new NewNiisAttachmentFileService(niisWebContext);

                _newNiisAttachmentFileService.CreateAttachment(attachment);
                _fileStorage.AddAsync(attachment.BucketName, attachment.ValidName, documentData.File,
                                      attachment.ContentType).Wait();

                request.MainAttachmentId = attachment.Id;

                niisWebContext.SaveChanges();

                migratedFilesCount++;
            }
        }
Exemplo n.º 2
0
        private async Task <Attachment> CreateAttachment(DocumentData oldAttachment, int newDocumentId)
        {
            try
            {
                var fileName = oldAttachment.FileName;
                var file     = oldAttachment.File;

                var documentInfo = SavedDocuments.FirstOrDefault(d => d.Id == newDocumentId);
                if (documentInfo == null)
                {
                    return(null);
                }

                var extentionPath = GetDocumentTypeName((byte)documentInfo.DocumentType);
                var bucketName    = GetBucketName(null, newDocumentId, null);

                if (string.IsNullOrWhiteSpace(fileName))
                {
                    fileName = $"{Guid.NewGuid()}.{FileTypes.Pdf}";
                }

                var originalName = GetFolderWithOriginalName(null, newDocumentId, null, fileName, extentionPath);
                var validName    = fileName.MakeValidFileName();
                var contentType  = FileTypeHelper.GetContentType(fileName);

                await _fileStorage.AddAsync(bucketName, originalName, file, contentType);

                var attachment = new Attachment
                {
                    AuthorId     = DeveloperUserId,
                    ContentType  = contentType,
                    BucketName   = bucketName,
                    IsMain       = true,
                    CopyCount    = documentInfo.CopyCount,
                    PageCount    = documentInfo.PageCount,
                    DateCreate   = DateTimeOffset.Now,
                    DateUpdate   = DateTimeOffset.Now,
                    OriginalName = originalName,
                    Length       = file.Length,
                    ValidName    = validName,
                    Hash         = _generateHash.GenerateFileHash(file),
                    ExternalId   = documentInfo.ExternalId,
                    DocumentId   = newDocumentId,
                    IsDeleted    = false
                };

                return(attachment);
            }
            catch (Exception)
            {
                return(null);
            }
        }
Exemplo n.º 3
0
        /// <summary>
        /// Загрузка медиа-файла на фауловое хранилище и прикрепление его к заявке
        /// </summary>
        /// <param name="requestId">Уникальный идентификатор заявки</param>
        /// <param name="file">Прикрепляемый файл из запроса</param>
        /// <returns></returns>
        public async Task ExecuteAsync(int requestId, IFormFile file)
        {
            var request = await Executor.GetQuery <GetRequestByIdQuery>().Process(q => q.ExecuteAsync(requestId));

            //Название папки на файловом хранилище minio
            var bucketName = $"requests";

            //var bucketName = $"request-{requestId}-media-{DateTimeOffset.Now:dd.MM.yyyy}";

            //var fileName = $"current/{requestId}/{file.FileName}";
            byte[] fileBytes;

            var extention   = Path.GetExtension(file.FileName);
            var newFileName = $"current/{requestId}/{Guid.NewGuid().ToString()}{extention}";


            //Чтение файла, запись его содержимого в массив байтов
            using (var stream = file.OpenReadStream())
                using (var memoryStream = new MemoryStream())
                {
                    stream.CopyTo(memoryStream);
                    fileBytes = memoryStream.ToArray();
                }

            //Загрузка файла на minio
            await _fileStorage.AddAsync(bucketName, newFileName, fileBytes, file.ContentType);

            foreach (var mediaFile in request.MediaFiles)
            {
                mediaFile.IsDeleted   = true;
                mediaFile.DeletedDate = DateTimeOffset.Now;
                await Executor.GetCommand <UpdateAttachmentCommand>().Process(c => c.ExecuteAsync(mediaFile));
            }

            //Создание сущности-прикрепления в базе
            var mediaAttachment = new Attachment
            {
                BucketName   = bucketName,
                ContentType  = file.ContentType,
                AuthorId     = NiisAmbientContext.Current.User.Identity.UserId,
                DateCreate   = DateTimeOffset.Now,
                DateUpdate   = DateTimeOffset.Now,
                OriginalName = newFileName,
                Length       = file.Length,
                ValidName    = file.FileName.MakeValidFileName(),
                //Hash = _generateHash.GenerateFileHash(fileBytes),
                RequestId = requestId
            };
            await Executor.GetCommand <CreateAttachmentCommand>().Process(c => c.ExecuteAsync(mediaAttachment));
        }
Exemplo n.º 4
0
        public void AttachFile(AttachedFileModel attachedFile, Document document)
        {
            var attachment = new Attachment
            {
                DateCreate   = DateTimeOffset.Now,
                DocumentId   = document.Id,
                IsMain       = attachedFile.IsMain,
                CopyCount    = attachedFile.CopyCount,
                Length       = attachedFile.Length,
                AuthorId     = _configuration.AuthorAttachmentDocumentId,
                PageCount    = attachedFile.PageCount,
                OriginalName = "integration/" + GetDocumentTypeName(document.DocumentType) + "/" + Guid.NewGuid(), //attachedFile.Name,
                ValidName    = attachedFile.Name.MakeValidFileName(),
                ContentType  = FileTypeHelper.GetContentType(attachedFile.Name),
                Hash         = _generateHash.GenerateFileHash(attachedFile.File),
                BucketName   = "documents"
            };
            var attachmentId = CreateAttachment(attachment);

            Task.Run(() => _fileStorage.AddAsync(attachment.BucketName, attachment.OriginalName, attachedFile.File, attachment.ContentType)).Wait();

            document.MainAttachmentId = attachmentId;
        }
        public async Task <Request> Execute(IntellectualPropertyScannerDto data)
        {
            using (var fileStream = File.OpenRead(Path.Combine(Path.GetTempPath(),
                                                               data.Attachment.TempName)))
            {
                if (!data.Id.HasValue)
                {
                    throw new Exception("Request not Fount");
                }

                var request = await Executor.GetQuery <GetRequestByIdQuery>().Process(q => q.ExecuteAsync((int)data.Id));

                if (request == null)
                {
                    throw new Exception("Request not Fount");
                }

                var bucketName = "requests";
                var userId     = NiisAmbientContext.Current.User.Identity.UserId;
                var fileName   = $"{request.Barcode}_{request.ProtectionDocType.NameRu}{Path.GetExtension(data.Attachment.Name)}";
                //var originalName = $"current/{request.Id}/{fileName}";

                var extention    = Path.GetExtension(fileName);
                var originalName = $"current/{request.Id}/{Guid.NewGuid().ToString()}{extention}";

                var newAttachment = data.Attachment.ContentType.Equals(ContentType.Pdf)
                    ? _attachmentHelper.NewPdfObject(data.Attachment, userId, bucketName, fileStream, originalName, fileName, true)
                    : _attachmentHelper.NewFileObject(data.Attachment, userId, bucketName, fileStream, originalName, fileName, true);

                // TODO: Transaction with complex logic
                //using (var transaction = _context.Database.BeginTransaction())
                //{
                try
                {
                    await Executor.GetCommand <CreateAttachmentCommand>().Process(q => q.ExecuteAsync(newAttachment));

                    await _fileStorage.AddAsync(newAttachment.BucketName, newAttachment.OriginalName, fileStream, newAttachment.ContentType);

                    var oldAttachment = request.MainAttachment;

                    request.MainAttachment   = newAttachment;
                    request.MainAttachmentId = newAttachment.Id;
                    request.PageCount        = newAttachment.PageCount;
                    request.CopyCount        = newAttachment.CopyCount;
                    await Executor.GetCommand <UpdateRequestCommand>().Process(q => q.ExecuteAsync(request));

                    //transaction.Commit();

                    if (oldAttachment != null)
                    {
                        if (oldAttachment.ValidName != newAttachment.ValidName)
                        {
                            await _fileStorage.Remove(oldAttachment.BucketName, oldAttachment.OriginalName);
                        }

                        await Executor.GetCommand <DeleteAttachmentCommand>().Process(q => q.ExecuteAsync(oldAttachment));
                    }
                }
                catch
                {
                    //todo: log exception
                    throw;
                }

                return(request);
            }
        }
        public async Task <Document> Execute(MaterialDetailDto data)
        {
            using (var fileStream = System.IO.File.OpenRead(Path.Combine(Path.GetTempPath(),
                                                                         data.Attachment.TempName)))
            {
                if (!data.Id.HasValue)
                {
                    throw new Exception("Document not Found");
                }
                var document = await Executor.GetQuery <GetDocumentByIdQuery>().Process(q => q.ExecuteAsync(data.Id.Value));

                if (document == null)
                {
                    throw new Exception("Document not Found");
                }

                var    bucketName = "documents";
                string extentionPath;

                switch (document.DocumentType)
                {
                case DocumentType.Incoming:
                    extentionPath = "incoming";
                    break;

                case DocumentType.Outgoing:
                    extentionPath = "outgoing";
                    break;

                case DocumentType.Internal:
                    extentionPath = "internal";
                    break;

                case DocumentType.DocumentRequest:
                    extentionPath     = "documentRequest";
                    document.StatusId = Executor.GetQuery <GetDocumentStatusByCodeQuery>().Process(q => q.Execute(DicDocumentStatusCodes.Completed)).Id;
                    break;

                default:
                    extentionPath = "unknown";
                    break;
                }
                var fileName = $"{document.Barcode}_{document.Type.Code}{Path.GetExtension(data.Attachment.Name)}";
                //var extentionPathResult = extentionPath != null ? $"{extentionPath}/" : string.Empty;
                //var originalName = $"current/{extentionPathResult}{document.Id}/{fileName}";

                var extention    = Path.GetExtension(fileName);
                var originalName = $"current/{extentionPath}/{document.Id}/{Guid.NewGuid().ToString()}{extention}";

                var userId        = NiisAmbientContext.Current.User.Identity.UserId;
                var newAttachment = data.Attachment.ContentType.Equals(ContentType.Pdf)
                    ? _attachmentHelper.NewPdfObject(data.Attachment, userId, bucketName, fileStream, originalName, fileName, data.Attachment.IsMain, document.Id)
                    : _attachmentHelper.NewFileObject(data.Attachment, userId, bucketName, fileStream, originalName, fileName, data.Attachment.IsMain, document.Id);

                // TODO: Transaction with complex logic
                //using (var transaction = _context.Database.BeginTransaction())
                //{
                try
                {
                    await Executor.GetCommand <CreateAttachmentCommand>().Process(q => q.ExecuteAsync(newAttachment));

                    document.WasScanned = data.Attachment.WasScanned;
                    if (data.Attachment.IsMain)
                    {
                        var oldAttachment = document.MainAttachment;
                        document.MainAttachment   = newAttachment;
                        document.MainAttachmentId = newAttachment.Id;
                        await Executor.GetCommand <UpdateDocumentCommand>().Process(c => c.Execute(document));

                        if (oldAttachment != null)
                        {
                            await Executor.GetCommand <DeleteAttachmentCommand>()
                            .Process(q => q.ExecuteAsync(oldAttachment));

                            try
                            {
                                await _fileStorage.Remove(oldAttachment.BucketName, oldAttachment.ValidName);
                            }
                            catch (Exception exception)
                            {
                                var contextExceptionMessage = $"{Guid.NewGuid()}: {exception.Message}";
                                Log.Warning(exception, contextExceptionMessage);
                            }
                        }
                    }
                    else
                    {
                        var oldAttachment = document.AdditionalAttachments.FirstOrDefault(d => d.IsMain == false);

                        if (oldAttachment != null)
                        {
                            await Executor.GetCommand <DeleteAttachmentCommand>()
                            .Process(q => q.ExecuteAsync(oldAttachment));

                            try
                            {
                                await _fileStorage.Remove(oldAttachment.BucketName, oldAttachment.OriginalName);
                            }
                            catch (Exception exception)
                            {
                                var contextExceptionMessage = $"{Guid.NewGuid()}: {exception.Message}";
                                Log.Warning(exception, contextExceptionMessage);
                            }
                        }
                        await Executor.GetCommand <UpdateDocumentCommand>().Process(c => c.Execute(document));
                    }

                    await _fileStorage.AddAsync(newAttachment.BucketName, newAttachment.OriginalName, fileStream, newAttachment.ContentType);

                    //transaction.Commit();
                }
                catch
                {
                    //todo: log exception
                    throw;
                }
                // }

                return(document);
            }
        }
Exemplo n.º 7
0
            public async Task <MaterialDetailDto> Handle(Command message)
            {
                using (var fileStream = File.OpenRead(Path.Combine(_tempFolderPath,
                                                                   message.MaterialIncomingDataDto.Attachment.TempName)))
                {
                    var document = await _context.Documents
                                   .Include(d => d.MainAttachment)
                                   .SingleAsync(d => d.Id == message.MaterialIncomingDataDto.Id);

                    switch (document.DocumentType)
                    {
                    case DocumentType.Incoming:
                        _bucketName = $"document-{document.Id}-incoming";
                        break;

                    case DocumentType.Outgoing:
                        _bucketName = $"document-{document.Id}-outgoing";
                        break;

                    case DocumentType.Internal:
                        _bucketName = $"document-{document.Id}-internal";
                        break;

                    default:
                        throw new Exception("Type is undefined");
                    }

                    Attachment newAttachment;

                    if (message.MaterialIncomingDataDto.Attachment.ContentType.Equals(ContentType.Pdf))
                    {
                        newAttachment = _attachmentHelper.NewPdfObject(message.MaterialIncomingDataDto.Attachment,
                                                                       message.UserId, document.Id, _bucketName, fileStream, true);
                    }
                    else
                    {
                        newAttachment = _attachmentHelper.NewFileObject(message.MaterialIncomingDataDto.Attachment,
                                                                        message.UserId, document.Id, _bucketName, fileStream, true);
                    }



                    using (var transaction = _context.Database.BeginTransaction())
                    {
                        try
                        {
                            await _context.AddAsync(newAttachment);

                            var oldAttachment = document.MainAttachment;

                            document.MainAttachment = newAttachment;
                            if (newAttachment.PageCount.HasValue && message.MaterialIncomingDataDto.Owners.Any(o => o.OwnerType == Owner.Type.Request))
                            {
                                AddPageCountToRequest(message.MaterialIncomingDataDto.Owners.Where(o => o.OwnerType == Owner.Type.Request).Select(o => o.OwnerId).ToArray()[0], newAttachment.PageCount.Value, oldAttachment?.PageCount);
                            }
                            await _context.SaveChangesAsync();

                            await _fileStorage.AddAsync(document.MainAttachment.BucketName,
                                                        document.MainAttachment.ValidName, fileStream, document.MainAttachment.ContentType);

                            transaction.Commit();

                            if (oldAttachment != null)
                            {
                                await _fileStorage.Remove(oldAttachment.BucketName, oldAttachment.ValidName);

                                _context.Attachments.Remove(oldAttachment);
                            }
                        }
                        catch (Exception e)
                        {
                            throw;
                        }
                    }

                    return(_mapper.Map <Document, MaterialDetailDto>(document));
                }
            }