Beispiel #1
0
        public void AddRemoveAADUserByOID()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOID");
            GraphUserCreationContext addAADUserContext = new GraphUserOriginIdCreationContext
            {
                OriginId = "e97b0e7f-0a61-41ad-860c-748ec5fcb20b"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: get the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetUser-AddRemoveAADUserByOID");
            newUser = graphClient.GetUserAsync(userDescriptor).Result;

            //
            // Part 3: remove the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteUser-AddRemoveAADUserByOID");
            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipState-AddRemoveAADUserByOID");
            GraphMembershipState membershipState = graphClient.GetMembershipStateAsync(userDescriptor).Result;

            try
            {
                if (membershipState.Active)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
        public void LookupSubject()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOIDWithStorageKey");
            GraphUserCreationContext addAADUserContext = new GraphUserOriginIdCreationContext
            {
                OriginId   = "e97b0e7f-0a61-41ad-860c-748ec5fcb20b",
                StorageKey = Guid.NewGuid()
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: add the AAD group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADGroupByOIDWithStorageKey");
            GraphGroupCreationContext addAADGroupContext = new GraphGroupOriginIdCreationContext
            {
                OriginId   = "f0d20172-7b96-42f6-9436-941433654b48",
                StorageKey = Guid.NewGuid()
            };

            GraphGroup newGroup        = graphClient.CreateGroupAsync(addAADGroupContext).Result;
            string     groupDescriptor = newGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);


            //
            // Part 3: lookup subjects
            //
            GraphSubjectLookup subjectLookup = new GraphSubjectLookup(new[] {
                new GraphSubjectLookupKey(newGroup.Descriptor),
                new GraphSubjectLookupKey(newUser.Descriptor)
            });

            ClientSampleHttpLogger.SetOperationName(this.Context, "LookupSubjects");
            IReadOnlyDictionary <SubjectDescriptor, GraphSubject> lookups = graphClient.LookupSubjectsAsync(subjectLookup).Result;
        }
Beispiel #3
0
        public void AddRemoveAADUserByUPN()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateUserAAD");
            GraphUserCreationContext addAADUserContext = new GraphUserPrincipalNameCreationContext
            {
                PrincipalName = "*****@*****.**"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: get the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetUserAAD");
            newUser = graphClient.GetUserAsync(userDescriptor).Result;

            //
            // Part 3: remove the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteUserAAD");
            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipStateAAD");
            GraphMembershipState membershipState = graphClient.GetMembershipStateAsync(userDescriptor).Result;

            try
            {
                if (membershipState.Active)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
        public void AddRemoveAADUserByUPN()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateUserAAD");
            GraphUserCreationContext addAADUserContext = new GraphUserPrincipalNameCreationContext
            {
                PrincipalName = "*****@*****.**"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: get the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetUserAAD");
            //newUser = graphClient.GetUserAsync(userDescriptor).Result;  //BUG ???: {"TF14045: The identity with type 'Microsoft.IdentityModel.Claims.ClaimsIdentity' and identifier '45aa3d2d-7442-473d-b4d3-3c670da9dd96\\[email protected]' could not be found."}

            //
            // Part 3: remove the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteUserAAD");
            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            try
            {
                ClientSampleHttpLogger.SetOperationName(this.Context, "GetDisabledUserAAD");
                newUser = graphClient.GetUserAsync(userDescriptor).Result;
                if (!newUser.Disabled)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
Beispiel #5
0
        public GitRefUpdateResult CreateBranchInner(bool cleanUp)
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            // find a project, repo, and source ref to branch from
            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);
            string defaultBranch         = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch);
            GitRef sourceRef             = gitClient.GetRefsAsync(repo.Id, filter: defaultBranch).Result.First();

            // create a new branch from the source
            GitRefUpdateResult refCreateResult = gitClient.UpdateRefsAsync(
                new GitRefUpdate[] { new GitRefUpdate()
                                     {
                                         OldObjectId = new string('0', 40),
                                         NewObjectId = sourceRef.ObjectId,
                                         Name        = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}",
                                     } },
                repositoryId: repo.Id).Result.First();

            Console.WriteLine("project {0}, repo {1}, source branch {2}", project.Name, repo.Name, sourceRef.Name);
            Console.WriteLine("new branch {0} (success={1} status={2})", refCreateResult.Name, refCreateResult.Success, refCreateResult.UpdateStatus);

            if (cleanUp)
            {
                // silently (no logging) delete up the branch we just created
                ClientSampleHttpLogger.SetSuppressOutput(this.Context, true);
                GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync(
                    new GitRefUpdate[]
                {
                    new GitRefUpdate()
                    {
                        OldObjectId = refCreateResult.NewObjectId,
                        NewObjectId = new string('0', 40),
                        Name        = refCreateResult.Name,
                    }
                },
                    repositoryId: refCreateResult.RepositoryId).Result.First();

                return(null);
            }

            return(refCreateResult);
        }
        public void AddRemoveAADUserByOID()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOID");
            GraphUserCreationContext addAADUserContext = new GraphUserOriginIdCreationContext
            {
                OriginId = "e97b0e7f-0a61-41ad-860c-748ec5fcb20b"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: get the user
            //
            //newUser = graphClient.GetUserAsync(userDescriptor).Result; //BUG ???: TF14045: The identity with type 'Microsoft.IdentityModel.Claims.ClaimsIdentity' and identifier '45aa3d2d-7442-473d-b4d3-3c670da9dd96\[email protected]' could not be found.

            //
            // Part 3: remove the user
            //

            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            try
            {
                newUser = graphClient.GetUserAsync(userDescriptor).Result;
                if (!newUser.Disabled)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
        public void AddRemoveAADGroupByOIDWithStorageKey()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADGroupByOIDWithStorageKey");
            GraphGroupCreationContext addAADGroupContext = new GraphGroupOriginIdCreationContext
            {
                OriginId   = "f0d20172-7b96-42f6-9436-941433654b48",
                StorageKey = Guid.NewGuid()
                             //TODO: Remove Hard coded GUID StorageKey = new Guid("fc24f8cc-aed7-4bd4-be08-052d7fd30c39")
            };

            GraphGroup newGroup        = graphClient.CreateGroupAsync(addAADGroupContext).Result;
            string     groupDescriptor = newGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);

            //
            // Part 2: get the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetGroup-AddRemoveAADGroupByOIDWithStorageKey");
            newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;

            //
            // Part 3: remove the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteGroup-AddRemoveAADGroupByOIDWithStorageKey");
            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            // Try to get the deleted group (should result in an exception)
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetDisabledGroup-AddRemoveAADGroupByOIDWithStorageKey");
            try
            {
                newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;
            }
            catch (Exception e)
            {
                Context.Log("Unable to get the removed group:" + e.Message);
            }
        }
Beispiel #8
0
        public bool ChangeProjectDescription()
        {
            // Use the project created in the earlier "create project" sample method
            TeamProject project;

            if (!Context.TryGetValue <TeamProject>("$newProject", out project))
            {
                Console.WriteLine("No previously created project to change the description of.");
                return(false);
            }

            TeamProject updatedProject = new TeamProject()
            {
                Description = "An event better description for my project!"
            };

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

            Console.WriteLine("Queuing project update...");

            // Queue the update operation
            Guid updateOperationId = projectClient.UpdateProject(project.Id, updatedProject).Result.Id;

            ClientSampleHttpLogger.SetSuppressOutput(Context, true);

            // Check the operation status every 2 seconds (for up to 30 seconds)
            Operation detailedUpdateOperation = WaitForLongRunningOperation(updateOperationId, 2, 30).Result;

            // Check if the operation succeeded (the project was created) or failed
            if (detailedUpdateOperation.Status == OperationStatus.Succeeded)
            {
                Console.WriteLine();
                Console.WriteLine("Project description change from:\n {1}\nto\n {2}", project.Name, project.Description, updatedProject.Description);
                return(true);
            }
            else
            {
                Console.WriteLine();
                Console.WriteLine("Unable to change the description for project {0}", project.Name);
                return(false);
            }
        }
Beispiel #9
0
        public void AddRemoveAADUserByOIDWithVSID()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOIDWithVSID");
            GraphUserCreationContext addAADUserContext = new GraphUserOriginIdCreationContext
            {
                OriginId = "e97b0e7f-0a61-41ad-860c-748ec5fcb20b"
                           /* TODO: Id = Guid.NewGuid() */
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: get the user
            //
            //newUser = graphClient.GetUserAsync(userDescriptor).Result;

            //
            // Part 3: remove the user
            //

            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            try
            {
                newUser = graphClient.GetUserAsync(userDescriptor).Result;
                // TODO: if (!newUser.Disabled) throw new Exception();
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
        public void AddRemoveAADGroupByOID()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADGroupByOID");
            GraphGroupCreationContext addAADGroupContext = new GraphGroupOriginIdCreationContext
            {
                OriginId = "77ed2186-aaf6-4299-ac9e-37ba282c2b95"
            };

            GraphGroup newGroup        = graphClient.CreateGroupAsync(addAADGroupContext).Result;
            string     groupDescriptor = newGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);

            //
            // Part 2: get the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetGroup-AddRemoveAADGroupByOID");
            newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;

            //
            // Part 3: remove the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteGroup-AddRemoveAADGroupByOID");
            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            // Try to get the deleted group (should result in an exception)
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetDisabledGroup-AddRemoveAADGroupByOID");
            try
            {
                newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;
            }
            catch (Exception e)
            {
                Context.Log("Unable to get the removed group:" + e.Message);
            }
        }
Beispiel #11
0
        public void AddRemoveAADGroupByOIDWithVSID()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADGroupByOIDWithVSID");
            GraphGroupCreationContext addAADGroupContext = new GraphGroupOriginIdCreationContext
            {
                OriginId = "f0d20172-7b96-42f6-9436-941433654b48",
                Id       = Guid.NewGuid()
            };

            GraphGroup newGroup        = graphClient.CreateGroupAsync(addAADGroupContext).Result;
            string     groupDescriptor = newGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);

            //
            // Part 2: get the group
            //
            newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;

            //
            // Part 3: remove the group
            //

            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            // Try to get the deleted group (should result in an exception)
            try
            {
                newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;
            }
            catch (Exception e)
            {
                Context.Log("Unable to get the removed group:" + e.Message);
            }
        }
Beispiel #12
0
        public bool RenameProject()
        {
            // Use the project created in the earlier "create project" sample method
            TeamProject project;

            if (!Context.TryGetValue <TeamProject>("$newProject", out project))
            {
                Console.WriteLine("No previously created project to change the name of.");

                return(false);
            }

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

            TeamProject updatedProject = new TeamProject()
            {
                Name = project.Name + " (renamed)"
            };

            Console.WriteLine("Queuing project update...");

            // Queue the update operation
            Guid updateOperationId = projectClient.UpdateProject(project.Id, updatedProject).Result.Id;

            ClientSampleHttpLogger.SetSuppressOutput(Context, true);

            // Check the operation status every 2 seconds (for up to 30 seconds)
            Operation detailedUpdateOperation = WaitForLongRunningOperation(updateOperationId, 2, 30).Result;

            if (detailedUpdateOperation.Status == OperationStatus.Succeeded)
            {
                Console.WriteLine();
                Console.WriteLine("Project renamed from:\n {0}\nto\n {1}", project.Name, updatedProject.Name);
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public static GitPullRequest AbandonPullRequest(ClientSampleContext context, GitRepository repo, int pullRequestId)
        {
            VssConnection connection = context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            using (new ClientSampleHttpLoggerOutputSuppression())
            {
                // clean up after ourselves (and in case logging is on, don't log these calls)
                ClientSampleHttpLogger.SetSuppressOutput(context, true);

                // abandon the PR
                GitPullRequest updatedPr = new GitPullRequest()
                {
                    Status = PullRequestStatus.Abandoned,
                };

                var pullRequest = gitClient.UpdatePullRequestAsync(updatedPr, repo.Id, pullRequestId).Result;

                return(pullRequest);
            }
        }
        public GitPullRequest AbandonPullRequest()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            // first we need to create a pull request
            GitPullRequest pr = CreatePullRequestInner(cleanUp: false);

            // now abandon the PR
            GitPullRequest updatedPr = new GitPullRequest()
            {
                Status = PullRequestStatus.Abandoned,
            };
            GitPullRequest abandonedPr = gitClient.UpdatePullRequestAsync(updatedPr, repo.Id, pr.PullRequestId).Result;

            Console.WriteLine("{0} (#{1}) {2}",
                              abandonedPr.Title.Substring(0, Math.Min(40, pr.Title.Length)),
                              abandonedPr.PullRequestId,
                              abandonedPr.Status);

            // delete the branch that was associated with the PR (and do not log)
            ClientSampleHttpLogger.SetSuppressOutput(this.Context, true);
            GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync(
                new GitRefUpdate[]
            {
                new GitRefUpdate()
                {
                    OldObjectId = gitClient.GetRefsAsync(repo.Id, filter: GitSampleHelpers.WithoutRefsPrefix(pr.SourceRefName)).Result.First().ObjectId,
                    NewObjectId = new string('0', 40),
                    Name        = pr.SourceRefName,
                }
            },
                repositoryId: repo.Id).Result.First();

            return(abandonedPr);
        }
        public void AddRemoveVSTSGroupMembership()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: create a group at the account level
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateVSTSGroup-AddRemoveVSTSGroupMembership");
            GraphGroupCreationContext createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Developers-" + Guid.NewGuid(),
                Description = "Group created via client library"
            };
            GraphGroup parentGroup           = graphClient.CreateGroupAsync(createGroupContext).Result;
            string     parentGroupDescriptor = parentGroup.Descriptor;

            Context.Log("New group created! ID: {0}", parentGroupDescriptor);

            //
            // Part 2: create a second group at the account level
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "AddUserToGroup-AddRemoveVSTSGroupMembership");
            createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Contractors",
                Description = "Child group created via client library"
            };
            GraphGroup childGroup           = graphClient.CreateGroupAsync(createGroupContext).Result;
            string     childGroupDescriptor = childGroup.Descriptor;

            Context.Log("New group created! ID: {0}", childGroupDescriptor);

            //
            // Part 3: Make the 'Contractors' group a member of the 'Developers' group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateMembershipVSTSGroup");
            GraphMembership graphMembership = graphClient.AddMembershipAsync(childGroupDescriptor, parentGroupDescriptor).Result;

            //
            // Part 4: get the membership
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipVSTSGroup");
            graphMembership = graphClient.GetMembershipAsync(childGroupDescriptor, parentGroupDescriptor).Result;

            //
            // Part 5: Check to see if the 'Contractors' group is a member of the 'Developers' group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CheckMembershipExistenceVSTSGroup");
            graphClient.CheckMembershipExistenceAsync(childGroupDescriptor, parentGroupDescriptor).SyncResult();

            //
            // Part 6: Get every group the subject('Contractors') is a member of
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "BatchGetMembershipsVSTSGroupUp");
            List <GraphMembership> membershipsForUser = graphClient.ListMembershipsAsync(childGroupDescriptor).Result;

            //
            // Part 7: Get every member of the 'Developers' group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "BatchGetMembershipsVSTSGroupDown");
            List <GraphMembership> membershipsOfGroup = graphClient.ListMembershipsAsync(parentGroupDescriptor, Microsoft.VisualStudio.Services.Graph.GraphTraversalDirection.Down).Result;

            //
            // Part 8: Remove member from the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteMembershipVSTSGroup");
            graphClient.RemoveMembershipAsync(childGroupDescriptor, parentGroupDescriptor).SyncResult();
            try
            {
                ClientSampleHttpLogger.SetOperationName(this.Context, "CheckMembershipExistenceVSTSGroupDeleted");
                graphClient.CheckMembershipExistenceAsync(childGroupDescriptor, parentGroupDescriptor).SyncResult();
            }
            catch (Exception e)
            {
                Context.Log("'Contractors' is no longer a member of the group:" + e.Message);
            }

            //
            // Part 9: delete the groups
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteChildGroup-AddRemoveVSTSGroupMembership");
            graphClient.DeleteGroupAsync(childGroupDescriptor).SyncResult();
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteParentGroup-AddRemoveVSTSGroupMembership");
            graphClient.DeleteGroupAsync(parentGroupDescriptor).SyncResult();
        }
        public void AddRemoveAADGroupMembership()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: create a group at the account level
            //

            GraphGroupCreationContext createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Developers-" + Guid.NewGuid(),
                Description = "Group created via client library"
            };
            GraphGroup parentGroup           = graphClient.CreateGroupAsync(createGroupContext).Result;
            string     parentGroupDescriptor = parentGroup.Descriptor;

            Context.Log("New group created! ID: {0}", parentGroupDescriptor);

            //
            // Part 2: add the AAD group
            //

            GraphGroupCreationContext addAADGroupContext = new GraphGroupOriginIdCreationContext
            {
                OriginId = "a42aad15-d654-4b16-9309-9ee34d5aacfb"
            };
            GraphGroup aadGroup           = graphClient.CreateGroupAsync(addAADGroupContext).Result;
            string     aadGroupDescriptor = aadGroup.Descriptor;

            Context.Log("AAD group added! ID: {0}", aadGroupDescriptor);

            //
            // Part 3: Make the AAD group a member of the VSTS 'Developers' group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateMembershipAADGroup");
            GraphMembership graphMembership = graphClient.AddMembershipAsync(aadGroupDescriptor, parentGroupDescriptor).Result;

            //
            // Part 4: get the membership
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipAADGroup");
            graphMembership = graphClient.GetMembershipAsync(aadGroupDescriptor, parentGroupDescriptor).Result;

            //
            // Part 5: Check to see if the AAD group is a member of the VSTS 'Developers' group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CheckMembershipAADGroup");
            graphClient.CheckMembershipAsync(aadGroupDescriptor, parentGroupDescriptor).SyncResult();

            //
            // Part 6: Get every group the subject(AAD group) is a member of
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipsAADGroupDown");
            List <GraphMembership> membershipsForUser = graphClient.GetMembershipsAsync(aadGroupDescriptor).Result;

            //
            // Part 7: Get every member of the VSTS 'Developers' group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipsAADGroupUp");
            List <GraphMembership> membershipsOfGroup = graphClient.GetMembershipsAsync(parentGroupDescriptor, Microsoft.VisualStudio.Services.Graph.GraphTraversalDirection.Down.ToString()).Result; //Bug 967647: REST: GetMembershipsAsync shouldn't take direction as string, it should be the GraphTraversalDirection enum

            //
            // Part 8: Remove member from the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteMembershipAADGroup");
            graphClient.RemoveMembershipAsync(aadGroupDescriptor, parentGroupDescriptor).SyncResult();
            try
            {
                graphClient.CheckMembershipAsync(aadGroupDescriptor, parentGroupDescriptor).SyncResult();
            }
            catch (Exception e)
            {
                Context.Log("AAD Group is no longer a member of the group:" + e.Message);
            }

            //
            // Part 9: delete the groups
            //
            graphClient.DeleteGroupAsync(aadGroupDescriptor).SyncResult();
            graphClient.DeleteGroupAsync(parentGroupDescriptor).SyncResult();
        }
        public void AddRemoveUserMembership()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: create a group at the account level
            //

            GraphGroupCreationContext createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Developers-" + Guid.NewGuid(),
                Description = "Group created via client library"
            };

            GraphGroup newGroup        = graphClient.CreateGroupAsync(createGroupContext).Result;
            string     groupDescriptor = newGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);

            //
            // Part 2: add the user
            //

            GraphUserCreationContext addUserContext = new GraphUserPrincipalNameCreationContext
            {
                PrincipalName = "*****@*****.**"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 3: Make the user a member of the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateMembershipUser");
            GraphMembership graphMembership = graphClient.AddMembershipAsync(userDescriptor, groupDescriptor).Result;

            //
            // Part 4: get the membership
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipUser");
            graphMembership = graphClient.GetMembershipAsync(userDescriptor, groupDescriptor).Result;

            //
            // Part 5: Check to see if the user is a member of the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CheckMembershipUser");
            graphClient.CheckMembershipAsync(userDescriptor, groupDescriptor).SyncResult();

            //
            // Part 6: Get every group the subject(user) is a member of
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipsUserUp");
            List <GraphMembership> membershipsForUser = graphClient.GetMembershipsAsync(userDescriptor).Result;

            //
            // Part 7: Get every member of the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipsGroupDown");
            List <GraphMembership> membershipsOfGroup = graphClient.GetMembershipsAsync(groupDescriptor, Microsoft.VisualStudio.Services.Graph.GraphTraversalDirection.Down.ToString()).Result; //Bug 967647: REST: GetMembershipsAsync shouldn't take direction as string, it should be the GraphTraversalDirection enum

            //
            // Part 8: Remove member from the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteMembershipUser");
            graphClient.RemoveMembershipAsync(userDescriptor, groupDescriptor).SyncResult();
            try {
                graphClient.CheckMembershipAsync(userDescriptor, groupDescriptor).SyncResult();
            }
            catch (Exception e) {
                Context.Log("User is no longer a member of the group:" + e.Message);
            }

            //
            // Part 9: delete the group
            //

            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            //
            // Part 10: remove the user

            graphClient.DeleteUserAsync(userDescriptor).SyncResult();
            //
            // Try to get the deleted user
            try
            {
                newUser = graphClient.GetUserAsync(userDescriptor).Result;
                if (!newUser.Disabled)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
Beispiel #18
0
        public GitPush CreatePush()
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            // we will create a new push by making a small change to the default branch
            // first, find the default branch
            string defaultBranchName = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch);
            GitRef defaultBranch     = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First();

            // next, craft the branch and commit that we'll push
            GitRefUpdate newBranch = new GitRefUpdate()
            {
                Name        = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}",
                OldObjectId = defaultBranch.ObjectId,
            };
            string       newFileName = $"{GitSampleHelpers.ChooseItemsafeName()}.md";
            GitCommitRef newCommit   = new GitCommitRef()
            {
                Comment = "Add a sample file",
                Changes = new GitChange[]
                {
                    new GitChange()
                    {
                        ChangeType = VersionControlChangeType.Add,
                        Item       = new GitItem()
                        {
                            Path = $"/vsts-api-sample/{newFileName}"
                        },
                        NewContent = new ItemContent()
                        {
                            Content     = "# Thank you for using VSTS!",
                            ContentType = ItemContentType.RawText,
                        },
                    }
                },
            };

            // create the push with the new branch and commit
            GitPush push = gitClient.CreatePushAsync(new GitPush()
            {
                RefUpdates = new GitRefUpdate[] { newBranch },
                Commits    = new GitCommitRef[] { newCommit },
            }, repo.Id).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            Console.WriteLine("push {0} updated {1} to {2}",
                              push.PushId, push.RefUpdates.First().Name, push.Commits.First().CommitId);

            // now clean up after ourselves (and in case logging is on, don't log these calls)
            ClientSampleHttpLogger.SetSuppressOutput(this.Context, true);

            // delete the branch
            GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync(
                new GitRefUpdate[]
            {
                new GitRefUpdate()
                {
                    OldObjectId = push.RefUpdates.First().NewObjectId,
                    NewObjectId = new string('0', 40),
                    Name        = push.RefUpdates.First().Name,
                }
            },
                repositoryId: repo.Id).Result.First();

            // pushes and commits are immutable, so no way to clean them up
            // but the commit will be unreachable after this

            return(push);
        }
Beispiel #19
0
        public TeamProject CreateProject()
        {
            string projectName        = "Sample project " + Guid.NewGuid();
            string projectDescription = "Short description for my new project";
            string processName        = "Agile";

            // Setup version control properties
            Dictionary <string, string> versionControlProperties = new Dictionary <string, string>();

            versionControlProperties[TeamProjectCapabilitiesConstants.VersionControlCapabilityAttributeName] =
                SourceControlTypes.Git.ToString();

            // Setup process properties
            ProcessHttpClient processClient = Context.Connection.GetClient <ProcessHttpClient>();
            Guid processId = processClient.GetProcessesAsync().Result.Find(process => { return(process.Name.Equals(processName, StringComparison.InvariantCultureIgnoreCase)); }).Id;

            Dictionary <string, string> processProperaties = new Dictionary <string, string>();

            processProperaties[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityTemplateTypeIdAttributeName] =
                processId.ToString();

            // Construct capabilities dictionary
            Dictionary <string, Dictionary <string, string> > capabilities = new Dictionary <string, Dictionary <string, string> >();

            capabilities[TeamProjectCapabilitiesConstants.VersionControlCapabilityName] =
                versionControlProperties;
            capabilities[TeamProjectCapabilitiesConstants.ProcessTemplateCapabilityName] =
                processProperaties;

            // Construct object containing properties needed for creating the project
            TeamProject projectCreateParameters = new TeamProject()
            {
                Name         = projectName,
                Description  = projectDescription,
                Capabilities = capabilities
            };

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

            TeamProject project = null;

            try
            {
                Console.WriteLine("Queuing project creation...");

                // Queue the project creation operation
                // This returns an operation object that can be used to check the status of the creation
                OperationReference operation = projectClient.QueueCreateProject(projectCreateParameters).Result;

                ClientSampleHttpLogger.SetSuppressOutput(Context, true);

                // Check the operation status every 5 seconds (for up to 30 seconds)
                Operation completedOperation = WaitForLongRunningOperation(operation.Id, 5, 30).Result;

                // Check if the operation succeeded (the project was created) or failed
                if (completedOperation.Status == OperationStatus.Succeeded)
                {
                    // Get the full details about the newly created project
                    project = projectClient.GetProject(
                        projectCreateParameters.Name,
                        includeCapabilities: true,
                        includeHistory: true).Result;

                    Console.WriteLine();
                    Console.WriteLine("Project created (ID: {0})", project.Id);

                    // Save the newly created project (other sample methods will use it)
                    Context.SetValue <TeamProject>("$newProject", project);
                }
                else
                {
                    Console.WriteLine("Project creation operation failed: " + completedOperation.ResultMessage);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception during create project: ", ex.Message);
            }

            return(project);
        }
Beispiel #20
0
        public void GetDescriptorById()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: add the AAD user
            //
            Guid storageKey = new Guid("9b71f216-4c4f-6b74-a911-efb0fa9c777f");

            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOIDWithStorageKey");
            GraphUserCreationContext addAADUserContext = new GraphUserOriginIdCreationContext
            {
                OriginId   = "27dbfced-5593-4756-98a3-913c39af7612",
                StorageKey = storageKey
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 2: get the descriptor
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetDescriptorById");
            GraphDescriptorResult descriptor = graphClient.GetDescriptorAsync(storageKey).Result; //TODO: This is failing!!!!!

            try
            {
                if (descriptor.Value != userDescriptor)
                {
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                Context.Log("The descriptors don't match!");
            }

            //
            // Part 3: remove the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteUser");
            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipState");
            GraphMembershipState membershipState = graphClient.GetMembershipStateAsync(userDescriptor).Result;

            try
            {
                if (membershipState.Active)
                {
                    throw new Exception();
                }
            }
            catch (Exception e)
            {
                Context.Log("The deleted user is not disabled!");
            }
        }
        public GitPullRequest CreatePullRequestInner(bool cleanUp)
        {
            VssConnection connection = this.Context.Connection;
            GitHttpClient gitClient  = connection.GetClient <GitHttpClient>();

            TeamProjectReference project = ClientSampleHelpers.FindAnyProject(this.Context);
            GitRepository        repo    = GitSampleHelpers.FindAnyRepository(this.Context, project.Id);

            // we need a new branch with changes in order to create a PR
            // first, find the default branch
            string defaultBranchName = GitSampleHelpers.WithoutRefsPrefix(repo.DefaultBranch);
            GitRef defaultBranch     = gitClient.GetRefsAsync(repo.Id, filter: defaultBranchName).Result.First();

            // next, craft the branch and commit that we'll push
            GitRefUpdate newBranch = new GitRefUpdate()
            {
                Name        = $"refs/heads/vsts-api-sample/{GitSampleHelpers.ChooseRefsafeName()}",
                OldObjectId = defaultBranch.ObjectId,
            };
            string       newFileName = $"{GitSampleHelpers.ChooseItemsafeName()}.md";
            GitCommitRef newCommit   = new GitCommitRef()
            {
                Comment = "Add a sample file",
                Changes = new GitChange[]
                {
                    new GitChange()
                    {
                        ChangeType = VersionControlChangeType.Add,
                        Item       = new GitItem()
                        {
                            Path = $"/vsts-api-sample/{newFileName}"
                        },
                        NewContent = new ItemContent()
                        {
                            Content     = "# Thank you for using VSTS!",
                            ContentType = ItemContentType.RawText,
                        },
                    }
                },
            };

            // create the push with the new branch and commit
            GitPush push = gitClient.CreatePushAsync(new GitPush()
            {
                RefUpdates = new GitRefUpdate[] { newBranch },
                Commits    = new GitCommitRef[] { newCommit },
            }, repo.Id).Result;

            // finally, create a PR
            var pr = gitClient.CreatePullRequestAsync(new GitPullRequest()
            {
                SourceRefName = newBranch.Name,
                TargetRefName = repo.DefaultBranch,
                Title         = $"Add {newFileName} (from VSTS REST samples)",
                Description   = "Adding this file from the pull request samples",
            },
                                                      repo.Id).Result;

            Console.WriteLine("project {0}, repo {1}", project.Name, repo.Name);
            Console.WriteLine("{0} (#{1}) {2} -> {3}",
                              pr.Title.Substring(0, Math.Min(40, pr.Title.Length)),
                              pr.PullRequestId,
                              pr.SourceRefName,
                              pr.TargetRefName);

            if (cleanUp)
            {
                // clean up after ourselves (and in case logging is on, don't log these calls)
                ClientSampleHttpLogger.SetSuppressOutput(this.Context, true);

                // abandon the PR
                GitPullRequest updatedPr = new GitPullRequest()
                {
                    Status = PullRequestStatus.Abandoned,
                };
                pr = gitClient.UpdatePullRequestAsync(updatedPr, repo.Id, pr.PullRequestId).Result;

                // delete the branch
                GitRefUpdateResult refDeleteResult = gitClient.UpdateRefsAsync(
                    new GitRefUpdate[]
                {
                    new GitRefUpdate()
                    {
                        OldObjectId = push.RefUpdates.First().NewObjectId,
                        NewObjectId = new string('0', 40),
                        Name        = push.RefUpdates.First().Name,
                    }
                },
                    repositoryId: repo.Id).Result.First();
            }

            return(pr);
        }
Beispiel #22
0
        public void AddRemoveAADUserByUPNToGroup()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: create a group at the account level
            //
            GraphGroupCreationContext createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Developers-" + Guid.NewGuid(),
                Description = "Group created via client library"
            };

            GraphGroup newVSTSGroup = graphClient.CreateGroupAsync(createGroupContext).Result;
            IEnumerable <VisualStudio.Services.Common.SubjectDescriptor> parentGroup = new List <VisualStudio.Services.Common.SubjectDescriptor>()
            {
                newVSTSGroup.Descriptor
            };
            string groupDescriptor = newVSTSGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);

            //
            // Part 2: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOIDAsMember");
            GraphUserCreationContext addAADUserContext = new GraphUserPrincipalNameCreationContext
            {
                PrincipalName = "*****@*****.**"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext, parentGroup).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 3: get the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetUser-AddRemoveAADUserByUPNToGroup");
            newUser = graphClient.GetUserAsync(userDescriptor).Result;

            //
            // Part 4: remove the user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteUser-AddRemoveAADUserByUPNToGroup");
            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipState-AddRemoveAADUserByUPNToGroup");
            GraphMembershipState membershipState = graphClient.GetMembershipStateAsync(userDescriptor).Result;

            try
            {
                if (membershipState.Active)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }

            // Part 5: remove the group
            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            // Try to get the deleted group
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetMembershipStateAADGroup");
            membershipState = graphClient.GetMembershipStateAsync(groupDescriptor).Result;
            try
            {
                if (membershipState.Active)
                {
                    throw new Exception();
                }
            }
            catch (Exception)
            {
                Context.Log("The deleted group is not disabled!");
            }
        }
Beispiel #23
0
        public void AddRemoveAADUserByUPNToGroup()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: create a group at the account level
            //
            GraphGroupCreationContext createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Developers-" + Guid.NewGuid(),
                Description = "Group created via client library"
            };

            GraphGroup newVSTSGroup = graphClient.CreateGroupAsync(createGroupContext).Result;
            IEnumerable <VisualStudio.Services.Common.SubjectDescriptor> parentGroup = new List <VisualStudio.Services.Common.SubjectDescriptor>()
            {
                newVSTSGroup.Descriptor
            };
            string groupDescriptor = newVSTSGroup.Descriptor;

            Context.Log("New group created! ID: {0}", groupDescriptor);

            //
            // Part 2: add the AAD user
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADUserByOIDAsMember");
            GraphUserCreationContext addAADUserContext = new GraphUserPrincipalNameCreationContext
            {
                PrincipalName = "*****@*****.**"
            };

            GraphUser newUser        = graphClient.CreateUserAsync(addAADUserContext, parentGroup).Result;
            string    userDescriptor = newUser.Descriptor;

            Context.Log("New user added! ID: {0}", userDescriptor);

            //
            // Part 3: get the user
            //
            //newUser = graphClient.GetUserAsync(userDescriptor).Result;  //BUG ???: {"TF14045: The identity with type 'Microsoft.IdentityModel.Claims.ClaimsIdentity' and identifier '45aa3d2d-7442-473d-b4d3-3c670da9dd96\\[email protected]' could not be found."}

            //
            // Part 4: remove the user
            //

            graphClient.DeleteUserAsync(userDescriptor).SyncResult();

            // Try to get the deleted user
            try
            {
                newUser = graphClient.GetUserAsync(userDescriptor).Result;
                // TODO: if (!newUser.Disabled) throw new Exception();
            }
            catch (Exception)
            {
                Context.Log("The deleted user is not disabled!");
            }

            // Part 5: remove the group
            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();
        }