public async Task AddFileTest()
        {
            // Arrange
            var createDocumentCommand =
                new CreateDocumentCommand(DateTime.UtcNow.Ticks.ToString(), "Test document");
            var addFileCommand = new AddFileCommand("Test", "Test file");

            // Act
            var documentUri = await _client.CreateDocumentAsync(createDocumentCommand);

            var fileUri = await _client.AddFileAsync(documentUri, addFileCommand);

            var file = await _client.GetAsync <File>(fileUri);

            var files = await _client.GetFiles(documentUri);

            // Assert
            Assert.NotNull(file);
            Assert.Equal(addFileCommand.FileName, file.Name);
            Assert.Equal(addFileCommand.FileDescription, file.Description);

            Assert.NotNull(files);
            Assert.Single(files);
            Assert.Equal(file.Id, files.First().Id);
        }
Exemple #2
0
        public async Task <IActionResult> OnPostSave([FromBody] CreateDocumentCommand command)
        {
            FileStorage _storage = new FileStorage();

            command.ContentType = _storage.GetContentType(command.Path);
            command.Root        = _configuration["Document"];
            try
            {
                List <SearchedDocumentModel> dbResult = new List <SearchedDocumentModel>();
                dbResult = await Mediator.Send(command);

                return(new JsonResult(new UIResult()
                {
                    Data = new { list = dbResult },
                    Status = UIStatus.Success,

                    Text = "اسناد و ضمایم موفقانه ثبت گردید",
                    Description = string.Empty
                }));
            }
            catch (Exception ex)
            {
                return(new JsonResult(new UIResult()
                {
                    Data = null,
                    Status = UIStatus.Failure,

                    Text = CustomMessages.InternalSystemException,
                    Description = ex.Message + " \n StackTrace : " + ex.StackTrace
                }));
            }
        }
Exemple #3
0
        public async Task ValidRequest_ReturnsResponse()
        {
            // Arrange

            var createRequest = new CreateDocumentCommand
            {
                Name = "My doc",
                Text = "This is some text",
            };

            // Act

            var createHttpResponse = await Fixture.Api.Documents.CreateDocumentAsync(createRequest);

            // Assert

            createHttpResponse.StatusCode.Should().Be(HttpStatusCode.Created);

            var createResponse = createHttpResponse.Data;

            createResponse.Id.Should().NotBeEmpty();
            createResponse.Should().BeEquivalentTo(createRequest);

            var id          = createResponse.Id;
            var findRequest = new ViewDocumentQuery {
                Id = id
            };
            var findHttpResponse = await Fixture.Api.Documents.ViewDocumentAsync(findRequest);

            var findResponse = findHttpResponse.Data;

            findHttpResponse.StatusCode.Should().Be(HttpStatusCode.OK);
            findResponse.Should().BeEquivalentTo(createResponse);
        }
Exemple #4
0
        private Task <string> UploadDocuments(CreateDocumentCommand command)
        {
            List <string> files      = new List <string>();
            string        folderPath = GetFolderPath(command.Code);

            if (command.Files != null && command.Files.Any())
            {
                foreach (HttpFile file in command.Files)
                {
                    string filePath = $"{folderPath}/{file.FileName}";
                    command.FolderName = folderPath.Replace(UploadFolderPath, string.Empty);
                    command.LinkFile   = $"/downloadfile/viewfile?sourcedoc={folderPath.Replace(UploadFolderPath, string.Empty)}/{file.FileName}";
                    files.Add(file.FileName);
                    SaveAs(filePath, file);
                }
            }

            if (command.AppendiceFiles != null && command.AppendiceFiles.Any())
            {
                int index = 0;
                foreach (HttpFile file in command.AppendiceFiles)
                {
                    string filePath = $"{folderPath}/{file.FileName}";
                    SaveAs(filePath, file);
                    command.Appendices[index].LinkFile = $"/downloadfile/viewfile?sourcedoc={folderPath.Replace(UploadFolderPath, string.Empty)}/{file.FileName}";
                    index++;
                }
            }
            return(Task.FromResult(string.Join(";", files)));
        }
Exemple #5
0
        public async Task <int> Create([FromBody] CreateDocumentCommand createDocumentCommand)
        {
            createDocumentCommand.CreatedBy = User.Identity.GetUserName();
            createDocumentCommand.CreatedOn = DateTime.Now;
            createDocumentCommand.Deleted   = false;
            createDocumentCommand.FileName  = await UploadDocuments(createDocumentCommand);

            return(await Mediator.Send(createDocumentCommand));
        }
 public static Document ToDocument(this CreateDocumentCommand cmd)
 {
     return(new Document {
         DocumentTypeId = cmd.DocumentTypeId,
         EntityId = cmd.EntityId,
         PublicationDate = cmd.PublicationDate,
         PublicationYear = cmd.PublicationDate.Year,
         Number = cmd.Number
     });
 }
        public async Task <IActionResult> Post([FromForm] CreateDocumentCommand command)
        {
            if (command == null)
            {
                throw new ApiProblemDetailsException("Invalid JSON.", StatusCodes.Status400BadRequest);
            }

            BasicApiResponse <ReadDocumentResponse> response = await Mediator.Send(command);

            return(CreatedAtAction(nameof(Get), new { id = response.Result.Id }, response));
        }
Exemple #8
0
        public async Task <CreateDocumentCommand> CreateCreateDocumentCommand(Document document, IMessageDataRepository messageDataRepository)
        {
            var messageData = await messageDataRepository.PutBytes(document.Content, TimeSpan.FromMinutes(10));

            var createDocumentCommand = new CreateDocumentCommand(
                document.Id, document.Name, (int)document.DocumentStatus.Id,
                document.DocumentName, document.ContentType,
                document.Created.On, document.Created.UserId,
                document.Updated.On, document.Updated.UserId,
                messageData);

            return(createDocumentCommand);
        }
 public Document CreateFromCommand(Guid id, CreateDocumentCommand command)
 {
     return(new Document(id)
     {
         Name = command.Name,
         DocumentName = command.File.FileName,
         DocumentStatus = DocumentStatusFactory.Create(command.DocumentStatusId),
         Content = command.File.FileContent,
         ContentType = command.File.FileContentType,
         Created = new AuditTrack(_userId, _dateTime),
         Updated = new AuditTrack(_userId, _dateTime)
     });
 }
Exemple #10
0
        public ActionResult Create([FromBody] CreateDocumentCommand model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest());
            }

            var newDocument = new Document(Guid.NewGuid().ToString(), model.Title, model.Description ?? string.Empty);

            Archive.Add(newDocument);

            return(CreatedAtAction(nameof(GetById), new { id = newDocument.Id }, newDocument));
        }
Exemple #11
0
        public async Task <int> CreateAndRelease([FromBody] CreateDocumentCommand createDocumentCommand)
        {
            createDocumentCommand.CreatedBy = User.Identity.GetUserName();
            createDocumentCommand.CreatedOn = DateTime.Now;
            createDocumentCommand.Deleted   = false;
            createDocumentCommand.FileName  = await UploadDocuments(createDocumentCommand);

            int id = await Mediator.Send(createDocumentCommand);

            if (id > 0)
            {
                await SendMailReleaseDocument(createDocumentCommand);
            }
            return(id);
        }
        public async Task CreateDocumentTest()
        {
            // Arrange
            var createDocumentCommand = new CreateDocumentCommand(DateTime.UtcNow.Ticks.ToString(), "Test document");

            // Act
            var documentUri = await _client.CreateDocumentAsync(createDocumentCommand);

            var document = await _client.GetAsync <Document>(documentUri);

            // Assert
            Assert.NotNull(document);
            Assert.Equal(createDocumentCommand.Number, document.Number);
            Assert.Equal(createDocumentCommand.Description, document.Description);
            Assert.Equal(DocumentStatus.Draft.ToString(), document.Status);
        }
        public IActionResult CreateDocument(
            [ModelBinder(BinderType = typeof(JsonModelBinder))] CreateDocumentCommand value,
            IList <IFormFile> files)
        {
            Stream stream = null;

            if (files != null && files.Length() > 0)
            {
                var file = files[0];
                stream     = file.OpenReadStream();
                value.File = stream;
            }

            return(_createCommandHandler.Execute(value)
                   .Match(x => x.Match <IActionResult>(Ok, BadRequest),
                          ex => StatusCode(500, ex)));
        }
Exemple #14
0
        public async Task TestCreateDocumentInvalidCommandBadRequestResult()
        {
            //Arrange
            var command = new CreateDocumentCommand(string.Empty, "test");

            _documentsController = new DocumentsController(TestHelper.ValidReadEventsFunc(), TestHelper.SaveAndPublish,
                                                           DocumentExistsByNumber, TestHelper.GetDocumentById(), TestHelper.GetCurrentUserId());

            //Act
            var result = await _documentsController.CreateDocument(command);

            //Assert
            var badRequestResult = result as BadRequestObjectResult;

            Assert.NotNull(badRequestResult);
            Assert.NotNull(badRequestResult.Value);
        }
Exemple #15
0
        public async Task TestCreateDocumentCreatedResult()
        {
            //Arrange
            var command = new CreateDocumentCommand("1234", "test");

            _documentsController = new DocumentsController(TestHelper.ValidReadEventsFunc(), TestHelper.SaveAndPublish,
                                                           DocumentExistsByNumber, TestHelper.GetDocumentById(), TestHelper.GetCurrentUserId());

            //Act
            var result = await _documentsController.CreateDocument(command);

            //Assert
            var createdResult = result as CreatedResult;

            Assert.NotNull(createdResult);
            Assert.NotNull(createdResult.Location);
        }
Exemple #16
0
        public async Task <IActionResult> CreateDocument([FromBody] CreateDocumentCommand command)
        {
            //More than three from clauses does not work, that's why two of them are combined to local helper function
            Task <Validation <Error, (CreateDocumentCommand Command, Guid UserId)> > ValidateCommandAndGetUserId() =>
            from id in GetCurrentUserId(HttpContext)
            .Map(x => x.ToValidation <Error>("Current user Id was not found"))
            from cmd in ValidateCreateCommand(command)
            select(cmd, id);

            var outcome =
                from result in ValidateCommandAndGetUserId()
                from evt in result.Command.ToEvent(Guid.NewGuid(), result.UserId).AsTask()
                from _ in SaveAndPublishEventAsync(evt)
                select evt;

            return(await outcome.Map(val => val.ToActionResult(evt => Created($"documents/{evt.EntityId}", null))));
        }
Exemple #17
0
        public async Task TestCreateDocumentDocumentExistsBadRequestResult()
        {
            //Arrange
            var command = new CreateDocumentCommand("1234", "test");
            var documentExistsByNumber = new DocumentRepository.DocumentExistsByNumber(_ => Task.FromResult(true));

            _documentsController = new DocumentsController(TestHelper.ValidReadEventsFunc(), TestHelper.SaveAndPublish,
                                                           documentExistsByNumber, TestHelper.GetDocumentById(), TestHelper.GetCurrentUserId());

            //Act
            var result = await _documentsController.CreateDocument(command);

            //Assert
            var badRequestResult = result as BadRequestObjectResult;

            Assert.NotNull(badRequestResult);
            Assert.NotNull(badRequestResult.Value);
        }
Exemple #18
0
        public async Task ExecuteAsync()
        {
            var reader = _readerFactory.Create();

            var document = reader.Read();

            var request = new CreateDocumentCommand
            {
                Name = document.Name,
                Text = document.Text,
            };

            var response = await _apiClient.Documents.CreateDocumentAsync(request);

            Console.WriteLine($"Word count is: {response.Data.WordCount}");

            Console.ReadKey();
        }
        public async Task CreateDocumentCommand_CustomerDataCreateOnFile()
        {
            //Arange
            var ocrRServiceMoq   = new Mock <IOCRService>();
            var writeIRepository = new Mock <IWriteIRepository> ();
            var command          = new CreateDocumentCommand()
            {
                FileName = "test", UserId = 1
            };
            var config  = new MapperConfiguration(cfg => cfg.AddProfile <OCRProfile>());
            var handler = new CreateDocumentCommandHandler(ocrRServiceMoq.Object, writeIRepository.Object, config.CreateMapper());

            //Act
            DocumentDTO x = await handler.Handle(command, new System.Threading.CancellationToken());

            //Asert
            ocrRServiceMoq.Verify(x => x.GetText(It.IsAny <byte[]>()), Times.Once);
        }
        public async Task SendDocumentForApprovalTest()
        {
            // Arrange
            var createDocumentCommand = new CreateDocumentCommand(DateTime.UtcNow.Ticks.ToString(), "Test document");
            var addFileCommand        = new AddFileCommand("Test", "Test file");

            // Act
            var documentUri = await _client.CreateDocumentAsync(createDocumentCommand);

            await _client.AddFileAsync(documentUri, addFileCommand);

            await _client.SendDocumentForApprovalAsync(documentUri);

            var document = await _client.GetAsync <Document>(documentUri);

            // Assert
            Assert.NotNull(document);
            Assert.Equal(DocumentStatus.WaitingForApproval.ToString(), document.Status);
        }
Exemple #21
0
        public async Task Handler_GivenEmptyFileParameters_ReturnsTrue()
        {
            var filename          = "example.pdf";
            var bytes             = new byte[0];
            var cancellationToken = new CancellationToken();

            var dateCreated      = new DateTime(2000, 12, 31, 01, 02, 03);
            var dateTimeProvider = new Mock <IDateTimeProvider>();

            dateTimeProvider.Setup(x => x.UtcNow).Returns(dateCreated);

            var repository = new Mock <IDocumentRepository>();
            var factory    = new DocumentFactory(dateTimeProvider.Object);

            var request = new CreateDocumentCommand(filename, bytes.Length);
            var handler = new CreateDocumentCommandHandler(repository.Object, factory);

            var result = await handler.Handle(request, cancellationToken);

            result.IsSuccessful.ShouldBeFalse();
        }
        public async Task <ActionResult <CreateDocumentResponse> > CreateDocumentAsync([FromBody] CreateDocumentRequest model,
                                                                                       [ClaimModelBinder(AppClaimsPrincipalFactory.Score)] int score,
                                                                                       CancellationToken token)
        {
            var userId = _userManager.GetLongUserId(User);

            if (!model.BlobName.StartsWith("file-", StringComparison.OrdinalIgnoreCase))
            {
                ModelState.AddModelError(nameof(model.Name), "Invalid file name");
                return(BadRequest(ModelState));
            }
            var command = new CreateDocumentCommand(model.BlobName, model.Name,
                                                    model.Course, userId, model.Price, model.Description);
            await _commandBus.DispatchAsync(command, token);

            //var url = Url.RouteUrl("ShortDocumentLink", new
            //{
            //    base62 = new Base62(command.Id).ToString()
            //});
            return(new CreateDocumentResponse(score >= Privileges.Post));
        }
 public async Task <ActionResult> Post([FromBody] CreateDocumentCommand createDocument)
 {
     return(Created(string.Empty, await mediator.Send(createDocument)));
 }
Exemple #24
0
 public static Document ToDocument(this CreateDocumentCommand command)
 {
     return(command.MapTo <CreateDocumentCommand, Document>());
 }
 public ActionResult AddNewDocument([FromBody] CreateDocumentCommand command)
 {
     _mediator.Send(command);
     return(Ok());
 }
        public async Task <ActionResult <CreateDocumentCommandResponse> > CreateDocumentAsync(CreateDocumentCommand request)
        {
            var response = await _messageBus.SendAsync(request);

            return(CreatedAtRoute("view-document", new { id = response.Id }, response));
        }
Exemple #27
0
 ToEvent(this CreateDocumentCommand command, Guid documentId, Guid userId) =>
 (DocumentNumber.Create(command.Number), DocumentDescription.Create(command.Description)).Apply(
Exemple #28
0
 ValidateDocument(CreateDocumentCommand document)
 => from x in ValidateFieldNonNull(document, nameof(document))
 from y in (
Exemple #29
0
        protected async Task <int> SendMailReleaseDocument(CreateDocumentCommand command)
        {
            string host         = ConfigurationManager.AppSettings["Host"].ToString();
            string mailTemplate = GetMailTemplate("ReleaseDocument.html");

            ClaimsPrincipal user  = User as ClaimsPrincipal;
            string          token = user.FindFirst("access_token").Value;
            Func <Task <IEnumerable <dynamic> > > users = async() => await CallApi(new Uri($"{MasterDataEndpoint}/api/v1/masterdatas/getallusers"), token);

            IEnumerable <dynamic> result = await AppCache.GetOrAddAsync(CacheKeys.UserCacheKey, users);

            Func <Task <IEnumerable <dynamic> > > groupsFunc = async() => await CallApi(new Uri($"{MasterDataEndpoint}/api/v1/masterdatas/getalldepartments"), token);

            IEnumerable <dynamic> groups = await AppCache.GetOrAddAsync(CacheKeys.DepartmentCacheKey, groupsFunc);

            List <string> groupEmails = new List <string>();

            string[] deployments = command.ScopeOfDeloyment.Split(";");

            if (deployments != null && deployments.Any())
            {
                foreach (string deployment in deployments)
                {
                    dynamic group = groups.FirstOrDefault(g => g.code == deployment);
                    if (group != null)
                    {
                        string email = group.email;
                        groupEmails.Add(email.Replace(";", ","));
                    }

                    IEnumerable <dynamic> userGroups = result.Where(u => u.departmentName == deployment);
                    if (userGroups != null)
                    {
                        foreach (dynamic userGroup in userGroups)
                        {
                            string email = userGroup.email;
                            if (!email.IsNullOrEmpty())
                            {
                                groupEmails.Add(email);
                            }
                        }
                    }
                }
            }

            string draterFullName = GetUserFullName(command.Drafter, result);

            string auditorFullName = GetUserFullName(command.Auditor, result);

            string approverFullName = GetUserFullName(command.Approver, result);

            string createdEmail = User.Identity.GetUserEmail();

            if (!createdEmail.IsNullOrEmpty())
            {
                groupEmails.Add(createdEmail);
            }

            if (!mailTemplate.IsNullOrEmpty())
            {
                string effectiveDateString = string.Empty;
                if (command.EffectiveDate.HasValue)
                {
                    effectiveDateString = $"{command.EffectiveDate.Value.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture)}";
                }

                string reviewDateString = string.Empty;
                if (command.ReviewDate.HasValue)
                {
                    reviewDateString = $"{command.ReviewDate.Value.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture)}";
                }

                string     linkFile   = $"<a href=\"{host}/downloadfile/viewfile?sourceDoc={command.FolderName}/{command.FileName}\">{command.FileName}</a>";
                MailHelper mailHelper = new MailHelper
                {
                    Sender      = MailSender,
                    Recipient   = string.Join(",", groupEmails.ToArray()),
                    RecipientCC = string.Join(",", new string[] { }),
                    Subject     = $"DCC - Ban hành tài liệu mới",
                    Body        = string.Format(mailTemplate,
                                                $"DCC - Ban hành tài liệu mới;#{command.DepartmentName} : {command.FileName}",
                                                "Ban hành tài liệu mới",
                                                command.Name,
                                                command.ScopeOfApplication.Replace("\n", "<br>"),
                                                effectiveDateString,
                                                command.Description.Replace("\n", "<br>"),
                                                command.ScopeOfDeloyment,
                                                command.DocumentNumber,
                                                command.ReviewNumber,
                                                reviewDateString,
                                                draterFullName,
                                                auditorFullName,
                                                approverFullName,
                                                linkFile,
                                                $"<a href=\"{host}/operationdata/detail?code={command.Code}\">{host}/operationdata/detail?code={command.Code}</a>",
                                                $"<a href=\"{host}/operationdata/list?code={command.DocumentType}\">{host}/operationdata/list?code={command.DocumentType}</a>"
                                                )
                };
                mailHelper.Send();
            }

            return(1);
        }
        public async Task <IActionResult> CreateAsync([FromBody] CreateDocumentCommand command)
        {
            var response = await _mediator.Send(command);

            return(JsonResult(response));
        }