Esempio n. 1
0
        public async Task CreateProjectServiceEvent(Guid organizationId, Guid projectId, Guid serviceId, ProjectServiceEventPostRp resource)
        {
            DomainModels.Organization organization = await _organizationRepository.GetOrganizationById(organizationId);

            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return;
            }

            service.AddEvent(BaseEventType.Build, resource.GetEventType().GetDescription(), resource.Message.Text, resource.Status, JsonConvert.SerializeObject(resource.DetailedMessage), JsonConvert.SerializeObject(resource.DetailedMessage), JsonConvert.SerializeObject(resource.Resource), resource.Date);

            _organizationRepository.Update(organization);

            await _organizationRepository.SaveChanges();
        }
        public async Task <ProjectServiceEventListRp> GetProjectServiceEvents(Guid organizationId, Guid projectId, Guid serviceId, BaseEventType baseEventType)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return(null);
            }

            ProjectServiceEventListRp list = new ProjectServiceEventListRp();

            if (service.Events != null)
            {
                if (baseEventType == BaseEventType.None)
                {
                    list.Items = service.Events.Select(x => new ProjectServiceEventListItemRp
                    {
                        EventType        = x.EventType,
                        EventDescription = x.EventDescription,
                        EventStatus      = x.EventStatus,
                        CreationDate     = x.CreationDate,
                        EventDate        = x.EventDate
                    }).OrderByDescending(x => x.EventDate).Take(10).ToList();
                }
                else
                {
                    list.Items = service.Events.Where(x => x.BaseEventType == baseEventType).Select(x => new ProjectServiceEventListItemRp
                    {
                        EventType        = x.EventType,
                        EventDescription = x.EventDescription,
                        EventStatus      = x.EventStatus,
                        CreationDate     = x.CreationDate,
                        EventDate        = x.EventDate
                    }).OrderByDescending(x => x.EventDate).Take(10).ToList();
                }
            }

            return(list);
        }
        public async Task CompleteApprovalProjectService(Guid organizationId, Guid projectId, Guid serviceId, int approvalId, ProjectServiceApprovalPutRp resource)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to modify a service.");

                return;
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return;
            }

            if (service.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The pipe with id {serviceId} must be in status Active to complete an approval.");

                return;
            }
            CMSPipelineApprovalParamModel completeApprovalOptions = new CMSPipelineApprovalParamModel();

            completeApprovalOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
            completeApprovalOptions.VSTSAccountName      = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName) : _fakeAccountOptions.Value.AccountId;
            completeApprovalOptions.VSTSAccessSecret     = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret) : _fakeAccountOptions.Value.AccessSecret;
            completeApprovalOptions.VSTSAccountProjectId = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? project.Name : project.ProjectVSTSFakeName;

            completeApprovalOptions.ProjectName       = project.Name;
            completeApprovalOptions.ProjectExternalId = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? project.ProjectExternalId : project.ProjectVSTSFakeId;
            completeApprovalOptions.ApprovalId        = approvalId;
            completeApprovalOptions.Status            = resource.Status;
            completeApprovalOptions.Comments          = resource.Comments;

            await _cmsPipelineService.CompleteApproval(completeApprovalOptions);
        }
        public async Task <CPSCloudResourceSummaryModel> GetProjectFeatureServiceCloudSummary(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id ${organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeatureService featureService = feature.GetFeatureServiceById(serviceId);
            if (featureService == null)
            {
                await _domainManagerService.AddNotFound($"The project feature pipe with id {serviceId} does not exists.");

                return(null);
            }

            var environments = new List <string>()
            {
                DomainConstants.Environments.Development
            };

            CPSAuthCredentialModel authCredentials = new CPSAuthCredentialModel();

            authCredentials.AccessId        = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId);
            authCredentials.AccessName      = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName);
            authCredentials.AccessSecret    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret);
            authCredentials.AccessRegion    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion);
            authCredentials.AccessAppId     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId);
            authCredentials.AccessAppSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret);
            authCredentials.AccessDirectory = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory);

            var summary = await _cpsQueryService(project.OrganizationCPS.Type).GetSummary(organization.Name, project.Name, featureService.ProjectService.Name, environments, feature.Name, authCredentials);

            return(summary);
        }
Esempio n. 5
0
        public async Task <ProjectFeatureServiceDeliveryListRp> GetProjectFeatureServiceDeliveries(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The feature with id {featureId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeatureService featureService = feature.GetFeatureServiceById(serviceId);
            if (featureService == null)
            {
                await _domainManagerService.AddNotFound($"The feature pipe with id {featureId} does not exists.");

                return(null);
            }

            ProjectFeatureServiceDeliveryListRp list = new ProjectFeatureServiceDeliveryListRp();

            if (featureService.Deliveries != null)
            {
                list.Items = featureService.Deliveries
                             .OrderByDescending(x => x.DeliveryDate)
                             .Take(5)
                             .Select(x => new ProjectFeatureServiceDeliveryListItemRp
                {
                    VersionId    = x.VersionId,
                    VersionName  = x.VersionName,
                    DeliveryDate = x.DeliveryDate,
                    Data         = JsonConvert.DeserializeObject <ProjectServiceDeliveryDataRp>(x.Data)
                }).ToList();
            }

            return(list);
        }
        public async Task <ProjectFeatureAllServiceListRp> GetProjectFeatureAllServices(Guid organizationId, Guid projectId, Guid featureId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

            ProjectFeatureAllServiceListRp list = new ProjectFeatureAllServiceListRp();

            var projectServices = project.GetServices();

            foreach (var projectService in projectServices)
            {
                var featureService = feature.GetFeatureServiceById(projectService.ProjectServiceId);

                var item = new ProjectFeatureAllServiceListItemRp()
                {
                    ProjectServiceId = projectService.ProjectServiceId,
                    Name             = projectService.Name
                };

                if (featureService != null)
                {
                    item.IsFeatureService = true;
                }

                list.Items.Add(item);
            }

            return(list);
        }
        public async Task <ProjectFeatureServiceActivityListRp> GetProjectFeatureServiceActivities(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The feature with id {featureId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeatureService featureService = feature.GetFeatureServiceById(serviceId);
            if (featureService == null)
            {
                await _domainManagerService.AddNotFound($"The feature pipe with id {featureId} does not exists.");

                return(null);
            }

            ProjectFeatureServiceActivityListRp list = new ProjectFeatureServiceActivityListRp();

            if (featureService.Activities != null)
            {
                list.Items = featureService.Activities.Select(x => new ProjectFeatureServiceActivityListItemRp
                {
                    Name           = x.Name,
                    Log            = x.Log,
                    ActivityStatus = x.ActivityStatus,
                    CreationDate   = x.CreationDate
                }).OrderBy(x => x.CreationDate).ToList();
            }

            return(list);
        }
        public async Task <ProjectFeatureServiceListRp> GetProjectFeatureServices(Guid organizationId, Guid projectId, Guid featureId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

            ProjectFeatureServiceListRp list = new ProjectFeatureServiceListRp();

            if (feature.Services != null)
            {
                list.Items = feature.Services.Select(x => new ProjectFeatureServiceListItemRp()
                {
                    ProjectFeatureId = x.ProjectFeatureId,
                    ProjectServiceId = x.ProjectServiceId,
                    Name             = x.ProjectService.Name,
                    Description      = x.ProjectService.Description,
                    Template         = x.ProjectService.ProjectServiceTemplate.Name,
                    Status           = x.Status,
                    PipelineStatus   = x.PipelineStatus
                }).ToList();
            }

            return(list);
        }
Esempio n. 9
0
        public async Task <ProjectEnvironmentVariableListRp> GetProjectEnvironmentVariables(Guid organizationId, Guid projectId, Guid environmentId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectEnvironment environment = project.GetEnvironmentById(environmentId);
            if (environment == null)
            {
                return(null);
            }

            DomainModels.ProjectEnvironment  defaultEnvironment = project.GetRootEnvironment();
            ProjectEnvironmentVariableListRp list = new ProjectEnvironmentVariableListRp();

            if (environment.Variables != null)
            {
                var variables = from dv in defaultEnvironment.Variables
                                join ev in environment.Variables on dv.Name equals ev.Name into ev
                                from p in ev.DefaultIfEmpty()
                                select new ProjectEnvironmentVariableListItemRp
                {
                    Name  = dv.Name,
                    Value = p == null ? "" : p.Value
                };

                list.Items = variables.ToList();
            }

            return(list);
        }
        public async Task UpdateProjectService(Guid organizationId, Guid projectId, Guid serviceId, ProjectServicePutRp resource)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to modify a service.");

                return;
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return;
            }

            user.UpdateProjectService(organizationId, projectId, serviceId, resource.Name, resource.Description);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();
        }
        public async Task <ProjectServiceGetRp> GetProjectServiceById(Guid organizationId, Guid projectId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                return(null);
            }

            ProjectServiceGetRp serviceRp = new ProjectServiceGetRp
            {
                ProjectServiceId   = service.ProjectServiceId,
                Name               = service.Name,
                Description        = service.Description,
                Template           = service.ProjectServiceTemplate.Name,
                Status             = service.Status,
                PipelineStatus     = service.PipelineStatus,
                ServiceExternalUrl = service.ProjectServiceExternalUrl,
                GitProviderType    = service.OrganizationCMS.Type,
            };

            return(serviceRp);
        }
Esempio n. 12
0
        public async Task <ProjectFeatureGetRp> GetProjectFeatureById(Guid organizationId, Guid projectId, Guid featureId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                return(null);
            }

            ProjectFeatureGetRp featureRp = new ProjectFeatureGetRp
            {
                ProjectFeatureId = feature.ProjectFeatureId,
                Name             = feature.Name,
                Description      = feature.Description,
                StartDate        = feature.CreationDate,
                CompletionDate   = feature.CompletionDate,
                Status           = feature.GetStatusName()
            };

            return(featureRp);
        }
Esempio n. 13
0
        public async Task <ProjectFeatureListRp> GetProjectFeatures(Guid organizationId, Guid projectId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            ProjectFeatureListRp list = new ProjectFeatureListRp();

            if (project.Features != null)
            {
                list.Items = project.Features.Select(x => new ProjectFeatureListItemRp()
                {
                    ProjectFeatureId = x.ProjectFeatureId,
                    Name             = x.Name,
                    Description      = x.Description,
                    StartDate        = x.CreationDate,
                    CompletionDate   = x.CompletionDate,
                    Status           = x.GetStatusName()
                }).ToList();
            }

            return(list);
        }
        public async Task <ProjectServiceFeatureListRp> GetProjectServiceFeaturesById(Guid organizationId, Guid projectId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                return(null);
            }

            ProjectServiceFeatureListRp featureListRp = new ProjectServiceFeatureListRp
            {
                Items = service.Features.Select(x => new ProjectServiceFeatureListItemRp()
                {
                    FeatureId   = x.ProjectFeatureId,
                    FeatureName = x.ProjectFeature.Name
                }).ToList()
            };

            return(featureListRp);
        }
Esempio n. 15
0
        public async Task <ProjectEnvironmentGetRp> GetProjectEnvironmentById(Guid organizationId, Guid projectId, Guid environmentId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectEnvironment environment = project.GetEnvironmentById(environmentId);
            if (environment == null)
            {
                return(null);
            }

            ProjectEnvironmentGetRp environmentRp = new ProjectEnvironmentGetRp
            {
                ProjectEnvironmentId = environment.ProjectEnvironmentId,
                Name        = environment.Name,
                Description = environment.Description,
                Status      = environment.Status,
                Type        = environment.Type
            };

            return(environmentRp);
        }
Esempio n. 16
0
        public async Task CreateReleaseProjectEnvironment(Guid organizationId, Guid projectId, Guid environmentId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to create a release in an environment.");

                return;
            }

            DomainModels.ProjectEnvironment environment = project.GetEnvironmentById(environmentId);
            if (environment == null)
            {
                await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists.");

                return;
            }
            ;

            var projectServices = project.GetServicesWithReleaseStages();

            var environmentsToBeSkippedList = project.Environments.Where(x => x.Rank < environment.Rank);
            var descriptionsToBeSkipped     = $"Release created from PipelineSpace.";

            if (environmentsToBeSkippedList.Any())
            {
                descriptionsToBeSkipped = $"{descriptionsToBeSkipped} Detail: {string.Join(", ", environmentsToBeSkippedList.Select(x => $"PS_SKIP_ENVIRONMENT_{x.Name}"))}";
            }

            Parallel.ForEach(projectServices, async(service) =>
            {
                var previousEnvironment = service.Environments.FirstOrDefault(x => x.ProjectEnvironment.Rank == ((environment.Type == EnvironmentType.Root) ? environment.Rank : environment.Rank - 1));
                if (!string.IsNullOrEmpty(previousEnvironment.LastSuccessVersionId))
                {
                    CMSPipelineReleaseParamModel releaseBuildOptions = new CMSPipelineReleaseParamModel();
                    releaseBuildOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
                    releaseBuildOptions.VSTSAccountName      = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName) : _fakeAccountOptions.Value.AccountId;
                    releaseBuildOptions.VSTSAccessSecret     = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret) : _fakeAccountOptions.Value.AccessSecret;
                    releaseBuildOptions.VSTSAccountProjectId = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? project.Name : project.ProjectVSTSFakeName;

                    releaseBuildOptions.ProjectName         = project.Name;
                    releaseBuildOptions.ProjectExternalId   = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? project.ProjectExternalId : project.ProjectVSTSFakeId;
                    releaseBuildOptions.ReleaseDefinitionId = service.ReleaseStageId.Value;
                    releaseBuildOptions.Alias = service.Name;

                    releaseBuildOptions.VersionId   = int.Parse(previousEnvironment.LastSuccessVersionId);
                    releaseBuildOptions.VersionName = previousEnvironment.LastSuccessVersionName;
                    releaseBuildOptions.Description = descriptionsToBeSkipped;

                    await _cmsPipelineService.CreateRelease(releaseBuildOptions);
                }
            });
        }
Esempio n. 17
0
        public async Task InactivateProjectEnvironment(Guid organizationId, Guid projectId, Guid environmentId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.PipelineRole role = user.GetRoleInProject(projectId);
            if (role != DomainModels.PipelineRole.ProjectAdmin)
            {
                await _domainManagerService.AddForbidden($"You are not authorized to delete environments in this project.");

                return;
            }

            if (project.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to inactivate a project environment.");

                return;
            }

            DomainModels.ProjectEnvironment environment = project.GetEnvironmentById(environmentId);
            if (environment == null)
            {
                await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists.");

                return;
            }
            ;

            if (environment.Type == DomainModels.EnvironmentType.Fact)
            {
                await _domainManagerService.AddConflict($"The environment fact cannot be inactivated.");

                return;
            }
            ;

            if (environment.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The environment {environment.Name} must be in status Active to be inactivated.");

                return;
            }

            user.InactivateProjectEnvironment(organizationId, projectId, environmentId);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            var projectServices = project.GetServicesWithReleaseStages();

            foreach (var projectService in projectServices)
            {
                var @event = new ProjectEnvironmentInactivatedEvent(_correlationId)
                {
                    OrganizationId            = organization.OrganizationId,
                    OrganizationName          = organization.Name,
                    ProjectId                 = project.ProjectId,
                    ProjectExternalId         = project.ProjectExternalId,
                    ProjectExternalEndpointId = project.ProjectExternalEndpointId,
                    ProjectVSTSFakeName       = project.ProjectVSTSFakeName,
                    ProjectName               = project.Name,
                    ServiceName               = projectService.Name,
                    CMSType         = project.OrganizationCMS.Type,
                    CMSAccountId    = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                    CMSAccountName  = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                    CMSAccessId     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId),
                    CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                    CMSAccessToken  = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken),
                    EnvironmentName = environment.Name,
                    ReleseStageId   = projectService.ReleaseStageId.Value
                };

                //Cloud Provider Data
                @event.CPSType            = project.OrganizationCPS.Type;
                @event.CPSAccessId        = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId);
                @event.CPSAccessName      = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName);
                @event.CPSAccessSecret    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret);
                @event.CPSAccessRegion    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion);
                @event.CPSAccessAppId     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId);
                @event.CPSAccessAppSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret);
                @event.CPSAccessDirectory = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory);

                await _eventBusService.Publish(queueName : "ProjectEnvironmentInactivatedEvent", @event : @event);
            }
        }
Esempio n. 18
0
        public async Task CreateProjectEnvironment(Guid organizationId, Guid projectId, ProjectEnvironmentPostRp resource)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.PipelineRole role = user.GetRoleInProject(projectId);
            if (role != DomainModels.PipelineRole.ProjectAdmin)
            {
                await _domainManagerService.AddForbidden($"You are not authorized to create environments in this project.");

                return;
            }


            if (project.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature.");

                return;
            }

            var activeServices = project.GetServicesWithReleaseStages();

            if (!activeServices.Any())
            {
                await _domainManagerService.AddConflict($"At least one pipe must be configured in the project.");

                return;
            }

            DomainModels.ProjectEnvironment existingEnvironment = project.GetEnvironmentByName(resource.Name);
            if (existingEnvironment != null)
            {
                await _domainManagerService.AddConflict($"The environment name {resource.Name} has already been taken.");

                return;
            }

            DomainModels.ProjectEnvironment newEnvironment = user.CreateProjectEnvironment(organizationId, projectId, resource.Name, resource.Description, resource.RequiresApproval, resource.AutoProvision);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            await _domainManagerService.AddResult("EnvironmentId", newEnvironment.ProjectEnvironmentId);
        }
Esempio n. 19
0
        public async Task CreateProjectEnvironmentVariables(Guid organizationId, Guid projectId, Guid environmentId, ProjectEnvironmentVariablePostRp resource)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.PipelineRole role = user.GetRoleInProject(projectId);
            if (role != DomainModels.PipelineRole.ProjectAdmin)
            {
                await _domainManagerService.AddForbidden($"You are not authorized to create environments variables in this project.");

                return;
            }

            if (project.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature.");

                return;
            }

            DomainModels.ProjectEnvironment environment = project.GetEnvironmentById(environmentId);
            if (environment == null)
            {
                await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists.");

                return;
            }

            bool autoProvision = false;

            if (environment.Type == DomainModels.EnvironmentType.Root)
            {
                foreach (var resourceVariable in resource.Items)
                {
                    if (string.IsNullOrEmpty(resourceVariable.Name) || string.IsNullOrEmpty(resourceVariable.Value))
                    {
                        await _domainManagerService.AddConflict($"The environment variable name/value is mandatory.");

                        return;
                    }

                    var variable = environment.GetVariableByName(resourceVariable.Name);
                    if (variable != null)
                    {
                        environment.SetVariable(resourceVariable.Name, resourceVariable.Value);
                    }
                    else
                    {
                        environment.AddVariable(resourceVariable.Name, resourceVariable.Value);
                    }
                }
            }
            else
            {
                DomainModels.ProjectEnvironment rootEnvironment = project.GetRootEnvironment();

                foreach (var variable in rootEnvironment.Variables)
                {
                    var resourceVariable = resource.Items.FirstOrDefault(x => x.Name.Equals(variable.Name, StringComparison.InvariantCultureIgnoreCase));
                    if (resourceVariable == null)
                    {
                        await _domainManagerService.AddConflict($"The environment variable {variable.Name} is mandatory.");

                        return;
                    }

                    if (string.IsNullOrEmpty(resourceVariable.Value))
                    {
                        await _domainManagerService.AddConflict($"The environment variable value {variable.Name} is mandatory.");

                        return;
                    }

                    var existingVariable = environment.GetVariableByName(resourceVariable.Name);
                    if (existingVariable != null)
                    {
                        environment.SetVariable(resourceVariable.Name, resourceVariable.Value);
                    }
                    else
                    {
                        environment.AddVariable(resourceVariable.Name, resourceVariable.Value);
                    }
                }

                if (environment.Status == DomainModels.EntityStatus.Preparing)
                {
                    autoProvision = environment.AutoProvision;
                }

                environment.Activate();
            }

            var projectServices = project.GetServicesWithReleaseStages();

            //replicate service environments
            foreach (var projectService in projectServices)
            {
                var rootVariables = projectService.GetRootEnvironmentVariables();
                projectService.AddEnvironment(environment.ProjectEnvironmentId, rootVariables);
            }

            _userRepository.Update(user);
            await _userRepository.SaveChanges();

            //send events
            foreach (var projectService in projectServices)
            {
                var @event = new ProjectEnvironmentCreatedEvent(_correlationId)
                {
                    OrganizationId            = organization.OrganizationId,
                    OrganizationName          = organization.Name,
                    ProjectId                 = project.ProjectId,
                    ProjectExternalId         = project.ProjectExternalId,
                    ProjectExternalEndpointId = project.ProjectExternalEndpointId,
                    ProjectVSTSFakeName       = project.ProjectVSTSFakeName,
                    ProjectName               = project.Name,
                    CMSType                            = project.OrganizationCMS.Type,
                    CMSAccountId                       = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                    CMSAccountName                     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                    CMSAccessId                        = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId),
                    CMSAccessSecret                    = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                    CMSAccessToken                     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken),
                    EnvironmentId                      = environment.ProjectEnvironmentId,
                    EnvironmentName                    = environment.Name,
                    EnvironmentRank                    = environment.Rank,
                    EnvironmentAutoProvision           = autoProvision,
                    ReleseStageId                      = projectService.ReleaseStageId.Value,
                    ServiceName                        = projectService.Name,
                    ServiceLastBuildSuccessVersionId   = projectService.LastBuildSuccessVersionId,
                    ServiceLastBuildSuccessVersionName = projectService.LastBuildSuccessVersionName
                };

                @event.Environments = new List <ProjectEnvironmentItemCreatedEvent>();

                foreach (var item in projectService.Environments)
                {
                    var parentEnvironment = project.GetEnvironments().First(x => x.ProjectEnvironmentId == item.ProjectEnvironmentId);

                    var serviceEnvironment = new ProjectEnvironmentItemCreatedEvent();
                    serviceEnvironment.Id                     = item.ProjectEnvironmentId;
                    serviceEnvironment.Name                   = parentEnvironment.Name;
                    serviceEnvironment.RequiredApproval       = parentEnvironment.RequiresApproval;
                    serviceEnvironment.Variables              = new List <ProjectEnvironmentItemVariableCreatedEvent>();
                    serviceEnvironment.Rank                   = parentEnvironment.Rank;
                    serviceEnvironment.LastSuccessVersionId   = item.LastSuccessVersionId;
                    serviceEnvironment.LastSuccessVersionName = item.LastSuccessVersionName;

                    if (parentEnvironment.Variables != null)
                    {
                        foreach (var variable in parentEnvironment.Variables)
                        {
                            serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent()
                            {
                                Name  = variable.Name,
                                Value = variable.Value
                            });
                        }
                    }

                    if (item.Variables != null)
                    {
                        foreach (var variable in item.Variables)
                        {
                            serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent()
                            {
                                Name  = variable.Name,
                                Value = variable.Value
                            });
                        }
                    }


                    @event.Environments.Add(serviceEnvironment);
                }

                //Cloud Provider Data
                @event.CPSType         = project.OrganizationCPS.Type;
                @event.CPSAccessId     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId);
                @event.CPSAccessName   = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName);
                @event.CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret);
                @event.CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion);

                await _eventBusService.Publish(queueName : "ProjectEnvironmentCreatedEvent", @event : @event);
            }
        }
Esempio n. 20
0
        public async Task <ProjectEnvironmentListRp> GetProjectEnvironments(Guid organizationId, Guid projectId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            ProjectEnvironmentListRp list = new ProjectEnvironmentListRp();

            if (project.Environments != null)
            {
                list.Items = project.Environments.Select(x => new ProjectEnvironmentListItemRp()
                {
                    ProjectEnvironmentId = x.ProjectEnvironmentId,
                    Name        = x.Name,
                    Description = x.Description,
                    Type        = x.Type,
                    Status      = x.Status,
                    Rank        = x.Rank
                }).OrderBy(x => x.Rank).ToList();


                var services = project.Services.Select(x => new
                {
                    ProjectServiceId = x.ProjectServiceId,
                    Name             = x.Name
                }).ToList();

                CPSAuthCredentialModel authCredentials = new CPSAuthCredentialModel();
                authCredentials.AccessId        = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId);
                authCredentials.AccessName      = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName);
                authCredentials.AccessSecret    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret);
                authCredentials.AccessRegion    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion);
                authCredentials.AccessAppId     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId);
                authCredentials.AccessAppSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret);
                authCredentials.AccessDirectory = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory);

                if (services != null && services.Any())
                {
                    foreach (var env in list.Items)
                    {
                        var projectServiceEnvironments    = new ProjectServiceEnvironmentListRp();
                        var projectServiceEnvironmentList = new ConcurrentBag <ProjectServiceEnvironmentListItemRp>();

                        await services.ForEachAsync(5, async service =>
                        {
                            var projectServiceEnvironmentListItem     = new ProjectServiceEnvironmentListItemRp();
                            projectServiceEnvironmentListItem.Name    = service.Name;
                            projectServiceEnvironmentListItem.Summary = await _cpsQueryService(project.OrganizationCPS.Type).GetEnvironmentSummary(organization.Name, project.Name, service.Name, env.Name, "Root", authCredentials);
                            projectServiceEnvironmentList.Add(projectServiceEnvironmentListItem);
                        });

                        projectServiceEnvironments.Items = projectServiceEnvironmentList.ToList();

                        env.Services = projectServiceEnvironments;
                    }
                }
            }

            return(list);
        }
        public async Task CreateProjectFeatureService(Guid organizationId, Guid projectId, Guid featureId, ProjectFeatureServicePostRp resource)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.PipelineRole role = user.GetRoleInProject(projectId);
            if (role != DomainModels.PipelineRole.ProjectAdmin)
            {
                await _domainManagerService.AddForbidden($"You are not authorized to create features in this project.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new feature service.");

                return;
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return;
            }

            if (feature.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project feature with id {featureId} must be in status Active to add a new feature service.");

                return;
            }

            if (resource.Services.Length == 0)
            {
                await _domainManagerService.AddConflict($"At least one pipe must be included.");

                return;
            }

            List <ProjectFeatureServiceCreatedEvent> projectFeatureServiceCreatedEventList = new List <ProjectFeatureServiceCreatedEvent>();

            foreach (var item in resource.Services)
            {
                DomainModels.ProjectService projectService = project.GetServiceById(item);
                if (projectService == null)
                {
                    await _domainManagerService.AddConflict($"The pipe with id {item} does not exists.");

                    return;
                }

                if (projectService.Status != EntityStatus.Active)
                {
                    await _domainManagerService.AddConflict($"The pipe with id {item} must be in status Active to be added as a feature service.");

                    return;
                }

                DomainModels.ProjectFeatureService projectFeatureService = feature.GetFeatureServiceById(item);
                if (projectFeatureService != null)
                {
                    await _domainManagerService.AddConflict($"The pipe with id {item} already exists in the feature.");

                    return;
                }

                var variables = projectService.Environments.First(x => x.ProjectEnvironment.Type == EnvironmentType.Root).Variables;

                feature.AddService(item, variables);

                projectFeatureServiceCreatedEventList.Add(new ProjectFeatureServiceCreatedEvent(_correlationId)
                {
                    OrganizationId             = organization.OrganizationId,
                    ProjectId                  = project.ProjectId,
                    FeatureId                  = feature.ProjectFeatureId,
                    ProjectExternalId          = project.ProjectExternalId,
                    ProjectExternalEndpointId  = project.ProjectExternalEndpointId,
                    ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint,
                    ProjectVSTSFakeName        = project.ProjectVSTSFakeName,
                    ProjectVSTSFakeId          = project.ProjectVSTSFakeId,
                    OrganizationName           = organization.Name,
                    ProjectName                = project.Name,
                    FeatureName                = feature.Name,
                    CMSType             = project.OrganizationCMS.Type,
                    CMSAccountId        = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                    CMSAccountName      = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                    CMSAccessId         = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId),
                    CMSAccessSecret     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                    CMSAccessToken      = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken),
                    CPSType             = project.OrganizationCPS.Type,
                    CPSAccessId         = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId),
                    CPSAccessName       = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName),
                    CPSAccessSecret     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret),
                    CPSAccessRegion     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion),
                    ServiceId           = item,
                    ServiceExternalId   = projectService.ProjectServiceExternalId,
                    ServiceExternalUrl  = projectService.ProjectServiceExternalUrl,
                    ServiceName         = projectService.Name,
                    InternalServiceName = projectService.InternalName,
                    ServiceTemplateUrl  = projectService.ProjectServiceTemplate.Url,
                    ReleaseStageId      = projectService.ReleaseStageId,
                    AgentPoolId         = project.AgentPoolId,
                    UserId = loggedUserId
                });
            }

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            //send events
            foreach (var @event in projectFeatureServiceCreatedEventList)
            {
                await _eventBusService.Publish(queueName : "ProjectFeatureServiceCreatedEvent", @event : @event);
            }
        }
        public async Task CreateProjectService(Guid organizationId, Guid projectId, ProjectServicePostRp resource, string userId = null)
        {
            string loggedUserId = userId ?? _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.ProjectServiceTemplate projectServiceTemplate = await _projectServiceTemplateRepository.GetProjectServiceTemplateById(resource.ProjectServiceTemplateId);

            if (projectServiceTemplate == null)
            {
                await _domainManagerService.AddConflict($"The pipe template with id {resource.ProjectServiceTemplateId} does not exists.");

                return;
            }

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId, false);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new service.");

                return;
            }

            DomainModels.ProjectService existingService = project.GetServiceByName(resource.Name);
            if (existingService != null)
            {
                await _domainManagerService.AddConflict($"The pipe name {resource.Name} has already been taken.");

                return;
            }

            CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(project.OrganizationCMS.Type).GetToken(
                _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken));

            CMSServiceAvailabilityResultModel cmsServiceAvailability = await _cmsService(project.OrganizationCMS.Type).ValidateServiceAvailability(cmsAuthCredential, project.OrganizationExternalId, project.ProjectExternalId, project.Name, resource.RepositoryName);

            if (!cmsServiceAvailability.Success)
            {
                await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceAvailability.GetReasonForNoSuccess()}");

                return;
            }

            DomainModels.ProjectService newService = user.CreateProjectService(organizationId, projectId, project.OrganizationCMSId, resource.AgentPoolId, resource.Name, resource.RepositoryName, resource.Description, resource.ProjectServiceTemplateId, projectServiceTemplate.PipeType);

            //SaveChanges in CMS
            CMSServiceCreateModel       serviceCreateModel = CMSServiceCreateModel.Factory.Create(project.OrganizationExternalId, project.ProjectExternalId, project.Name, resource.RepositoryName, project.ProjectVisibility == ProjectVisibility.Public ? true : false);
            CMSServiceCreateResultModel cmsServiceCreate   = await _cmsService(project.OrganizationCMS.Type).CreateService(cmsAuthCredential, serviceCreateModel);

            if (!cmsServiceCreate.Success)
            {
                await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceCreate.GetReasonForNoSuccess()}");

                return;
            }

            newService.UpdateExternalInformation(cmsServiceCreate.ServiceExternalId, cmsServiceCreate.ServiceExternalUrl, resource.Name);
            newService.AddEnvironmentsAndVariables(projectServiceTemplate.Parameters);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            await _domainManagerService.AddResult("ServiceId", newService.ProjectServiceId);

            if (project.OrganizationCPS == null)
            {
                project.OrganizationCPS = new OrganizationCPS {
                    Type = CloudProviderService.None
                }
            }
            ;

            var @event = new ProjectServiceCreatedEvent(_correlationId)
            {
                OrganizationId             = organization.OrganizationId,
                OrganizationName           = organization.Name,
                ProjectId                  = project.ProjectId,
                ServiceId                  = newService.ProjectServiceId,
                ProjectExternalId          = project.ProjectExternalId,
                ProjectExternalEndpointId  = project.ProjectExternalEndpointId,
                ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint,
                ProjectVSTSFakeId          = project.ProjectVSTSFakeId,
                ProjectVSTSFakeName        = project.ProjectVSTSFakeName,
                ProjectName                = project.Name,
                InternalProjectName        = project.InternalName,
                AgentPoolId                = newService.AgentPoolId,
                ServiceExternalId          = newService.ProjectServiceExternalId,
                ServiceExternalUrl         = newService.ProjectServiceExternalUrl,
                ServiceName                = resource.Name,
                InternalServiceName        = newService.InternalName,
                ServiceTemplateUrl         = projectServiceTemplate.Url,
                CMSType            = project.OrganizationCMS.Type,
                CMSAccountId       = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                CMSAccountName     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                CMSAccessId        = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId),
                CMSAccessSecret    = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                CMSAccessToken     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken),
                UserId             = loggedUserId,
                TemplateParameters = projectServiceTemplate.Parameters.Select(x => new ProjectServiceTemplateParameterCreatedEvent()
                {
                    VariableName = x.VariableName,
                    Value        = x.Value,
                    Scope        = x.Scope
                }).ToList(),
                CPSType                = project.OrganizationCPS.Type,
                CPSAccessId            = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId),
                CPSAccessName          = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName),
                CPSAccessSecret        = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret),
                CPSAccessRegion        = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion),
                TemplateAccess         = projectServiceTemplate.TemplateAccess,
                NeedCredentials        = projectServiceTemplate.NeedCredentials,
                RepositoryCMSType      = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.Credential.CMSType : ConfigurationManagementService.VSTS,
                RepositoryAccessId     = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessId) : string.Empty : string.Empty,
                RepositoryAccessSecret = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessSecret) : string.Empty : string.Empty,
                RepositoryAccessToken  = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessToken) : string.Empty : string.Empty
            };

            //Cloud Provider Data


            await _eventBusService.Publish(queueName : "ProjectServiceCreatedEvent", @event : @event);
        }
        public async Task CreateReleaseProjectFeatureService(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.PipelineRole role = user.GetRoleInProject(projectId);
            if (role != DomainModels.PipelineRole.ProjectAdmin)
            {
                await _domainManagerService.AddForbidden($"You are not authorized to delete features in this project.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to delete a feature service.");

                return;
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return;
            }

            if (feature.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project feature with id {featureId} must be in status Active to delete a feature service.");

                return;
            }

            DomainModels.ProjectFeatureService featureService = feature.GetFeatureServiceById(serviceId);
            if (featureService == null)
            {
                await _domainManagerService.AddNotFound($"The feature pipe with id {serviceId} does not exists.");

                return;
            }

            if (string.IsNullOrEmpty(featureService.LastBuildSuccessVersionId))
            {
                await _domainManagerService.AddConflict($"The feature service with id {serviceId} does not have any success build yet.");

                return;
            }

            CMSPipelineReleaseParamModel releaseBuildOptions = new CMSPipelineReleaseParamModel();

            releaseBuildOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
            releaseBuildOptions.VSTSAccountName      = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName) : _fakeAccountOptions.Value.AccountId;
            releaseBuildOptions.VSTSAccessSecret     = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret) : _fakeAccountOptions.Value.AccessSecret;
            releaseBuildOptions.VSTSAccountProjectId = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? project.Name : project.ProjectVSTSFakeName;

            releaseBuildOptions.ProjectName         = project.Name;
            releaseBuildOptions.ProjectExternalId   = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? project.ProjectExternalId : project.ProjectVSTSFakeId;
            releaseBuildOptions.ReleaseDefinitionId = featureService.ReleaseStageId.Value;
            releaseBuildOptions.Alias = $"{featureService.ProjectService.Name}-ft-{feature.Name.ToLower()}";

            releaseBuildOptions.VersionId   = int.Parse(featureService.LastBuildSuccessVersionId);
            releaseBuildOptions.VersionName = featureService.LastBuildSuccessVersionName;
            releaseBuildOptions.Description = "Release created from PipelineSpace";

            await _cmsPipelineService.CreateRelease(releaseBuildOptions);
        }
        //actions
        public async Task CreateBuildProjectService(Guid organizationId, Guid projectId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to modify a service.");

                return;
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return;
            }

            if (service.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The pipe with id {serviceId} must be in status Active to request a Build.");

                return;
            }

            var serviceCredential = this._cloudCredentialService.ProjectServiceCredentialResolver(project, service);

            CMSPipelineAgentQueueParamModel getQueueOptions = new CMSPipelineAgentQueueParamModel();

            getQueueOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
            getQueueOptions.CMSType              = serviceCredential.CMSType;
            getQueueOptions.VSTSAccountName      = serviceCredential.AccountName;
            getQueueOptions.VSTSAccessSecret     = serviceCredential.AccessSecret;
            getQueueOptions.VSTSAccountProjectId = serviceCredential.AccountProjectId;

            getQueueOptions.ProjectName = serviceCredential.ProjectName;
            getQueueOptions.AgentPoolId = project.AgentPoolId;

            var queue = await _cmsPipelineService.GetQueue(getQueueOptions);

            if (queue == null)
            {
                await _domainManagerService.AddConflict($"The agent pool id {project.AgentPoolId} is not available.");

                return;
            }

            CMSPipelineBuildParamModel queueBuildOptions = new CMSPipelineBuildParamModel();

            queueBuildOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
            queueBuildOptions.VSTSAccountName      = serviceCredential.AccountName;
            queueBuildOptions.VSTSAccessSecret     = serviceCredential.AccessSecret;
            queueBuildOptions.VSTSAccountProjectId = serviceCredential.AccountProjectId;

            queueBuildOptions.ProjectName       = serviceCredential.ProjectName;
            queueBuildOptions.ProjectExternalId = serviceCredential.ProjectExternalId;
            queueBuildOptions.QueueId           = queue.QueueId;
            queueBuildOptions.BuildDefinitionId = service.CommitStageId.Value;
            queueBuildOptions.SourceBranch      = service.BranchName;

            await _cmsPipelineService.CreateBuild(queueBuildOptions);

            var @event = new ProjectServiceBuildQueuedEvent(_correlationId)
            {
                OrganizationId = organization.OrganizationId,
                ProjectId      = project.ProjectId,
                ServiceId      = service.ProjectServiceId
            };

            await _eventBusService.Publish(queueName : "ProjectServiceBuildQueuedEvent", @event : @event);
        }
        public async Task DeleteProjectService(Guid organizationId, Guid projectId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to modify a service.");

                return;
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return;
            }

            if (service.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The pipe with id {serviceId} must be in status Active to be modified/deleted.");

                return;
            }

            /*Check If any feature is associated with the service*/
            var features = project.GetFeatures();

            foreach (var feature in features)
            {
                var featureService = feature.GetFeatureServiceById(serviceId);
                if (featureService != null)
                {
                    await _domainManagerService.AddConflict($"The are active features ({feature.Name}) using the service, you cannot delete the service.");

                    return;
                }
            }

            user.DeleteProjectService(organizationId, projectId, serviceId);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            if (project.OrganizationCPS == null)
            {
                project.OrganizationCPS = new OrganizationCPS {
                    Type = CloudProviderService.None
                }
            }
            ;

            //send event
            var projectServiceDeletedEvent = new ProjectServiceDeletedEvent(_correlationId)
            {
                OrganizationExternalId                = project.OrganizationExternalId,
                OrganizationName                      = organization.Name,
                ProjectName                           = project.Name,
                ServiceName                           = service.Name,
                ProjectVSTSFakeName                   = project.ProjectVSTSFakeName,
                ProjectExternalId                     = project.ProjectExternalId,
                ProjectServiceExternalId              = service.ProjectServiceExternalId,
                CommitStageId                         = service.CommitStageId,
                ReleaseStageId                        = service.ReleaseStageId,
                CommitServiceHookId                   = service.CommitServiceHookId,
                CodeServiceHookId                     = service.CodeServiceHookId,
                ReleaseStartedServiceHookId           = service.ReleaseStartedServiceHookId,
                ReleasePendingApprovalServiceHookId   = service.ReleasePendingApprovalServiceHookId,
                ReleaseCompletedApprovalServiceHookId = service.ReleaseCompletedApprovalServiceHookId,
                ReleaseServiceHookId                  = service.ReleaseServiceHookId,
                Environments                          = project.GetEnvironments().Select(x => x.Name).ToList(),
                CMSType            = project.OrganizationCMS.Type,
                CMSAccountId       = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                CMSAccountName     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                CMSAccessId        = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId),
                CMSAccessSecret    = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                CMSAccessToken     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken),
                CPSType            = project.OrganizationCPS.Type,
                CPSAccessId        = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId),
                CPSAccessName      = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName),
                CPSAccessSecret    = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret),
                CPSAccessRegion    = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion),
                CPSAccessAppId     = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId),
                CPSAccessAppSecret = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret),
                CPSAccessDirectory = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory),
                SourceEvent        = DomainModels.Enums.SourceEvent.Service
            };

            await _eventBusService.Publish(queueName : "ProjectServiceDeletedEvent", @event : projectServiceDeletedEvent);
        }
        public async Task <ProjectFeatureServicePipelineGetRp> GetProjectFeatureServicePipelineById(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeatureService featureService = feature.GetFeatureServiceById(serviceId);
            if (featureService == null)
            {
                return(null);
            }

            ProjectFeatureServicePipelineGetRp featureServicePipelineRp = new ProjectFeatureServicePipelineGetRp
            {
                Name        = featureService.ProjectService.Name,
                Description = featureService.ProjectService.Description,
                Status      = featureService.Status,
                PipeType    = featureService.ProjectService.PipeType,
                Phases      = new List <ProjectFeatureServicePipelinePhaseGetRp>()
            };

            featureServicePipelineRp.Phases.Add(new ProjectFeatureServicePipelinePhaseGetRp()
            {
                Type                   = "Build",
                Name                   = "Build",
                Rank                   = 1,
                LastStatusCode         = featureService.LastPipelineBuildStatus.ToString(),
                LastStatusDescription  = featureService.LastPipelineBuildStatus.GetDescription(),
                LastVersionId          = featureService.LastBuildVersionId,
                LastVersionName        = featureService.LastBuildVersionName,
                LastSuccessVersionId   = featureService.LastBuildSuccessVersionId,
                LastSuccessVersionName = featureService.LastBuildSuccessVersionName,
                LastApprovalId         = string.Empty
            });

            foreach (var environment in featureService.Environments)
            {
                featureServicePipelineRp.Phases.Add(new ProjectFeatureServicePipelinePhaseGetRp()
                {
                    Type                   = "Release",
                    Name                   = environment.ProjectFeatureEnvironment.Name,
                    Rank                   = environment.ProjectFeatureEnvironment.Rank + 1,
                    LastStatusCode         = string.IsNullOrEmpty(environment.LastStatusCode) ? PipelineReleaseStatus.Pending.ToString() : environment.LastStatusCode,
                    LastStatusDescription  = string.IsNullOrEmpty(environment.LastStatus) ? PipelineReleaseStatus.Pending.ToString() : environment.LastStatus,
                    LastVersionId          = environment.LastVersionId,
                    LastVersionName        = environment.LastVersionName,
                    LastSuccessVersionId   = environment.LastSuccessVersionId,
                    LastSuccessVersionName = environment.LastSuccessVersionName,
                    LastApprovalId         = environment.LastApprovalId
                });
            }

            //Order
            featureServicePipelineRp.Phases = featureServicePipelineRp.Phases.OrderBy(x => x.Rank).ToList();

            return(featureServicePipelineRp);
        }
        public async Task <ProjectFeatureServiceSummaryGetRp> GetProjectFeatureServiceSummaryById(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeatureService featureService = feature.GetFeatureServiceById(serviceId);
            if (featureService == null)
            {
                return(null);
            }

            ProjectFeatureServiceSummaryGetRp featureServiceSummaryRp = new ProjectFeatureServiceSummaryGetRp
            {
                Name                      = featureService.ProjectService.Name,
                Description               = featureService.ProjectService.Description,
                Status                    = featureService.Status,
                PipeType                  = featureService.ProjectService.PipeType,
                PipelineStatus            = featureService.PipelineStatus,
                LastPipelineBuildStatus   = featureService.LastPipelineBuildStatus,
                LastPipelineReleaseStatus = featureService.LastPipelineReleaseStatus,
                Activities                = new ProjectFeatureServiceActivityListRp()
                {
                    Items = featureService.Activities.OrderBy(x => x.CreationDate).Select(x => new ProjectFeatureServiceActivityListItemRp()
                    {
                        Name           = x.Name,
                        Log            = x.Log,
                        CreationDate   = x.CreationDate,
                        ActivityStatus = x.ActivityStatus,
                    }).ToList()
                },
                Events = new ProjectFeatureServiceEventListRp()
                {
                    Items = featureService.Events.OrderByDescending(x => x.EventDate).Take(6).Select(x => new ProjectFeatureServiceEventListItemRp()
                    {
                        EventDescription = x.EventDescription,
                        EventType        = x.EventType,
                        EventStatus      = x.EventStatus,
                        CreationDate     = x.CreationDate,
                        EventDate        = x.EventDate
                    }).ToList()
                }
            };

            return(featureServiceSummaryRp);
        }
Esempio n. 28
0
        public async Task SortProjectEnvironments(Guid organizationId, Guid projectId, ProjectEnvironmentSortPostRp resource)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            DomainModels.PipelineRole role = user.GetRoleInProject(projectId);
            if (role != DomainModels.PipelineRole.ProjectAdmin)
            {
                await _domainManagerService.AddForbidden($"You are not authorized to sort environments in this project.");

                return;
            }

            if (project.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to sort de environments.");

                return;
            }

            var developmentEnvironment = project.GetDevelopmentEnvironment();
            var productionEnvironment  = project.GetProductionEnvironment();

            foreach (var item in resource.Items)
            {
                var environment = project.GetEnvironmentById(item.EnvironmentId);

                if (environment == null)
                {
                    await _domainManagerService.AddNotFound($"The environment with id {item.EnvironmentId}) does not exists.");

                    return;
                }

                if (environment.Type == EnvironmentType.Root || environment.Type == EnvironmentType.Fact)
                {
                    await _domainManagerService.AddConflict($"The environment {environment.Name} ({environment.ProjectEnvironmentId}) is not sortable.");

                    return;
                }

                if (!(developmentEnvironment.Rank < item.Rank && item.Rank < productionEnvironment.Rank))
                {
                    await _domainManagerService.AddConflict($"The rank of the environment {environment.Name} ({environment.ProjectEnvironmentId}) must be between {developmentEnvironment.Rank + 1} and {productionEnvironment.Rank - 1}.");

                    return;
                }

                environment.Rank = item.Rank;
            }

            var groupped = project.Environments.GroupBy(x => x.Rank);

            if (groupped.Count() != project.Environments.Count)
            {
                await _domainManagerService.AddConflict($"The rank of the environments must be sorted sequentially between {developmentEnvironment.Rank + 1} and {productionEnvironment.Rank - 1}.");

                return;
            }

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            var projectServices = project.GetServicesWithReleaseStages();

            //send events
            foreach (var projectService in projectServices)
            {
                var @event = new ProjectEnvironmentCreatedEvent(_correlationId)
                {
                    OrganizationId            = organization.OrganizationId,
                    OrganizationName          = organization.Name,
                    ProjectId                 = project.ProjectId,
                    ProjectExternalId         = project.ProjectExternalId,
                    ProjectExternalEndpointId = project.ProjectExternalEndpointId,
                    ProjectVSTSFakeName       = project.ProjectVSTSFakeName,
                    ProjectName               = project.Name,
                    CMSType         = project.OrganizationCMS.Type,
                    CMSAccountId    = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId),
                    CMSAccountName  = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName),
                    CMSAccessId     = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId),
                    CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret),
                    CMSAccessToken  = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken),
                    ReleseStageId   = projectService.ReleaseStageId.Value,
                    ServiceName     = projectService.Name,
                    ServiceLastBuildSuccessVersionId   = projectService.LastBuildSuccessVersionId,
                    ServiceLastBuildSuccessVersionName = projectService.LastBuildSuccessVersionName
                };

                @event.Environments = new List <ProjectEnvironmentItemCreatedEvent>();

                foreach (var item in projectService.Environments)
                {
                    var parentEnvironment = project.GetEnvironments().First(x => x.ProjectEnvironmentId == item.ProjectEnvironmentId);

                    var serviceEnvironment = new ProjectEnvironmentItemCreatedEvent();
                    serviceEnvironment.Id                     = item.ProjectEnvironmentId;
                    serviceEnvironment.Name                   = parentEnvironment.Name;
                    serviceEnvironment.RequiredApproval       = parentEnvironment.RequiresApproval;
                    serviceEnvironment.Variables              = new List <ProjectEnvironmentItemVariableCreatedEvent>();
                    serviceEnvironment.Rank                   = parentEnvironment.Rank;
                    serviceEnvironment.LastSuccessVersionId   = item.LastSuccessVersionId;
                    serviceEnvironment.LastSuccessVersionName = item.LastSuccessVersionName;

                    if (parentEnvironment.Variables != null)
                    {
                        foreach (var variable in parentEnvironment.Variables)
                        {
                            serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent()
                            {
                                Name  = variable.Name,
                                Value = variable.Value
                            });
                        }
                    }

                    if (item.Variables != null)
                    {
                        foreach (var variable in item.Variables)
                        {
                            serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent()
                            {
                                Name  = variable.Name,
                                Value = variable.Value
                            });
                        }
                    }

                    @event.Environments.Add(serviceEnvironment);
                }

                //Cloud Provider Data
                @event.CPSType         = project.OrganizationCPS.Type;
                @event.CPSAccessId     = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId);
                @event.CPSAccessName   = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName);
                @event.CPSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret);
                @event.CPSAccessRegion = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion);

                await _eventBusService.Publish(queueName : "ProjectEnvironmentCreatedEvent", @event : @event);
            }
        }
        public async Task CreateReleaseProjectService(Guid organizationId, Guid projectId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return;
            }

            DomainModels.Project project = organization.GetProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return;
            }

            if (project.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to modify a service.");

                return;
            }

            DomainModels.ProjectService service = project.GetServiceById(serviceId);
            if (service == null)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return;
            }

            if (service.Status != EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The pipe with id {serviceId} must be in status Active to request a Request.");

                return;
            }

            if (string.IsNullOrEmpty(service.LastBuildSuccessVersionId))
            {
                await _domainManagerService.AddConflict($"The project service with id {serviceId} does not have any success build yet.");

                return;
            }

            var serviceCredential = this._cloudCredentialService.ProjectServiceCredentialResolver(project, service);

            CMSPipelineReleaseParamModel releaseBuildOptions = new CMSPipelineReleaseParamModel();

            releaseBuildOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
            releaseBuildOptions.VSTSAccountName      = serviceCredential.AccountName;
            releaseBuildOptions.VSTSAccessSecret     = serviceCredential.AccessSecret;
            releaseBuildOptions.VSTSAccountProjectId = serviceCredential.AccountProjectId;

            releaseBuildOptions.ProjectName         = serviceCredential.ProjectName;
            releaseBuildOptions.ProjectExternalId   = serviceCredential.ProjectExternalId;
            releaseBuildOptions.ReleaseDefinitionId = service.ReleaseStageId.Value;
            releaseBuildOptions.Alias = service.Name;

            releaseBuildOptions.VersionId   = int.Parse(service.LastBuildSuccessVersionId);
            releaseBuildOptions.VersionName = service.LastBuildSuccessVersionName;
            releaseBuildOptions.Description = "Release created from PipelineSpace";

            await _cmsPipelineService.CreateRelease(releaseBuildOptions);
        }
        public async Task <ProjectFeatureServiceExternalGetRp> GetProjectFeatureServiceExternalById(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            DomainModels.User user = await _userRepository.GetUser(loggedUserId);

            DomainModels.Organization organization = user.FindOrganizationById(organizationId);
            if (organization == null)
            {
                await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists.");

                return(null);
            }

            DomainModels.Project project = user.FindProjectById(projectId);
            if (project == null)
            {
                await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists.");

                return(null);
            }

            DomainModels.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

            CMSAuthCredentialModel cmsAuthCredential = null;
            var serviceExternalName = string.Empty;
            var projectExternalId   = project.ProjectExternalId;
            var service             = feature.Services.FirstOrDefault(c => c.ProjectServiceId.Equals(serviceId)).ProjectService;

            //Auth
            cmsAuthCredential = this._cmsCredentialService(service.OrganizationCMS.Type).GetToken(
                _dataProtectorService.Unprotect(service.OrganizationCMS.AccountId),
                _dataProtectorService.Unprotect(service.OrganizationCMS.AccountName),
                _dataProtectorService.Unprotect(service.OrganizationCMS.AccessSecret),
                _dataProtectorService.Unprotect(service.OrganizationCMS.AccessToken));

            switch (service.OrganizationCMS.Type)
            {
            case ConfigurationManagementService.VSTS:
                serviceExternalName = service.ProjectServiceExternalName;
                projectExternalId   = project.ProjectExternalId;
                break;

            case ConfigurationManagementService.Bitbucket:
                serviceExternalName = service.ProjectServiceExternalId;
                projectExternalId   = project.OrganizationExternalId;
                break;

            case ConfigurationManagementService.GitHub:
                serviceExternalName = service.ProjectServiceExternalName;
                projectExternalId   = project.ProjectExternalId;
                break;

            case ConfigurationManagementService.GitLab:
                serviceExternalName = service.ProjectServiceExternalId;
                projectExternalId   = project.ProjectExternalId;
                break;

            default:
                break;
            }

            if (service.IsImported)
            {
                projectExternalId = service.ProjectExternalId;
            }

            var serviceExternal = await this._cmsQueryService(service.OrganizationCMS.Type).GetRepository(projectExternalId, serviceExternalName, cmsAuthCredential);

            return(new ProjectFeatureServiceExternalGetRp
            {
                DefaultBranch = feature.Name,
                GitUrl = serviceExternal.Link,
                SSHUrl = serviceExternal.SSHUrl
            });
        }