public async Task<IActionResult> CreateOrganization(CreateOrganizationCommand command, ApiVersion version)
	{
		var organization = await Mediator.Send(command);
		return CreatedAtAction(nameof(GetOrganization),
			new { id = organization.Id, version = version.ToString() }, 
			organization);
	}  
        public async Task <IHttpActionResult> CreateOrganization(string description,
                                                                 string details,
                                                                 OrganizationType organizationType,
                                                                 ReportingFrequency reportingFrequency,
                                                                 EntityReference parent)
        {
            try
            {
                if (!_userContext.CurrentUserIsSystemUser())
                {
                    return(Unauthorized());
                }

                if (string.IsNullOrWhiteSpace(description))
                {
                    throw new ArgumentException("Value cannot be null or whitespace.", nameof(description));
                }

                if (!_userContext.CurrentUserIsSystemAdmin())
                {
                    return(Unauthorized());
                }

                var cmd = new CreateOrganizationCommand(description, details, organizationType, reportingFrequency, parent);
                await _endpointInstance().SendWithSignalRMetaData(cmd, Request);

                return(this.Accepted());
            }
            catch (Exception ex)
            {
                _log.Error(ex);
                return(InternalServerError());
            }
        }
        public async Task <IActionResult> CreateOrganization([FromBody] CreateOrganizationCommand createOrganizationCommand, CancellationToken cancellationToken = default)
        {
            createOrganizationCommand.CreatedBy = User.ExtractIdentifier();
            var result = await _mediator.Send(createOrganizationCommand, cancellationToken);

            return(Created($"{nameof(Organization)}/{result.Id}", result));
        }
        public void CreateOrganizationCommand_WithoutTitle_ShouldThrowValidationException()
        {
            var command = new CreateOrganizationCommand();

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
        public async Task <IActionResult> Create(CreateOrganizationCommand command)
        {
            logger.LogInformation("Creating organization");

            var result = await service.Handle(command);

            return(FromResult(result));
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Create([FromBody] CreateOrganizationCommand request)
        {
            var response = await _mediator.Send(request);

            if (response.WithError)
            {
                return(BadRequest(response));
            }
            return(Ok(response));
        }
        public void CreateOrganizationCommand_WithoutCurrentUserId_ShouldThrowDbUpdateException()
        {
            var command = new CreateOrganizationCommand
            {
                Title = "Test"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <DbUpdateException>();
        }
        /**
         * Creates an organization
         */
        public int CreateOrganization(CreateOrganizationCommand command)
        {
            var organization = mapper.Map <OrganizationEntity>(command);

            organization.CreatedAt = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
            this.context.Organizations.Add(organization);
            this.context.SaveChanges();

            return(organization.OrganizationEntityId);
        }
        public void CreateOrganizationCommand_WithTitleMoreThan200Characters_ShouldThrowValidationException()
        {
            var command = new CreateOrganizationCommand
            {
                Title = "This is a very long title for an organization so we could test Request validator. In this case we expect a validation exception because our title is more that 200 character. so let's test it and see our test result"
            };

            FluentActions.Invoking(() =>
                                   SendAsync(command)).Should().Throw <ValidationException>();
        }
Exemplo n.º 10
0
        public IOrganization CreateOrganization(string name, string description)
        {
            userContext.CheckPermission(Permissions.UserMaintenance);

            Guid     organizationId = Guid.NewGuid();
            ICommand command        = new CreateOrganizationCommand(organizationId, name, description);

            commandBus.Value.Send(Envelope.Create(command));
            return(GetOrganization(organizationId));
        }
Exemplo n.º 11
0
        public async Task <IActionResult> Create(CreateOrganizationCommand createOrganizationCommand)
        {
            var result = await Mediator.Send(createOrganizationCommand);

            if (result.Success == false)
            {
                return(result.ApiResult);
            }

            return(Created(Url.Link("GetOrganizationInfo", new { id = result.Data.Id }), result.Data));
        }
 /// <summary>
 /// Creates organization
 /// </summary>
 /// <param name="createOrganizationCommand">Model for all needed fields to create a tenant</param>
 /// <returns>ID of created Organization</returns>
 /// <exception cref="InvalidCreateOrganizationDataError">If create data is not valid</exception>
 /// <exception cref="OrganizationAlreadyExistsError">If organization already exists</exception>
 public Result <int> CreateOrganization(CreateOrganizationCommand createOrganizationCommand)
 {
     if (createOrganizationCommand?.Name == null || createOrganizationCommand.Name.Length == 0)
     {
         return(new Result <int>(OrganizationServiceErrors.InvalidCreateOrganizationDataError(nameof(createOrganizationCommand.Name))));
     }
     if (this.organizationRepository.OrganizationExistsByName(createOrganizationCommand.Name))
     {
         return(new Result <int>(OrganizationServiceErrors.OrganizationAlreadyExistsError()));
     }
     return(new Result <int>(this.organizationRepository.CreateOrganization(createOrganizationCommand)));
 }
Exemplo n.º 13
0
        public async Task <ActionResult> Create(OrganizationViewModel model, CancellationToken cancellationToken)
        {
            if (ModelState.IsValid)
            {
                var command = new CreateOrganizationCommand(model.Name, User.Identity.GetUserId());

                Organization organization = await _createOrganization.Execute(command, cancellationToken);

                return(RedirectToAction("Details", new { id = organization.Id }));
            }

            return(View());
        }
Exemplo n.º 14
0
        public HttpResponseMessage Post(CreateOrganizationCommand command)
        {
            if (command.Id == Guid.Empty)
            {
                command.Id = Guid.NewGuid();
            }

            m_CreateHandler.Handle(command);

            var response = Request.CreateResponse(HttpStatusCode.Created, command.Id);

            return(response);
        }
Exemplo n.º 15
0
        public async Task<ActionResult> Create(OrganizationViewModel model, CancellationToken cancellationToken)
        {
            if (ModelState.IsValid)
            {
                var command = new CreateOrganizationCommand(model.Name, User.Identity.GetUserId());

                Organization organization = await _createOrganization.Execute(command, cancellationToken);

                return RedirectToAction("Details", new {id = organization.Id});
            }

            return View();
        }
        public async Task Handle_Success(CreateOrganizationCommand orgDto, Mock <ILogger <CreateOrganizationCommandHandler> > logger)
        {
            //Arrange
            var workerService = new Mock <IOrganizationWorkerService>();

            workerService.Setup(x => x.AddOrganization(It.IsAny <OrganizationDto>()));
            var system = new CreateOrganizationCommandHandler(workerService.Object, logger.Object);

            //Act
            await system.Handle(orgDto);

            //Assert
            workerService.Verify(x => x.AddOrganization(It.IsAny <OrganizationDto>()), Times.Once);
        }
Exemplo n.º 17
0
        public async Task CreateOrganizationCommandValidationTests(CreateOrganizationCommand command, Action <CreateOrganizationCommand, CreateOrganizationCommandValidator> assertation)
        {
            var user = Fixture.Build <CreateUserCommand>().Create();

            var handler = new CreateUserCommandHandler(Context, _mapper);

            var result = await handler.Handle(user);

            await Context.SaveChangesAsync();

            var validator = new CreateOrganizationCommandValidator(Context);

            command.CreatedBy = result.Id;
            assertation(command, validator);
        }
Exemplo n.º 18
0
        public Task <Organization> AddOrganizationAsync(CreateOrganizationCommand command)
        {
            // Creates entity
            var person = new Organization
            {
                Id         = OrganizationsDB.Items.Count + 1,
                Name       = command.Name,
                Integrants = command.Integrants
            };

            // Insert it
            OrganizationsDB.Items.Add(person);

            return(Task.FromResult(person));
        }
 public async Task CreateOrganization(OrganizationDto newOrganization)
 {
     var id      = Guid.NewGuid();
     var command = new CreateOrganizationCommand(
         id,
         newOrganization.Name,
         newOrganization.Street,
         newOrganization.StreetExtended,
         newOrganization.PostalCode,
         newOrganization.City,
         newOrganization.Country,
         newOrganization.VatNumber,
         newOrganization.Website,
         newOrganization.ChangeDate,
         newOrganization.ChangedBy);
     await _bus.Send(command);
 }
        public void CreateNewOrganizationWithUserThenDelete()
        {
            var command = new CreateOrganizationCommand();

            command.Name = "Test Org";
            command.PrimaryEmailAddress = "*****@*****.**";
            command.WebsiteUrl          = "www.n-dexed.com";

            IHashProvider hashProvider = new PublicPrivateKeyHasher();
            string        publicKey    = ConfigurationManager.AppSettings["PublicKey"];
            string        privateKey   = ConfigurationManager.AppSettings["PrivateKey"];

            hashProvider.RegisterKeyPair(publicKey, privateKey);

            IRepository <UserInfo, UserInfo>           userRepository   = new MockUserRepository();
            ISearchableRepository <UserInfo, UserInfo> searchRepository = new MockUserRepository();

            var        messager  = new MockMailMessager();
            IEncryptor encryptor = new RijndaelManagedEncryptor();

            IAuthorizationTokenProvider         tokenProvider  = new HashAuthorizationTokenProvider(hashProvider, encryptor);
            ICommandHandler <CreateUserCommand> commandHandler = new UserCommandHandler(hashProvider, userRepository, messager, tokenProvider, searchRepository);

            var handler = new OrganizationCommandHandler(new MockOrganizationRepository(), searchRepository,
                                                         commandHandler);

            try
            {
                handler.Handle(command);
            }
            finally
            {
                try
                {
                    var searchCriteria = new UserInfo()
                    {
                        EmailAddress = command.PrimaryEmailAddress
                    };
                    var user = searchRepository.Search(searchCriteria).First();
                    userRepository.Remove(user);
                }
                catch
                {
                }
            }
        }
        public async Task CreateOrganizationCommand_WithTitle_ShouldInsertOrganizationAndReturnOrganizationId()
        {
            var defaultUserId = await RunAsDefaultUserAsync();

            var command = new CreateOrganizationCommand
            {
                Title = "Test"
            };

            var organizationId = await SendAsync(command);

            var organization = await FindAsync <Organization>(organizationId);

            organization.ShouldNotBeNull();
            organization.Title.ShouldBe("Test");
            organization.Id.ShouldBe(organizationId);
        }
Exemplo n.º 22
0
        public void Instansiate_NoStreetExtended_Success(Guid id, string name, string street, string postalCode, string city, string country, string vatNumber, string website, DateTime changeDate, string changedBy)
        {
            var command = new CreateOrganizationCommand(
                id,
                name,
                street,
                string.Empty,
                postalCode,
                city,
                country,
                vatNumber,
                website,
                changeDate,
                changedBy
                );

            command.Should().BeOfType <CreateOrganizationCommand>();
        }
        public async Task <Guid> Handle(CreateOrganizationRequest request, CancellationToken cancellationToken)
        {
            var command = new CreateOrganizationCommand(
                new Guid(request.Id),
                request.Name,
                request.Street,
                request.StreetExtended,
                request.PostalCode,
                request.City,
                request.Country,
                request.VatNumber,
                request.Website,
                request.ChangeDate,
                request.ChangedBy);

            await _bus.Send(command);

            return(await Task.FromResult(Guid.Empty));
        }
        public async Task CreateOrganizationCommand_WithTitle_ShouldInsertCurrentUserAsAdminOfOrganizationAndReturnOrganizationId()
        {
            var defaultUserId = await RunAsDefaultUserAsync();

            var command = new CreateOrganizationCommand
            {
                Title = "Test"
            };

            var organizationId = await SendAsync(command);

            var organization = await FindAsync <Organization>(organizationId);

            organization.ShouldNotBeNull();
            organization.Title.ShouldBe("Test");
            organization.Id.ShouldBe(organizationId);

            var context         = GetContext();
            var orgnizationUser = await context.OrganizationUsers.SingleOrDefaultAsync(x => x.OrganizationId == organizationId && x.UserId == defaultUserId && x.Type == UserType.Admin);

            orgnizationUser.ShouldNotBeNull();
        }
Exemplo n.º 25
0
        public async Task <Result <CommandResult> > Handle(CreateOrganizationCommand request, CancellationToken cancellationToken)
        {
            if (!request.IsValid())
            {
                await PublishValidationErrorsAsync(request);

                return(Result.Failure <CommandResult>(ApplicationMessages.Create_Failed));
            }

            var organization = _mapper.Map <Organization>(request);

            var exist = await _organizationRepository.ExistByNameAsync(organization.Id, organization.Name);

            if (exist)
            {
                await _mediator.Publish(new DomainNotification("", ApplicationMessages.Name_Already_Exist));

                return(Result.Failure <CommandResult>(ApplicationMessages.Create_Failed));
            }

            await _organizationRepository.CreateAsync(organization);

            return(Result.Success(new CommandResult(organization.Id, ApplicationMessages.Create_Success)));
        }
Exemplo n.º 26
0
 public async Task <Result <Guid> > CreateOrganization(
     [FromBody] CreateOrganizationCommand command, CancellationToken token)
 => await Mediator.Send(command, token);
 public async Task <ActionResult <Guid> > Create(CreateOrganizationCommand command)
 {
     return(await Mediator.Send(command));
 }
Exemplo n.º 28
0
 public async Task <ActionResult> CreateOrganization(CreateOrganizationCommand command)
 {
     command.UserId = User.GetUserId();
     return(await this.SendCreateCommand(command, nameof(GetOrganization)));
 }
Exemplo n.º 29
0
 public Task <CommandResult <int> > CreateOrganization(CreateOrganizationCommand cmd)
 {
     throw new NotImplementedException();
 }
Exemplo n.º 30
0
 public async Task <IActionResult> CreateOrganization([FromBody] CreateOrganizationCommand command) =>
 await HandleCommandAsync(command, _commandService.CreateOrganization);