I want to get a list of group names based on the object id I provide. For example if the id is 5458409c-013f-40d6-8352-522654ae1422 then I want to get the group name of that id which could be 'Marketing' for example. However I keep getting back the wrong group.
Here is the implementation I have so far:
List<AccessGroup> accessGroups = new List<AccessGroup>();
try
{
foreach(var id in group_ids)
{
var page = await graph_client.Groups[id].Members.Request().GetAsync();
string group_name = "";
group_name = page.OfType<Group>().Select(x => x.DisplayName).FirstOrDefault();
while (page.NextPageRequest != null)
{
page = await page.NextPageRequest.GetAsync();
group_name = page.OfType<Group>().Select(x => x.DisplayName).FirstOrDefault();
}
accessGroups.Add(new AccessGroup { Id = id, Name = group_name });
}
}
catch (Exception ex)
{
Logger.Warning(ex.Message);
Logger.Warning("Error getting group name from azure security groups");
throw;
}
CodePudding user response:
Hello and thanks for your question. Looks like you want to store the first member display name of each page, however accessGroups.Add(new AccessGroup { Id = id, Name = group_name });
is being called only once. You should add it within the while
block.
If you want to get the displayName only for the first group member then you may try something like this:
async Task GetGroupFirstMemberDisplayName()
{
var members = (await client.Groups.Request().Select(g => g.Id).Expand("members($select=displayName)").GetAsync())
.Select(g => new { GroupId = g.Id, FirstMemberDisplayName = g.Members.OfType<Group>().FirstOrDefault()?.DisplayName });
foreach (var item in members)
{
Console.WriteLine($"Group {item.GroupId} first member display name: {item?.FirstMemberDisplayName ?? ""}");
}
}
If you just want to get the displayName for all your groups then you can try something like:
async Task GetGroupDisplayNames()
{
var names = (await client.Groups.Request().Select(g => g.DisplayName).GetAsync())
.Select(g => g.DisplayName);
Console.WriteLine(string.Join(", ", names));
}
Hope that helps!