Ejemplo n.º 1
0
    static void Main(string[] args)
    {
        string ur = "https://xxxxxxx/";
        TfsTeamProjectCollection ttpc = new TfsTeamProjectCollection(new Uri(ur));
        //Get build information
        BuildHttpClient bhc         = ttpc.GetClient <BuildHttpClient>();
        string          projectname = "Project";
        int             buildId     = 1;
        Build           bui         = bhc.GetBuildAsync(projectname, buildId).Result;
        //Get test run for the build
        TestManagementHttpClient ithc = ttpc.GetClient <TestManagementHttpClient>();

        Console.WriteLine(bui.BuildNumber);

        QueryModel qm = new QueryModel("Select * From TestRun Where BuildNumber Contains '" + bui.BuildNumber + "'");

        List <TestRun> testruns = ithc.GetTestRunsByQueryAsync(qm, projectname).Result;

        foreach (TestRun testrun in testruns)
        {
            List <TestCaseResult> testresults = ithc.GetTestResultsAsync(projectname, testrun.Id).Result;
            foreach (TestCaseResult tcr in testresults)
            {
                Console.WriteLine(tcr.TestCase.Name);
                Console.WriteLine(tcr.Outcome);
            }

            Console.ReadLine();
        }
        Console.ReadLine();
    }
Ejemplo n.º 2
0
        public virtual List <TeamCapacity> GetCapacity(DateTime start, DateTime end)
        {
            var searcher = new CapacitySearcher(Project, _itemStore, _managementService, _teamService,
                                                Project.GetClient <WorkHttpClient>());

            return(searcher.SearchCapacities(Name, start, end));
        }
Ejemplo n.º 3
0
        private async Task <IList <ComponentActivityInfo> > GetWorkItemTrackingActivityAsync(ApplicationTask task, TfsTeamProjectCollection tfs, TeamProjectInfo teamProject, int numberOfActivities, IList <string> userExclusions)
        {
            var activities = new List <ComponentActivityInfo>();
            var client     = tfs.GetClient <WorkItemTrackingHttpClient>();

            // First execute the query to get the work item id's.
            var queryBuilder = new StringBuilder();

            queryBuilder.Append("SELECT [System.Id] FROM WorkItems WHERE [System.TeamProject] = @project");
            foreach (var userExclusion in userExclusions)
            {
                queryBuilder.AppendFormat(" AND [System.ChangedBy] NOT CONTAINS '{0}'", userExclusion.Replace("'", "''"));
            }
            queryBuilder.Append(" ORDER BY [System.ChangedDate] DESC");
            var queryResult = await client.QueryByWiqlAsync(new Wiql { Query = queryBuilder.ToString() }, teamProject.Name, top : numberOfActivities);

            var ids = queryResult.WorkItems.Select(w => w.Id).ToArray();

            // Then get the details for the returned work item id's.
            if (ids.Any() && !task.IsCanceled)
            {
                var workItems = await client.GetWorkItemsAsync(ids, new[] { "System.Id", "System.Title", "System.ChangedDate", "System.ChangedBy", "System.WorkItemType" }, queryResult.AsOf);

                foreach (var workItem in ids.Select(id => workItems.Single(w => w.Id == id)))
                {
                    var time        = (DateTime)workItem.Fields["System.ChangedDate"];
                    var user        = (string)workItem.Fields["System.ChangedBy"];
                    var description = string.Format(CultureInfo.CurrentCulture, "{0} {1}: {2}", workItem.Fields["System.WorkItemType"], workItem.Id, workItem.Fields["System.Title"]);
                    activities.Add(new ComponentActivityInfo("Work Item Tracking", time, user, description));
                }
            }
            return(activities);
        }
Ejemplo n.º 4
0
        public void TestBuild()
        {
            var tfs =
                new TfsTeamProjectCollection(new Uri("https://msk-tfs1.securitycode.ru/tfs/Endpoint%20Security"));

            var client      = tfs.GetClient <BuildHttpClient>();
            var buildServer = tfs.GetService <IBuildServer>();
            var store       = tfs.GetService <WorkItemStore>();
            var teamService = tfs.GetService <TfsTeamService>();

            var project = store.Projects["SNES"];

            var observer = new BuildSearcher(client, project.Guid);

            var a = observer.FindCompletedBuilds(DateTime.Now.AddHours(-15), DateTime.Now, actor: tfs.AuthorizedIdentity.DisplayName);
            //var r = observer.FindBuilds(DateTime.Now.AddHours(-5), DateTime.Now);

            // var teams = teamService.QueryTeams(project.Uri.ToString()).ToList();

            //foreach (Project i in store.Projects)
            //{
            //    var result = observer.FindQueuedBuilds(i.Name);
            //}


            // observer.FindBuilds(finish: DateTime.Now);
        }
Ejemplo n.º 5
0
        public Initializer(string sourceBranch, string destBranch)
        {
            Console.WriteLine($"Auto Merging tool start on {DateTime.Now:MM-dd-yyyy-HH-mm-ss}");
            Console.WriteLine($"Source branch: {sourceBranch}, Target Branch: {destBranch}");

            string password = GetPassword(settings.VsoSecretName).Result;

            ProjectCollection = new TfsTeamProjectCollection(
                new Uri(settings.VSTSUrl),
                new VssBasicCredential(settings.UserName, password));

            try
            {
                ProjectCollection.Authenticate();
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Could not authenticate with {settings.VSTSUrl}");
                Console.WriteLine(ex);
            }

            var gitClient = ProjectCollection.GetClient <GitHttpClient>();

            MergeTool = new VstsMergeTool(gitClient, sourceBranch, destBranch);
        }
        public VstsConnectionFacade(VstsContext context)
        {
            _context = context;
            var uri = _context.CollectionUri;

            _connection = context.AccessToken == null
                ? new TfsTeamProjectCollection(uri)
                : new TfsTeamProjectCollection(uri, new VssBasicCredential(string.Empty, context.AccessToken));

            _httpClient                 = GetHttpClient();
            _projectHttpClient          = _connection.GetClient <ProjectHttpClient>();
            _workItemTrackingHttpClient = _connection.GetClient <WorkItemTrackingHttpClient>();
            _gitHttpClient              = _connection.GetClient <GitHttpClient>();
            _buildHttpClient            = _connection.GetClient <BuildHttpClient>();
            _processHttpClient          = _connection.GetClient <ProcessHttpClient>();
            _identityService            = _connection.GetService <IIdentityManagementService>();
            _securityService            = _connection.GetService <ISecurityService>();
        }
Ejemplo n.º 7
0
        static public void GetChangesetWorkItemFromLabel(string tfsCollectionUrl, string personalAccessToken)
        {
            Console.WriteLine("Loading Labels Items and associated work items ... ");

            VssBasicCredential credentials = new VssBasicCredential(string.Empty, personalAccessToken);

            using (TfsTeamProjectCollection tpc = new TfsTeamProjectCollection(new Uri(tfsCollectionUrl), credentials))
            {
                // Can retrieve SOAP service from TfsTeamProjectCollection instance
                //VersionControlServer vcServer = tpc.GetService<VersionControlServer>();
                //ItemSet itemSet = vcServer.GetItems("$/", RecursionType.OneLevel);
                //foreach (Item item in itemSet.Items)
                //{
                //    Console.WriteLine(item.ServerItem);
                //}

                // Can retrieve REST client from same TfsTeamProjectCollection instance
                TfvcHttpClient tfvcClient = tpc.GetClient <TfvcHttpClient>();
                //List<TfvcItem> tfvcItems = tfvcClient.GetItemsAsync("$/", VersionControlRecursionType.OneLevel).Result;
                //foreach (TfvcItem item in tfvcItems)
                //{
                //    Console.WriteLine(item.Path);
                //}

                TfvcLabelRequestData tfvcLabelRequestData = new TfvcLabelRequestData();

                List <TfvcLabelRef> labelRefs = tfvcClient.GetLabelsAsync(tfvcLabelRequestData).Result;

                foreach (TfvcLabelRef item in labelRefs)
                {
                    Console.WriteLine("Label Id: " + item.Id + "\tName: " + item.Name + "\t Modified:" + item.ModifiedDate);
                    TfvcLabel       tfvcLabel  = tfvcClient.GetLabelAsync(item.Id.ToString(), tfvcLabelRequestData).Result;
                    List <TfvcItem> labelItems = tfvcClient.GetLabelItemsAsync(item.Id.ToString()).Result;
                    foreach (TfvcItem vcItem in labelItems)
                    {
                        Console.WriteLine("\tItem:" + vcItem.Path + "\t ChangesetVersion: " + vcItem.ChangesetVersion);

                        List <AssociatedWorkItem> changesetWorkItems = tfvcClient.GetChangesetWorkItemsAsync(vcItem.ChangesetVersion).Result;
                        foreach (AssociatedWorkItem assItem in changesetWorkItems)
                        {
                            Console.WriteLine("\t\t Associated WorkItem Id: " + assItem.Id + "\t Title: " + assItem.Title);
                        }
                    }
                }
            }

            Console.ReadLine();
        }
Ejemplo n.º 8
0
        public Initializer(string sourceBranch, string destBranch)
        {
            logger = LogManager.GetCurrentClassLogger();
            logger.Info($"Auto Merging tool start on {DateTime.Now:MM-dd-yyyy-HH-mm-ss}");
            logger.Info($"Source branch: {sourceBranch}, Target Branch: {destBranch}");

            string password = GetPassword(settings.VsoSecretName).Result;

            ProjectCollection = new TfsTeamProjectCollection(
                new Uri($"https://{settings.AccountName}.visualstudio.com/{settings.TFSProjectName}"),
                new VssBasicCredential(settings.UserName, password));

            var gitClient = ProjectCollection.GetClient <GitHttpClient>();

            MergeTool = new VstsMergeTool(gitClient, sourceBranch, destBranch);
        }
Ejemplo n.º 9
0
        private async Task <IList <ComponentActivityInfo> > GetGitActivityAsync(ApplicationTask task, TfsTeamProjectCollection tfs, TeamProjectInfo teamProject, int numberOfActivities, IList <string> userExclusions, IList <string> commentExclusions)
        {
            var activities = new List <ComponentActivityInfo>();
            var client     = tfs.GetClient <GitHttpClient>();
            var top        = numberOfActivities;

            // Find all repos.
            var repos = await client.GetRepositoriesAsync(project : teamProject.Name);

            var criteria = new GitQueryCommitsCriteria {
                Top = top, IncludeLinks = false
            };

            foreach (var repo in repos)
            {
                var skip = 0;
                while (activities.Count < numberOfActivities && !task.IsCanceled)
                {
                    var commits = await client.GetCommitsAsync(repo.Id, criteria, skip : skip, top : top);

                    foreach (var commit in commits)
                    {
                        if ((string.IsNullOrEmpty(commit.Comment) || !commentExclusions.Any(x => commit.Comment.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0)) && !userExclusions.Any(x => commit.Author.Name.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0 || commit.Committer.Name.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
                        {
                            var commentSuffix = string.IsNullOrEmpty(commit.Comment) ? null : ": " + commit.Comment.Trim();
                            var time          = commit.Author.Date;
                            var user          = commit.Author.Name;
                            var description   = string.Format(CultureInfo.CurrentCulture, "Commit {0}{1}", commit.CommitId.Substring(0, 7), commentSuffix);
                            activities.Add(new ComponentActivityInfo("Git", time, user, description));
                        }
                    }
                    if (commits.Count < top)
                    {
                        // There are no more pages.
                        break;
                    }
                    else
                    {
                        skip += top;
                    }
                }
            }
            return(activities);
        }
Ejemplo n.º 10
0
        private async Task <IList <ComponentActivityInfo> > GetTfvcActivityAsync(ApplicationTask task, TfsTeamProjectCollection tfs, TeamProjectInfo teamProject, int numberOfActivities, IList <string> userExclusions, IList <string> commentExclusions)
        {
            var activities = new List <ComponentActivityInfo>();

            try
            {
                var client = tfs.GetClient <TfvcHttpClient>();
                var skip   = 0;
                var top    = numberOfActivities;
                while (activities.Count < numberOfActivities && !task.IsCanceled)
                {
                    var changesets = await client.GetChangesetsAsync(project : teamProject.Name, skip : skip, top : top);

                    foreach (var changeset in changesets)
                    {
                        if ((string.IsNullOrEmpty(changeset.Comment) || !commentExclusions.Any(x => changeset.Comment.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0)) && !userExclusions.Any(x => changeset.Author.DisplayName.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0 || changeset.CheckedInBy.DisplayName.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
                        {
                            var commentSuffix = string.IsNullOrEmpty(changeset.Comment) ? null : ": " + changeset.Comment.Trim();
                            var time          = changeset.CreatedDate;
                            var user          = changeset.Author.DisplayName;
                            var description   = string.Format(CultureInfo.CurrentCulture, "Changeset {0}{1}", changeset.ChangesetId, commentSuffix);
                            activities.Add(new ComponentActivityInfo("TFVC", time, user, description));
                        }
                    }
                    if (changesets.Count < top)
                    {
                        // There are no more pages.
                        break;
                    }
                    else
                    {
                        skip += top;
                    }
                }
            }
            catch (VssServiceException exc)
            {
                // This is thrown when the Team Project doesn't contain a TFVC repository, ignore it.
                Logger.Log("Error retrieving TFVC activity from Team Project " + teamProject.Name, exc, TraceEventType.Verbose);
            }
            return(activities);
        }
Ejemplo n.º 11
0
        public void TestIterations()
        {
            var tfs =
                new TfsTeamProjectCollection(new Uri("https://msk-tfs1.securitycode.ru/tfs/Endpoint%20Security"));

            var store     = tfs.GetService <WorkItemStore>();
            var structure = tfs.GetService <ICommonStructureService4>();
            var client    = tfs.GetClient <WorkHttpClient>();

            var project = store.Projects["SNES"];

            var iterations = client.GetTeamIterationsAsync(new TeamContext(project.Name)).Result;

            var iterations2 = project
                              .IterationRootNodes
                              .OfType <Node>()
                              .Select(x => structure.GetNode(x.Uri.AbsoluteUri))
                              .AsParallel()
                              .ToList();

            var same = iterations.Count == iterations2.Count;


            //var iters =
            //        .Where(x => x.InRange(start, end))
            //        .Select(x => new TeamSettingsIteration()
            //        {
            //            Attributes = new TeamIterationAttributes
            //            {
            //                FinishDate = x.FinishDate,
            //                StartDate = x.StartDate,
            //            },
            //            Path = x.Path,
            //            Name = x.Name,
            //            Url = x.Uri,

            //        })
            //        .AsParallel()
            //        .ToList();
        }
Ejemplo n.º 12
0
        private async Task <IList <ComponentActivityInfo> > GetXamlBuildActivityAsync(ApplicationTask task, TfsTeamProjectCollection tfs, TeamProjectInfo teamProject, int numberOfActivities, IList <string> userExclusions)
        {
            var activities = new List <ComponentActivityInfo>();
            var client     = tfs.GetClient <XamlBuildHttpClient>();

            // There is no paging API for build queries, so we page the results manually by
            // limiting on the max finish time as being the finish time of the last returned result.
            // This will yield an overlap of 1 build per page which we can filter out.
            // Retrieve at least 2 builds to get the "manual paging" system working.
            var pageSize           = Math.Max(2, numberOfActivities);
            var lastRetrievedBuild = default(Build);

            while (activities.Count < numberOfActivities && !task.IsCanceled)
            {
                var maxFinishTime = lastRetrievedBuild == null ? null : lastRetrievedBuild.FinishTime;
                var builds        = await client.GetBuildsAsync(teamProject.Name, top : pageSize, maxFinishTime : maxFinishTime, queryOrder : Microsoft.TeamFoundation.Build.WebApi.BuildQueryOrder.FinishTimeDescending);

                var unseenBuilds = builds.Where(b => lastRetrievedBuild == null || b.Uri != lastRetrievedBuild.Uri);
                foreach (var build in unseenBuilds)
                {
                    lastRetrievedBuild = build;
                    if (build.RequestedFor == null || !userExclusions.Any(x => build.RequestedFor.DisplayName.IndexOf(x, StringComparison.OrdinalIgnoreCase) >= 0))
                    {
                        var time        = build.FinishTime ?? build.StartTime ?? build.QueueTime ?? DateTime.MinValue;
                        var user        = build.RequestedFor.DisplayName;
                        var description = string.Format(CultureInfo.CurrentCulture, "Build Number \"{0}\" from Build Definition \"{1}\"", build.BuildNumber, build.Definition.Name);
                        activities.Add(new ComponentActivityInfo("XAML Build", time, user, description));
                    }
                }
                if (!unseenBuilds.Any())
                {
                    break;
                }
            }

            return(activities);
        }
        protected static void ProcessCollection(TfsTeamProjectCollection collection)
        {
            Console.WriteLine(String.Format("Processing collection {0}", collection.DisplayName));
            Console.WriteLine(String.Empty);

            // Get Core, security, and identity services
            ISecurityService            securityService = collection.GetService <ISecurityService>();
            SecurityNamespace           hooksSecurity   = securityService.GetSecurityNamespace(ServiceHooksSecurityNamespaceId);
            IIdentityManagementService2 identityService = collection.GetService <IIdentityManagementService2>();
            ProjectHttpClient           projectClient   = collection.GetClient <ProjectHttpClient>();

            IEnumerable <TeamProjectReference> projects = projectClient.GetProjects(stateFilter: Microsoft.TeamFoundation.Common.ProjectState.WellFormed).Result;

            // Iterate over each project, check SH permissions, and grant if needed
            foreach (var project in projects)
            {
                Console.WriteLine(String.Format("Project {0} ({1})", project.Name, project.Id));

                var groups = identityService.ListApplicationGroups(project.Id.ToString(), ReadIdentityOptions.None, null, Microsoft.TeamFoundation.Framework.Common.IdentityPropertyScope.Both);

                String adminGroupName = String.Format("vstfs:///Classification/TeamProject/{0}\\Project Administrators", project.Id);

                try
                {
                    TeamFoundationIdentity adminGroup = groups.First(g => String.Equals(g.UniqueName, adminGroupName, StringComparison.InvariantCultureIgnoreCase));

                    Console.WriteLine(" - Checking Project Administrators group permissions");

                    AccessControlEntry ace           = new AccessControlEntry(adminGroup.Descriptor, 7, 0); // 7 = view, create, delete
                    String             securityToken = "PublisherSecurity/" + project.Id;

                    bool hasPermission = hooksSecurity.HasPermission(securityToken, adminGroup.Descriptor, 7, false);

                    if (!hasPermission)
                    {
                        Console.WriteLine(" - Missing. Granting...");

                        hooksSecurity.SetAccessControlEntry(securityToken, ace, true);

                        // check permission again after granting
                        hasPermission = hooksSecurity.HasPermission(securityToken, adminGroup.Descriptor, 7, false);
                        if (hasPermission)
                        {
                            Console.WriteLine(" - Granted");
                        }
                        else
                        {
                            Console.WriteLine(" - Still does not have permission. Check to make sure it has not been explicitly denied.");
                        }
                    }
                    else
                    {
                        Console.WriteLine(" - Already has permission");
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(String.Format("Admin group: Not found! ({0})", ex.Message));
                }

                Console.WriteLine("");
            }
        }
        private static readonly string SpecialGroupName = "Service Hooks Administrators"; // assumed to be a collection-level group containing people that will have management permissions for SH in each project

        public void Run(Uri collectionUri)
        {
            Console.WriteLine("Utility to remove Service Hooks management permissions from the Project Administrators groups.");
            Console.WriteLine("");
            Console.WriteLine(" All projects in account/collection: " + collectionUri);
            Console.WriteLine("");

            Console.WriteLine("WARNING! This operation will remove the permissions.\n\n  Are you sure you want to continue (Y/N)?");
            int confirmChar = Console.In.Read();

            if (confirmChar != 'y' || confirmChar != 'Y')
            {
                return;
            }

            if (collectionUri != null)
            {
                TfsTeamProjectCollection connection = new TfsTeamProjectCollection(collectionUri);

                // Get Core, security, and identity services
                ISecurityService            securityService = connection.GetService <ISecurityService>();
                SecurityNamespace           hooksSecurity   = securityService.GetSecurityNamespace(ServiceHooksSecurityNamespaceId);
                IIdentityManagementService2 identityService = connection.GetService <IIdentityManagementService2>();
                ProjectHttpClient           projectClient   = connection.GetClient <ProjectHttpClient>();

                IEnumerable <TeamProjectReference> projects = projectClient.GetProjects(stateFilter: Microsoft.TeamFoundation.Common.ProjectState.WellFormed).Result;

                // Iterate over each project, check SH permissions, and remove if the project administrators group has access
                foreach (var project in projects)
                {
                    // Remove manage permissions from the project's administrators group (but leave it "view" access)
                    Console.WriteLine(String.Format("Project {0} ({1})", project.Name, project.Id));

                    var groups = identityService.ListApplicationGroups(project.Id.ToString(), ReadIdentityOptions.None, null, Microsoft.TeamFoundation.Framework.Common.IdentityPropertyScope.Both);

                    String adminGroupName = String.Format("vstfs:///Classification/TeamProject/{0}\\Project Administrators", project.Id);

                    try
                    {
                        TeamFoundationIdentity adminGroup = groups.First(g => String.Equals(g.UniqueName, adminGroupName, StringComparison.InvariantCultureIgnoreCase));

                        Console.WriteLine(" - Checking Project Administrators group permissions");

                        String securityToken = "PublisherSecurity/" + project.Id;

                        bool hasPermission = hooksSecurity.HasPermission(securityToken, adminGroup.Descriptor, ManagePermissions, false);

                        // Project admin group has "manage" permissions for SH in the project
                        if (hasPermission)
                        {
                            // Remove manage permissions from the project's administrators group (but leave it "view" access)
                            Console.WriteLine(" - Has permissions. Removing...");

                            // Give the admin group only view permissions
                            hooksSecurity.SetPermissions(securityToken, adminGroup.Descriptor, ViewPermissions, 0, false);

                            // check permission again after granting
                            hasPermission = hooksSecurity.HasPermission(securityToken, adminGroup.Descriptor, ManagePermissions, false);
                            if (!hasPermission)
                            {
                                Console.WriteLine(" - Verified permissions correctly removed.");
                            }
                            else
                            {
                                Console.WriteLine(" - Project Administrators Group still has manage permissions.");
                            }
                        }
                        else
                        {
                            Console.WriteLine(" - Does not have permissions to manage service hook subscriptions.");
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(String.Format("Admin group: Not found! ({0})", ex.Message));
                    }

                    Console.WriteLine("");
                }

                // Grant the group manage permissions across the entire collection
                TeamFoundationIdentity specialGroup = identityService.ReadIdentity(IdentitySearchFactor.DisplayName, SpecialGroupName, MembershipQuery.None, ReadIdentityOptions.None);

                if (specialGroup != null)
                {
                    Console.WriteLine("Granting full manage permissions to: {0}", specialGroup.UniqueName);

                    String rootSecurityToken = "PublisherSecurity/";
                    hooksSecurity.SetPermissions(rootSecurityToken, specialGroup.Descriptor, ManagePermissions, 0, false);
                }
                else
                {
                    Console.WriteLine("Could not find this group.");
                }
            }
        }