예제 #1
0
        /// <summary>
        /// Gets all teams for the given <paramref name="projectId"/>.
        /// </summary>
        /// <param name="client">The <see cref="TeamHttpClient"/> to use.</param>
        /// <param name="projectId">The project identifier.</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 async Task <IList <WebApiTeam> > GetAllTeams(this TeamHttpClient client, string projectId, int pageSize = 10, object userState = null, CancellationToken cancellationToken = default(CancellationToken))
        {
            if (client == null)
            {
                throw new ArgumentNullException(nameof(client));
            }
            if (projectId == null)
            {
                throw new ArgumentNullException(nameof(projectId));
            }

            var result = new List <WebApiTeam>();

            int currentPage         = 0;
            var teamsForCurrentPage = (await client.GetTeamsAsync(projectId, pageSize, currentPage, userState, cancellationToken).ConfigureAwait(false)).ToList();

            while (teamsForCurrentPage.Count > 0)
            {
                cancellationToken.ThrowIfCancellationRequested();
                result.AddRange(teamsForCurrentPage);

                // check whether the recently returned item(s) were less than the max page size
                if (teamsForCurrentPage.Count < pageSize)
                {
                    break; // if so, break the loop as we've read all instances
                }
                // otherwise continue
                cancellationToken.ThrowIfCancellationRequested();
                teamsForCurrentPage = (await client.GetTeamsAsync(projectId, pageSize, currentPage, userState, cancellationToken).ConfigureAwait(false)).ToList();
            }

            cancellationToken.ThrowIfCancellationRequested();
            return(result);
        }
        public static bool FindAnyTeam(ClientSampleContext context, Guid?projectId, out WebApiTeamRef team)
        {
            if (!projectId.HasValue)
            {
                TeamProjectReference project;
                if (FindAnyProject(context, out project))
                {
                    projectId = project.Id;
                }
            }

            // Check if we already have a team that has been cached for this project
            if (!context.TryGetValue <WebApiTeamRef>("$" + projectId + "Team", out team))
            {
                TeamHttpClient teamClient = context.Connection.GetClient <TeamHttpClient>();

                using (new ClientSampleHttpLoggerOutputSuppression())
                {
                    team = teamClient.GetTeamsAsync(projectId.ToString(), top: 1).Result.FirstOrDefault();
                }

                if (team != null)
                {
                    context.SetValue <WebApiTeamRef>("$" + projectId + "Team", team);
                }
                else
                {
                    // create a team?
                    throw new Exception("No team available for running this sample.");
                }
            }

            return(team != null);
        }
예제 #3
0
 public static IEnumerable <WebApiTeam> GetTeams(string _project, VssBasicCredential _credentials, Uri _uri)
 {
     using (var teamHttpClient = new TeamHttpClient(_uri, _credentials))
     {
         return(teamHttpClient.GetTeamsAsync(_project).Result);
     }
 }
예제 #4
0
 /// <summary>
 /// получение списка команд в проекте
 /// </summary>
 /// <param name="projectId">иден. проекта</param>
 /// <returns></returns>
 public List <WebApiTeam> GetTeamsResult(string projectId)
 {
     using (TeamHttpClient teamHttpClient = VssConnection.GetConnection().GetClient <TeamHttpClient>())
     {
         return(teamHttpClient.GetTeamsAsync(projectId, null, 100).GetAwaiter().GetResult());
     }
 }
예제 #5
0
        public IEnumerable <WebApiTeam> GetTeams()
        {
            VssConnection            connection     = new VssConnection(_uri, _credentials);
            TeamHttpClient           teamHttpClient = connection.GetClient <TeamHttpClient>();
            IEnumerable <WebApiTeam> results        = teamHttpClient.GetTeamsAsync(_configuration.Project).Result;

            return(results);
        }
예제 #6
0
 public IEnumerable <WebApiTeam> GetTeams(string project)
 {
     // create team object
     using (TeamHttpClient teamHttpClient = new TeamHttpClient(_uri, _credentials))
     {
         IEnumerable <WebApiTeam> results = teamHttpClient.GetTeamsAsync(project).Result;
         return(results);
     }
 }
        public void ShowAllTeamSubscriptions()
        {
            VssConnection connection = Context.Connection;

            //
            // Step 1: construct query to find all subscriptions belonging to teams in the project
            //

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);

            // Get all teams in the project
            TeamHttpClient           teamClient = connection.GetClient <TeamHttpClient>();
            IEnumerable <WebApiTeam> teams      = teamClient.GetTeamsAsync(project.Id.ToString()).Result;

            // Construct a set of query conditions (one for each team)
            IEnumerable <SubscriptionQueryCondition> conditions =
                teams.Select <WebApiTeam, SubscriptionQueryCondition>(team =>
            {
                return(new SubscriptionQueryCondition()
                {
                    SubscriberId = team.Id
                });
            }
                                                                      );

            // Construct the query, making sure to return basic details for subscriptions the caller doesn't have read access to
            SubscriptionQuery query = new SubscriptionQuery()
            {
                Conditions = conditions,
                QueryFlags = SubscriptionQueryFlags.AlwaysReturnBasicInformation
            };

            //
            // Part 2: query and show the results
            //

            NotificationHttpClient notificationClient            = connection.GetClient <NotificationHttpClient>();
            IEnumerable <NotificationSubscription> subscriptions = notificationClient.QuerySubscriptionsAsync(query).Result;

            var subscriptionsBySubscriber = subscriptions.GroupBy <NotificationSubscription, Guid>(sub => { return(Guid.Parse(sub.Subscriber.Id)); });

            foreach (var team in teams)
            {
                // Find the corresponding team for this group
                var group = subscriptionsBySubscriber.First(t => t.Key == team.Id);

                // Show the details for each subscription owned by this team
                foreach (NotificationSubscription subscription in group)
                {
                    LogSubscription(subscription);
                }
            }
        }
예제 #8
0
        /// <summary>
        /// Gets all teams for the given <paramref name="teamHttpClient" />, optionally for a specific project corresponding to the <paramref name="projectNameOrId" />.
        /// </summary>
        /// <param name="teamHttpClient">The team HTTP client.</param>
        /// <param name="projectNameOrId">The project name or identifier.</param>
        /// <param name="mine">If true return all the teams requesting user is member, otherwise return all the teams user has read access</param>
        /// <param name="count">The amount of teams to retrieve at most.</param>
        /// <param name="skip">How many teams to skip.</param>
        /// <param name="expandIdentity">A value indicating whether or not to expand <see cref="T:Microsoft.VisualStudio.Services.Identity.Identity" /> information in the result <see cref="T:Microsoft.TeamFoundation.Core.WebApi.WebApiTeam" /> object.</param>
        /// <param name="userState">The user state object to pass along to the underlying method.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">teamHttpClient</exception>
        public static IObservable <WebApiTeam> GetTeams(
            this TeamHttpClient teamHttpClient, string projectNameOrId = "", bool?mine = null, int?count = null, int?skip = null, bool?expandIdentity = null, object userState = null)
        {
            if (teamHttpClient == null)
            {
                throw new ArgumentNullException(nameof(teamHttpClient));
            }

            return(!string.IsNullOrWhiteSpace(projectNameOrId)
                ? Observable.FromAsync(cancellationToken => teamHttpClient.GetTeamsAsync(projectNameOrId, mine, count, skip, expandIdentity, userState, cancellationToken))
                   .SelectMany(webApiTeams => webApiTeams)
                : Observable.FromAsync(cancellationToken => teamHttpClient.GetAllTeamsAsync(mine, count, skip, expandIdentity, userState, cancellationToken))
                   .SelectMany(webApiTeams => webApiTeams));
        }
예제 #9
0
        /// <summary>
        /// Gets all teams for the given <paramref name="teamHttpClient" />, optionally for a specific project corresponding to the <paramref name="projectNameOrId" />.
        /// </summary>
        /// <param name="teamHttpClient">The team HTTP client.</param>
        /// <param name="projectNameOrId">The project name or identifier.</param>
        /// <param name="mine">If true return all the teams requesting user is member, otherwise return all the teams user has read access</param>
        /// <param name="count">The amount of teams to retrieve at most.</param>
        /// <param name="skip">How many teams to skip.</param>
        /// <param name="expandIdentity">A value indicating whether or not to expand <see cref="T:Microsoft.VisualStudio.Services.Identity.Identity" /> information in the result <see cref="T:Microsoft.TeamFoundation.Core.WebApi.WebApiTeam" /> object.</param>
        /// <param name="userState">The user state object to pass along to the underlying method.</param>
        /// <returns></returns>
        /// <exception cref="ArgumentNullException">teamHttpClient</exception>
        public static IAsyncEnumerable <WebApiTeam> GetTeams(
            this TeamHttpClient teamHttpClient, string projectNameOrId = "", bool?mine = null, int?count = null, int?skip = null, bool?expandIdentity = null, object userState = null)
        {
            if (teamHttpClient == null)
            {
                throw new ArgumentNullException(nameof(teamHttpClient));
            }

            return(!string.IsNullOrWhiteSpace(projectNameOrId)
                ? AsyncEnumerabletHelper.GetAsyncEnumerableForListProducer(
                       iterationInput => teamHttpClient.GetTeamsAsync(projectNameOrId, mine, iterationInput.Count, iterationInput.Skip, expandIdentity, userState, iterationInput.CancellationToken), count, skip)
                : AsyncEnumerabletHelper.GetAsyncEnumerableForListProducer(
                       iterationInput => teamHttpClient.GetAllTeamsAsync(mine, iterationInput.Count, iterationInput.Skip, expandIdentity, userState, iterationInput.CancellationToken), count, skip));
        }
예제 #10
0
        /// <summary>
        /// Get all teams
        /// </summary>
        /// <param name="TeamProjectName"></param>
        static void GetTeams(string TeamProjectName)
        {
            TeamProject project = ProjectClient.GetProject(TeamProjectName).Result;

            Console.WriteLine("Teams for Project: " + project.Name);
            Console.WriteLine("Default Team Name: " + project.DefaultTeam.Name);

            List <WebApiTeam> teams = TeamClient.GetTeamsAsync(TeamProjectName).Result;

            Console.WriteLine("Project Teams:");

            foreach (WebApiTeam team in teams)
            {
                Console.WriteLine(team.Name);
            }
        }
        static void Main(string[] args)
        {
            String         collectionUri = "http://TFS2017:8080/tfs/defaultcollection";
            VssCredentials creds         = new VssClientCredentials();

            creds.Storage = new VssClientCredentialStorage();
            VssConnection  connection = new VssConnection(new Uri(collectionUri), creds);
            TeamHttpClient thc        = connection.GetClient <TeamHttpClient>();

            List <WebApiTeam> irs = thc.GetTeamsAsync("AgileProject").Result;

            foreach (WebApiTeam ir in irs)
            {
                Console.WriteLine(ir.Name);
            }
        }
예제 #12
0
        public async Task <List <TeamMemberModel> > GetProjectTeamMembers(string projectName)
        {
            List <TeamMemberModel> tempLst = new List <TeamMemberModel>();
            DevOpsConnectionPool   poolObj = _builderPool.Get();

            try
            {
                //VssCredentials creds = new VssBasicCredential(string.Empty, personalaccesstoken);
                //VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
                TeamHttpClient    teamClient = poolObj.VssConnection.GetClient <TeamHttpClient>();
                List <WebApiTeam> teams      = await teamClient.GetTeamsAsync(projectName);

                if (teams != null && teams.Count > 0)
                {
                    foreach (var team in teams)
                    {
                        var teamsMembers = await GetTeamMembers(team.ProjectId.ToString(), team.Id.ToString(), teamClient);

                        if (teamsMembers != null && teamsMembers.Count > 0)
                        {
                            tempLst.AddRange(teamsMembers);
                        }
                    }
                    tempLst = tempLst.GroupBy(x => x.Email).Select(x => x.First()).ToList();//remove dupicate
                }
                else
                {
                    tempLst.Add(new TeamMemberModel()
                    {
                        Email = string.Empty
                    });
                }
            }
            catch (Exception)
            {
                tempLst.Add(new TeamMemberModel()
                {
                    Email = string.Empty
                });
            }
            finally
            {
                _builderPool.Return(poolObj);
            }

            return(tempLst);
        }
예제 #13
0
        public async Task <List <TeamModel> > GetProjectTeams(string projectName)
        {
            List <TeamModel>     lst       = new List <TeamModel>();
            TeamModel            teammodel = null;
            DevOpsConnectionPool poolObj   = _builderPool.Get();

            try
            {
                //    VssCredentials creds = new VssBasicCredential(string.Empty, personalaccesstoken);
                //    // Connect to Azure DevOps Services
                //    VssConnection connection = new VssConnection(new Uri(c_collectionUri), creds);
                TeamHttpClient    teamClient = poolObj.VssConnection.GetClient <TeamHttpClient>();
                List <WebApiTeam> teams      = await teamClient.GetTeamsAsync(projectName);

                if (teams != null && teams.Count > 0)
                {
                    foreach (var team in teams)
                    {
                        teammodel          = new TeamModel();
                        teammodel.TeamId   = team.Id;
                        teammodel.TeamName = team.Name;
                        teammodel.TeamUrl  = team.Url;
                        var teamsMembers = await GetTeamMembers(team.ProjectId.ToString(), team.Id.ToString(), teamClient);

                        if (teamsMembers != null && teamsMembers.Count > 0)
                        {
                            teammodel.TeamMembers = new List <TeamMemberModel>();
                            teammodel.TeamMembers.AddRange(teamsMembers);
                        }
                        lst.Add(teammodel);
                    }
                }
            }
            catch (Exception)
            {
            }
            finally
            {
                _builderPool.Return(poolObj);
            }
            return(lst);
        }
예제 #14
0
        public List <Assignee> GetAssigneesNames(int projectId)
        {
            List <Assignee>   onlineTeamMembersList = new List <Assignee>();
            List <WebApiTeam> teams = _teamClient.GetTeamsAsync(OnlineTfsProjectId).Result;

            foreach (WebApiTeam team in teams)
            {
                List <TeamMember> teamMembers = _teamClient.GetTeamMembersWithExtendedPropertiesAsync(OnlineTfsProjectId, team.Id.ToString()).Result;
                foreach (TeamMember member in teamMembers)
                {
                    onlineTeamMembersList.Add(new Assignee
                    {
                        IsActive  = 1,
                        ProjectId = projectId,
                        Name      = member.Identity.DisplayName
                    });
                }
            }
            return(onlineTeamMembersList);
        }
예제 #15
0
        /// <summary>
        /// Returns enumerable of accessible teams associated
        /// with the given team project
        /// </summary>
        /// <param name="teamProjectId">AzureDevOps team project ID for which to retrieve teams</param>
        /// <returns>teams associated with the given team project, or null if disconnected</returns>
        internal IEnumerable <Models.Team> GetTeamsFromProject(Models.TeamProject project)
        {
            if (!ConnectedToAzureDevOps)
            {
                return(null);
            }

            TeamHttpClient teamClient          = _baseServerConnection.GetClient <TeamHttpClient>();
            var            teams               = new List <WebApiTeamRef>();
            var            newElementsReturned = 0;

            // Continue to populate teams list until the number of new returned elements
            //  is less than the number of elements we requested
            do
            {
                var newTeams = teamClient.GetTeamsAsync(project.Id.ToString("D", CultureInfo.InvariantCulture), AzureDevOps_PAGE_SIZE, teams.Count()).Result;
                newElementsReturned = newTeams.Count();
                teams.AddRange(newTeams);
            }while (newElementsReturned >= AzureDevOps_PAGE_SIZE);

            return(teams.Select(t => new Models.Team(t.Name, t.Id, project)));
        }
        public IEnumerable <WebApiTeam> ListOrderedTeams()
        {
            // Get a random project to load the teams for
            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);

            // Get a client
            VssConnection  connection = Context.Connection;
            TeamHttpClient teamClient = connection.GetClient <TeamHttpClient>();

            // Get the teams for a project
            IEnumerable <WebApiTeam> teams = teamClient.GetTeamsAsync(project.Id.ToString()).Result;

            // Order the projects by name
            teams = teams.OrderBy(team => { return(team.Name); });

            Console.WriteLine("Project: " + project.Name);
            foreach (var team in teams)
            {
                Console.WriteLine("  " + team.Name);
            }

            return(teams);
        }
예제 #17
0
        public Dictionary <TeamProjectReference, IEnumerable <WebApiTeam> > ListAllProjectsAndTeams()
        {
            // Get the project and team clients
            VssConnection     connection    = Context.Connection;
            ProjectHttpClient projectClient = connection.GetClient <ProjectHttpClient>();
            TeamHttpClient    teamClient    = connection.GetClient <TeamHttpClient>();

            // Call to get the list of projects
            IEnumerable <TeamProjectReference> projects = projectClient.GetProjects().Result;

            Dictionary <TeamProjectReference, IEnumerable <WebApiTeam> > results = new Dictionary <TeamProjectReference, IEnumerable <WebApiTeam> >();

            // Iterate over the returned projects
            foreach (var project in projects)
            {
                // Get the teams for the project
                IEnumerable <WebApiTeam> teams = teamClient.GetTeamsAsync(project.Name).Result;

                // Add the project/teams item to the results dictionary
                results.Add(project, teams);

                Console.WriteLine(" " + project.Name);
                // Iterate over the teams and show the name
                foreach (var team in teams)
                {
                    Console.WriteLine("    " + team.Name);
                }
            }

            if (projects.Count() == 0)
            {
                Console.WriteLine("No projects found.");
            }

            return(results);
        }
예제 #18
0
        public async Task <bool> AddUser(string organization, string projectName, string userId)
        {
            if (string.IsNullOrWhiteSpace(organization))
            {
                throw new ArgumentException($"'{nameof(organization)}' cannot be null or whitespace.", nameof(organization));
            }

            if (string.IsNullOrWhiteSpace(projectName))
            {
                throw new ArgumentException($"'{nameof(projectName)}' cannot be null or whitespace.", nameof(projectName));
            }

            if (string.IsNullOrWhiteSpace(userId))
            {
                throw new ArgumentException($"'{nameof(userId)}' cannot be null or whitespace.", nameof(userId));
            }

            VssConnection   connection      = null;
            GraphHttpClient graphHttpClient = null;
            TeamHttpClient  teamClient      = null;
            var             result          = false;

            try
            {
                string url = $"https://dev.azure.com/{organization}";
                if (_adoConfig.UsePta)
                {
                    connection = new VssConnection(new Uri(url), new VssBasicCredential(string.Empty, _adoConfig.AdoPersonalAccessToken));
                }
                else
                {
                    //connection = new VssConnection(new Uri(url), new VssCredentials(true));
                    connection = new VssConnection(new Uri(url), new VssClientCredentials(true));
                }

                teamClient = connection.GetClient <TeamHttpClient>();
                var allteams = await teamClient.GetTeamsAsync(projectName, null, null, null, true);

                var defTeamGroupName = $"{projectName} Team";
                var defTeam          = allteams?.FirstOrDefault(a => a.Name.Contains(defTeamGroupName));
                if (defTeam != null)
                {
                    //var members = await teamClient.GetTeamMembersWithExtendedPropertiesAsync(projectName, defTeam.Id.ToString());
                    graphHttpClient = connection.GetClient <GraphHttpClient>();
                    List <SubjectDescriptor> groupSubjectDescriptors = new();
                    groupSubjectDescriptors.Add(SubjectDescriptor.FromString(defTeam.Identity.Descriptor.Identifier));
                    var contextCreate = new GraphUserPrincipalNameCreationContext {
                        PrincipalName = userId
                    };
                    var added = await graphHttpClient.CreateUserAsync(contextCreate, groupSubjectDescriptors);

                    //var membersAfter = await teamClient.GetTeamMembersWithExtendedPropertiesAsync(projectName, defTeam.Id.ToString());
                    result = true;
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine("Exception during create project: ", ex.Message);
                throw;
            }
            finally
            {
                connection?.Dispose();
                graphHttpClient?.Dispose();
                teamClient?.Dispose();
            }
            return(result);
        }
예제 #19
0
 public async Task <IEnumerable <WebApiTeam> > GetTeams(string projectId)
 {
     return(await teamClient.GetTeamsAsync(projectId));
 }
예제 #20
0
        public async Task <bool> RegisterIterations()
        {
            bool result = true;

            VssConnection connection = new VssConnection(new Uri(Options.Url),
                                                         new VssBasicCredential(string.Empty, Options.PAT));

            //  get VSTS's project collection
            ProjectHttpClient projectClient             = connection.GetClient <ProjectHttpClient>();
            IEnumerable <TeamProjectReference> projects = projectClient.GetProjects().Result;
            var targetProject =
                projects.FirstOrDefault(p => string.CompareOrdinal(p.Name, Options.Project) == 0);

            if (targetProject == null)
            {
                Console.WriteLine($"Project {Options.Project} not found in Server {Options.Url}");
                return(false);
            }

            // get team of project setting
            TeamHttpClient teamClient = connection.GetClient <TeamHttpClient>();
            var            teams      = await teamClient.GetTeamsAsync(targetProject.Id.ToString());

            // found specific team
            var team = teams.FirstOrDefault(p => string.CompareOrdinal(p.Name, Options.Team) == 0);

            if (team == null)
            {
                Console.WriteLine($"Team {Options.Team} not found in Project {Options.Project}");
                return(false);
            }
            WorkHttpClient workHttpClient = connection.GetClient <WorkHttpClient>();

            // get team's iteration
            var teamContext = new TeamContext(targetProject.Id, team.Id);
            var teamSetting = await workHttpClient.GetTeamIterationsAsync(teamContext);

            if (teamSetting == null)
            {
                Console.WriteLine("Can\'t get team Iteration");
                return(false);
            }
            try
            {
                int SprintCounter = Options.SprintStartIndex;
                do
                {
                    var teamIteration = new TeamSettingsIteration
                    {
                        // these date values looks like ignore.
                        Attributes = new TeamIterationAttributes
                        {
                            StartDate  = DateTime.Today,
                            FinishDate = DateTime.Today
                        },
                        Name = string.Format($"Sprint {SprintCounter}"),
                        Path = string.Format($"{Options.Project}\\{Options.SprintPrefix} {SprintCounter}"),
                    };

                    // add team iteration from Project iteration.
                    var execResult = await workHttpClient.PostTeamIterationAsync(teamIteration, teamContext);

                    if (execResult != null)
                    {
                        SprintCounter++;
                        Console.WriteLine($"Sprint {execResult.Path} add team iteration");
                    }
                } while (true);
            }
            catch (Exception ex)
            {
                // Exception is ignore, because PostTeamIteration Async method can't return error value.
            }
            return(result);
        }