public void CompleteProjectFeature(Guid organizationId, Guid projectId, Guid featureId)
        {
            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");
            }

            ProjectFeature feature = project.GetFeatureById(featureId);

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

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

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

            CPSAuthCredentialModel authCredentials = new CPSAuthCredentialModel();

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

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

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

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

            ProjectFeatureServiceDeliveryListRp list = new ProjectFeatureServiceDeliveryListRp();

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

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

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

            ProjectFeatureAllServiceListRp list = new ProjectFeatureAllServiceListRp();

            var projectServices = project.GetServices();

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

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

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

                list.Items.Add(item);
            }

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

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

            ProjectFeatureServiceActivityListRp list = new ProjectFeatureServiceActivityListRp();

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

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

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

            ProjectFeatureServiceListRp list = new ProjectFeatureServiceListRp();

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

            return(list);
        }
Example #7
0
        public async Task CreateProjectFeatureServiceEvent(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId, ProjectFeatureServiceEventPostRp 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.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return;
            }

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

                return;
            }

            featureService.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();
        }
Example #8
0
        public async Task <ProjectFeatureGetRp> GetProjectFeatureById(Guid organizationId, Guid projectId, Guid featureId)
        {
            string loggedUserId = _identityService.GetUserId();

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

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

                return(null);
            }

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

                return(null);
            }

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

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

            return(featureRp);
        }
        public async Task DeleteProjectFeatureService(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

            var services = feature.GetServices();

            if (services.Count == 1)
            {
                await _domainManagerService.AddConflict($"The project feature with id {featureId} must have at least one pipe, anycase you could delete the feature instead.");

                return;
            }

            feature.DeleteService(serviceId, loggedUserId);

            _userRepository.Update(user);

            await _userRepository.SaveChanges();

            var @event = new ProjectFeatureServiceDeletedEvent(_correlationId)
            {
                OrganizationId            = organization.OrganizationId,
                OrganizationName          = organization.Name,
                ProjectId                 = project.ProjectId,
                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),
                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),
                CPSAccessAppId                        = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppId),
                CPSAccessAppSecret                    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessAppSecret),
                CPSAccessDirectory                    = _dataProtectorService.Unprotect(project.OrganizationCPS.AccessDirectory),
                ServiceId                             = featureService.ProjectServiceId,
                ServiceExternalId                     = featureService.ProjectService.ProjectServiceExternalId,
                ServiceExternalUrl                    = featureService.ProjectService.ProjectServiceExternalUrl,
                ServiceName                           = featureService.ProjectService.Name,
                ServiceTemplateUrl                    = featureService.ProjectService.ProjectServiceTemplate.Url,
                CommitStageId                         = featureService.CommitStageId,
                ReleaseStageId                        = featureService.ReleaseStageId,
                CommitServiceHookId                   = featureService.CommitServiceHookId,
                ReleaseServiceHookId                  = featureService.ReleaseServiceHookId,
                CodeServiceHookId                     = featureService.CodeServiceHookId,
                ReleaseStartedServiceHookId           = featureService.ReleaseStartedServiceHookId,
                ReleasePendingApprovalServiceHookId   = featureService.ReleasePendingApprovalServiceHookId,
                ReleaseCompletedApprovalServiceHookId = featureService.ReleaseCompletedApprovalServiceHookId
            };

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

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

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

            return(featureServiceSummaryRp);
        }
Example #11
0
        public async Task CreateProjectFeatureServiceEnvironmentVariables(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId, Guid environmentId, ProjectFeatureServiceEnvironmentVariablePostRp 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.ProjectFeature projectFeature = project.GetFeatureById(featureId);
            if (projectFeature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return;
            }

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

                return;
            }

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

                return;
            }

            DomainModels.ProjectFeatureServiceEnvironment environment = projectFeatureService.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 ProjectFeatureEnvironmentCreatedEvent(_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   = projectFeatureService.ReleaseStageId.Value
            };

            @event.Environments = new List <ProjectFeatureEnvironmentItemCreatedEvent>();
            foreach (var item in projectFeatureService.Environments)
            {
                var parentEnvironment = projectFeature.GetEnvironments().First(x => x.ProjectFeatureEnvironmentId == item.ProjectFeatureEnvironmentId);

                var featureServiceEnvironment = new ProjectFeatureEnvironmentItemCreatedEvent();
                featureServiceEnvironment.Name             = parentEnvironment.Name;
                featureServiceEnvironment.RequiredApproval = parentEnvironment.RequiresApproval;
                featureServiceEnvironment.Rank             = parentEnvironment.Rank;

                featureServiceEnvironment.Variables = new List <ProjectFeatureEnvironmentItemVariableCreatedEvent>();
                foreach (var variable in parentEnvironment.Variables)
                {
                    featureServiceEnvironment.Variables.Add(new ProjectFeatureEnvironmentItemVariableCreatedEvent()
                    {
                        Name  = variable.Name,
                        Value = variable.Value
                    });
                }
                foreach (var variable in item.Variables)
                {
                    featureServiceEnvironment.Variables.Add(new ProjectFeatureEnvironmentItemVariableCreatedEvent()
                    {
                        Name  = variable.Name,
                        Value = variable.Value
                    });
                }
                @event.Environments.Add(featureServiceEnvironment);
            }

            //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 : "ProjectFeatureEnvironmentCreatedEvent", @event : @event);
        }
        public async Task <ProjectFeatureServiceExternalGetRp> GetProjectFeatureServiceExternalById(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

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

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

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

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

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

            default:
                break;
            }

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

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

            return(new ProjectFeatureServiceExternalGetRp
            {
                DefaultBranch = feature.Name,
                GitUrl = serviceExternal.Link,
                SSHUrl = serviceExternal.SSHUrl
            });
        }
Example #13
0
        public async Task <ProjectFeatureServiceEventListRp> GetProjectFeatureServiceEvents(Guid organizationId, Guid projectId, Guid featureId, 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.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return(null);
            }

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

                return(null);
            }

            ProjectFeatureServiceEventListRp list = new ProjectFeatureServiceEventListRp();

            if (featureService.Events != null)
            {
                if (baseEventType == BaseEventType.None)
                {
                    list.Items = featureService.Events.Select(x => new ProjectFeatureServiceEventListItemRp
                    {
                        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 = featureService.Events.Where(x => x.BaseEventType == baseEventType).Select(x => new ProjectFeatureServiceEventListItemRp
                    {
                        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 <ProjectFeatureServicePipelineGetRp> GetProjectFeatureServicePipelineById(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

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

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

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

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

            return(featureServicePipelineRp);
        }
        public async Task 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 CreateReleaseProjectFeatureService(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

            User user = await _userRepository.GetUser(loggedUserId);

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

            CMSPipelineReleaseParamModel releaseBuildOptions = new CMSPipelineReleaseParamModel();

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

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

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

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

            User user = await _userRepository.GetUser(loggedUserId);

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

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

                return;
            }

            var serviceCredential = this._cloudCredentialService.ProjectFeatureServiceCredentialResolver(project, featureService);

            CMSPipelineAgentQueueParamModel getQueueOptions = new CMSPipelineAgentQueueParamModel();

            getQueueOptions.CMSType              = serviceCredential.CMSType;
            getQueueOptions.VSTSAPIVersion       = _vstsOptions.Value.ApiVersion;
            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 = featureService.CommitStageId.Value;
            queueBuildOptions.SourceBranch      = project.OrganizationCMS.Type == ConfigurationManagementService.VSTS ? $"refs/heads/{feature.Name.ToLower()}" : feature.Name.ToLower();

            await _cmsPipelineService.CreateBuild(queueBuildOptions);

            var @event = new ProjectFeatureServiceBuildQueuedEvent(_correlationId)
            {
                OrganizationId = organization.OrganizationId,
                ProjectId      = project.ProjectId,
                FeatureId      = feature.ProjectFeatureId,
                ServiceId      = featureService.ProjectServiceId
            };

            await _eventBusService.Publish(queueName : "ProjectFeatureServiceBuildQueuedEvent", @event : @event);
        }
        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 <ProjectFeatureServiceEnvironmentListRp> GetFeatureProjectServiceEnvironments(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId)
        {
            string loggedUserId = _identityService.GetUserId();

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

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

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

                return(null);
            }

            ProjectFeatureServiceEnvironmentListRp list = new ProjectFeatureServiceEnvironmentListRp();

            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 (projectFeatureService.Environments != null)
            {
                List <ProjectFeatureServiceEnvironmentListItemRp> projectFeatureServiceEnvironmentList = new List <ProjectFeatureServiceEnvironmentListItemRp>();
                var environments = projectFeatureService.Environments.OrderBy(x => x.ProjectFeatureEnvironment.Rank);
                foreach (var item in environments)
                {
                    var projectServiceEnvironmentListItem = new ProjectFeatureServiceEnvironmentListItemRp();
                    projectServiceEnvironmentListItem.ProjectFeatureServiceEnvironmentId = item.ProjectFeatureServiceEnvironmentId;
                    projectServiceEnvironmentListItem.Name    = item.ProjectFeatureEnvironment.Name;
                    projectServiceEnvironmentListItem.Status  = item.Status;
                    projectServiceEnvironmentListItem.Summary = await _cpsQueryService(project.OrganizationCPS.Type).GetEnvironmentSummary(organization.Name, project.Name, projectFeatureService.ProjectService.Name, item.ProjectFeatureEnvironment.Name, projectFeature.Name, authCredentials);

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

            return(list);
        }
        public async Task CreateProjectFeatureServiceEvent(Guid organizationId, Guid projectId, Guid featureId, Guid serviceId, ProjectFeatureServiceEventPostRp 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.ProjectFeature feature = project.GetFeatureById(featureId);
            if (feature == null)
            {
                await _domainManagerService.AddNotFound($"The project feature with id {featureId} does not exists.");

                return;
            }

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

                return;
            }

            /*PIPELINE STATUS###########################################################################################################*/
            /*##########################################################################################################################*/
            //update pipeline status when build
            string        eventStatus   = string.Empty;
            DateTime      eventDate     = DateTime.UtcNow;
            BaseEventType baseEventType = BaseEventType.Build;

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

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

                    featureService.LastBuildEventDate = eventDate;
                }
            }

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

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

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

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

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

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

                    featureService.LastBuildEventDate = eventDate;
                }

                //Delivery
                featureService.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 = featureService.Environments.FirstOrDefault(x => x.ProjectFeatureEnvironment.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 > featureService.LasReleaseEventDate)
                {
                    featureService.PipelineStatus            = PipelineStatus.Deploying;
                    featureService.LastPipelineReleaseStatus = PipelineReleaseStatus.Deploying;

                    featureService.LasReleaseEventDate = eventDate;
                }

                //Delivery
                featureService.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 = featureService.Environments.FirstOrDefault(x => x.ProjectFeatureEnvironment.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 > featureService.LasReleaseEventDate)
                {
                    featureService.PipelineStatus            = PipelineStatus.DeployPendingApproval;
                    featureService.LastPipelineReleaseStatus = PipelineReleaseStatus.DeployPendingApproval;

                    featureService.LasReleaseEventDate = eventDate;
                }

                //Delivery
                featureService.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.CreatedOn;
                baseEventType = BaseEventType.Release;

                var environment = featureService.Environments.FirstOrDefault(x => x.ProjectFeatureEnvironment.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 > featureService.LasReleaseEventDate)
                {
                    featureService.PipelineStatus            = releaseApprovalModel.Approval.Status.Equals("rejected", StringComparison.InvariantCultureIgnoreCase) ? PipelineStatus.DeployRejectedApproval : PipelineStatus.DeployAcceptedApproval;
                    featureService.LastPipelineReleaseStatus = releaseApprovalModel.Approval.Status.Equals("rejected", StringComparison.InvariantCultureIgnoreCase) ? PipelineReleaseStatus.DeployRejectedApproval : PipelineReleaseStatus.DeployAcceptedApproval;

                    featureService.LasReleaseEventDate = eventDate;
                }

                //Delivery
                featureService.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 = featureService.Environments.FirstOrDefault(x => x.ProjectFeatureEnvironment.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 > featureService.LasReleaseEventDate)
                {
                    if (releaseModel.Environment.Status.Equals("Succeeded", StringComparison.InvariantCultureIgnoreCase))
                    {
                        featureService.PipelineStatus            = PipelineStatus.DeploySucceeded;
                        featureService.LastPipelineReleaseStatus = PipelineReleaseStatus.DeploySucceeded;
                    }

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

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

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

                    featureService.LasReleaseEventDate = eventDate;
                }

                //Delivery
                featureService.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)) &&
                featureService.Status == EntityStatus.Preparing)
            {
                featureService.Status = EntityStatus.Active;
            }

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

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

            //check if any feature service is in preparing status yet
            var preparingServices = feature.GetPreparingServices();

            if (!preparingServices.Any())
            {
                feature.Status = EntityStatus.Active;
            }

            _organizationRepository.Update(organization);

            await _organizationRepository.SaveChanges();
        }