Ejemplo n.º 1
0
        public void UpdateProjectService(Guid organizationId, Guid projectId, Guid serviceId, string name, string description)
        {
            Organization organization = FindOrganizationById(organizationId);

            if (organization == null)
            {
                throw new ApplicationException($"The organization with id {organizationId} does not exists");
            }

            Project project = organization.GetProjectById(projectId);

            if (project == null)
            {
                throw new ApplicationException($"The project with id {projectId} does not exists");
            }

            ProjectService projectService = project.GetServiceById(serviceId);

            if (projectService == null)
            {
                throw new ApplicationException($"The pipe with id {serviceId} does not exists");
            }

            projectService.UpdateBasicInformation(name, description);
            projectService.Audit(this.Id);
        }
Ejemplo n.º 2
0
        public void DeleteProjectService(Guid organizationId, Guid projectId, Guid serviceId)
        {
            Organization organization = FindOrganizationById(organizationId);

            if (organization == null)
            {
                throw new ApplicationException($"The organization with id {organizationId} does not exists");
            }

            Project project = organization.GetProjectById(projectId);

            if (project == null)
            {
                throw new ApplicationException($"The project with id {projectId} does not exists");
            }

            ProjectService projectService = project.GetServiceById(serviceId);

            if (projectService == null)
            {
                throw new ApplicationException($"The pipe with id {serviceId} does not exists");
            }

            projectService.Delete(this.Id);
        }
Ejemplo n.º 3
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);
        }
Ejemplo n.º 6
0
        public async Task <ProjectServiceDeliveryListRp> GetProjectServiceDeliveries(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)
            {
                await _domainManagerService.AddNotFound($"The pipe with id {serviceId} does not exists.");

                return(null);
            }

            ProjectServiceDeliveryListRp list = new ProjectServiceDeliveryListRp();

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

            return(list);
        }
        public async Task <CPSCloudResourceSummaryModel> GetProjectServiceCloudSummary(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)
            {
                await _domainManagerService.AddNotFound($"The project pipe with id {serviceId} does not exists.");

                return(null);
            }

            var environments = project.GetEnvironments().Select(x => 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);

            var summary = await _cpsQueryService(project.OrganizationCPS.Type).GetSummary(organization.Name, project.Name, service.Name, environments, "Root", authCredentials);

            return(summary);
        }
        public async Task <ProjectServiceActivityListRp> GetProjectServiceActivities(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)
            {
                await _domainManagerService.AddNotFound($"The pipe with id {serviceId} does not exists.");

                return(null);
            }

            ProjectServiceActivityListRp list = new ProjectServiceActivityListRp();

            if (service.Activities != null)
            {
                list.Items = service.Activities.Select(x => new ProjectServiceActivityListItemRp
                {
                    Name           = x.Name,
                    Log            = x.Log,
                    ActivityStatus = x.ActivityStatus,
                    CreationDate   = x.CreationDate
                }).OrderBy(x => x.CreationDate).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);
        }
        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);
        }
        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);
        }
        //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 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 <ProjectServicePipelineGetRp> GetProjectServicePipelineById(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);
            }

            ProjectServicePipelineGetRp servicePipelineRp = new ProjectServicePipelineGetRp
            {
                Name        = service.Name,
                Description = service.Description,
                Status      = service.Status,
                PipeType    = service.PipeType,
                Phases      = new List <ProjectServicePipelinePhaseGetRp>()
            };

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

            foreach (var environment in service.Environments)
            {
                servicePipelineRp.Phases.Add(new ProjectServicePipelinePhaseGetRp()
                {
                    Type                   = "Release",
                    Name                   = environment.ProjectEnvironment.Name,
                    Rank                   = environment.ProjectEnvironment.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
            servicePipelineRp.Phases = servicePipelineRp.Phases.OrderBy(x => x.Rank).ToList();

            return(servicePipelineRp);
        }
        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;
            }

            /*PIPELINE STATUS###########################################################################################################*/
            /*##########################################################################################################################*/
            string        eventStatus   = string.Empty;
            DateTime      eventDate     = DateTime.UtcNow;
            BaseEventType baseEventType = BaseEventType.Build;

            //update pipeline status when build
            if (resource.GetEventType() == PipelineEventType.BuildStarted)
            {
                baseEventType = BaseEventType.Build;
                eventStatus   = "Queued";

                if (eventDate > service.LastBuildEventDate)
                {
                    service.PipelineStatus          = PipelineStatus.Building;
                    service.LastPipelineBuildStatus = PipelineBuildStatus.Building;

                    service.LastBuildEventDate = eventDate;
                }
            }

            if (resource.GetEventType() == PipelineEventType.BuildCompleted)
            {
                var buildModel = resource.BuildBuildModel();
                eventStatus   = buildModel.Status.FirstCharToUpper();
                eventDate     = buildModel.FinishTime;
                baseEventType = BaseEventType.Build;

                service.LastBuildVersionId   = buildModel.Id.ToString();
                service.LastBuildVersionName = buildModel.BuildNumber;

                if (eventDate > service.LastBuildEventDate)
                {
                    if (buildModel.Status.Equals("Succeeded", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus          = PipelineStatus.BuildSucceeded;
                        service.LastPipelineBuildStatus = PipelineBuildStatus.BuildSucceeded;

                        service.LastBuildSuccessVersionId   = buildModel.Id.ToString();
                        service.LastBuildSuccessVersionName = buildModel.BuildNumber;
                    }

                    if (buildModel.Status.Equals("Failed", StringComparison.InvariantCultureIgnoreCase) ||
                        buildModel.Status.Equals("Error", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus          = PipelineStatus.BuildFailed;
                        service.LastPipelineBuildStatus = PipelineBuildStatus.BuildFailed;
                    }

                    if (buildModel.Status.Equals("Canceled", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus          = PipelineStatus.BuildCanceled;
                        service.LastPipelineBuildStatus = PipelineBuildStatus.BuildCanceled;
                    }

                    service.LastBuildEventDate = eventDate;
                }

                //Delivery
                service.AddDeliveryBuildCompleted(buildModel.Id, buildModel.BuildNumber, eventStatus, eventDate);
            }

            //update pipeline status when release
            if (resource.GetEventType() == PipelineEventType.ReleaseStarted)
            {
                var releaseModel = resource.BuildReleaseStartedModel();
                eventStatus   = releaseModel.Environment.Status.FirstCharToUpper();
                eventDate     = releaseModel.Release.CreatedOn;
                baseEventType = BaseEventType.Release;

                var environment = service.Environments.FirstOrDefault(x => x.ProjectEnvironment.Name.Equals(releaseModel.Environment.Name, StringComparison.InvariantCultureIgnoreCase));
                if (environment.LastEventDate < eventDate)
                {
                    environment.LastStatus     = releaseModel.Environment.Status.FirstCharToUpper();
                    environment.LastStatusCode = PipelineReleaseStatus.Deploying.ToString();
                    environment.LastEventDate  = eventDate;
                }

                if (eventDate > service.LasReleaseEventDate)
                {
                    service.PipelineStatus            = PipelineStatus.Deploying;
                    service.LastPipelineReleaseStatus = PipelineReleaseStatus.Deploying;

                    service.LasReleaseEventDate = eventDate;
                }

                //Delivery
                service.AddDeliveryReleaseStarted(int.Parse(releaseModel.VersionId),
                                                  releaseModel.VersionName,
                                                  releaseModel.Release.Environments.Select(x => new Domain.ModelUtility.DeliveryEnvironmentModel()
                {
                    Name = x.Name, Rank = x.Rank, Status = x.Status.FirstCharToUpper()
                }).ToList());
            }

            if (resource.GetEventType() == PipelineEventType.ReleasePendingApproval)
            {
                var releaseApprovalModel = resource.BuildReleaseApprovalModel();
                eventStatus   = "Release approval pending";
                eventDate     = releaseApprovalModel.Approval.CreatedOn;
                baseEventType = BaseEventType.Release;

                var environment = service.Environments.FirstOrDefault(x => x.ProjectEnvironment.Name.Equals(releaseApprovalModel.Approval.ReleaseEnvironment.Name, StringComparison.InvariantCultureIgnoreCase));
                if (environment.LastEventDate < eventDate)
                {
                    environment.LastStatus     = "Release approval pending";
                    environment.LastStatusCode = PipelineReleaseStatus.DeployPendingApproval.ToString();
                    environment.LastApprovalId = releaseApprovalModel.Approval.Id.ToString();
                    environment.LastEventDate  = eventDate;
                }

                if (eventDate > service.LasReleaseEventDate)
                {
                    service.PipelineStatus            = PipelineStatus.DeployPendingApproval;
                    service.LastPipelineReleaseStatus = PipelineReleaseStatus.DeployPendingApproval;

                    service.LasReleaseEventDate = eventDate;
                }

                //Delivery
                service.UpdateDeliveryReleaseStatus(int.Parse(releaseApprovalModel.VersionId), releaseApprovalModel.VersionName, releaseApprovalModel.Approval.ReleaseEnvironment.Name, eventStatus);
            }

            if (resource.GetEventType() == PipelineEventType.ReleaseCompletedApproval)
            {
                var releaseApprovalModel = resource.BuildReleaseApprovalModel();
                eventStatus   = $"Release approval {releaseApprovalModel.Approval.Status}";
                eventDate     = releaseApprovalModel.Approval.ModifiedOn;
                baseEventType = BaseEventType.Release;

                var environment = service.Environments.FirstOrDefault(x => x.ProjectEnvironment.Name.Equals(releaseApprovalModel.Approval.ReleaseEnvironment.Name, StringComparison.InvariantCultureIgnoreCase));
                if (environment.LastEventDate < eventDate)
                {
                    environment.LastStatus     = $"Release approval {releaseApprovalModel.Approval.Status}";
                    environment.LastStatusCode = releaseApprovalModel.Approval.Status.Equals("rejected", StringComparison.InvariantCultureIgnoreCase) ? PipelineReleaseStatus.DeployRejectedApproval.ToString() : PipelineReleaseStatus.DeployAcceptedApproval.ToString();
                    environment.LastEventDate  = eventDate;
                }

                if (eventDate > service.LasReleaseEventDate)
                {
                    service.PipelineStatus            = releaseApprovalModel.Approval.Status.Equals("rejected", StringComparison.InvariantCultureIgnoreCase) ? PipelineStatus.DeployRejectedApproval : PipelineStatus.DeployAcceptedApproval;
                    service.LastPipelineReleaseStatus = releaseApprovalModel.Approval.Status.Equals("rejected", StringComparison.InvariantCultureIgnoreCase) ? PipelineReleaseStatus.DeployRejectedApproval : PipelineReleaseStatus.DeployAcceptedApproval;

                    service.LasReleaseEventDate = eventDate;
                }

                //Delivery
                service.UpdateDeliveryReleaseStatus(int.Parse(releaseApprovalModel.VersionId), releaseApprovalModel.VersionName, releaseApprovalModel.Approval.ReleaseEnvironment.Name, eventStatus);
            }

            if (resource.GetEventType() == PipelineEventType.ReleaseCompleted)
            {
                var releaseModel = resource.BuildReleaseModel();
                eventStatus   = releaseModel.Environment.Status.FirstCharToUpper();
                eventDate     = releaseModel.Deployment.CompletedOn;
                baseEventType = BaseEventType.Release;

                if (releaseModel.Environment.Status.Equals("Rejected", StringComparison.InvariantCultureIgnoreCase))
                {
                    eventDate = releaseModel.Deployment.LastModifiedOn;
                }

                var environment = service.Environments.FirstOrDefault(x => x.ProjectEnvironment.Name.Equals(releaseModel.Environment.Name, StringComparison.InvariantCultureIgnoreCase));
                if (environment.LastEventDate < eventDate)
                {
                    environment.LastStatus      = releaseModel.Environment.Status.FirstCharToUpper();
                    environment.LastVersionId   = releaseModel.Deployment.VersionId;
                    environment.LastVersionName = releaseModel.Deployment.VersionName;
                    environment.LastEventDate   = eventDate;
                }

                if (releaseModel.Environment.Status.Equals("Succeeded", StringComparison.InvariantCultureIgnoreCase))
                {
                    environment.LastSuccessVersionId   = releaseModel.Deployment.VersionId;
                    environment.LastSuccessVersionName = releaseModel.Deployment.VersionName;
                    environment.LastStatusCode         = PipelineReleaseStatus.DeploySucceeded.ToString();
                }

                if (releaseModel.Environment.Status.Equals("Failed", StringComparison.InvariantCultureIgnoreCase) ||
                    releaseModel.Environment.Status.Equals("Error", StringComparison.InvariantCultureIgnoreCase))
                {
                    environment.LastStatusCode = PipelineReleaseStatus.DeployFailed.ToString();
                }

                if (releaseModel.Environment.Status.Equals("Canceled", StringComparison.InvariantCultureIgnoreCase))
                {
                    environment.LastStatusCode = PipelineReleaseStatus.DeployCanceled.ToString();
                }

                if (releaseModel.Environment.Status.Equals("Rejected", StringComparison.InvariantCultureIgnoreCase))
                {
                    environment.LastStatusCode = PipelineReleaseStatus.DeployRejected.ToString();
                }

                if (eventDate > service.LasReleaseEventDate)
                {
                    if (releaseModel.Environment.Status.Equals("Succeeded", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus            = PipelineStatus.DeploySucceeded;
                        service.LastPipelineReleaseStatus = PipelineReleaseStatus.DeploySucceeded;
                    }

                    if (releaseModel.Environment.Status.Equals("Failed", StringComparison.InvariantCultureIgnoreCase) ||
                        releaseModel.Environment.Status.Equals("Error", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus            = PipelineStatus.DeployFailed;
                        service.LastPipelineReleaseStatus = PipelineReleaseStatus.DeployFailed;
                    }

                    if (releaseModel.Environment.Status.Equals("Canceled", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus            = PipelineStatus.DeployCanceled;
                        service.LastPipelineReleaseStatus = PipelineReleaseStatus.DeployCanceled;
                    }

                    if (releaseModel.Environment.Status.Equals("Rejected", StringComparison.InvariantCultureIgnoreCase))
                    {
                        service.PipelineStatus            = PipelineStatus.DeployRejected;
                        service.LastPipelineReleaseStatus = PipelineReleaseStatus.DeployRejected;
                    }
                    service.LasReleaseEventDate = eventDate;
                }

                //Delivery
                service.UpdateDeliveryReleaseStatus(int.Parse(releaseModel.Deployment.VersionId), releaseModel.Deployment.VersionName, releaseModel.Environment.Name, eventStatus);
            }

            /*SERVICE STATUS###########################################################################################################*/
            /*#########################################################################################################################*/
            //activate the service when build is failed
            if (resource.GetEventType() == PipelineEventType.BuildCompleted &&
                (eventStatus.Equals("Failed", StringComparison.InvariantCultureIgnoreCase) ||
                 eventStatus.Equals("Error", StringComparison.InvariantCultureIgnoreCase) ||
                 eventStatus.Equals("Canceled", StringComparison.InvariantCultureIgnoreCase)) &&
                service.Status == EntityStatus.Preparing)
            {
                service.Status = EntityStatus.Active;
            }

            //activate the service when realease is completed (in any event status)
            if (resource.GetEventType() == PipelineEventType.ReleaseCompleted && service.Status == EntityStatus.Preparing)
            {
                service.Status = EntityStatus.Active;
            }

            service.AddEvent(baseEventType, resource.GetEventType().GetDescription(), resource.Message.Text, eventStatus, JsonConvert.SerializeObject(resource.DetailedMessage), JsonConvert.SerializeObject(resource.DetailedMessage), JsonConvert.SerializeObject(resource.Resource), eventDate);

            _organizationRepository.Update(organization);

            await _organizationRepository.SaveChanges();
        }
        public async Task CreateProjectServiceEnvironmentRelease(Guid organizationId, Guid projectId, Guid serviceId, 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 add a new feature.");

                return;
            }

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

                return;
            }

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

                return;
            }

            DomainModels.ProjectServiceEnvironment environment = projectService.GetServiceEnvironment(environmentId);
            if (environment == null)
            {
                await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists.");

                return;
            }

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

                return;
            }

            var previousEnvironment = projectService.Environments.FirstOrDefault(x => x.ProjectEnvironment.Rank == ((environment.ProjectEnvironment.Type == EnvironmentType.Root) ? environment.ProjectEnvironment.Rank : environment.ProjectEnvironment.Rank - 1));

            if (string.IsNullOrEmpty(previousEnvironment.LastSuccessVersionId))
            {
                await _domainManagerService.AddConflict($"The project service with id {serviceId} does not have any success deploy in the environment {previousEnvironment.ProjectEnvironment.Name} (This is a condition to create the release).");

                return;
            }

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

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

            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 = projectService.ReleaseStageId.Value;
            releaseBuildOptions.Alias = projectService.Name;

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

            await _cmsPipelineService.CreateRelease(releaseBuildOptions);
        }
        public async Task CompleteProjectFeature(Guid organizationId, Guid projectId, Guid featureId, bool deleteInfrastructure)
        {
            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 complete features in this project.");

                return;
            }

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

                return;
            }

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

                return;
            }

            if (feature.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The feature with id {featureId} must be in status Active to to ask for pull request.");

                return;
            }

            //if (feature.IsCompleted())
            //{
            //    await _domainManagerService.AddConflict($"The feature with id {featureId} has already been completed.");
            //    return;
            //}

            //services asociated (TODO: services on demand)
            List <ProjectFeatureServiceCompletedEvent> @events = new List <ProjectFeatureServiceCompletedEvent>();

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

                    return;
                }

                @events.Add(new ProjectFeatureServiceCompletedEvent(_correlationId)
                {
                    ServiceId          = item.ProjectServiceId,
                    ServiceExternalId  = projectService.ProjectServiceExternalId,
                    ServiceExternalUrl = projectService.ProjectServiceExternalUrl,
                    ServiceName        = projectService.Name,
                    ServiceTemplateUrl = projectService.ProjectServiceTemplate.Url,
                    CommitStageId      = item.CommitStageId,
                    ReleaseStageId     = item.ReleaseStageId
                });
            }

            user.CompleteProjectFeature(organizationId, projectId, featureId);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            var @event = new ProjectFeatureCompletedEvent(_correlationId)
            {
                OrganizationExternalId = project.OrganizationExternalId,
                OrganizationId         = organization.OrganizationId,
                OrganizationName       = organization.Name,
                ProjectId                 = project.ProjectId,
                Services                  = @events,
                ProjectExternalId         = project.ProjectExternalId,
                ProjectExternalEndpointId = project.ProjectExternalEndpointId,
                ProjectVSTSFakeName       = project.ProjectVSTSFakeName,
                ProjectName               = project.Name,
                FeatureId                 = feature.ProjectFeatureId,
                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),
                DeleteInfrastructure = deleteInfrastructure
            };

            //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 : "ProjectFeatureCompletedEvent", @event : @event);
        }
        public async Task <ProjectServiceEnvironmentListRp> GetProjectServiceEnvironments(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 projectService = project.GetServiceById(serviceId);
            if (projectService == null)
            {
                await _domainManagerService.AddNotFound($"The project service with id {serviceId} does not exists.");

                return(null);
            }

            ProjectServiceEnvironmentListRp list = new ProjectServiceEnvironmentListRp();

            if (project.OrganizationCPS.Type == DomainModels.CloudProviderService.None)
            {
                return(list);
            }

            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 (projectService.Environments != null)
            {
                List <ProjectServiceEnvironmentListItemRp> projectServiceEnvironmentList = new List <ProjectServiceEnvironmentListItemRp>();
                var environments = projectService.Environments.OrderBy(x => x.ProjectEnvironment.Rank);
                foreach (var item in environments)
                {
                    var projectServiceEnvironmentListItem = new ProjectServiceEnvironmentListItemRp();
                    projectServiceEnvironmentListItem.ProjectServiceEnvironmentId = item.ProjectServiceEnvironmentId;
                    projectServiceEnvironmentListItem.Name    = item.ProjectEnvironment.Name;
                    projectServiceEnvironmentListItem.Status  = item.Status;
                    projectServiceEnvironmentListItem.Summary = await _cpsQueryService(project.OrganizationCPS.Type).GetEnvironmentSummary(organization.Name, project.Name, projectService.Name, item.ProjectEnvironment.Name, "Root", authCredentials);

                    projectServiceEnvironmentListItem.Variables = item.Variables.Select(p => new ProjectServiceEnvironmentVariableListItemRp()
                    {
                        Name  = p.Name,
                        Value = p.Value
                    }).ToList();
                    projectServiceEnvironmentList.Add(projectServiceEnvironmentListItem);
                }
                list.Items = projectServiceEnvironmentList;
            }

            return(list);
        }
        public async Task CreateProjectServiceEnvironmentVariables(Guid organizationId, Guid projectId, Guid serviceId, Guid environmentId, ProjectServiceEnvironmentVariablePostRp 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.ProjectService projectService = project.GetServiceById(serviceId);
            if (projectService == null)
            {
                await _domainManagerService.AddNotFound($"The project service with id {serviceId} does not exists.");

                return;
            }

            if (projectService.Status != DomainModels.EntityStatus.Active)
            {
                await _domainManagerService.AddConflict($"The pipe with id {serviceId} must be in status Active to add/modify variables.");

                return;
            }

            DomainModels.ProjectServiceEnvironment environment = projectService.GetServiceEnvironment(environmentId);
            if (environment == null)
            {
                await _domainManagerService.AddNotFound($"The environment with id {environmentId} does not exists.");

                return;
            }

            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);
                }
            }

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

            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
            };

            @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.Name             = parentEnvironment.Name;
                serviceEnvironment.RequiredApproval = parentEnvironment.RequiresApproval;
                serviceEnvironment.Rank             = parentEnvironment.Rank;

                serviceEnvironment.Variables = new List <ProjectEnvironmentItemVariableCreatedEvent>();
                foreach (var variable in parentEnvironment.Variables)
                {
                    serviceEnvironment.Variables.Add(new ProjectEnvironmentItemVariableCreatedEvent()
                    {
                        Name  = variable.Name,
                        Value = variable.Value
                    });
                }
                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 <ProjectServiceSummaryGetRp> GetProjectServiceSummaryById(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);
            }

            ProjectServiceSummaryGetRp serviceSummaryRp = new ProjectServiceSummaryGetRp
            {
                Name                      = service.Name,
                Description               = service.Description,
                Status                    = service.Status,
                PipeType                  = service.PipeType,
                PipelineStatus            = service.PipelineStatus,
                LastPipelineBuildStatus   = service.LastPipelineBuildStatus,
                LastPipelineReleaseStatus = service.LastPipelineReleaseStatus,
                Activities                = new ProjectServiceActivityListRp()
                {
                    Items = service.Activities.OrderBy(x => x.CreationDate).Select(x => new ProjectServiceActivityListItemRp()
                    {
                        Name           = x.Name,
                        Log            = x.Log,
                        CreationDate   = x.CreationDate,
                        ActivityStatus = x.ActivityStatus
                    }).ToList()
                },
                Events = new ProjectServiceEventListRp()
                {
                    Items = service.Events.OrderByDescending(x => x.EventDate).Take(6).Select(x => new ProjectServiceEventListItemRp()
                    {
                        EventDescription = x.EventDescription,
                        EventType        = x.EventType,
                        EventStatus      = x.EventStatus,
                        CreationDate     = x.CreationDate,
                        EventDate        = x.EventDate
                    }).ToList()
                }
            };

            return(serviceSummaryRp);
        }
        public async Task CreateProjectFeature(Guid organizationId, Guid projectId, ProjectFeaturePostRp 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 features 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;
            }

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

                return;
            }

            var preparingServices = project.GetPreparingServices();

            if (preparingServices.Any())
            {
                await _domainManagerService.AddConflict($"The project with id {projectId} has pipes in status Preparing. All services must be in status Active to create a new feature");

                return;
            }

            DomainModels.ProjectFeature existingFeature = project.GetFeatureByName(resource.Name);
            if (existingFeature != null)
            {
                await _domainManagerService.AddConflict($"The feature name {resource.Name} has already been taken.");

                return;
            }

            DomainModels.ProjectFeature newFeature = user.CreateProjectFeature(organizationId, projectId, resource.Name, resource.Description);

            //services asociated (TODO: services on demand)
            List <ProjectFeatureServiceCreatedEvent> @events = new List <ProjectFeatureServiceCreatedEvent>();

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

                    return;
                }

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

                newFeature.AddService(item, variables);

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

                @events.Add(new ProjectFeatureServiceCreatedEvent(_correlationId)
                {
                    ServiceId                  = item,
                    ServiceExternalId          = projectService.ProjectServiceExternalId,
                    ServiceExternalUrl         = projectService.ProjectServiceExternalUrl,
                    ServiceName                = projectService.Name,
                    InternalServiceName        = projectService.InternalName,
                    ServiceTemplateUrl         = serviceCredential.BranchUrl,
                    ReleaseStageId             = projectService.ReleaseStageId,
                    AgentPoolId                = project.AgentPoolId,
                    OrganizationId             = organization.OrganizationId,
                    ProjectId                  = project.ProjectId,
                    FeatureId                  = newFeature.ProjectFeatureId,
                    ProjectExternalId          = serviceCredential.ProjectExternalId,
                    ProjectExternalEndpointId  = project.ProjectExternalEndpointId,
                    ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint,
                    ProjectVSTSFakeName        = project.ProjectVSTSFakeName,
                    ProjectVSTSFakeId          = project.ProjectVSTSFakeId,
                    OrganizationName           = organization.Name,
                    ProjectName                = serviceCredential.ProjectName,
                    FeatureName                = newFeature.Name,
                    CMSType                = serviceCredential.CMSType,
                    CMSAccountId           = serviceCredential.AccountId,
                    CMSAccountName         = serviceCredential.AccountName,
                    CMSAccessId            = serviceCredential.AccessId,
                    CMSAccessSecret        = serviceCredential.AccessSecret,
                    CMSAccessToken         = serviceCredential.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),
                    TemplateAccess         = projectService.ProjectServiceTemplate.TemplateAccess,
                    IsImported             = projectService.IsImported,
                    NeedCredentials        = projectService.ProjectServiceTemplate.NeedCredentials,
                    RepositoryCMSType      = serviceCredential.CMSType,
                    RepositoryAccessId     = serviceCredential.AccessId,
                    RepositoryAccessSecret = serviceCredential.AccessSecret,
                    RepositoryAccessToken  = serviceCredential.AccessToken,
                    UserId = loggedUserId
                });
            }

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            await _domainManagerService.AddResult("FeatureId", newFeature.ProjectFeatureId);

            //send events
            foreach (var @event in @events)
            {
                await _eventBusService.Publish(queueName : "ProjectFeatureServiceCreatedEvent", @event : @event);
            }
        }
        public async Task <ProjectServiceExternalGetRp> GetProjectServiceExternalById(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);
            }

            CMSAuthCredentialModel cmsAuthCredential = null;
            var serviceExternalName = string.Empty;
            var projectExternalId   = string.Empty;

            //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.ProjectServiceExternalId;
                projectExternalId   = service.ProjectExternalId;
                break;

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

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

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

            default:
                break;
            }

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

            return(new ProjectServiceExternalGetRp {
                DefaultBranch = serviceExternal.DefaultBranch,
                GitUrl = serviceExternal.Link,
                SSHUrl = serviceExternal.SSHUrl
            });
        }