public async Task <CMSProjectCreateResultModel> CreateProject(CMSAuthCredentialModel authCredential, CMSProjectCreateModel model) { //default data var vstsmodel = new CMSVSTSProjectCreateModel(); vstsmodel.Name = model.Name; vstsmodel.Description = model.Description; vstsmodel.Visibility = model.ProjectVisibility == Domain.Models.ProjectVisibility.Private ? "private" : "public"; vstsmodel.Capabilities = new CMSVSTSProjectCapabilityModel(); vstsmodel.Capabilities.VersionControl = new CMSVSTSProjectVersionControlModel(); vstsmodel.Capabilities.VersionControl.SourceControlType = "Git"; vstsmodel.Capabilities.ProcessTemplate = new CMSVSTSProjectProcessTemplateModel(); vstsmodel.Capabilities.ProcessTemplate.TemplateTypeId = "adcc42ab-9882-485e-a3ed-7678f01f66bc"; CMSProjectCreateResultModel result = new CMSProjectCreateResultModel(); var response = await _httpProxyService.PostAsync($"/_apis/projects?api-version={_vstsOptions.Value.ApiVersion}", vstsmodel, authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } return(result); }
public async Task <CMSProjectCreateResultModel> CreateProject(CMSAuthCredentialModel authCredential, CMSProjectCreateModel model) { CMSProjectCreateResultModel result = new CMSProjectCreateResultModel(); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authCredential.AccessToken); client.BaseAddress = new Uri(authCredential.Url); var teamResult = await GetAccountTeams(client, authCredential); var defaultTeam = teamResult.Teams.FirstOrDefault(c => c.TeamId.Equals(model.TeamId)); var projectKey = model.Name.Replace(" ", "").ToLower(); var bitbucketModel = new { name = model.Name, key = projectKey, description = model.Description, is_private = model.ProjectVisibility == Domain.Models.ProjectVisibility.Public ? true : false }; var response = await client.PostAsync($"/{API_VERSION}/teams/{defaultTeam.UserName}/projects/", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(bitbucketModel), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var projectCreated = await response.MapTo <CMSBitBucketProjectModel>(); result.ProjectExternalId = projectKey; return(result); }
public ProjectCloudCredentialModel ProjectCredentialResolver(OrganizationCMS organizationCMS, Project project) { var accountId = organizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(organizationCMS.AccountId) : this._fakeAccountOptions.Value.AccountId; var accountName = organizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(organizationCMS.AccountName) : _fakeAccountOptions.Value.AccountId; var accessSecret = organizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(organizationCMS.AccessSecret) : _fakeAccountOptions.Value.AccessSecret; var accountProjectId = organizationCMS.Type == ConfigurationManagementService.VSTS ? project.Name : project.ProjectVSTSFakeName; var projectName = organizationCMS.Type == ConfigurationManagementService.VSTS ? project.Name : project.ProjectVSTSFakeName; var projectExternalId = organizationCMS.Type == ConfigurationManagementService.VSTS ? project.ProjectExternalId : project.ProjectVSTSFakeId; var accessToken = organizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(organizationCMS.AccessToken) : this._fakeAccountOptions.Value.AccessSecret; var accessId = organizationCMS.Type == ConfigurationManagementService.VSTS ? _dataProtectorService.Unprotect(organizationCMS.AccessId) : this._fakeAccountOptions.Value.AccessId; var cmsType = organizationCMS.Type == ConfigurationManagementService.VSTS ? organizationCMS.Type : ConfigurationManagementService.VSTS; CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(cmsType).GetToken(accountId, accountName, accessSecret, accessToken); return(new ProjectCloudCredentialModel { AccessId = accessId, AccountId = accountId, AccessToken = accessToken, AccountName = accountName, AccessSecret = accessSecret, AccountProjectId = accountProjectId, ProjectExternalId = projectExternalId, ProjectName = projectName, CMSType = cmsType, CMSAuthCredential = cmsAuthCredential }); }
public async Task <CMSAgentPoolListModel> GetAgentPools(CMSAuthCredentialModel authCredential) { CMSAgentPoolListModel result = new CMSAgentPoolListModel(); var response = await _httpProxyService.GetAsync($"/_apis/distributedtask/pools", authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var agentoPoolResult = await response.MapTo <CMSAgentPoolListModel>(); result.Items = agentoPoolResult.Items.Where(x => x.Size > 0).Select(x => new CMSAgentPoolListItemModel() { Id = x.Id, Name = x.Name, IsHosted = x.IsHosted }).ToList(); return(result); }
public async Task <ProjectServiceTemplateDefinitionGetRp> GetProjectServiceTemplateDefinition(Guid projectServiceTemplateId) { var serviceTemplate = await this._projectServiceTemplateRepository.FindFirst(c => c.ProjectServiceTemplateId.Equals(projectServiceTemplateId)); //Auth CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(ConfigurationManagementService.VSTS).GetToken( this._vstsOptions.Value.AccountId, this._vstsOptions.Value.AccessId, this._vstsOptions.Value.AccessSecret, this._vstsOptions.Value.AccessSecret); var templateSplit = serviceTemplate.Url.Split('/'); var repository = templateSplit[templateSplit.Length - 1]; var templateName = $"{serviceTemplate.Path}"; var templateBuildDefinition = await this._templateService.GetTemplateBuildDefinition(repository, templateName, "build.definition.yml", cmsAuthCredential); var templateInfraDefinition = await this._templateService.GetTemplateInfraDefinition(repository, templateName, serviceTemplate.ServiceCPSType == CloudProviderService.AWS? "infra.definition.yml" : "infra.definition.json", cmsAuthCredential); return(new ProjectServiceTemplateDefinitionGetRp { ProjectServiceTemplateId = serviceTemplate.ProjectServiceTemplateId, Name = serviceTemplate.Name, Description = serviceTemplate.Description, Framework = serviceTemplate.Framework, ProgrammingLanguageName = serviceTemplate.Framework, BuildDefinition = templateBuildDefinition.Content, InfraDefinition = templateInfraDefinition.Content }); }
private async Task <CMSAccountListModel> GetAccounts(CMSAuthCredentialModel authCredential) { var list = new CMSAccountListModel() { Items = new List <CMSAccountListItemModel>() }; var response = await _httpProxyService.GetAsync($"/user", authCredential, Headers); var user = await response.MapTo <CMSGitHubUserModel>(); list.Items.Add(new CMSAccountListItemModel { AccountId = user.AccountId, Name = user.UserName, Description = user.UserName, IsOrganization = false, }); response = await _httpProxyService.GetAsync($"/user/orgs", authCredential, Headers); var teamResult = await response.MapTo <List <CMSGitHubTeamModel> >(); list.Items.AddRange(teamResult.Select(c => new CMSAccountListItemModel { AccountId = c.TeamId, Description = c.DisplayName, Name = c.DisplayName, IsOrganization = true })); return(list); }
public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model) { var vstsmodel = new CMSVSTSServiceCreateModel(); vstsmodel.Name = model.Name; vstsmodel.Project = new CMSVSTSServiceProjectCreateModel(); vstsmodel.Project.Id = model.ProjectExternalId; CMSServiceCreateResultModel result = new CMSServiceCreateResultModel(); var response = await _httpProxyService.PostAsync($"{model.ProjectExternalId}/_apis/git/repositories?api-version={_vstsOptions.Value.ApiVersion}", vstsmodel, authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var responseModel = await response.MapTo <CMSVSTSServiceCreateResultModel>(); result.ServiceExternalId = responseModel.Id; result.ServiceExternalUrl = responseModel.RemoteUrl; return(result); }
public async Task <CMSProjectListModel> GetProjects(string accountId, CMSAuthCredentialModel authCredential) { CMSProjectListModel result = new CMSProjectListModel(); var response = await _httpProxyService.GetAsync($"/_apis/projects?api-version=5.0", authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var projectListResult = await response.MapTo <CMSProjectListModel>(); result.Items = projectListResult.Items.Select(x => new CMSProjectListItemModel() { Id = x.Id, Name = x.Name }).ToList(); return(result); }
public async Task <CMSProjectListModel> GetProjects(string accountId, CMSAuthCredentialModel authCredential) { var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authCredential.AccessToken); client.BaseAddress = new Uri(authCredential.Url); var response = await client.GetAsync($"/{API_VERSION}/teams?role=admin"); var teamResult = await response.MapTo <CMSBitBucketTeamListModel>(); CMSProjectListModel list = new CMSProjectListModel(); var projectList = new List <CMSProjectListItemModel>(); foreach (var item in teamResult.Teams) { response = await client.GetAsync($"/{API_VERSION}/teams/{item.UserName}/projects/"); var projectResult = await response.MapTo <CMSBitBucketProjectListModel>(); foreach (var project in projectResult.Projects) { projectList.Add(new CMSProjectListItemModel { Id = project.Key, DisplayName = $@"{item.DisplayName}\{project.Name}", Name = project.Name }); } } list.Items = projectList.ToList(); return(list); }
public async Task <CMSPipelineAgentQueueResultModel> GetQueue(CMSPipelineAgentQueueParamModel @options) { string accountUrl = $"https://{@options.VSTSAccountName}.visualstudio.com"; CMSAuthCredentialModel authCredentials = new CMSAuthCredentialModel(); authCredentials.Type = "Basic"; authCredentials.AccessToken = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", @options.VSTSAccessSecret))); authCredentials.Url = accountUrl; string queueUrl = $"/{@options.VSTSAccountProjectId}/_apis/distributedtask/queues"; var queueResponse = await _httpProxyService.GetAsync(queueUrl, authCredentials); queueResponse.EnsureSuccessStatusCode(); var queues = await queueResponse.MapTo <CMSPipelineQueueListModel>(); var defaultQueue = queues.Items.FirstOrDefault(x => x.Pool.Id == int.Parse(@options.AgentPoolId)); if (defaultQueue == null) { throw new Exception($"Agent Pool with id {@options.AgentPoolId} was not found"); } return(new CMSPipelineAgentQueueResultModel() { QueueId = defaultQueue.Id, QueueName = defaultQueue.Name, PoolId = defaultQueue.Pool.Id, PoolName = defaultQueue.Pool.Name }); }
public async Task <CMSRepositoryListModel> GetRepositories(string projectId, CMSAuthCredentialModel authCredential) { CMSRepositoryListModel result = new CMSRepositoryListModel(); string repositoryUrl = $"{authCredential.Url}/{projectId}/_apis/git/repositories?api-version=4.1&api-version={_vstsOptions.Value.ApiVersion}"; var response = await _httpProxyService.GetAsync(repositoryUrl, authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var serviceResult = await response.MapTo <CMSVSTSRepositoryListModel>(); result.Items = serviceResult.Items.Select(c => new CMSRepositoryListItemModel { AccountId = authCredential.AccountId, Name = c.Name, Link = c.RemoteUrl, Description = c.Name, ServiceId = c.Id }).ToList(); return(result); }
public async Task <CMSAgentPoolListModel> GetAgentPools(CMSAuthCredentialModel authCredential) { authCredential.Url = $"https://{_fakeAccountServiceOptions.Value.AccountId}.visualstudio.com"; authCredential.Type = "Basic"; authCredential.AccessToken = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", _fakeAccountServiceOptions.Value.AccessSecret))); CMSAgentPoolListModel result = new CMSAgentPoolListModel(); var response = await _httpProxyService.GetAsync($"/_apis/distributedtask/pools", authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var agentoPoolResult = await response.MapTo <CMSAgentPoolListModel>(); result.Items = agentoPoolResult.Items.Where(x => x.Size > 0).Select(x => new CMSAgentPoolListItemModel() { Id = x.Id, Name = x.Name }).ToList(); return(result); }
public async Task <CMSRepositoryListModel> GetRepositories(string projectId, CMSAuthCredentialModel authCredential) { var accountList = await GetAccounts(authCredential); var defaultTeam = accountList.Items.FirstOrDefault(c => c.AccountId.Equals(authCredential.AccountId)); var urlRepo = ""; if (defaultTeam != null && defaultTeam.IsOrganization) { urlRepo = $"/orgs/{defaultTeam.Name}/repos"; } else { urlRepo = $"/user/repos"; } var response = await _httpProxyService.GetAsync(urlRepo, authCredential, Headers); var serviceResult = await response.MapTo <List <CMSGitHubRepositoryModel> >(); var model = new CMSRepositoryListModel(); model.Items = serviceResult.Select(c => new CMSRepositoryListItemModel { ServiceId = c.Name, Name = c.FullName, Description = c.FullName, Link = c.CloneUrl }).ToList(); return(model); }
public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model) { CMSServiceCreateResultModel result = new CMSServiceCreateResultModel(); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authCredential.AccessToken); client.BaseAddress = new Uri(authCredential.Url); var teamResult = await GetAccountTeams(client, authCredential); var defaultTeam = teamResult.Teams.FirstOrDefault(c => c.TeamId.Equals(model.TeamId)); var response = await client.GetAsync($"/{API_VERSION}/teams/{defaultTeam.UserName}/projects/"); var projectResult = await response.MapTo <CMSBitBucketProjectListModel>(); var defaultProject = projectResult.Projects.FirstOrDefault(c => c.Key.Equals(model.ProjectExternalId)); var bitbucketModel = new { scm = "git", is_private = true, name = model.Name, description = model.Name, project = new { key = defaultProject.Key } }; var repositoryKey = model.Name.ToLower().Replace(" ", ""); response = await client.PostAsync($"/{API_VERSION}/repositories/{defaultTeam.UserName}/{repositoryKey}", new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(bitbucketModel), Encoding.UTF8, "application/json")); if (!response.IsSuccessStatusCode) { result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var serviceCreated = await response.MapTo <CMSBitBucketRepositoryModel>(); result.ServiceExternalId = repositoryKey; result.ServiceExternalUrl = serviceCreated.Links.Clone.FirstOrDefault(c => c.Name.Equals("https", StringComparison.OrdinalIgnoreCase)).Href; return(result); }
public async Task CompleteApproval(CMSPipelineApprovalParamModel @options) { string accountUrl = $"https://{@options.VSTSAccountName}.vsrm.visualstudio.com"; CMSAuthCredentialModel authCredentials = new CMSAuthCredentialModel(); authCredentials.Type = "Basic"; authCredentials.AccessToken = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", @options.VSTSAccessSecret))); authCredentials.Url = accountUrl; string completeApprovalUrl = $"/{@options.VSTSAccountProjectId}/_apis/release/approvals/{@options.ApprovalId}?api-version={@options.VSTSAPIVersion}"; var completeApproval = PipelineApprovalModel.Create(@options.Status, @options.Comments); var completeApprovalResponse = await _httpProxyService.PatchAsync(completeApprovalUrl, completeApproval, authCredentials); completeApprovalResponse.EnsureSuccessStatusCode(); }
public async Task CreateRelease(CMSPipelineReleaseParamModel @options) { string accountUrl = $"https://{@options.VSTSAccountName}.vsrm.visualstudio.com"; CMSAuthCredentialModel authCredentials = new CMSAuthCredentialModel(); authCredentials.Type = "Basic"; authCredentials.AccessToken = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", @options.VSTSAccessSecret))); authCredentials.Url = accountUrl; string queueReleaseUrl = $"/{@options.VSTSAccountProjectId}/_apis/release/releases?api-version={@options.VSTSAPIVersion}"; var queueRelease = PipelineReleaseModel.Create(@options.ReleaseDefinitionId, @options.Alias, @options.VersionId, @options.VersionName, options.Description); var queueReleaseResponse = await _httpProxyService.PostAsync(queueReleaseUrl, queueRelease, authCredentials); queueReleaseResponse.EnsureSuccessStatusCode(); }
public async Task CreateBuild(CMSPipelineBuildParamModel @options) { string accountUrl = $"https://{@options.VSTSAccountName}.visualstudio.com"; CMSAuthCredentialModel authCredentials = new CMSAuthCredentialModel(); authCredentials.Type = "Basic"; authCredentials.AccessToken = Convert.ToBase64String(ASCIIEncoding.ASCII.GetBytes(string.Format("{0}:{1}", "", @options.VSTSAccessSecret))); authCredentials.Url = accountUrl; string queueBuildUrl = $"/{@options.VSTSAccountProjectId}/_apis/build/builds?api-version={@options.VSTSAPIVersion}"; var queueBuild = PipelineBuildModel.Create(@options.QueueId, @options.BuildDefinitionId, @options.ProjectExternalId, @options.SourceBranch); var queueBuildResponse = await _httpProxyService.PostAsync(queueBuildUrl, queueBuild, authCredentials); queueBuildResponse.EnsureSuccessStatusCode(); }
public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model) { CMSServiceCreateResultModel result = new CMSServiceCreateResultModel(); var accountList = await GetAccounts(authCredential); var defaultTeam = accountList.Items.FirstOrDefault(c => c.AccountId.Equals(authCredential.AccountId)); var gitHubModel = new { name = GetServiceName(model.ProjectName, model.Name), description = model.ProjectName, Private = model.IsPublic ? false : true, has_issues = true, has_projects = true, has_wiki = true }; var urlRepo = ""; if (defaultTeam != null && defaultTeam.IsOrganization) { urlRepo = $"/orgs/{defaultTeam.Name}/repos"; } else { urlRepo = $"/user/repos"; } var response = await _httpProxyService.PostAsync(urlRepo, gitHubModel, authCredential, Headers); if (!response.IsSuccessStatusCode) { result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var serviceCreated = await response.MapTo <CMSGitHubRepositoryModel>(); result.ServiceExternalId = serviceCreated.Id; result.ServiceExternalUrl = serviceCreated.CloneUrl; return(result); }
public async Task CreateVSTSFakeProject(Guid organizationId, Guid projectId) { var project = await _projectRepository.GetProjectWithOrgAndAccountOwnerByProjectId(organizationId, projectId); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } var cmsType = ConfigurationManagementService.VSTS; var projectName = this._slugService.GetSlug($"{project.Organization.Owner.Email} {project.Organization.Name} {project.Name}"); var resource = new { Name = projectName, Description = project.Description }; CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(cmsType).GetToken(_vstsFakeOptions.Value.AccountId, _vstsFakeOptions.Value.AccountId, _vstsFakeOptions.Value.AccessSecret); CMSProjectAvailabilityResultModel cmsProjectAvailability = await _cmsService(cmsType).ValidateProjectAvailability(cmsAuthCredential, string.Empty, resource.Name); if (!cmsProjectAvailability.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsProjectAvailability.GetReasonForNoSuccess()}"); return; } CMSProjectCreateModel projectCreateModel = CMSProjectCreateModel.Factory.Create(project.Organization.Name, resource.Name, resource.Description, ProjectVisibility.Private); CMSProjectCreateResultModel cmsProjectCreate = await _cmsService(cmsType).CreateProject(cmsAuthCredential, projectCreateModel); if (!cmsProjectCreate.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsProjectCreate.GetReasonForNoSuccess()}"); return; } project.SetFakeVSTSProject(projectName); this._projectRepository.Update(project); await this._projectRepository.SaveChanges(); }
public async Task <CMSProjectCreateResultModel> CreateProject(CMSAuthCredentialModel authCredential, CMSProjectCreateModel model) { CMSProjectCreateResultModel result = new CMSProjectCreateResultModel(); var dic = new Dictionary <string, string>(); dic.Add("Accept", "application/vnd.github.inertia-preview+json"); dic.Add("User-Agent", API_UserAgent); var accountList = await GetAccounts(authCredential); var defaultTeam = accountList.Items.FirstOrDefault(c => c.AccountId.Equals(authCredential.AccountId)); var gitHubModel = new { name = model.Name, body = model.Description, }; if (defaultTeam.IsOrganization) { //var response = await _httpProxyService.PostAsync($"/orgs/{defaultTeam.Name}/projects", gitHubModel, authCredential, dic); //if (!response.IsSuccessStatusCode) //{ // result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); // return result; //} // //var projectCreated = await response.MapTo<CMSGitHubProjectModel>(); // //result.ProjectExternalId = projectCreated.Id; result.ProjectExternalId = $"{Guid.NewGuid()}"; } else { result.ProjectExternalId = $"{Guid.NewGuid()}"; } return(result); }
public async Task <CMSAccountListModel> GetAccounts(CMSAuthCredentialModel authCredential) { var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", authCredential.AccessToken); client.BaseAddress = new Uri(authCredential.Url); var response = await client.GetAsync($"/{API_VERSION}/teams?role=admin"); var teamResult = await response.MapTo <CMSBitBucketTeamListModel>(); CMSAccountListModel list = new CMSAccountListModel(); list.Items = teamResult.Teams.Select(c => new CMSAccountListItemModel { AccountId = c.TeamId, Description = c.DisplayName, Name = c.UserName }).ToList(); return(list); }
public async Task <CMSServiceCreateResultModel> CreateService(CMSAuthCredentialModel authCredential, CMSServiceCreateModel model) { CMSServiceCreateResultModel result = new CMSServiceCreateResultModel(); var httpClient = new HttpClient(); var gitLabModel = new { name = model.Name, description = model.ProjectName, namespace_id = model.ProjectExternalId, issues_enabled = true, merge_requests_enabled = true, ci_config_path = "scripts/build.definition.yml" }; var request = new HttpRequestMessage(HttpMethod.Post, $"{authCredential.Url}/projects"); request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(gitLabModel), Encoding.UTF8, "application/json"); request.Headers.Add("Private-Token", authCredential.AccessToken); var response = await httpClient.SendAsync(request); if (!response.IsSuccessStatusCode) { result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var serviceCreated = await response.MapTo <CMSGitLabProjectModel>(); result.ServiceExternalId = serviceCreated.Id.ToString(); result.ServiceExternalUrl = serviceCreated.CloneUrl; return(result); }
public async Task <CMSProjectCreateResultModel> CreateProject(CMSAuthCredentialModel authCredential, CMSProjectCreateModel model) { CMSProjectCreateResultModel result = new CMSProjectCreateResultModel(); var httpClient = new HttpClient(); var organizationKey = model.OrganizationName.Replace(" ", "").ToLower(); var projectKey = model.Name.Replace(" ", "").ToLower(); var gitLabModel = new { name = model.Name, path = $"{organizationKey}-{projectKey}", description = model.Description, visibility = model.ProjectVisibility == Domain.Models.ProjectVisibility.Private ? "private" : "public", }; var request = new HttpRequestMessage(HttpMethod.Post, $"{authCredential.Url}/groups"); request.Content = new StringContent(Newtonsoft.Json.JsonConvert.SerializeObject(gitLabModel), Encoding.UTF8, "application/json"); request.Headers.Add("Private-Token", authCredential.AccessToken); var response = await httpClient.SendAsync(request); if (!response.IsSuccessStatusCode) { result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var projectCreated = await response.MapTo <CMSGitLabProjectModel>(); result.ProjectExternalId = projectCreated.Id.ToString(); return(result); }
public async Task <CMSRepositoryListModel> GetRepositories(string projectId, CMSAuthCredentialModel authCredential) { var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, $"{authCredential.Url}/projects/{projectId}"); request.Headers.Add("Private-Token", authCredential.AccessToken); var response = await httpClient.SendAsync(request); var serviceResult = await response.MapTo <List <CMSGitLabRepositoryModel> >(); var model = new CMSRepositoryListModel(); model.Items = serviceResult.Select(c => new CMSRepositoryListItemModel { ServiceId = c.Name, Name = c.FullName, Description = c.FullName, Link = c.CloneUrl }).ToList(); return(model); }
public async Task <CMSServiceAvailabilityResultModel> ValidateServiceAvailability(CMSAuthCredentialModel authCredential, string teamId, string projectExternalId, string projectName, string name) { CMSServiceAvailabilityResultModel result = new CMSServiceAvailabilityResultModel(); var response = await _httpProxyService.GetAsync($"{projectExternalId}/_apis/git/repositories?api-version={_vstsOptions.Value.ApiVersion}", authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var serviceResult = await response.MapTo <CMSVSTSServiceListModel>(); var existsService = serviceResult.Items.Any(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (existsService) { result.Fail($"The service {name} has already been taken in the VSTS service (Repository)"); } return(result); }
public async Task <CMSProjectAvailabilityResultModel> ValidateProjectAvailability(CMSAuthCredentialModel authCredential, string organization, string name) { CMSProjectAvailabilityResultModel result = new CMSProjectAvailabilityResultModel(); var response = await _httpProxyService.GetAsync($"/_apis/projects?api-version={_vstsOptions.Value.ApiVersion}", authCredential); if (!response.IsSuccessStatusCode || response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { if (response.StatusCode == System.Net.HttpStatusCode.NonAuthoritativeInformation) { result.Fail($"Code: {response.StatusCode}, Reason: The credentials are not correct"); return(result); } result.Fail($"Code: {response.StatusCode}, Reason: {await response.Content.ReadAsStringAsync()}"); return(result); } var projectResult = await response.MapTo <CMSVSTSProjectListModel>(); var existsProject = projectResult.Items.Any(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (existsProject) { result.Fail($"The project {name} has already been taken in the CMS service"); } return(result); }
public async Task <CMSProjectAvailabilityResultModel> ValidateProjectAvailability(CMSAuthCredentialModel authCredential, string organization, string name) { CMSProjectAvailabilityResultModel result = new CMSProjectAvailabilityResultModel(); var dic = new Dictionary <string, string>(); dic.Add("Accept", "application/vnd.github.inertia-preview+json"); dic.Add("User-Agent", API_UserAgent); var accountList = await GetAccounts(authCredential); var defaultTeam = accountList.Items.FirstOrDefault(c => c.AccountId.Equals(authCredential.AccountId)); if (defaultTeam.IsOrganization) { var response = await _httpProxyService.GetAsync($"/orgs/{defaultTeam.Name}/projects", authCredential, dic); var projectResult = await response.MapTo <List <CMSGitHubProjectModel> >(); var existsProject = projectResult.Any(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (existsProject) { result.Fail($"The project {name} has already been taken in the CMS service"); } } return(result); }
public async Task CreateProjectService(Guid organizationId, Guid projectId, ProjectServicePostRp resource, string userId = null) { string loggedUserId = userId ?? _identityService.GetUserId(); User user = await _userRepository.GetUser(loggedUserId); DomainModels.ProjectServiceTemplate projectServiceTemplate = await _projectServiceTemplateRepository.GetProjectServiceTemplateById(resource.ProjectServiceTemplateId); if (projectServiceTemplate == null) { await _domainManagerService.AddConflict($"The pipe template with id {resource.ProjectServiceTemplateId} does not exists."); return; } DomainModels.Organization organization = user.FindOrganizationById(organizationId); if (organization == null) { await _domainManagerService.AddNotFound($"The organzation with id {organizationId} does not exists."); return; } DomainModels.Project project = user.FindProjectById(projectId, false); if (project == null) { await _domainManagerService.AddNotFound($"The project with id {projectId} does not exists."); return; } if (project.Status != EntityStatus.Active) { await _domainManagerService.AddConflict($"The project with id {projectId} must be in status Active to add a new service."); return; } DomainModels.ProjectService existingService = project.GetServiceByName(resource.Name); if (existingService != null) { await _domainManagerService.AddConflict($"The pipe name {resource.Name} has already been taken."); return; } CMSAuthCredentialModel cmsAuthCredential = this._cmsCredentialService(project.OrganizationCMS.Type).GetToken( _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken)); CMSServiceAvailabilityResultModel cmsServiceAvailability = await _cmsService(project.OrganizationCMS.Type).ValidateServiceAvailability(cmsAuthCredential, project.OrganizationExternalId, project.ProjectExternalId, project.Name, resource.RepositoryName); if (!cmsServiceAvailability.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceAvailability.GetReasonForNoSuccess()}"); return; } DomainModels.ProjectService newService = user.CreateProjectService(organizationId, projectId, project.OrganizationCMSId, resource.AgentPoolId, resource.Name, resource.RepositoryName, resource.Description, resource.ProjectServiceTemplateId, projectServiceTemplate.PipeType); //SaveChanges in CMS CMSServiceCreateModel serviceCreateModel = CMSServiceCreateModel.Factory.Create(project.OrganizationExternalId, project.ProjectExternalId, project.Name, resource.RepositoryName, project.ProjectVisibility == ProjectVisibility.Public ? true : false); CMSServiceCreateResultModel cmsServiceCreate = await _cmsService(project.OrganizationCMS.Type).CreateService(cmsAuthCredential, serviceCreateModel); if (!cmsServiceCreate.Success) { await _domainManagerService.AddConflict($"The CMS data is not valid. {cmsServiceCreate.GetReasonForNoSuccess()}"); return; } newService.UpdateExternalInformation(cmsServiceCreate.ServiceExternalId, cmsServiceCreate.ServiceExternalUrl, resource.Name); newService.AddEnvironmentsAndVariables(projectServiceTemplate.Parameters); _userRepository.Update(user); await _userRepository.SaveChanges(); await _domainManagerService.AddResult("ServiceId", newService.ProjectServiceId); if (project.OrganizationCPS == null) { project.OrganizationCPS = new OrganizationCPS { Type = CloudProviderService.None } } ; var @event = new ProjectServiceCreatedEvent(_correlationId) { OrganizationId = organization.OrganizationId, OrganizationName = organization.Name, ProjectId = project.ProjectId, ServiceId = newService.ProjectServiceId, ProjectExternalId = project.ProjectExternalId, ProjectExternalEndpointId = project.ProjectExternalEndpointId, ProjectExternalGitEndpoint = project.ProjectExternalGitEndpoint, ProjectVSTSFakeId = project.ProjectVSTSFakeId, ProjectVSTSFakeName = project.ProjectVSTSFakeName, ProjectName = project.Name, InternalProjectName = project.InternalName, AgentPoolId = newService.AgentPoolId, ServiceExternalId = newService.ProjectServiceExternalId, ServiceExternalUrl = newService.ProjectServiceExternalUrl, ServiceName = resource.Name, InternalServiceName = newService.InternalName, ServiceTemplateUrl = projectServiceTemplate.Url, CMSType = project.OrganizationCMS.Type, CMSAccountId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountId), CMSAccountName = _dataProtectorService.Unprotect(project.OrganizationCMS.AccountName), CMSAccessId = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessId), CMSAccessSecret = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessSecret), CMSAccessToken = _dataProtectorService.Unprotect(project.OrganizationCMS.AccessToken), UserId = loggedUserId, TemplateParameters = projectServiceTemplate.Parameters.Select(x => new ProjectServiceTemplateParameterCreatedEvent() { VariableName = x.VariableName, Value = x.Value, Scope = x.Scope }).ToList(), CPSType = project.OrganizationCPS.Type, CPSAccessId = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessId), CPSAccessName = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessName), CPSAccessSecret = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessSecret), CPSAccessRegion = project.OrganizationCPS.Type == CloudProviderService.None ? string.Empty : _dataProtectorService.Unprotect(project.OrganizationCPS.AccessRegion), TemplateAccess = projectServiceTemplate.TemplateAccess, NeedCredentials = projectServiceTemplate.NeedCredentials, RepositoryCMSType = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.Credential.CMSType : ConfigurationManagementService.VSTS, RepositoryAccessId = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessId) : string.Empty : string.Empty, RepositoryAccessSecret = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessSecret) : string.Empty : string.Empty, RepositoryAccessToken = projectServiceTemplate.TemplateAccess == DomainModels.Enums.TemplateAccess.Organization ? projectServiceTemplate.NeedCredentials ? _dataProtectorService.Unprotect(projectServiceTemplate.Credential.AccessToken) : string.Empty : string.Empty }; //Cloud Provider Data await _eventBusService.Publish(queueName : "ProjectServiceCreatedEvent", @event : @event); }
public async Task <CMSProjectAvailabilityResultModel> ValidateProjectAvailability(CMSAuthCredentialModel authCredential, string organization, string name) { CMSProjectAvailabilityResultModel result = new CMSProjectAvailabilityResultModel(); var httpClient = new HttpClient(); var request = new HttpRequestMessage(HttpMethod.Get, $"{authCredential.Url}/groups?owned=true"); request.Headers.Add("Private-Token", authCredential.AccessToken); var response = await httpClient.SendAsync(request); var data = response.Content.ReadAsStringAsync().Result; var projectResult = await response.MapTo <List <CMSGitLabTeamModel> >(); var existsProject = projectResult.Any(x => x.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)); if (existsProject) { result.Fail($"The project {name} has already been taken in the {authCredential.Provider} service"); } return(result); }
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 }); }