public async Task CollectDeviations() { // Arrange var applicationGroup = new ApplicationGroup { Name = "ApplicationGroup" }; var graphService = new Mock <IGraphService>(); var teamProject = new TeamProject(); graphService.Setup(s => s.GetApplicationGroups(teamProject)).ReturnsAsync(new List <ApplicationGroup>()); var target = new SecurityPattern(graphService.Object); target.ApplicationGroups.Add(applicationGroup); // Act var actual = await target.CollectDeviations(teamProject).ConfigureAwait(false); // Assert actual .Should() .SatisfyRespectively( first => { first.Should().BeOfType <ApplicationGroupDeviation>(); ((ApplicationGroupDeviation)first).ApplicationGroup.Should().Be(applicationGroup); }); await Task.CompletedTask; }
public async Task <bool> Handle(CreateProjectWithAzureSECommand request, CancellationToken cancellationToken) { TeamProject projectCreateParameters = new TeamProject() { Name = request.ProjectName, Description = request.Description, Capabilities = SetCapabilities(request.ProcessName, request.VersionControl) }; var client = _vstsClient.GetClient(); var stringContent = _vstsClient.ConvertBody(projectCreateParameters); var response = await client.PostAsync($"{request.Organization}/_apis/projects?api-version=6.0", stringContent, cancellationToken); if (response.IsSuccessStatusCode) { await CreateServiceEndpoint(request, cancellationToken); return(true); } else { //log return(false); } }
public void ShowProject(TFS tfs, TeamProject teamProject) { Tfs = tfs; TeamProject = teamProject; Title = teamProject.Name + "- TFSMonkey"; RaisePropertyChanged(nameof(Title)); SqliteConnection = new SqliteConnection("Data Source=" + System.IO.Path.Combine(appPath, $"{AppData.SanitizePath(Tfs.Url)}-{AppData.SanitizePath(TeamProject.ServerItem)}.sqlite")); Settings = Settings.LoadSettings(SqliteConnection); DataSource = new DataSource(SqliteConnection, tfs, TeamProject, Settings); Page = new Uri("/Views/CombinedPage.xaml", UriKind.Relative); RaisePropertyChanged(nameof(Page)); Task.Factory.StartNew(() => { DataSource.GetData(); new Timer(state => { DataSource.RefreshData(); }).Change(1000 * 60 * 10, 1000 * 60 * 10); }); }
public async Task <IActionResult> AssignNewProjectToTeam(long teamId, long projectId) { var oldTeamProject = await _dbContext.TeamProjects.SingleOrDefaultAsync (q => q.IsValid && q.ProjectId == projectId); var user = await _dbContext.Projects.SingleAsync(q => q.Id == projectId); user.CurrentTeamId = teamId; if (oldTeamProject != null) { oldTeamProject.IsValid = false; oldTeamProject.UnAssignDate = DateTime.Now; } var newTeamProject = new TeamProject() { IsValid = true, AssignDate = DateTime.Now, TeamId = teamId, ProjectId = projectId }; _dbContext.Add(newTeamProject); await _dbContext.SaveChangesAsync(); return(NoContent()); }
private async static Task CheckProjectPermission(WorkItemClientConnection client, string project, int requestedPermission) { Logger.LogInformation($"Checking project security permissions for {client.Connection.AuthorizedIdentity.DisplayName} in {project}"); SecurityHttpClient securityHttpClient = null; ProjectHttpClient projectHttpClient = null; TeamProject teamProject = null; try { securityHttpClient = client.Connection.GetClient <SecurityHttpClient>(); projectHttpClient = client.Connection.GetClient <ProjectHttpClient>(); teamProject = await projectHttpClient.GetProject(project); } catch (Exception e) when(e.InnerException is VssUnauthorizedException) { throw new ValidationException(client.Connection.Uri.ToString(), (VssUnauthorizedException)e.InnerException); } catch (Exception e) { throw new ValidationException("An unexpected error occurred while reading the classification nodes to validate project permissions", e); } await HasPermission(securityHttpClient, project, $"$PROJECT:vstfs:///Classification/TeamProject/{teamProject.Id}", ProjectSecurityNamespace, requestedPermission); }
public OperationReference CreateTeamProject(string name) { Dictionary <string, Dictionary <string, string> > capabilities = new Dictionary <string, Dictionary <string, string> >(); Dictionary <string, string> versionControl = new Dictionary <string, string>(); Dictionary <string, string> processTemplate = new Dictionary <string, string>(); versionControl.Add("sourceControlType", "Git"); processTemplate.Add("templateTypeId", "6b724908-ef14-45cf-84f8-768b5384da45"); capabilities.Add("versioncontrol", versionControl); capabilities.Add("processTemplate", processTemplate); TeamProject teamProject = new TeamProject() { Name = name, Description = "VanDelay Industries travel app", Capabilities = capabilities }; VssConnection connection = new VssConnection(_uri, _credentials); ProjectHttpClient projectHttpClient = connection.GetClient <ProjectHttpClient>(); var operationReferencee = projectHttpClient.QueueCreateProject(teamProject).Result; return(operationReferencee); }
public async Task <string> RunActivity( [ActivityTrigger] Project project, ILogger log) { if (project is null) { throw new ArgumentNullException(nameof(project)); } using (log.BeginProjectScope(project)) { try { using var processClient = await authenticationService .GetClientAsync <ProcessHttpClient>() .ConfigureAwait(false); var processTemplates = await processClient .GetProcessesAsync() .ConfigureAwait(false); var processCapabilities = new Dictionary <string, string>() { { TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityTemplateTypeIdAttributeName, processTemplates.Single(pt => pt.Name.Equals("Agile", StringComparison.OrdinalIgnoreCase)).Id.ToString() } }; var versionControlCapabilities = new Dictionary <string, string>() { { TeamProjectCapabilitiesConstants.VersionControlCapabilityAttributeName, SourceControlTypes.Git.ToString() } }; var projectTemplate = new TeamProject() { Name = project.Name, Description = string.Empty, Capabilities = new Dictionary <string, Dictionary <string, string> >() { { TeamProjectCapabilitiesConstants.VersionControlCapabilityName, versionControlCapabilities }, { TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityName, processCapabilities } } }; using var projectClient = await authenticationService .GetClientAsync <ProjectHttpClient>() .ConfigureAwait(false); var projectOperation = await projectClient .QueueCreateProject(projectTemplate) .ConfigureAwait(false); return(projectOperation.Id.ToString()); } catch (Exception exc) { log.LogError(exc, $"{nameof(ProjectCreateActivity)} failed: {exc.Message}"); throw exc.AsSerializable(); } } }
/// <summary> /// Initializes a new instance of <see cref="TestContext"/>. /// </summary> /// <param name="subscriptions">The set of subscription metadata describing the Git repos that are listening for changes to base images.</param> /// <param name="allSubscriptionImagePaths">Multiple sets of mappings between subscriptions and their associated image paths.</param> /// <param name="inProgressBuilds">The set of in-progress builds that should be configured.</param> /// <param name="allBuilds">The set of failed builds that should be configured.</param> public TestContext( Subscription[] subscriptions, IEnumerable <IEnumerable <SubscriptionImagePaths> > allSubscriptionImagePaths, PagedList <WebApi.Build> inProgressBuilds, PagedList <WebApi.Build> allBuilds) { this.allSubscriptionImagePaths = allSubscriptionImagePaths; this.inProgressBuilds = inProgressBuilds; this.allBuilds = allBuilds; this.subscriptionsPath = this.SerializeJsonObjectToTempFile(subscriptions); TeamProject project = new TeamProject { Id = Guid.NewGuid() }; Mock <IProjectHttpClient> projectHttpClientMock = CreateProjectHttpClientMock(project); this.buildHttpClientMock = CreateBuildHttpClientMock(project, this.inProgressBuilds, this.allBuilds); Mock <IVssConnectionFactory> connectionFactoryMock = CreateVssConnectionFactoryMock( projectHttpClientMock, this.buildHttpClientMock); _notificationServiceMock = new Mock <INotificationService>(); this.command = this.CreateCommand(connectionFactoryMock); }
/// <summary> /// Initializes variables and fetches build definitions from VSTS/TFS /// </summary> /// <param name="projectName">Project name in which the build definitions reside</param> /// <param name="vstsUrl">Url to the Team Project (VSTS) or Collection (TFS)</param> /// <param name="credentials">Credentials to use when authenticating with VSTS/TFS. Default value is VssBasicCredential, works for instance when authenticating via NTLM to TFS-server.</param> /// <param name="logAction">Trace.WriteLine is being used by default, override if wanted.</param> /// <param name="buildFailedAction">Trace.WriteLine is being used by default. Override if you want to for instance throw an Exception and abort.</param> /// <returns></returns> public async Task <IBuildQueuer> InitConfig(string projectName, string vstsUrl, VssCredentials credentials = null, Action <string> logAction = null, Action <string> buildFailedAction = null) { if (buildFailedAction != null) { _buildFailedAction = buildFailedAction; } if (logAction != null) { _logAction = logAction; } if (credentials == null) { credentials = new VssBasicCredential(); } var vstsUri = new Uri(vstsUrl); var projectHttpClient = new ProjectHttpClient(vstsUri, credentials); _buildHttpClient = new BuildHttpClient(vstsUri, credentials); _teamproject = await projectHttpClient.GetProject(projectName); _buildDefinitions = await _buildHttpClient.GetDefinitionsAsync(_teamproject.Id); _listener.Init(_buildHttpClient, _teamproject); _logAction("Configuration is initialized"); return(this); }
/// <summary> /// Update team project description /// </summary> /// <param name="project"></param> /// <returns></returns> public async Task <TeamProject> UpdateTeamProject(TeamProject project) { string response = await PatchResponse(project.Id.ToString(), new { description = project.Description }, null, MediaType.JSON_MEDIA_TYPE); JsonConvert.PopulateObject(response, project); return(project); }
public async Task GetApplicationGroups() { // Arrange var credentials = new VssBasicCredential(string.Empty, this.PAT); var url = $"https://dev.azure.com/{this.Organization}"; var connection = new VssConnection(new Uri(url), credentials); var teamProject = new TeamProject { Id = this.Antidrift, Name = "Antidrift" }; var expected = new List <string> { "Project Valid Users", "Project Administrators", "Contributors", "Build Administrators", "Readers", "Antidrift Team" }; var target = new GraphService(connection); // Act var actual = await target.GetApplicationGroups(teamProject).ConfigureAwait(false); // Assert actual.Select(a => a.Name).Should().Contain(expected); await Task.CompletedTask.ConfigureAwait(false); }
private TeamProject GetTeamProject() { VersionControlServer versionControl = (VersionControlServer)tpCollection.GetService(typeof(VersionControlServer)); TeamProject teamProject = versionControl.GetTeamProject(teamProjectName); return(teamProject); }
public List <TfsUser> Users() { List <TfsUser> lst = new List <TfsUser>(); TeamProject tp = GetTeamProject(); Identity[] appGroups = secSrv.ListApplicationGroups(tp.ArtifactUri.AbsoluteUri); foreach (Identity group in appGroups) { Identity[] groupMembers = secSrv.ReadIdentities(SearchFactor.Sid, new string[] { group.Sid }, QueryMembership.Direct); foreach (Identity member in groupMembers) { if (member.Members != null) { foreach (string memberSid in member.Members) { lst.Add(GetTfsUser(memberSid)); } } } } return(lst); }
public async Task GetMembers() { // Arrange var credentials = new VssBasicCredential(string.Empty, this.PAT); var url = $"https://dev.azure.com/{this.Organization}"; var connection = new VssConnection(new Uri(url), credentials); var applicationGroup = new ApplicationGroup { Name = "Contributors" }; var teamProject = new TeamProject { Id = new Guid("755bb057-51ac-43f6-a91a-54103f19b800"), Name = "Antidrift" }; var expected = new List <string> { "Antidrift Team" }; var target = new GraphService(connection); // Act var actual = await target.GetMembers(teamProject, applicationGroup).ConfigureAwait(false); // Assert actual.Should().Contain(expected); await Task.CompletedTask.ConfigureAwait(false); }
public ActionResult Assign(FormCollection col) { int enquiryId = Convert.ToInt32(col.GetValue("Enquiry").AttemptedValue); int projectId = Convert.ToInt32(col.GetValue("Project").AttemptedValue); int TeamType = Convert.ToInt32(col.GetValue("TeamType").AttemptedValue); string TeamTypeName = (TeamType == 1)?"Non Kenwood Team":"Kenwood Team"; string TeamName = String.Empty; if (TeamType == 1) { TeamName = col.GetValue("Non_Kenwood").AttemptedValue.ToString(); } else { TeamName = teamRepository.Find(Convert.ToInt32(col.GetValue("Team").AttemptedValue)).TeamName; } TeamProject team = new TeamProject(); team.ProjectID = projectId; team.TeamID = Convert.ToInt32(col.GetValue("Team").AttemptedValue); BusinessFlowContext context = new BusinessFlowContext(); context.TeamProjects.Add(team); context.SaveChanges(); return(RedirectToAction("TeamAssigned", team)); }
//public static TeamProject Get_TeamProject(TfsTeamProjectCollection teamProjectCollection, string teamProjectName) //{ // teamProjectCollection.CatalogNode.QueryChildren(); // TeamProject teamProject = null; // return teamProject; //} public static TeamProject Get_TeamProject( VersionControlServer vcServer, string teamProjectName) { Int64 startTicks = Log.DOMAINSERVICES("Enter", Common.LOG_APPNAME); TeamProject teamProject = default; try { teamProject = vcServer.GetTeamProject(teamProjectName); } catch (VersionControlException vce) { //throw; //teamProject = null; } catch (TimeoutException te) { throw; } catch (Exception ex) { throw; } Log.DOMAINSERVICES("Exit", Common.LOG_APPNAME, startTicks); return(teamProject); }
public string Commit(string serverItemPath, string changedContent, string commitComment) { TfsTeamProjectCollection collection = new TfsTeamProjectCollection(new Uri(ConfigHelper.Instance.FuncTestCollection)); var vcs = collection.GetService <VersionControlServer>(); TeamProject tp = vcs.GetTeamProject(ConfigHelper.Instance.FuncTestsProject); ItemSet itemSet = vcs.GetItems(tp.ServerItem, VersionSpec.Latest, RecursionType.Full, DeletedState.NonDeleted, ItemType.File); Item item = itemSet.Items.FirstOrDefault(x => x.ServerItem == serverItemPath); string localItem = _workspace.GetLocalItemForServerItem(item.ServerItem); int changesetId = _workspace.PendEdit(localItem); using (var file = File.OpenWrite(localItem)) { var changes = new UTF8Encoding(true).GetBytes(changedContent); file.Seek(0, SeekOrigin.End); file.Write(changes, 0, changes.Length); } PendingChange[] pendingChanges = _workspace.GetPendingChanges().Where(x => x.ChangeType == ChangeType.Edit).ToArray(); int changeset = _workspace.CheckIn(pendingChanges, ConfigHelper.Instance.Login, commitComment, null, null, null); Changeset latestChangeset = vcs.GetChangeset(changeset); collection.Dispose(); return(latestChangeset.ChangesetId.ToString(CultureInfo.InvariantCulture)); }
public string GetLastButOneRevision() { var collection = new TfsTeamProjectCollection(new Uri(ConfigHelper.Instance.FuncTestCollection)); var vcs = collection.GetService <VersionControlServer>(); TeamProject tp = vcs.GetTeamProject(ConfigHelper.Instance.FuncTestsProject); var changesets = vcs.QueryHistory( tp.ServerItem, VersionSpec.Latest, 0, RecursionType.Full, null, null, null, Int32.MaxValue, true, true).Cast <Changeset>().ToArray(); collection.Dispose(); if (changesets.Count() == 1) { return(changesets.First().ChangesetId.ToString()); } int lastButOneChangeset = changesets.Where(x => x.ChangesetId < changesets.Max(m => m.ChangesetId)).Max(x => x.ChangesetId); return(lastButOneChangeset.ToString(CultureInfo.InvariantCulture)); }
public async Task <bool> Handle(CreateProjectCommand request, CancellationToken cancellationToken) { TeamProject projectCreateParameters = new TeamProject() { Name = request.ProjectName, Description = request.Description, Capabilities = SetCapabilities(request.ProcessName, request.VersionControl) }; var client = _vstsClient.GetClient(); var stringContent = _vstsClient.ConvertBody(projectCreateParameters); var response = await client.PostAsync($"{request.Organization}/_apis/projects?api-version=6.0", stringContent, cancellationToken); if (response.IsSuccessStatusCode) { using var contents = await response.Content.ReadAsStreamAsync(); var responseResult = await System.Text.Json.JsonSerializer.DeserializeAsync <Response>(contents); return(true); } else { //log return(false); } }
internal static XlHlp.XlLocation Add_Info( XlHlp.XlLocation insertAt, TeamProject teamProject) { long startTicks = XlHlp.DisplayInWatchWindow(insertAt); insertAt.MarkStart(); XlHlp.AddLabeledInfo(insertAt.AddRow(2), "TP Name", teamProject.Name); XlHlp.AddLabeledInfo(insertAt.AddRow(2), "AbsoluteUri", teamProject.ArtifactUri.AbsoluteUri); XlHlp.AddLabeledInfo(insertAt.AddRow(2), "ServerItem", teamProject.ServerItem); XlHlp.AddLabeledInfo(insertAt.AddRow(2), "VCS ServerGuid", teamProject.VersionControlServer.ServerGuid.ToString()); // TODO(crhodes) // What else can we get here? // Capabilities // Template? // Creation Date? insertAt.MarkEnd(); if (!insertAt.OrientVertical) { // Skip past the info just added. insertAt.SetLocation(insertAt.RowStart, insertAt.MarkEndColumn + 1); } XlHlp.DisplayInWatchWindow(insertAt, startTicks, "End"); return(insertAt); }
public async Task <IEnumerable <string> > GetMembers(TeamProject teamProject, ApplicationGroup applicationGroup) { if (teamProject == null) { throw new ArgumentNullException(nameof(teamProject)); } if (applicationGroup == null) { throw new ArgumentNullException(nameof(applicationGroup)); } var client = this.connection.GetClient <GraphHttpClient>(); var descriptor = await client.GetDescriptorAsync(teamProject.Id).ConfigureAwait(false); var graphGroups = await client.ListGroupsAsync(descriptor.Value).ConfigureAwait(false); // TODO: Overhead var group = graphGroups.GraphGroups.FirstOrDefault(g => g.DisplayName.Equals(applicationGroup.Name, StringComparison.OrdinalIgnoreCase)); if (group == null) { throw new InvalidOperationException($"Cannot get the members fro application group {applicationGroup.Name}. the application group is not available."); } var memberships = await client.ListMembershipsAsync(group.Descriptor.ToString(), GraphTraversalDirection.Down).ConfigureAwait(false); var lookupKeys = memberships .Select(m => new GraphSubjectLookupKey(m.MemberDescriptor)) // TODO: not sure what to fill in subject type. .ToList(); var result = await client.LookupSubjectsAsync(new GraphSubjectLookup(lookupKeys)).ConfigureAwait(false); return(result.Select(l => l.Value.DisplayName).ToList()); }
private void Deploy() { TfsTeamProjectCollection collection; // if setting "Domen" in config file initialized - it means that test run on the local machine, // otherwise means that test run on the specialized testing machine if (string.IsNullOrEmpty(ConfigHelper.Instance.Domen)) { collection = new TfsTeamProjectCollection(new Uri(ConfigHelper.Instance.TestCollection)); } else { collection = new TfsTeamProjectCollection( new Uri(ConfigHelper.Instance.TestCollection), new NetworkCredential(ConfigHelper.Instance.Login, ConfigHelper.Instance.Password, ConfigHelper.Instance.Domen)); } var vcs = collection.GetService <VersionControlServer>(); TeamProject tp = vcs.GetTeamProject(ConfigHelper.Instance.TestCollectionProject); const string workspaceName = "MyWorkspace"; Workspace[] workspaces = vcs.QueryWorkspaces(workspaceName, vcs.AuthorizedUser, Workstation.Current.Name); foreach (var workspace in workspaces) { foreach (var workingFolder in workspace.Folders) { if (Directory.Exists(workingFolder.LocalItem)) { var files = Directory.GetFiles(workingFolder.LocalItem, "*.*", SearchOption.AllDirectories); foreach (var file in files) { File.SetAttributes(file, File.GetAttributes(file) & ~FileAttributes.ReadOnly); } Directory.Delete(workingFolder.LocalItem, true); } workspace.DeleteMapping(workingFolder); } vcs.DeleteWorkspace(workspace.Name, vcs.AuthorizedUser); } string projectPath = tp.ServerItem; string workingDirectory = ClonedRepoFolder; Directory.CreateDirectory(workingDirectory); _workspace = vcs.CreateWorkspace(workspaceName, vcs.AuthorizedUser, "Test Workspace"); try { _workspace.Map(projectPath, workingDirectory); GetRequest request = new GetRequest(new ItemSpec(projectPath, RecursionType.Full), VersionSpec.Latest); GetStatus status = _workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite); } catch { throw; } }
public void Expand() { var graphService = new Mock <IGraphService>(); var applicationGroup = new ApplicationGroup { Name = "[{teamProject.Name}]\\Project Administrators" }; var pattern = new SecurityPattern(graphService.Object) { Name = "Test" }; pattern.ApplicationGroups.Add(applicationGroup); var teamProject = new TeamProject { Name = "Test", Key = "1" }; teamProject.Patterns.Add(new SecurityPattern(graphService.Object) { Name = "Test" }); var target = new Organization(); target.Mappings.Add("1", Guid.NewGuid()); target.Patterns.Add(pattern); target.TeamProjects.Add(teamProject); target.Expand(); ((SecurityPattern)teamProject.Patterns[0]).ApplicationGroups[0].Name.Should().Be("[Test]\\Project Administrators"); }
public async Task CollectDeviations() { // Arrange var pattern1 = new Mock <Pattern>(); var pattern2 = new Mock <Pattern>(); var deviation1 = new Deviation(); var deviation2 = new Deviation(); var target = new TeamProject(); target.Patterns.Add(pattern1.Object); target.Patterns.Add(pattern2.Object); pattern1.Setup(t => t.CollectDeviations(target)).ReturnsAsync(new List <Deviation> { deviation1 }); pattern2.Setup(t => t.CollectDeviations(target)).ReturnsAsync(new List <Deviation> { deviation2 }); // Act var actual = await target.CollectDeviations().ConfigureAwait(false); // Assert pattern1.VerifyAll(); pattern2.VerifyAll(); actual.Should() .Contain(deviation1) .And .Contain(deviation2); await Task.CompletedTask.ConfigureAwait(false); }
public async Task <IActionResult> Edit(int id, [Bind("ID,Project,Team")] TeamProject teamProject) { if (!User.IsInRole(Constants.ROLE_ADMIN)) { return(NotFound()); } if (id != teamProject.ID) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(teamProject); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!TeamProjectExists(teamProject.ID)) { return(NotFound()); } else { throw; } } return(RedirectToAction("Index")); } return(View(teamProject)); }
public TeamProjectReference GetTeamProjectWithCapabilities(string name) { VssConnection connection = new VssConnection(_uri, _credentials); ProjectHttpClient projectHttpClient = connection.GetClient <ProjectHttpClient>(); TeamProject project = projectHttpClient.GetProject(name, true).Result; return(project); }
private Guid GetCollectionIdFromProject(TeamProject project) { var url = ((ReferenceLink)project.Links.Links["web"]).Href; var collectionIdAsString = url.Split("/").Last(); var collectionId = Guid.Parse(collectionIdAsString); return(collectionId); }
public UsersLocator(IGroupSecurityService groupSecurityService, VersionControlServer versionControlServer, TeamProject teamProject, IGroupsLocator groupsLocator) { m_groupSecurityService = groupSecurityService; m_versionControlServer = versionControlServer; m_teamProject = teamProject; m_groupsLocator = groupsLocator; }
/// <summary> /// returns info object with both server url and last usage set to i /// </summary> /// <param name="i"></param> /// <returns></returns> private ConnectionInfo GetConnectionInfo(int i, bool hasProject = false) { TeamProject project = hasProject ? GetProject(i) : null; ConnectionInfo info = new ConnectionInfo(new Uri($"http://fake.fake/{i}"), project, null); info.SetLastUsage(BaseDateTime.AddTicks(i)); return(info); }
/// <summary> /// Gets all teams for the given <paramref name="project"/>. /// </summary> /// <param name="client">The <see cref="TeamHttpClient"/> to use.</param> /// <param name="project">The project.</param> /// <param name="pageSize">Page size to use while retrieving the projects.</param> /// <param name="userState">The user state object.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static Task<IList<WebApiTeam>> GetAllTeams(this TeamHttpClient client, TeamProject project, int pageSize = 10, object userState = null, CancellationToken cancellationToken = default(CancellationToken)) { if (client == null) throw new ArgumentNullException(nameof(client)); if (project == null) throw new ArgumentNullException(nameof(project)); return client.GetAllTeams(project.Id, pageSize, userState, cancellationToken); }
private static Mock <IProjectHttpClient> CreateProjectHttpClientMock(TeamProject project) { Mock <IProjectHttpClient> projectHttpClientMock = new Mock <IProjectHttpClient>(); projectHttpClientMock .Setup(o => o.GetProjectAsync(It.IsAny <string>())) .ReturnsAsync(project); return(projectHttpClientMock); }
internal ChangesetViewModel(TeamProject project, Changeset changeset, IChangeInfo info) { this.Project = project; if (changeset == null) throw new ArgumentNullException("changeset"); this.Info = info; this.Changeset = changeset; }
public JsonTeamProject(TeamProject model) { id = model.Id; name = model.Name; isDefault = model.IsDefault; environments = model.MergeEnvironments != null?model.MergeEnvironments.Select(m => new JsonMergeEnvironment(m)) : null; activities = model.Activities != null?model.Activities.Select(m => new JsonActivity(m)) : null; }
public OneWorkItemPolicyForm(OneWorkItemPolicyConfig config, TeamProject teamProject) : this() { Config = config; rdoExactly.Checked = config.ExactlyOne; rdoAtLeast.Checked = !config.ExactlyOne; InitWorkItemTypes(teamProject); rdoAtLeast.CheckedChanged += rdoAtLeast_CheckedChanged; rdoExactly.CheckedChanged += rdoExactly_CheckedChanged; }
private void InitWorkItemTypes(TeamProject teamProject) { var store = teamProject.TeamProjectCollection.GetService<WorkItemStore>(); cmbTypes.Items.Clear(); foreach(WorkItemType wit in store.Projects[teamProject.Name].WorkItemTypes) { cmbTypes.Items.Add(wit.Name); } cmbTypes.SelectedItem = Config.WorkItemType; if (cmbTypes.SelectedIndex == -1) { cmbTypes.SelectedIndex = 0; } }
private void AnalyzeTfsTeamProject(TeamProject teamProject, bool verbose) { List<PackageDependency> teamProjectDependencies = new List<PackageDependency>(); string repositorySearchQuery = string.Format("$/{0}/*{1}", teamProject.Name, repositoriesConfigFileName); ItemSet repositories = teamProject.VersionControlServer.GetItems(repositorySearchQuery, RecursionType.Full); foreach (Item repository in repositories.Items) { IEnumerable<PackageDependency> repositoryDependencies = GetPackageDependenciesFromRepositoriesConfig(teamProject, repository); foreach (PackageDependency packageDependency in repositoryDependencies) { if (teamProjectDependencies.Where(dp => dp.Id == packageDependency.Id && dp.VersionSpec == packageDependency.VersionSpec).FirstOrDefault() == null) teamProjectDependencies.Add(packageDependency); } } ConsolePrinter.PrintPackageDependenciesForProject(teamProjectDependencies, verbose); }
public Changeset GetLatestCheckin(TeamProject project) { var list = project.VersionControlServer.QueryHistory( project.ServerItem, VersionSpec.Latest, 0, RecursionType.Full, null, new ChangesetVersionSpec(1), VersionSpec.Latest, 1, true, false); Changeset result = list.OfType<Changeset>().FirstOrDefault(); return result; }
public IUsersLocator New(IGroupSecurityService groupSecurityService, VersionControlServer versionControlServer, TeamProject teamProject, IGroupsLocator groupsLocator) { return new UsersLocator(groupSecurityService, versionControlServer, teamProject, groupsLocator); }
/// <summary> /// Update team project description /// </summary> /// <param name="project"></param> /// <returns></returns> public async Task<TeamProject> UpdateTeamProject(TeamProject project) { string response = await PatchResponse(project.Id.ToString(), new { description = project.Description }, null, JSON_MEDIA_TYPE); JsonConvert.PopulateObject(response, project); return project; }
/// <summary> /// Retrieves the queued builds for a specific build definition in the specified project /// </summary> /// <param name="oneProject">project we are interested in</param> /// <param name="definitionName">the build definition we are looking at to check for queued, null means no matching on name</param> /// <returns>an array of queued builds that match the parameters criterea</returns> public IQueuedBuild[] GetQueuedBuilds(TeamProject oneProject, string definitionName) { IQueuedBuildSpec qbs; if (definitionName != null) { qbs = this.Connection.BuildServer.CreateBuildQueueSpec(oneProject.Name, definitionName); } else { qbs = this.Connection.BuildServer.CreateBuildQueueSpec(oneProject.Name); } IQueuedBuildQueryResult foundQueuedBuilds = this.Connection.BuildServer.QueryQueuedBuilds(qbs); IQueuedBuild[] extractedQueuedBuilds = foundQueuedBuilds.QueuedBuilds; return extractedQueuedBuilds; }
/// <summary> /// Rets the last two builds for all build definitions matching the passe din parameters /// </summary> /// <param name="teamProject">the team project to uery against</param> /// <param name="buildDefinitionPattern">optional build definition pattern</param> /// <returns>build result pairs</returns> public TfsLastTwoBuildResults[] GetLastTwoBuilds(TeamProject teamProject, string buildDefinitionPattern) { log.Debug("Finding build results for definition pattern " + buildDefinitionPattern); IBuildDetailSpec buildDetailsQuerySpec; if (buildDefinitionPattern != null) { buildDetailsQuerySpec = this.Connection.BuildServer.CreateBuildDetailSpec(teamProject.Name, buildDefinitionPattern); } else { buildDetailsQuerySpec = this.Connection.BuildServer.CreateBuildDetailSpec(teamProject.Name); } //// Failure to set this property results in ALL of the build information being retrieved resulting in 10X+ call times //// You can retrieve subsets with something like //// buildDetailsQuerySpec.InformationTypes = new string[] { "ActivityTracking", "AgentScopeActivityTracking" }; buildDetailsQuerySpec.InformationTypes = null; //// last and previous buildDetailsQuerySpec.MaxBuildsPerDefinition = 2; //// use start time descending because InProgress builds don't seem to sort correctly when using EndTimeDescending buildDetailsQuerySpec.QueryOrder = BuildQueryOrder.StartTimeDescending; IBuildQueryResult buildResults = this.Connection.BuildServer.QueryBuilds(buildDetailsQuerySpec); IDictionary<string, TfsLastTwoBuildResults> results = new SortedDictionary<string, TfsLastTwoBuildResults>(); //// create placeholder result objects, one for each build, that we will fill with results foreach (IBuildDetail oneDetail in buildResults.Builds) { if (!results.ContainsKey(oneDetail.BuildDefinition.Name)) { results.Add(oneDetail.BuildDefinition.Name, new TfsLastTwoBuildResults(oneDetail.BuildDefinition, null, null)); } } //// now fill the results. //// The builds are in reverse start time order so the last build shold always be first putting it in the last build slot foreach (IBuildDetail oneDetail in buildResults.Builds) { TfsLastTwoBuildResults corresponding = results[oneDetail.BuildDefinition.Name]; //// sorted by start time descending so latest should always come first if (corresponding.LastBuild == null) { corresponding.LastBuild = oneDetail; } else { corresponding.PreviousBuild = oneDetail; } } if (log.IsDebugEnabled) { foreach (string key in results.Keys) { TfsLastTwoBuildResults oneResult = results[key]; log.Debug(" " + oneResult.BuildDefinition.Name); log.Debug(" " + oneResult.LastBuild.BuildNumber + " " + oneResult.LastBuild.Status); if (oneResult.PreviousBuild != null) { log.Debug(" " + oneResult.PreviousBuild.BuildNumber + " " + oneResult.PreviousBuild.Status); } } } //// convert the dictionary to an array TfsLastTwoBuildResults[] resultsAsArray = new TfsLastTwoBuildResults[results.Values.Count]; results.Values.CopyTo(resultsAsArray, 0); return resultsAsArray; }
/// <summary> /// gets all the definitions for the specified project that match the definition name /// </summary> /// <param name="oneProject">the project we are searching</param> /// <param name="definitionName">wildcards supported</param> /// <returns>list of build definitions</returns> public IBuildDefinition[] GetBuildDefinitions(TeamProject oneProject, string definitionName) { IBuildDefinitionSpec spec; if (definitionName != null) { spec = this.Connection.BuildServer.CreateBuildDefinitionSpec(oneProject.Name, definitionName); } else { spec = this.Connection.BuildServer.CreateBuildDefinitionSpec(oneProject.Name); } IBuildDefinitionQueryResult buildDefQueryRsult = this.Connection.BuildServer.QueryBuildDefinitions(spec); return buildDefQueryRsult.Definitions; }
private void GetBuildResults(TeamProject teamProject, IBuildServer buildServer, IEnumerable<IBuildDefinition> buildDefinitions) { Parallel.ForEach(buildDefinitions, buildDefinition => { IBuildDetailSpec buildDetailSpec = buildServer.CreateBuildDetailSpec(teamProject.Name, buildDefinition.Name); buildDetailSpec.MaxBuildsPerDefinition = 5; buildDetailSpec.QueryOrder = BuildQueryOrder.FinishTimeDescending; var buildResult = buildServer.QueryBuilds(buildDetailSpec); try { Application.Current.Dispatcher.BeginInvoke(new Action(() => BuildResults.Add(buildResult))); } catch (NullReferenceException) { } }); }
protected List<String> GetPeopleInAProject(TeamProject teamProject) { TfsTeamProjectCollection collection = teamProject.TeamProjectCollection; List<String> people = new List<string>(); var gss = collection.GetService<IGroupSecurityService>(); Identity SIDS = gss.ReadIdentity(SearchFactor.EveryoneApplicationGroup, null, QueryMembership.Direct); Identity[] GroupIds = gss.ReadIdentities(SearchFactor.Sid, SIDS.Members, QueryMembership.None); var Groups = GroupIds.Where(u => u.Domain == teamProject.ArtifactUri.ToString()).ToArray(); foreach (var Group in Groups) { Identity SubSIDS = gss.ReadIdentity(SearchFactor.Sid, Group.Sid, QueryMembership.Expanded); if (SubSIDS.Members.Length == 0) { continue; } Identity[] MemberIds = gss.ReadIdentities(SearchFactor.Sid, SubSIDS.Members, QueryMembership.None); var Members = MemberIds.Where(u => !u.SecurityGroup).ToArray(); foreach (var member in Members) { people.Add(member.Sid); } } return people.Distinct().ToList(); }
public TfsTeamProject(TeamProject teamProject, ITreeViewItemViewModel parent) : base(teamProject.Name, parent, true) { m_teamProject = teamProject; ImageNormal = @"..\Icons\16\SourcesA.png"; ImageMaster = @"..\Icons\16\SourcesCA.png"; }
/// <summary> /// Gets all team members for the given <paramref name="project" /> and <paramref name="team" />. /// </summary> /// <param name="client">The <see cref="TeamHttpClient" /> to use.</param> /// <param name="connection">The connection for the <paramref name="client" /> that will be used to retrieve the identities for the team members.</param> /// <param name="project">The project.</param> /// <param name="team">The team.</param> /// <param name="pageSize">Page size to use while retrieving the projects.</param> /// <param name="userState">The user state object.</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> /// <exception cref="System.ArgumentNullException"> /// </exception> public static Task<IReadOnlyCollection<Identity>> GetAllTeamMembers(this TeamHttpClient client, VssConnection connection, TeamProject project, WebApiTeam team, int pageSize = 10, object userState = null, CancellationToken cancellationToken = default(CancellationToken)) { if (client == null) throw new ArgumentNullException(nameof(client)); if (connection == null) throw new ArgumentNullException(nameof(connection)); if (project == null) throw new ArgumentNullException(nameof(project)); if (team == null) throw new ArgumentNullException(nameof(team)); return client.GetAllTeamMembers(connection, project.Id, team.Id, pageSize, userState, cancellationToken); }
private IEnumerable<PackageDependency> GetPackageDependenciesFromRepositoriesConfig(TeamProject teamProject, Item repository) { List<PackageDependency> repositoryDependencies = new List<PackageDependency>(); Stream repoFileStream = repository.DownloadFile(); XDocument repoXml = XDocument.Load(repoFileStream); IEnumerable<string> relativePackageConfigPaths = configInterpreter.GetRelativePackagesConfigPathsFromRepositoriesConfig(repoXml); string repositoriesConfigServerPath = repository.ServerItem; int repositoriesConfigLength = repositoriesConfigFileName.Length; string packageConfigFolderServerPath = repositoriesConfigServerPath.Remove(repositoriesConfigServerPath.Length - repositoriesConfigLength, repositoriesConfigLength); foreach (string packageConfigPathRelativeToRepositoriesConfig in relativePackageConfigPaths) { // navigate to the folder server path for the repositories.config file string repositoryNodeServerItem = tfsServerPathTranslator.GetServerPath(packageConfigFolderServerPath, packageConfigPathRelativeToRepositoriesConfig); Item packageConfig = teamProject.VersionControlServer.GetItem(repositoryNodeServerItem); if (packageConfig != null) { Stream packagesConfigStream = packageConfig.DownloadFile(); XDocument packagesConfigXml = XDocument.Load(packagesConfigStream); IEnumerable<PackageDependency> packageDependencies = configInterpreter.GetPackageDependenciesFromPackagesConfig(packagesConfigXml); foreach (PackageDependency packageDependency in packageDependencies) { if (repositoryDependencies.Where(dp => dp.Id == packageDependency.Id && dp.VersionSpec == packageDependency.VersionSpec).FirstOrDefault() == null) repositoryDependencies.Add(packageDependency); } } } return repositoryDependencies; }