Gordana Tasic

Gordana Tasic

  • 1.9k
  • 56
  • 1.7k

How to display channels in ListView using Graph API?

Mar 18 2021 11:37 AM
I’m developing a small Windows form app to test Graph API functions. I have two functionalities in the application, user's log in and get channels for specified team. I created a class that contains functions for user login and for returning channels for specified team. I have a ListView on Form in which I want to show all the channels, but when I call a function for returning channels in button event, nothing happens, nothing is displayed in the ListView. Here is the code:
  1. public static class GraphHelper    
  2. {    
  3.   
  4.     public static GraphServiceClient graphClient;    
  5.     public static string token;    
  6.   
  7.     private static string[] scopes = new string[] { "user.read" };    
  8.     public static string TokenForUser = null;    
  9.     public static DateTimeOffset expiration;    
  10.   
  11.     private const string ClientId = "599ed98d-4356-4a96-ad37-04391e9c48dc";    
  12.   
  13.     private const string Tenant = "common"// Alternatively "[Enter your tenant, as obtained from the Azure portal, e.g. kko365.onmicrosoft.com]"    
  14.     private const string Authority = "https://login.microsoftonline.com/" + Tenant;    
  15.   
  16.     // The MSAL Public client app    
  17.     private static IPublicClientApplication PublicClientApp;    
  18.   
  19.     private static string MSGraphURL = "https://graph.microsoft.com/beta/";    
  20.     private static AuthenticationResult authResult;    
  21.   
  22.     public static GraphServiceClient GetGraphClient(string token)    
  23.     {    
  24.         if (graphClient == null)    
  25.         {    
  26.             // Create Microsoft Graph client.    
  27.             try    
  28.             {    
  29.                 graphClient = new GraphServiceClient(    
  30.                     "https://graph.microsoft.com/v1.0",    
  31.                     new DelegateAuthenticationProvider(    
  32.                         async (requestMessage) =>    
  33.                         {    
  34.                             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);    
  35.                             // This header has been added to identify our sample in the Microsoft Graph service.  If extracting this code for your project please remove.    
  36.                             requestMessage.Headers.Add("SampleID""uwp-csharp-snippets-sample");    
  37.   
  38.                         }));    
  39.                 return graphClient;    
  40.             }    
  41.   
  42.             catch (Exception ex)    
  43.             {    
  44.                 Debug.WriteLine("Could not create a graph client: " + ex.Message);    
  45.             }    
  46.         }    
  47.         return graphClient;    
  48.     }    
  49.   
  50.     public static async Task<string> GetTokenForUserAsync()    
  51.     {    
  52.         if (TokenForUser == null || expiration <= DateTimeOffset.UtcNow.AddMinutes(10))    
  53.         {    
  54.             PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)    
  55.           .WithAuthority(Authority)    
  56.           .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")    
  57.            .WithLogging((level, message, containsPii) =>    
  58.            {    
  59.                Debug.WriteLine($"MSAL: {level} {message} ");    
  60.            }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)    
  61.           .Build();    
  62.   
  63.             // It's good practice to not do work on the UI thread, so use ConfigureAwait(false) whenever possible.    
  64.             IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);    
  65.             IAccount firstAccount = accounts.FirstOrDefault();    
  66.   
  67.             try    
  68.             {    
  69.                 authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)    
  70.                                                   .ExecuteAsync();    
  71.             }    
  72.             catch (MsalUiRequiredException ex)    
  73.             {    
  74.                 // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token    
  75.                 Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");    
  76.   
  77.                 authResult = await PublicClientApp.AcquireTokenInteractive(scopes)    
  78.                                                   .ExecuteAsync()    
  79.                                                   .ConfigureAwait(false);    
  80.             }    
  81.   
  82.             TokenForUser = authResult.AccessToken;    
  83.         }    
  84.   
  85.         return TokenForUser;    
  86.     }    
  87.   
  88.     public static async Task<User> GetMeAsync(string token)    
  89.     {    
  90.         GraphHelper.graphClient = GraphHelper.GetGraphClient(token);    
  91.         try    
  92.         {    
  93.             // GET /me    
  94.             return await GraphHelper.graphClient.Me    
  95.                 .Request()    
  96.                 .Select(u => new    
  97.                 {    
  98.                     u.DisplayName    
  99.                 })    
  100.                 .GetAsync();    
  101.         }    
  102.         catch (ServiceException ex)    
  103.         {    
  104.             Console.WriteLine($"Error getting signed-in user: {ex.Message}");    
  105.             return null;    
  106.         }    
  107.     }    
  108.     public static async Task<IEnumerable<Channel>> GetChannels(string teamId)    
  109.     {    
  110.         graphClient = GetGraphClient(token);    
  111.   
  112.         var channels = await graphClient.Teams[teamId].Channels    
  113.             .Request()    
  114.             .GetAsync();    
  115.   
  116.         return channels;    
  117.     }    
  118. }    
  119.   
  120. public partial class Form1 : Form    
  121. {    
  122.     public static GraphServiceClient graphClient;    
  123.     public static string token;    
  124.     public Form1()    
  125.     {    
  126.         InitializeComponent();    
  127.     }    
  128.         
  129.     private async void button1_Click(object sender, EventArgs e)    
  130.     {    
  131.         token = await GraphHelper.GetTokenForUserAsync();    
  132.         User graphUser = await GraphHelper.GetMeAsync(token);    
  133.         label2.Text = graphUser.DisplayName;    
  134.     }    
  135.   
  136.     private async void button3_Click(object sender, EventArgs e)    
  137.     {    
  138.         var channels = GraphHelper.GetChannels("8557483b-a233-4710-82de-e1bdb03bb9a9").Result;    
  139.   
  140.         foreach (var ch in channels)    
  141.         {    
  142.             ListViewItem item = new ListViewItem(new string[] { ch.DisplayName, ch.Id});    
  143.             listView1.Items.Add(item);    
  144.         }    
  145.     }    
  146. }  
Does anyone know how to solve this?

Answers (2)