Ejemplo n.º 1
0
        public async Task <IActionResult> Post([FromBody] UserDefinition userDefinition)
        {
            if (userDefinition is null)
            {
                throw new ArgumentNullException(nameof(userDefinition));
            }

            var validation = new UserDefinitionValidator().Validate(userDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound($"No TeamCloud Instance was found.")
                       .ActionResult());
            }

            var newUser = await userService
                          .GetUserAsync(userDefinition)
                          .ConfigureAwait(false);

            if (newUser is null)
            {
                return(ErrorResult
                       .NotFound($"A User with the Email '{userDefinition.Email}' could not be found.")
                       .ActionResult());
            }

            if (teamCloudInstance.Users.Contains(newUser))
            {
                return(ErrorResult
                       .Conflict($"A User with the Email '{userDefinition.Email}' already exists on this TeamCloud Instance. Please try your request again with a unique email or call PUT to update the existing User.")
                       .ActionResult());
            }

            var command = new OrchestratorTeamCloudUserCreateCommand(CurrentUser, newUser);

            var commandResult = await orchestrator
                                .InvokeAsync(command)
                                .ConfigureAwait(false);

            if (commandResult.Links.TryGetValue("status", out var statusUrl))
            {
                return(StatusResult
                       .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus)
                       .ActionResult());
            }

            throw new Exception("This shouldn't happen, but we need to decide to do when it does.");
        }
Ejemplo n.º 2
0
    public IActionResult GetClientError(ActionContext actionContext, IClientErrorActionResult clientError)
    {
        if (clientError is null)
        {
            throw new System.ArgumentNullException(nameof(clientError));
        }

        if (clientError.StatusCode.HasValue)
        {
            switch (clientError.StatusCode.Value)
            {
            case StatusCodes.Status400BadRequest:
                return(ErrorResult.BadRequest().ToActionResult());

            case StatusCodes.Status401Unauthorized:
                return(ErrorResult.Unauthorized().ToActionResult());

            case StatusCodes.Status403Forbidden:
                return(ErrorResult.Forbidden().ToActionResult());

            case StatusCodes.Status404NotFound:
                return(ErrorResult.NotFound("Not Found").ToActionResult());

            case StatusCodes.Status409Conflict:
                return(ErrorResult.Conflict("Conflict").ToActionResult());

            case StatusCodes.Status500InternalServerError:
                return(ErrorResult.ServerError().ToActionResult());
            }
        }

        return(ErrorResult.Unknown(clientError.StatusCode).ToActionResult());
    }
Ejemplo n.º 3
0
        public async Task <IActionResult> Post([FromBody] ProjectType projectType)
        {
            if (projectType is null)
            {
                return(ErrorResult
                       .BadRequest("Request body must not be empty.", ResultErrorCode.ValidationError)
                       .ToActionResult());
            }

            if (!projectType.TryValidate(out var validationResult, serviceProvider: HttpContext.RequestServices))
            {
                return(ErrorResult
                       .BadRequest(validationResult)
                       .ToActionResult());
            }

            var projectTypeDocument = await projectTypeRepository
                                      .GetAsync(projectType.Id)
                                      .ConfigureAwait(false);

            if (projectTypeDocument != null)
            {
                return(ErrorResult
                       .Conflict($"A ProjectType with id '{projectType.Id}' already exists.  Please try your request again with a unique id or call PUT to update the existing ProjectType.")
                       .ToActionResult());
            }

            var providers = await ProviderRepository
                            .ListAsync(includeServiceProviders : false)
                            .ToListAsync()
                            .ConfigureAwait(false);

            var validProviders = projectType.Providers
                                 .All(p => providers.Any(provider => provider.Id == p.Id));

            if (!validProviders)
            {
                var validProviderIds = string.Join(", ", providers.Select(p => p.Id));

                return(ErrorResult
                       .BadRequest(new ValidationError {
                    Field = "projectType", Message = $"All provider ids on a ProjectType must match the id of a registered Provider on the TeamCloud instance and cannot be a Service Provider. Valid provider ids are: {validProviderIds}"
                })
                       .ToActionResult());
            }

            var currentUser = await UserService
                              .CurrentUserAsync()
                              .ConfigureAwait(false);

            projectTypeDocument = new ProjectTypeDocument()
                                  .PopulateFromExternalModel(projectType);

            return(await Orchestrator
                   .InvokeAndReturnActionResultAsync <ProjectTypeDocument, ProjectType>(new OrchestratorProjectTypeCreateCommand(currentUser, projectTypeDocument), Request)
                   .ConfigureAwait(false));
        }
Ejemplo n.º 4
0
        public async Task <IActionResult> Post([FromBody] UserDefinition userDefinition)
        {
            if (userDefinition is null)
            {
                throw new ArgumentNullException(nameof(userDefinition));
            }

            var validation = new UserDefinitionTeamCloudValidator().Validate(userDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var userId = await userService
                         .GetUserIdAsync(userDefinition.Identifier)
                         .ConfigureAwait(false);

            if (string.IsNullOrEmpty(userId))
            {
                return(ErrorResult
                       .NotFound($"The user '{userDefinition.Identifier}' could not be found.")
                       .ActionResult());
            }

            var user = await usersRepository
                       .GetAsync(userId)
                       .ConfigureAwait(false);

            if (user != null)
            {
                return(ErrorResult
                       .Conflict($"The user '{userDefinition.Identifier}' already exists on this TeamCloud Instance. Please try your request again with a unique user or call PUT to update the existing User.")
                       .ActionResult());
            }

            user = new Model.Internal.Data.User
            {
                Id         = userId,
                Role       = Enum.Parse <TeamCloudUserRole>(userDefinition.Role, true),
                Properties = userDefinition.Properties,
                UserType   = UserType.User
            };

            var currentUserForCommand = await userService
                                        .CurrentUserAsync()
                                        .ConfigureAwait(false);

            var command = new OrchestratorTeamCloudUserCreateCommand(currentUserForCommand, user);

            return(await orchestrator
                   .InvokeAndReturnAccepted(command)
                   .ConfigureAwait(false));
        }
        public async Task <IActionResult> Post([FromBody] ProjectType projectType)
        {
            if (projectType is null)
            {
                throw new ArgumentNullException(nameof(projectType));
            }

            var validation = new ProjectTypeValidator().Validate(projectType);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var existingProjectType = await projectTypesRepository
                                      .GetAsync(projectType.Id)
                                      .ConfigureAwait(false);

            if (existingProjectType != null)
            {
                return(ErrorResult
                       .Conflict($"A ProjectType with id '{projectType.Id}' already exists.  Please try your request again with a unique id or call PUT to update the existing ProjectType.")
                       .ActionResult());
            }

            var teamCloud = await teamCloudRepository
                            .GetAsync()
                            .ConfigureAwait(false);

            var validProviders = projectType.Providers
                                 .All(projectTypeProvider => teamCloud.Providers.Any(teamCloudProvider => teamCloudProvider.Id == projectTypeProvider.Id));

            if (!validProviders)
            {
                var validProviderIds = string.Join(", ", teamCloud.Providers.Select(p => p.Id));
                return(ErrorResult
                       .BadRequest(new ValidationError {
                    Field = "projectType", Message = $"All provider ids on a ProjectType must match the id of a registered Provider on the TeamCloud instance. Valid provider ids are: {validProviderIds}"
                })
                       .ActionResult());
            }

            var addResult = await orchestrator
                            .AddAsync(projectType)
                            .ConfigureAwait(false);

            var baseUrl  = HttpContext.GetApplicationBaseUrl();
            var location = new Uri(baseUrl, $"api/projectTypes/{addResult.Id}").ToString();

            return(DataResult <ProjectType>
                   .Created(addResult, location)
                   .ActionResult());
        }
        public async Task <IActionResult> Post([FromBody] TeamCloudInstance teamCloudInstance)
        {
            if (teamCloudInstance is null)
            {
                throw new ArgumentNullException(nameof(teamCloudInstance));
            }

            var validation = new TeamCloudInstanceValidaor().Validate(teamCloudInstance);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var existingTeamCloudInstance = await teamCloudRepository
                                            .GetAsync()
                                            .ConfigureAwait(false);

            if (existingTeamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound("The TeamCloud instance could not be found.")
                       .ActionResult());
            }

            if (existingTeamCloudInstance.ResourceGroup != null ||
                existingTeamCloudInstance.Version != null ||
                (existingTeamCloudInstance.Tags?.Any() ?? false))
            {
                return(ErrorResult
                       .Conflict($"The TeamCloud instance already exists.  Call PUT to update the existing instance.")
                       .ActionResult());
            }

            existingTeamCloudInstance.Version       = teamCloudInstance.Version;
            existingTeamCloudInstance.ResourceGroup = teamCloudInstance.ResourceGroup;
            existingTeamCloudInstance.Tags          = teamCloudInstance.Tags;

            var setResult = await orchestrator
                            .SetAsync(existingTeamCloudInstance)
                            .ConfigureAwait(false);

            var baseUrl  = HttpContext.GetApplicationBaseUrl();
            var location = new Uri(baseUrl, $"api/admin/teamCloudInstance").ToString();

            var returnSetResult = setResult.PopulateExternalModel();

            return(DataResult <TeamCloudInstance>
                   .Created(returnSetResult, location)
                   .ActionResult());
        }
Ejemplo n.º 7
0
        public async Task <IActionResult> Post([FromBody] UserDefinition userDefinition)
        {
            if (userDefinition is null)
            {
                throw new ArgumentNullException(nameof(userDefinition));
            }

            if (string.IsNullOrEmpty(ProjectId))
            {
                return(ErrorResult
                       .BadRequest($"Project Id provided in the url path is invalid.  Must be a valid GUID.", ResultErrorCode.ValidationError)
                       .ActionResult());
            }

            var validation = new UserDefinitionProjectValidator().Validate(userDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var user = await userService
                       .ResolveUserAsync(userDefinition)
                       .ConfigureAwait(false);

            if (user is null)
            {
                return(ErrorResult
                       .NotFound($"The user '{userDefinition.Identifier}' could not be found.")
                       .ActionResult());
            }

            if (user.IsMember(ProjectId))
            {
                return(ErrorResult
                       .Conflict($"The user '{userDefinition.Identifier}' already exists on this Project. Please try your request again with a unique user or call PUT to update the existing User.")
                       .ActionResult());
            }

            user.EnsureProjectMembership(ProjectId, Enum.Parse <ProjectUserRole>(userDefinition.Role, true), userDefinition.Properties);

            var currentUserForCommand = await userService
                                        .CurrentUserAsync()
                                        .ConfigureAwait(false);

            var command = new OrchestratorProjectUserCreateCommand(currentUserForCommand, user, ProjectId);

            return(await orchestrator
                   .InvokeAndReturnAccepted(command)
                   .ConfigureAwait(false));
        }
Ejemplo n.º 8
0
        public async Task <IActionResult> Post([FromBody] Dictionary <string, string> tags)
        {
            if (!ProjectId.HasValue)
            {
                return(ErrorResult
                       .BadRequest($"Project Id provided in the url path is invalid.  Must be a valid GUID.", ResultErrorCode.ValidationError)
                       .ActionResult());
            }

            var tag = tags.FirstOrDefault();

            if (tag.Key is null)
            {
                return(ErrorResult
                       .BadRequest()
                       .ActionResult());
            }

            var project = await projectsRepository
                          .GetAsync(ProjectId.Value)
                          .ConfigureAwait(false);

            if (project is null)
            {
                return(ErrorResult
                       .NotFound($"A Project with the ID '{ProjectId.Value}' could not be found in this TeamCloud Instance.")
                       .ActionResult());
            }

            if (project.Tags.ContainsKey(tag.Key))
            {
                return(ErrorResult
                       .Conflict($"A Tag with the key '{tag.Key}' already exists on this Project. Please try your request again with a unique key or call PUT to update the existing Tag.")
                       .ActionResult());
            }

            // TODO:
            return(new OkResult());

            // var command = new ProjectUserCreateCommand(CurrentUser, newUser, ProjectId.Value);

            // var commandResult = await orchestrator
            //     .InvokeAsync(command)
            //     .ConfigureAwait(false);

            // if (commandResult.Links.TryGetValue("status", out var statusUrl))
            //     return StatusResult
            //         .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus)
            //         .ActionResult();

            throw new Exception("This shoudn't happen, but we need to decide to do when it does.");
        }
Ejemplo n.º 9
0
    public async Task <IActionResult> Post([FromBody] OrganizationDefinition organizationDefinition)
    {
        if (organizationDefinition is null)
        {
            throw new ArgumentNullException(nameof(organizationDefinition));
        }

        if (!organizationDefinition.TryValidate(ValidatorProvider, out var validationResult))
        {
            return(ErrorResult
                   .BadRequest(validationResult)
                   .ToActionResult());
        }

        var nameExists = await organizationRepository
                         .NameExistsAsync(UserService.CurrentUserTenant, organizationDefinition.Slug)
                         .ConfigureAwait(false);

        if (nameExists)
        {
            return(ErrorResult
                   .Conflict($"The Organication '{organizationDefinition.Slug}' already exists. Please try your request again with a unique Organization Name or Id.")
                   .ToActionResult());
        }

        var organization = new Organization
        {
            Id             = Guid.NewGuid().ToString(),
            Tenant         = UserService.CurrentUserTenant,
            DisplayName    = organizationDefinition.DisplayName,
            SubscriptionId = organizationDefinition.SubscriptionId,
            Location       = organizationDefinition.Location
        };

        var currentUser = await UserService
                          .CurrentUserAsync(null, null, allowUnsafe : true)
                          .ConfigureAwait(false);

        currentUser.Role             = OrganizationUserRole.Owner;
        currentUser.Organization     = organization.Id;
        currentUser.OrganizationName = organization.Slug;

        var command = new OrganizationCreateCommand(currentUser, organization);

        return(await Orchestrator
               .InvokeAndReturnActionResultAsync(command, Request)
               .ConfigureAwait(false));
    }
Ejemplo n.º 10
0
        public async Task <IActionResult> Post([FromBody] TeamCloudInstance teamCloudInstance)
        {
            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .BadRequest("Request body must not be empty.", ResultErrorCode.ValidationError)
                       .ToActionResult());
            }

            if (!teamCloudInstance.TryValidate(out var validationResult, serviceProvider: HttpContext.RequestServices))
            {
                return(ErrorResult
                       .BadRequest(validationResult)
                       .ToActionResult());
            }

            var teamCloudInstanceDocument = await teamCloudRepository
                                            .GetAsync()
                                            .ConfigureAwait(false);

            if (teamCloudInstanceDocument is null)
            {
                return(ErrorResult
                       .NotFound("The TeamCloud instance could not be found.")
                       .ToActionResult());
            }

            if (teamCloudInstanceDocument.ResourceGroup != null ||
                teamCloudInstanceDocument.Version != null ||
                (teamCloudInstanceDocument.Tags?.Any() ?? false))
            {
                return(ErrorResult
                       .Conflict($"The TeamCloud instance already exists.  Call PUT to update the existing instance.")
                       .ToActionResult());
            }

            teamCloudInstanceDocument.Version       = teamCloudInstance.Version;
            teamCloudInstanceDocument.ResourceGroup = teamCloudInstance.ResourceGroup;
            teamCloudInstanceDocument.Tags          = teamCloudInstance.Tags;

            var currentUser = await UserService
                              .CurrentUserAsync(allowUnsafe : true)
                              .ConfigureAwait(false);

            return(await Orchestrator
                   .InvokeAndReturnActionResultAsync <TeamCloudInstanceDocument, TeamCloudInstance>(new OrchestratorTeamCloudInstanceSetCommand(currentUser, teamCloudInstanceDocument), Request)
                   .ConfigureAwait(false));
        }
        public async Task <IActionResult> Post([FromBody] Dictionary <string, string> tags)
        {
            if (string.IsNullOrEmpty(ProjectId))
            {
                return(ErrorResult
                       .BadRequest($"Project Id provided in the url path is invalid.  Must be a valid GUID.", ResultErrorCode.ValidationError)
                       .ActionResult());
            }

            var tag = tags.FirstOrDefault();

            if (tag.Key is null)
            {
                return(ErrorResult
                       .BadRequest()
                       .ActionResult());
            }

            var project = await projectsRepository
                          .GetAsync(ProjectId)
                          .ConfigureAwait(false);

            if (project is null)
            {
                return(ErrorResult
                       .NotFound($"A Project with the ID '{ProjectId}' could not be found in this TeamCloud Instance.")
                       .ActionResult());
            }

            if (project.Tags.ContainsKey(tag.Key))
            {
                return(ErrorResult
                       .Conflict($"A Tag with the key '{tag.Key}' already exists on this Project. Please try your request again with a unique key or call PUT to update the existing Tag.")
                       .ActionResult());
            }

            // TODO:
            return(new OkResult());
            // var command = new ProjectUserCreateCommand(CurrentUser, newUser, projectId);

            // return await orchestrator
            //     .InvokeAndReturnAccepted(command)
            //     .ConfigureAwait(false);
        }
Ejemplo n.º 12
0
        public async Task <IActionResult> Post([FromBody] Provider provider)
        {
            if (provider is null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            var validation = new ProviderValidator().Validate(provider);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var existingProvider = await providersRepository
                                   .GetAsync(provider.Id)
                                   .ConfigureAwait(false);

            if (existingProvider != null)
            {
                return(ErrorResult
                       .Conflict($"A Provider with the ID '{provider.Id}' already exists on this TeamCloud Instance. Please try your request again with a unique ID or call PUT to update the existing Provider.")
                       .ActionResult());
            }

            var currentUserForCommand = await userService
                                        .CurrentUserAsync()
                                        .ConfigureAwait(false);

            var commandProvider = new TeamCloud.Model.Internal.Data.Provider();

            commandProvider.PopulateFromExternalModel(provider);

            var command = new OrchestratorProviderCreateCommand(currentUserForCommand, commandProvider);

            return(await orchestrator
                   .InvokeAndReturnAccepted(command)
                   .ConfigureAwait(false));
        }
Ejemplo n.º 13
0
        public async Task <IActionResult> Post([FromBody] Dictionary <string, string> tags)
        {
            var tag = tags.FirstOrDefault();

            if (tag.Key is null)
            {
                return(ErrorResult
                       .BadRequest()
                       .ActionResult());
            }

            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance is null)
            {
                return(ErrorResult
                       .NotFound($"No TeamCloud Instance was found.")
                       .ActionResult());
            }

            if (teamCloudInstance.Tags.ContainsKey(tag.Key))
            {
                return(ErrorResult
                       .Conflict($"A Tag with the key '{tag.Key}' already exists on this TeamCloud Instance. Please try your request again with a unique key or call PUT to update the existing Tag.")
                       .ActionResult());
            }

            // TODO:
            return(new OkResult());
            // var command = new ProjectUserCreateCommand(CurrentUser, newUser, ProjectId.Value);

            // return await orchestrator
            //     .InvokeAndReturnAccepted(command)
            //     .ConfigureAwait(false);
        }
Ejemplo n.º 14
0
        public async Task <IActionResult> Post([FromBody] TeamCloudConfiguration teamCloudConfiguraiton)
        {
            var validation = new TeamCloudConfigurationValidator().Validate(teamCloudConfiguraiton);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var teamCloudInstance = await teamCloudRepository
                                    .GetAsync()
                                    .ConfigureAwait(false);

            if (teamCloudInstance != null)
            {
                return(ErrorResult
                       .Conflict("A TeamCloud Instance already existis.")
                       .ActionResult());
            }

            var command = new OrchestratorTeamCloudCreateCommand(CurrentUser, teamCloudConfiguraiton);

            var commandResult = await orchestrator
                                .InvokeAsync(command)
                                .ConfigureAwait(false);

            if (commandResult.Links.TryGetValue("status", out var statusUrl))
            {
                return(StatusResult
                       .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus)
                       .ActionResult());
            }

            throw new Exception("This shoudn't happen, but we need to decide to do when it does.");
        }
Ejemplo n.º 15
0
        public async Task <IActionResult> Post([FromBody] ProjectDefinition projectDefinition)
        {
            if (projectDefinition is null)
            {
                throw new ArgumentNullException(nameof(projectDefinition));
            }

            var validation = new ProjectDefinitionValidator().Validate(projectDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ActionResult());
            }

            var users = await ResolveUsersAsync(projectDefinition)
                        .ConfigureAwait(false);

            var nameExists = await projectsRepository
                             .NameExistsAsync(projectDefinition.Name)
                             .ConfigureAwait(false);

            if (nameExists)
            {
                return(ErrorResult
                       .Conflict($"A Project with name '{projectDefinition.Name}' already exists. Project names must be unique. Please try your request again with a unique name.")
                       .ActionResult());
            }

            var project = new Project
            {
                Id    = Guid.NewGuid(),
                Users = users,
                Name  = projectDefinition.Name,
                Tags  = projectDefinition.Tags
            };

            if (!string.IsNullOrEmpty(projectDefinition.ProjectType))
            {
                project.Type = await projectTypesRepository
                               .GetAsync(projectDefinition.ProjectType)
                               .ConfigureAwait(false);

                if (project.Type is null)
                {
                    return(ErrorResult
                           .BadRequest(new ValidationError {
                        Field = "projectType", Message = $"A Project Type with the ID '{projectDefinition.ProjectType}' could not be found in this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'."
                    })
                           .ActionResult());
                }
            }
            else
            {
                project.Type = await projectTypesRepository
                               .GetDefaultAsync()
                               .ConfigureAwait(false);

                if (project.Type is null)
                {
                    return(ErrorResult
                           .BadRequest(new ValidationError {
                        Field = "projectType", Message = $"No value was provided for 'projectType' and there is no a default Project Type set for this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'."
                    })
                           .ActionResult());
                }
            }

            var command = new OrchestratorProjectCreateCommand(CurrentUser, project);

            var commandResult = await orchestrator
                                .InvokeAsync(command)
                                .ConfigureAwait(false);

            if (commandResult.Links.TryGetValue("status", out var statusUrl))
            {
                return(StatusResult
                       .Accepted(commandResult.CommandId.ToString(), statusUrl, commandResult.RuntimeStatus.ToString(), commandResult.CustomStatus)
                       .ActionResult());
            }

            throw new Exception("This shouldn't happen, but we need to decide to do when it does.");
        }
Ejemplo n.º 16
0
        public async Task <IActionResult> Post([FromBody] Provider provider)
        {
            if (provider is null)
            {
                throw new ArgumentNullException(nameof(provider));
            }

            var validation = new ProviderValidator().Validate(provider);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ToActionResult());
            }

            var providerDocument = await ProviderRepository
                                   .GetAsync(provider.Id)
                                   .ConfigureAwait(false);

            if (providerDocument != null)
            {
                return(ErrorResult
                       .Conflict($"A Provider with the ID '{provider.Id}' already exists on this TeamCloud Instance. Please try your request again with a unique ID or call PUT to update the existing Provider.")
                       .ToActionResult());
            }

            if (provider.Type == ProviderType.Virtual)
            {
                var serviceProviders = await ProviderRepository
                                       .ListAsync(providerType : ProviderType.Service)
                                       .ToListAsync()
                                       .ConfigureAwait(false);

                var serviceProvider = serviceProviders
                                      .FirstOrDefault(p => provider.Id.StartsWith($"{p.Id}.", StringComparison.Ordinal));

                if (serviceProvider is null)
                {
                    var validServiceProviderIds = string.Join(", ", serviceProviders.Select(p => p.Id));

                    return(ErrorResult
                           .BadRequest(new ValidationError {
                        Field = "id", Message = $"No matching service provider found. Virtual provider ids must begin with the associated Service provider id followed by a period (.). Available service providers: {validServiceProviderIds}"
                    })
                           .ToActionResult());
                }

                var urlPrefix = $"{serviceProvider.Url}?";

                if (!provider.Url.StartsWith(urlPrefix, StringComparison.OrdinalIgnoreCase))
                {
                    return(ErrorResult
                           .BadRequest(new ValidationError {
                        Field = "url", Message = $"Virtual provider url must match the associated service provider url followed by a query string. The url should begin with {urlPrefix}"
                    })
                           .ToActionResult());
                }
            }

            var currentUser = await UserService
                              .CurrentUserAsync()
                              .ConfigureAwait(false);

            providerDocument = new ProviderDocument()
                               .PopulateFromExternalModel(provider);

            var command = new OrchestratorProviderCreateCommand(currentUser, providerDocument);

            return(await Orchestrator
                   .InvokeAndReturnActionResultAsync <ProviderDocument, Provider>(command, Request)
                   .ConfigureAwait(false));
        }
Ejemplo n.º 17
0
        public async Task <IActionResult> Post([FromBody] ProjectDefinition projectDefinition)
        {
            if (projectDefinition is null)
            {
                throw new ArgumentNullException(nameof(projectDefinition));
            }

            var validation = new ProjectDefinitionValidator().Validate(projectDefinition);

            if (!validation.IsValid)
            {
                return(ErrorResult
                       .BadRequest(validation)
                       .ToActionResult());
            }

            var nameExists = await ProjectRepository
                             .NameExistsAsync(projectDefinition.Name)
                             .ConfigureAwait(false);

            if (nameExists)
            {
                return(ErrorResult
                       .Conflict($"A Project with name '{projectDefinition.Name}' already exists. Project names must be unique. Please try your request again with a unique name.")
                       .ToActionResult());
            }

            var projectId = Guid.NewGuid().ToString();

            var users = await ResolveUsersAsync(projectDefinition, projectId)
                        .ConfigureAwait(false);

            var project = new ProjectDocument
            {
                Id         = projectId,
                Users      = users,
                Name       = projectDefinition.Name,
                Tags       = projectDefinition.Tags,
                Properties = projectDefinition.Properties
            };

            if (!string.IsNullOrEmpty(projectDefinition.ProjectType))
            {
                project.Type = await projectTypeRepository
                               .GetAsync(projectDefinition.ProjectType)
                               .ConfigureAwait(false);

                if (project.Type is null)
                {
                    return(ErrorResult
                           .BadRequest(new ValidationError {
                        Field = "projectType", Message = $"A Project Type with the ID '{projectDefinition.ProjectType}' could not be found in this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'."
                    })
                           .ToActionResult());
                }
            }
            else
            {
                project.Type = await projectTypeRepository
                               .GetDefaultAsync()
                               .ConfigureAwait(false);

                if (project.Type is null)
                {
                    return(ErrorResult
                           .BadRequest(new ValidationError {
                        Field = "projectType", Message = $"No value was provided for 'projectType' and there is no a default Project Type set for this TeamCloud Instance. Please try your request again with a valid Project Type ID for 'projectType'."
                    })
                           .ToActionResult());
                }
            }

            var currentUser = users.FirstOrDefault(u => u.Id == UserService.CurrentUserId);

            var command = new OrchestratorProjectCreateCommand(currentUser, project);

            return(await Orchestrator
                   .InvokeAndReturnActionResultAsync <ProjectDocument, Project>(command, Request)
                   .ConfigureAwait(false));
        }