Beispiel #1
0
        private static List <AadGroupMember> ExpandAadGroups(string accessToken, GraphGroup group)
        {
            //List of users in an AAD group
            List <AadGroupMember> aadUsers = new List <AadGroupMember>();

            //Getting all members in all groups and nesteed groups
            List <AadGroupMember> members = new List <AadGroupMember>();

            members.AddRange(GetAADGroupMembers(accessToken, group.OriginId));
            while (members.Count != 0)
            {
                List <AadGroupMember> nestedGroups = new List <AadGroupMember>();
                foreach (var aadMember in members)
                {
                    switch (aadMember.type)
                    {
                    //member is a user
                    case "#microsoft.graph.user":
                        aadUsers.Add(aadMember);
                        break;

                    //member is a nested AAD group
                    case "#microsoft.graph.group":
                        nestedGroups.AddRange(GetAADGroupMembers(accessToken, aadMember.id));
                        break;

                    default:
                        throw new Exception("shouldn't be here");
                    }
                }
                members.Clear();
                members.AddRange(nestedGroups);
            }
            return(aadUsers);
        }
Beispiel #2
0
        public static async Task <GraphGroup> CreateGroup(GroupRequest request)
        {
            var uriEndPoint = $"{Constants.ResourceUrl}/{Constants.GraphApiVersion}/groups";

            GraphResponse <GraphGroup> result = null;
            var group = new GraphGroup()
            {
                Description = request.AccountId,
                DisplayName = request.AccountName,
                GroupTypes  = new List <string>()
                {
                    "Unified"
                },
                MailEnabled     = true,
                MailNickname    = request.AccountId,
                SecurityEnabled = false
            };

            // Create group with Graph API
            result = await Client.GetData <GraphGroup>(HttpMethod.Post, uriEndPoint, group).ConfigureAwait(false);

            if (!result.IsSuccessfull)
            {
                throw new Exception($"Error: group not created - API error: {result.Message}");
            }

            return(result.Data);
        }
Beispiel #3
0
 protected void LogGroup(GraphGroup group)
 {
     Context.Log(" {0} {1} {2}",
                 group.Descriptor.ToString().PadRight(8),
                 group.DisplayName.PadRight(20),
                 group.Description.PadRight(60));
 }
Beispiel #4
0
        public static string createUnifiedGroup(string token, string data, TraceWriter log)
        {
            string     endPoint           = "https://graph.microsoft.com/v1.0/groups/";
            string     contenType         = "application/json";
            string     responseFromServer = requestPost(token, endPoint, data, log, contenType);
            GraphGroup group = JsonConvert.DeserializeObject <GraphGroup>(responseFromServer);

            return(group.id);
        }
Beispiel #5
0
        public static string createTeamFromUnifiedGroup(string token, string data, string groupId)
        {
            string     endPoint           = "https://graph.microsoft.com/v1.0/groups/" + groupId + "/team";
            string     contenType         = "application/json";
            string     responseFromServer = requestPut(token, endPoint, data, contenType);
            GraphGroup group = JsonConvert.DeserializeObject <GraphGroup>(responseFromServer);

            return(group.id);
        }
        private static GroupMemberships ExpandVSTSGroup(GraphHttpClient graphClient, GraphGroup group)
        {
            groupCache.TryGetValue(group, out GroupMemberships groupMemberships);
            if (groupMemberships != null)
            {
                return(groupMemberships);
            }
            groupMemberships = new GroupMemberships();

            // Convert all memberships into GraphSubjectLookupKeys
            List <GraphSubjectLookupKey> lookupKeys  = new List <GraphSubjectLookupKey>();
            List <GraphMembership>       memberships = graphClient.ListMembershipsAsync(group.Descriptor, GraphTraversalDirection.Down).Result;

            foreach (var membership in memberships)
            {
                lookupKeys.Add(new GraphSubjectLookupKey(membership.MemberDescriptor));
            }
            IReadOnlyDictionary <SubjectDescriptor, GraphSubject> subjectLookups = graphClient.LookupSubjectsAsync(new GraphSubjectLookup(lookupKeys)).Result;

            foreach (GraphSubject subject in subjectLookups.Values)
            {
                if (subject.OriginId.Equals(group.OriginId))
                {
                    break;                                          //Father paradox
                }
                switch (subject.Descriptor.SubjectType)
                {
                //member is an AAD user
                case "aad":
                    groupMemberships.AddUser((GraphUser)subject);
                    break;

                //member is an MSA user
                case "asd2":
                    groupMemberships.AddUser((GraphUser)subject);
                    break;

                //member is a nested AAD group
                case "aadgp":
                    groupMemberships.AddAADGroup((GraphGroup)subject);
                    break;

                //member is a nested VSTS group
                case "vssgp":
                    GroupMemberships subGroupMemberships = ExpandVSTSGroup(graphClient, (GraphGroup)subject);
                    groupMemberships.Add(subGroupMemberships);
                    break;

                default:
                    throw new Exception("Unknown SubjectType: " + subject.Descriptor.SubjectType);
                }
            }

            groupCache.Add(group, groupMemberships);
            return(groupMemberships);
        }
        public void AddRemoveAADGroupByOIDAsMemberOfVSTSGroup()
        {
            // Get the client
            VssConnection   connection  = Context.Connection;
            GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

            //
            // Part 1: create the VSTS group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateVSTSGroup");
            GraphGroupCreationContext createVSTSGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Developers-" + Guid.NewGuid(),
                Description = "Group created via client library"
            };

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

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

            GraphGroupCreationContext addAADGroupContext = new GraphGroupOriginIdCreationContext
            {
                OriginId = "7dee3381-2ec2-41c2-869a-7afe9b574095"
            };

            ClientSampleHttpLogger.SetOperationName(this.Context, "MaterializeAADGroupByOIDAsMember");
            GraphGroup addedAADGroup      = graphClient.CreateGroupAsync(addAADGroupContext, null, parentGroup).Result;
            string     aadGroupDescriptor = addedAADGroup.Descriptor;

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

            //
            // Part 3: get the AAD group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetGroup-AddRemoveAADGroupByOIDAsMemberOfVSTSGroup");
            GraphGroup newGroup = graphClient.GetGroupAsync(aadGroupDescriptor).Result;

            //
            // Part 4: remove the AAD group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteAADGroup-AddRemoveAADGroupByOIDAsMemberOfVSTSGroup");
            graphClient.DeleteGroupAsync(aadGroupDescriptor).SyncResult();

            //
            // Part 5: delete the VSTS group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteVSTSGroup-AddRemoveAADGroupByOIDAsMemberOfVSTSGroup");
            graphClient.DeleteGroupAsync(vstsGroupDescriptor).SyncResult();
        }
Beispiel #8
0
        public void CreateDeleteProjectVSTSGroup()
        {
            // Get the client
            VssConnection connection = Context.Connection;

            //
            // Part 1: get the project id
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetProjectId");
            ProjectHttpClient projectClient = connection.GetClient <ProjectHttpClient>();
            string            projectName   = ClientSampleHelpers.FindAnyProject(this.Context).Name;
            TeamProject       project       = projectClient.GetProject(projectName, includeCapabilities: true, includeHistory: true).Result;
            Guid projectId = project.Id;

            //
            // Part 2: get the project scope descriptor
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetProjectScopeDescriptor");
            GraphHttpClient       graphClient       = connection.GetClient <GraphHttpClient>();
            GraphDescriptorResult projectDescriptor = graphClient.GetDescriptorAsync(projectId).Result;

            //
            // Part 3: create a group at the project level
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "CreateGroupInProject");
            GraphGroupCreationContext createGroupContext = new GraphGroupVstsCreationContext
            {
                DisplayName = "Project Developers-" + Guid.NewGuid(),
                Description = "Group at project level created via client library"
            };

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

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

            //
            // Part 4: delete the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteGroup");
            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            // Try to get the deleted group (should result in an exception)
            ClientSampleHttpLogger.SetOperationName(this.Context, "GetDisabledGroup");
            try
            {
                newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;
            }
            catch (Exception e)
            {
                Context.Log("Unable to get the deleted group:" + e.Message);
            }
        }
Beispiel #9
0
        public void CreateUpdateDeleteVSTSGroup()
        {
            // 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, "CreateGroup");
            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: update the description attribute for the group
            //
            ClientSampleHttpLogger.SetOperationName(this.Context, "UpdateGroup");
            Microsoft.VisualStudio.Services.WebApi.Patch.Json.JsonPatchDocument patchDocument = VssJsonPatchDocumentFactory.ConstructJsonPatchDocument(VisualStudio.Services.WebApi.Patch.Operation.Replace, Constants.GroupUpdateFields.Description, "Updated description");
            GraphGroup updatedGroup     = graphClient.UpdateGroupAsync(groupDescriptor, patchDocument).Result;
            string     groupDescription = updatedGroup.Description;

            Context.Log("Updated group description: {0}", groupDescription);

            //
            // Part 3: delete the group
            //

            ClientSampleHttpLogger.SetOperationName(this.Context, "DeleteGroup");
            graphClient.DeleteGroupAsync(groupDescriptor).SyncResult();

            // Try to get the deleted group (should result in an exception)
            try
            {
                ClientSampleHttpLogger.SetOperationName(this.Context, "GetDisabledGroup");
                newGroup = graphClient.GetGroupAsync(groupDescriptor).Result;
            }
            catch (Exception e)
            {
                Context.Log("Unable to get the deleted group:" + e.Message);
            }
        }
Beispiel #10
0
        //================ VSTS graph api helper code ===========================================================

        private static GraphGroup GetGraphGroupFromString(GraphHttpClient graphClient, string groupDisplayname)
        {
            PagedGraphGroups groups = graphClient.GetGroupsAsync().Result;

            GraphGroup selectedGroup = null;

            foreach (var group in groups.GraphGroups)
            {
                if (group.DisplayName.Equals(groupDisplayName))
                {
                    return(selectedGroup = group);
                }
            }
            return(null);
        }
        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 #12
0
        private static GroupMemberships ExpandVSTSGroup(GraphHttpClient graphClient, GraphGroup group)
        {
            GroupMemberships groupMemberships = new GroupMemberships();

            // Convert all memberships into GraphSubjectLookupKeys
            List <GraphSubjectLookupKey> lookupKeys  = new List <GraphSubjectLookupKey>();
            List <GraphMembership>       memberships = graphClient.GetMembershipsAsync(group.Descriptor, Microsoft.VisualStudio.Services.Graph.GraphTraversalDirection.Down).Result;

            foreach (var membership in memberships)
            {
                lookupKeys.Add(new GraphSubjectLookupKey(membership.MemberDescriptor));
            }
            IReadOnlyDictionary <SubjectDescriptor, GraphSubject> subjectLookups = graphClient.LookupSubjectsAsync(new GraphSubjectLookup(lookupKeys)).Result;

            foreach (GraphSubject subject in subjectLookups.Values)
            {
                switch (subject.Descriptor.SubjectType)
                {
                //member is an AAD user
                case Constants.SubjectType.AadUser:
                    groupMemberships.AddUser((GraphUser)subject);
                    break;

                //member is an MSA user
                case Constants.SubjectType.MsaUser:
                    groupMemberships.AddUser((GraphUser)subject);
                    break;

                //member is a nested AAD group
                case Constants.SubjectType.AadGroup:
                    groupMemberships.AddAADGroup((GraphGroup)subject);
                    break;

                //member is a nested VSTS group
                case Constants.SubjectType.VstsGroup:
                    GroupMemberships subGroupMemberships = ExpandVSTSGroup(graphClient, (GraphGroup)subject);
                    groupMemberships.Add(subGroupMemberships);
                    break;

                default:
                    throw new Exception("Unknown SubjectType: " + subject.Descriptor.SubjectType);
                }
            }

            return(groupMemberships);
        }
Beispiel #13
0
        public ActionResult CountCommentsOfPostsGraph()
        {
            // graph counting comments of posts diveded to ranges
            int[] RangesArrayConunt = new int[5];

            var posts = db.Posts.Select(p => p.Comments.Count).ToArray();

            foreach (var item in posts)
            {
                if (item <= RANGES[0])
                {
                    RangesArrayConunt[0]++;
                }
                else if (item <= RANGES[1] && item > RANGES[0])
                {
                    RangesArrayConunt[1]++;
                }
                else if (item <= RANGES[2] && item > RANGES[1])
                {
                    RangesArrayConunt[2]++;
                }
                else if (item <= RANGES[3] && item > RANGES[2])
                {
                    RangesArrayConunt[3]++;
                }
                else if (item <= RANGES[4] && item > RANGES[3])
                {
                    RangesArrayConunt[4]++;
                }
            }

            List <Models.GraphGroup> l = new List <Models.GraphGroup>();

            GraphGroup firstNode = new GraphGroup("0 - " + RANGES[0].ToString(), RangesArrayConunt[0].ToString(), "");

            l.Add(firstNode);
            for (int i = 1; i < GraphGroupNumber - 1; i++)
            {
                GraphGroup groupToAdd = new GraphGroup(RANGES[i - 1].ToString() + " - " + RANGES[i].ToString(), RangesArrayConunt[i].ToString(), "");
                l.Add(groupToAdd);
            }
            GraphGroup lastNode = new GraphGroup(RANGES[GraphGroupNumber - 1].ToString() + "+", RangesArrayConunt[GraphGroupNumber - 1].ToString(), "");

            return(Json(l, JsonRequestBehavior.AllowGet));
        }
        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);
            }
        }
        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 #16
0
        internal const string graphResourceId = "https://graph.microsoft.com";          //Constant value to target Microsoft Graph API. Do not change

        public static void Main(string[] args)
        {
            AuthenticationContext ctx    = GetAuthenticationContext(null);
            AuthenticationResult  result = null;

            try
            {
                //PromptBehavior.RefreshSession will enforce an authn prompt every time. NOTE: Auto will take your windows login state if possible
                result = ctx.AcquireTokenAsync(VstsResourceId, clientId, new Uri(replyUri), new PlatformParameters(PromptBehavior.Always)).Result;

                //connect to VSTS Graph API with ADAL access token
                VssConnection   connection  = new VssConnection(new Uri(vstsCollectionUrl), new VssOAuthAccessTokenCredential(result.AccessToken));
                GraphHttpClient graphClient = connection.GetClient <GraphHttpClient>();

                //get the VSTS group
                GraphGroup group = GetGraphGroupFromString(graphClient, groupDisplayName);

                //Loop through VSTS group and return all nested users and AAD groups underneath "groupDisplayName" group
                Tuple <List <GraphUser>, List <GraphGroup> > usersAndAadGroups = ExpandVstsGroup(graphClient, group);
                List <GraphUser>  vstsGroupUsers = usersAndAadGroups.Item1;
                List <GraphGroup> aadGroups      = usersAndAadGroups.Item2;

                //exchange VSTS token for Microsoft graph token
                AuthenticationResult graphAuthResult = ctx.AcquireTokenAsync(graphResourceId, clientId, new Uri(replyUri), new PlatformParameters(PromptBehavior.Auto)).Result;

                //use Microsoft graph token to return all users in AAD Groups
                List <AadGroupMember> aadGroupUsers = ExpandAadGroups(graphAuthResult.AccessToken, aadGroups);

                //print vsts and aad user lists to console
                foreach (GraphUser vstsGroupUser in vstsGroupUsers)
                {
                    Console.WriteLine(vstsGroupUser.PrincipalName);
                }
                foreach (AadGroupMember aadGroupUser in aadGroupUsers)
                {
                    Console.WriteLine(aadGroupUser.userPrincipalName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("{0}: {1}", ex.GetType(), ex.Message);
            }
        }
Beispiel #17
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 #18
0
        public List <string> RunEnumerateMembersOfGroupsUsingClientLib(string groupDisplayName)
        {
            Uri uri = new Uri(_uri);
            AuthenticationContext ctx            = GetAuthenticationContext(null);
            AuthenticationResult  vstsAuthResult = ctx.AcquireTokenAsync(VSTSResourceId, _clientId.ToString(), _replyUrl, new PlatformParameters(PromptBehavior.Always)).Result;
            VssConnection         vssConnection  = new VssConnection(new Uri(_uri), new VssOAuthAccessTokenCredential(vstsAuthResult.AccessToken));

            using (GraphHttpClient graphClient = vssConnection.GetClient <GraphHttpClient>())
            {
                // Get the VSTS group
                GraphGroup group = GetVSTSGroupByDisplayName(graphClient, groupDisplayName);

                // Expand membership of the VSTS group to users and AAD Groups
                GroupMemberships groupMemberships = ExpandVSTSGroup(graphClient, group);

                List <string> expandedUsers = new List <string>();
                foreach (GraphUser user in groupMemberships.Users)
                {
                    expandedUsers.Add(user.PrincipalName);
                }

                //exchange VSTS token for Microsoft graph token
                AuthenticationResult graphAuthResult = ctx.AcquireTokenAsync(GraphResourceId, _clientId.ToString(), _replyUrl, new PlatformParameters(PromptBehavior.Auto)).Result;

                // Resolve all AAD Groups to users using Microsoft graph
                foreach (GraphGroup AADGroup in groupMemberships.AADGroups)
                {
                    List <AadGroupMember> aadGroupUsers = ExpandAadGroups(graphAuthResult.AccessToken, AADGroup);
                    foreach (AadGroupMember aadGroupUser in aadGroupUsers)
                    {
                        expandedUsers.Add(aadGroupUser.userPrincipalName);
                    }
                }

                return(expandedUsers);
            }
        }
Beispiel #19
0
        public List <string> RunEnumerateEnumerateGroupMembershipsUsingClientLib(List <GraphUser> users)
        {
            Uri uri = new Uri(_uri);
            VssBasicCredential credentials = new VssBasicCredential("", _personalAccessToken);

            using (GraphHttpClient graphClient = new GraphHttpClient(uri, credentials))
            {
                List <string> memberships = new List <string>();

                foreach (GraphUser user in users)
                {
                    List <GraphMembership> groupMemberships = graphClient.GetMembershipsAsync(user.Descriptor).Result;
                    foreach (GraphMembership membership in groupMemberships)
                    {
                        GraphGroup resolvedGroup = graphClient.GetGroupAsync(membership.ContainerDescriptor).Result;
                        memberships.Add(String.Format("{0}:{1} --> {2}:{3}", user.DisplayName, user.PrincipalName, resolvedGroup.Origin, resolvedGroup.DisplayName));
                    }
                }

                return(memberships);
            }

            return(null);
        }
        //private List<ColumnSizeLocation> GetColumnsSizeLocation()
        //{
        //    List<ColumnSizeLocation> result = new List<ColumnSizeLocation>();

        //    int widthUnits = 0;
        //    var columns = ChartReportReportDTO.EntityListView.EntityListViewAllColumns.Where(x => x.RelationshipTailID == 0);
        //    foreach (var column in columns)
        //    {
        //        widthUnits += (column.WidthUnit == 0 ? 1 : column.WidthUnit);
        //    }
        //    var width = reportWidth;
        //    var perUnitWidth = width.Divide(widthUnits);
        //    var consumedWidthUnits = 0;


        //    if (ReportGroups != null)
        //        foreach (var reportGroup in ReportGroups)
        //        {
        //            ColumnSizeLocation columnSizeLocation = new ColumnSizeLocation();
        //            columnSizeLocation.LictViewColumnID = reportGroup.ListViewColumnID;
        //            SetColumnSizePosition(columnSizeLocation, reportGroup.EntityListViewColumn.WidthUnit, ref consumedWidthUnits, perUnitWidth);
        //            result.Add(columnSizeLocation);

        //        }
        //    foreach (var column in columns)
        //    {
        //        if (!result.Any(x => x.LictViewColumnID == column.ID))
        //        {
        //            ColumnSizeLocation columnSizeLocation = new ColumnSizeLocation();
        //            columnSizeLocation.LictViewColumnID = column.ID;
        //            SetColumnSizePosition(columnSizeLocation, column.WidthUnit, ref consumedWidthUnits, perUnitWidth);
        //            result.Add(columnSizeLocation);
        //        }
        //    }
        //    return result;
        //}
        //private void SetColumnSizePosition(ColumnSizeLocation columnSizeLocation, int currentWidthUnits, ref int consumedWidthUnits, Unit perUnitWidth)
        //{
        //    if (currentWidthUnits == 0)
        //        currentWidthUnits = 1;

        //    var width = currentWidthUnits * perUnitWidth;
        //    columnSizeLocation.Width = width;

        //    var xlocation = (reportWidth - width) - consumedWidthUnits * perUnitWidth;
        //    columnSizeLocation.XLocation = xlocation;


        //    consumedWidthUnits += currentWidthUnits;

        //}
        private Tuple <Report, Graph> SetReportDetails(Report report)
        {
            var detail = new Telerik.Reporting.DetailSection();

            detail.Height = Telerik.Reporting.Drawing.Unit.Cm(0.5);
            detail.Name   = "detail";

            ReportStyles.SetReportDetailStyle(detail.Style);
            report.Items.Add(detail);


            var graph = new Graph();

            graph.Width  = reportWidth;
            graph.Height = report.PageSettings.PaperSize.Height / 2;
            //reportWidth = report.Width;
            detail.Items.Add(graph);

            graph.Legend.Width            = Unit.Cm(3);
            graph.Legend.Style.LineColor  = System.Drawing.Color.LightGray;
            graph.Legend.Style.LineWidth  = Telerik.Reporting.Drawing.Unit.Inch(0D);
            graph.PlotAreaStyle.LineColor = System.Drawing.Color.LightGray;
            graph.PlotAreaStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Inch(0D);
            //graph.Size = new Telerik.Reporting.Drawing.SizeU(Telerik.Reporting.Drawing.Unit.Inch(6D), Telerik.Reporting.Drawing.Unit.Inch(3D));

            GraphAxis categoryAxis = new GraphAxis();

            categoryAxis.MajorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            categoryAxis.MajorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            categoryAxis.MinorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            categoryAxis.MinorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            categoryAxis.MinorGridLineStyle.Visible   = false;
            categoryAxis.Scale = new CategoryScale();

            GraphAxis valueAxis = new GraphAxis();

            valueAxis.MajorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            valueAxis.MajorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            valueAxis.MinorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            valueAxis.MinorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            valueAxis.MinorGridLineStyle.Visible   = false;
            valueAxis.Scale = new NumericalScale();

            var cartesianCoordinateSystem1 = new CartesianCoordinateSystem();

            cartesianCoordinateSystem1.Name  = "cartesianCoordinateSystem1";
            cartesianCoordinateSystem1.XAxis = categoryAxis;
            cartesianCoordinateSystem1.YAxis = valueAxis;
            graph.CoordinateSystems.Add(cartesianCoordinateSystem1);

            var categoryColumn = ChartReportReportDTO.EntityChartReportCategories.First();
            var categoryGroup  = new GraphGroup();

            categoryGroup.Name = categoryColumn.EntityListViewColumn.RelativeColumnName;
            categoryGroup.Groupings.Add(new Grouping(string.Format("= Fields.{0}", categoryColumn.EntityListViewColumn.RelativeColumnName)));
            categoryGroup.Sortings.Add(new Telerik.Reporting.Sorting(string.Format("= Fields.{0}", categoryColumn.EntityListViewColumn.RelativeColumnName), Telerik.Reporting.SortDirection.Asc));
            graph.CategoryGroups.Add(categoryGroup);

            foreach (var column in ChartReportReportDTO.EntityChartReportSeries)
            {
                foreach (var valuecolumn in ChartReportReportDTO.EntityChartReportValues)
                {
                    var barSeries = new Telerik.Reporting.BarSeries();
                    //if (column.EntityListViewColumnID == categoryColumn.EntityListViewColumnID)
                    //    barSeries.ArrangeMode = GraphSeriesArrangeMode.Overlapped;
                    //else
                    //{
                    if (column.ArrangeType == ChartSerieArrangeType.Clustered)
                    {
                        barSeries.ArrangeMode = GraphSeriesArrangeMode.Clustered;
                    }
                    else if (column.ArrangeType == ChartSerieArrangeType.Overlapped)
                    {
                        barSeries.ArrangeMode = GraphSeriesArrangeMode.Overlapped;
                    }
                    else if (column.ArrangeType == ChartSerieArrangeType.Stacked)
                    {
                        barSeries.ArrangeMode = GraphSeriesArrangeMode.Stacked;
                    }
                    else if (column.ArrangeType == ChartSerieArrangeType.Stacked100)
                    {
                        barSeries.ArrangeMode = GraphSeriesArrangeMode.Stacked100;
                    }
                    //}

                    barSeries.ToolTip.Text  = string.Format("= {0}(Fields.{1})", valuecolumn.FunctionType.ToString(), valuecolumn.EntityListViewColumn.RelativeColumnName);
                    barSeries.ToolTip.Title = string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName);
                    barSeries.Y             = string.Format("= {0}(Fields.{1})", valuecolumn.FunctionType.ToString(), valuecolumn.EntityListViewColumn.RelativeColumnName);



                    //categoryGroup.Groupings.Add(new Telerik.Reporting.Grouping());
                    //ChartSeries

                    var serieGroup = new GraphGroup();
                    serieGroup.Name = column.EntityListViewColumn.RelativeColumnName;
                    serieGroup.Groupings.Add(new Telerik.Reporting.Grouping(string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName)));
                    serieGroup.Sortings.Add(new Telerik.Reporting.Sorting(string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName), Telerik.Reporting.SortDirection.Asc));
                    graph.SeriesGroups.Add(serieGroup);

                    barSeries.SeriesGroup   = serieGroup;
                    barSeries.CategoryGroup = categoryGroup;

                    barSeries.CoordinateSystem            = cartesianCoordinateSystem1;
                    barSeries.DataPointLabel              = string.Format("= {0}(Fields.{1})", valuecolumn.FunctionType.ToString(), valuecolumn.EntityListViewColumn.RelativeColumnName);
                    barSeries.DataPointLabelStyle.Visible = true;
                    barSeries.DataPointStyle.LineWidth    = Telerik.Reporting.Drawing.Unit.Cm(0);
                    barSeries.DataPointStyle.Visible      = true;
                    barSeries.LegendItem.Value            = string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName);

                    graph.Series.Add(barSeries);
                }
            }

            return(new Tuple <Report, Graph>(report, graph));
        }
        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 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!");
            }
        }
        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();
        }
 private void CreatePermissionList(List <Permission> permissions, Dictionary <int, string> permission, string repositoryName, KeyValuePair <Microsoft.VisualStudio.Services.Identity.IdentityDescriptor, AccessControlEntry> kvp, GraphUser user, GraphGroup group = null)
 {
     foreach (var allow in GetPermissionString(kvp.Value.Allow, permission))
     {
         permissions.Add(new Permission
         {
             Repository = repositoryName,
             Name       = user?.DisplayName,
             Allow      = allow,
             ID         = user.Descriptor.Identifier,
             Group      = group?.DisplayName
         });
     }
     foreach (var deny in GetPermissionString(kvp.Value.Deny, permission))
     {
         permissions.Add(new Permission
         {
             Repository = repositoryName,
             Name       = user?.DisplayName,
             Deny       = deny,
             ID         = user.Descriptor.Identifier,
             Group      = group?.DisplayName
         });
     }
 }
Beispiel #25
0
        private static Tuple <List <GraphUser>, List <GraphGroup> > ExpandVstsGroup(GraphHttpClient graphClient, GraphGroup group)
        {
            //List of user principle names
            List <GraphUser> users = new List <GraphUser>();
            //List of Graph subjects for AAD groups
            List <GraphGroup> aadGroups = new List <GraphGroup>();

            List <GraphMembership> memberships = graphClient.GetMembershipsAsync(group.Descriptor, Microsoft.VisualStudio.Services.Graph.GraphTraversalDirection.Down).Result;

            while (memberships.Count != 0)
            {
                List <GraphSubjectLookupKey> lookupKeys = new List <GraphSubjectLookupKey>();
                foreach (var membership in memberships)
                {
                    lookupKeys.Add(new GraphSubjectLookupKey(membership.MemberDescriptor));
                }
                memberships.Clear();
                IReadOnlyDictionary <SubjectDescriptor, GraphSubject> memberDict = graphClient.LookupSubjectsAsync(new GraphSubjectLookup(lookupKeys)).Result;
                foreach (GraphSubject member in memberDict.Values)
                {
                    switch (member.Descriptor.SubjectType)
                    {
                    //member is an AAD user
                    case Constants.SubjectType.AadUser:
                        users.Add((GraphUser)member);
                        break;

                    //member is an MSA user
                    case Constants.SubjectType.MsaUser:
                        users.Add((GraphUser)member);
                        break;

                    //member is a nested AAD group
                    case Constants.SubjectType.AadGroup:
                        aadGroups.Add((GraphGroup)member);
                        break;

                    //member is a nested VSTS group
                    case Constants.SubjectType.VstsGroup:
                        memberships.AddRange(graphClient.GetMembershipsAsync(member.Descriptor, Microsoft.VisualStudio.Services.Graph.GraphTraversalDirection.Down).Result);
                        break;

                    default:
                        throw new Exception("shouldn't be here");
                    }
                }
            }
            return(new Tuple <List <GraphUser>, List <GraphGroup> >(users, aadGroups));
        }
        private void AddByGroup(List <Permission> permissions, GraphHttpClient graphClient, Dictionary <int, string> permission, string repositoryName, KeyValuePair <Microsoft.VisualStudio.Services.Identity.IdentityDescriptor, AccessControlEntry> kvp, GraphGroup group)
        {
            GroupMemberships expandedMembers = ExpandVSTSGroup(graphClient, group);

            foreach (var user in expandedMembers.Users)
            {
                CreatePermissionList(permissions, permission, repositoryName, kvp, user, group);
            }
        }
Beispiel #27
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 #28
0
 public void AddAADGroup(GraphGroup group)
 {
     this.AADGroups.Add(group);
 }
Beispiel #29
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();
        }
Beispiel #30
0
        private Tuple <Report, Graph> SetReportDetails(Report report)
        {
            var detail = new Telerik.Reporting.DetailSection();

            detail.Height = Telerik.Reporting.Drawing.Unit.Cm(0.5);
            detail.Name   = "detail";

            ReportStyles.SetReportDetailStyle(detail.Style);
            report.Items.Add(detail);


            var graph = new Graph();

            graph.Name   = "graph1";
            graph.Width  = reportWidth;
            graph.Height = report.PageSettings.PaperSize.Height / 2;
            //reportWidth = report.Width;
            detail.Items.Add(graph);

            graph.Legend.Width            = Unit.Cm(5);
            graph.Legend.Style.LineColor  = System.Drawing.Color.LightGray;
            graph.Legend.Style.LineWidth  = Telerik.Reporting.Drawing.Unit.Inch(0D);
            graph.PlotAreaStyle.LineColor = System.Drawing.Color.LightGray;
            graph.PlotAreaStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Inch(0D);
            //graph.Size = new Telerik.Reporting.Drawing.SizeU(Telerik.Reporting.Drawing.Unit.Inch(6D), Telerik.Reporting.Drawing.Unit.Inch(3D));


            CategoryScale categoryScale1 = new CategoryScale();

            categoryScale1.PositionMode     = Telerik.Reporting.AxisPositionMode.OnTicks;
            categoryScale1.SpacingSlotCount = 0D;

            GraphAxis categoryAxis = new GraphAxis();
            GraphAxis valueAxis    = new GraphAxis();

            var polarCoordinateSystem = new PolarCoordinateSystem();

            polarCoordinateSystem.AngularAxis = valueAxis;
            polarCoordinateSystem.RadialAxis  = categoryAxis;
            graph.CoordinateSystems.Add(polarCoordinateSystem);



            categoryAxis.MajorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            categoryAxis.MajorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            categoryAxis.MajorGridLineStyle.Visible   = false;
            categoryAxis.MinorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            categoryAxis.MinorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            categoryAxis.MinorGridLineStyle.Visible   = false;
            categoryAxis.Name               = "graphAxis2";
            categoryScale1.PositionMode     = Telerik.Reporting.AxisPositionMode.OnTicks;
            categoryScale1.SpacingSlotCount = 0D;
            categoryAxis.Scale              = categoryScale1;
            categoryAxis.Style.Visible      = false;


            valueAxis.MajorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            valueAxis.MajorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            valueAxis.MajorGridLineStyle.Visible   = false;
            valueAxis.MinorGridLineStyle.LineColor = System.Drawing.Color.LightGray;
            valueAxis.MinorGridLineStyle.LineWidth = Telerik.Reporting.Drawing.Unit.Pixel(1D);
            valueAxis.MinorGridLineStyle.Visible   = false;
            valueAxis.Name          = "graphAxis1";
            valueAxis.Scale         = new NumericalScale();;
            valueAxis.Style.Visible = false;



            var valuecolumn = ChartReportReportDTO.EntityChartReportValues.First();


            var categoryGroup = new GraphGroup();

            //categoryGroup.Groupings.Add(new Grouping());
            graph.CategoryGroups.Add(categoryGroup);


            //if(ChartReportReportDTO.EntityChartReportSeries.Count>0)
            //{

            //}

            var column = ChartReportReportDTO.EntityChartReportSeries.First();



            var barSeries = new Telerik.Reporting.BarSeries();

            graph.Series.Add(barSeries);
            barSeries.Name          = column.EntityListViewColumn.RelativeColumnName;
            barSeries.CategoryGroup = categoryGroup;

            barSeries.ToolTip.Text = string.Format("= Format('{0}', {1}(Fields.{2}) / CDbl(Exec(\'graph1\', {1}(Fields.{2}))))", "{0:P}", valuecolumn.FunctionType.ToString(), valuecolumn.EntityListViewColumn.RelativeColumnName);

            barSeries.X = string.Format("= {0}(Fields.{1})", valuecolumn.FunctionType.ToString(), valuecolumn.EntityListViewColumn.RelativeColumnName);

            var serieGroup = new GraphGroup();

            barSeries.SeriesGroup = serieGroup;
            //اگر نام ست نشده باشد گزارش درست کار نمیکند!!!!؟
            serieGroup.Name = column.EntityListViewColumn.RelativeColumnName;
            serieGroup.Groupings.Add(new Telerik.Reporting.Grouping(string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName)));
            serieGroup.Sortings.Add(new Telerik.Reporting.Sorting(string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName), Telerik.Reporting.SortDirection.Asc));
            graph.SeriesGroups.Add(serieGroup);



            //رو بقیه انواع خطا میدهد!اشکال تلریک هست در ورژن جدیدتر چک شود
            //شاید هم چون اصلا کتگوری ندارد و فقط سری دارد قانونش همینه
            barSeries.ArrangeMode             = Telerik.Reporting.GraphSeriesArrangeMode.Stacked100;
            barSeries.CoordinateSystem        = polarCoordinateSystem;
            barSeries.DataPointLabel          = string.Format("= {0}(Fields.{1}) / CDbl(Exec(\'graph1\', {0}(Fields.{1})))", valuecolumn.FunctionType.ToString(), valuecolumn.EntityListViewColumn.RelativeColumnName);
            barSeries.DataPointLabelAlignment = Telerik.Reporting.BarDataPointLabelAlignment.OutsideColumn;
            barSeries.DataPointLabelConnectorStyle.Padding.Bottom = Telerik.Reporting.Drawing.Unit.Point(2D);
            barSeries.DataPointLabelConnectorStyle.Padding.Top    = Telerik.Reporting.Drawing.Unit.Point(2D);
            barSeries.DataPointLabelFormat        = "{0:P}";
            barSeries.DataPointLabelOffset        = Telerik.Reporting.Drawing.Unit.Mm(5D);
            barSeries.DataPointLabelStyle.Visible = true;
            barSeries.DataPointStyle.LineWidth    = Telerik.Reporting.Drawing.Unit.Inch(0D);
            barSeries.DataPointStyle.Visible      = true;
            barSeries.LegendItem.Value            = string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName);

            var legendValue = string.Format("= Fields.{0}", column.EntityListViewColumn.RelativeColumnName);
            var parentGeoup = serieGroup;

            foreach (var cColumn in ChartReportReportDTO.EntityChartReportSeries.Where(x => x != column))
            {
                var newGroup = new GraphGroup();
                newGroup.Name = column.EntityListViewColumn.RelativeColumnName;
                newGroup.Groupings.Add(new Telerik.Reporting.Grouping(string.Format("= Fields.{0}", cColumn.EntityListViewColumn.RelativeColumnName)));
                newGroup.Sortings.Add(new Telerik.Reporting.Sorting(string.Format("= Fields.{0}", cColumn.EntityListViewColumn.RelativeColumnName), Telerik.Reporting.SortDirection.Asc));
                parentGeoup.ChildGroups.Add(newGroup);
                barSeries.SeriesGroup = newGroup;
                parentGeoup           = newGroup;
                legendValue          += "+ \'/\' +" + string.Format(" Fields.{0}", cColumn.EntityListViewColumn.RelativeColumnName);
            }

            barSeries.LegendItem.Value = legendValue;
            barSeries.ToolTip.Title    = legendValue;

            return(new Tuple <Report, Graph>(report, graph));
        }