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);
            }
        }
        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);
            }
        }
Example #3
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));
                }
            }