Gordana Tasic

Gordana Tasic

  • NA
  • 11
  • 703

How to display logged user name in windows form app?

Mar 22 2021 2:52 PM
I'm creating a Windows form application using Graph API. In application, I have more forms. Also, I have a function for logging in the user and when the user logs in his name is written on the label on the first form. On other forms I have a Cancel button, so when the user clicks on the Cancel button, the first form appears, but user name isn't written on the label. Does anyone know how to display user name on the first form when user clicks Cancel button? Here is the code:
  1. public static class GraphHelper  
  2. {  
  3.     private static string[] scopes = new string[] { "user.read" };  
  4.     public static string TokenForUser = null;  
  5.     public static DateTimeOffset expiration;  
  6.   
  7.     private const string ClientId = "599ed98d-4356-4a96-ad37-04391e9c48dc";  
  8.   
  9.     private const string Tenant = "common";   
  10.     private const string Authority = "https://login.microsoftonline.com/" + Tenant;  
  11.   
  12.     // The MSAL Public client app  
  13.     private static IPublicClientApplication PublicClientApp;  
  14.   
  15.     private static string MSGraphURL = "https://graph.microsoft.com/beta/";  
  16.     private static AuthenticationResult authResult;  
  17.   
  18.     public static GraphServiceClient graphClient;  
  19.     public static string token;  
  20.   
  21.     public static GraphServiceClient GetGraphClient(string token)  
  22.     {  
  23.         if (graphClient == null)  
  24.         {  
  25.             // Create Microsoft Graph client.  
  26.             try  
  27.             {  
  28.                 graphClient = new GraphServiceClient(  
  29.                     "https://graph.microsoft.com/beta",  
  30.                     new DelegateAuthenticationProvider(  
  31.                         async (requestMessage) =>  
  32.                         {  
  33.                             requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);  
  34.                             // This header has been added to identify our sample in the Microsoft Graph service.  If extracting this code for your project please remove.  
  35.                             requestMessage.Headers.Add("SampleID""uwp-csharp-snippets-sample");  
  36.   
  37.                         }));  
  38.                 return graphClient;  
  39.             }  
  40.   
  41.             catch (Exception ex)  
  42.             {  
  43.                 Debug.WriteLine("Could not create a graph client: " + ex.Message);  
  44.             }  
  45.         }  
  46.         return graphClient;  
  47.     }  
  48.   
  49.     public static async Task<string> GetTokenForUserAsync()  
  50.     {  
  51.         if (TokenForUser == null || expiration <= DateTimeOffset.UtcNow.AddMinutes(10))  
  52.         {  
  53.             PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)  
  54.           .WithAuthority(Authority)  
  55.           .WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")  
  56.            .WithLogging((level, message, containsPii) =>  
  57.            {  
  58.                Debug.WriteLine($"MSAL: {level} {message} ");  
  59.            }, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)  
  60.           .Build();  
  61.   
  62.             // It's good practice to not do work on the UI thread, so use ConfigureAwait(false) whenever possible.  
  63.             IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);  
  64.             IAccount firstAccount = accounts.FirstOrDefault();  
  65.   
  66.             try  
  67.             {  
  68.                 authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)  
  69.                                                   .ExecuteAsync();  
  70.             }  
  71.             catch (MsalUiRequiredException ex)  
  72.             {  
  73.                 // A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token  
  74.                 Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");  
  75.   
  76.                 authResult = await PublicClientApp.AcquireTokenInteractive(scopes)  
  77.                                                   .ExecuteAsync()  
  78.                                                   .ConfigureAwait(false);  
  79.             }  
  80.   
  81.             TokenForUser = authResult.AccessToken;  
  82.         }  
  83.   
  84.         return TokenForUser;  
  85.     }  
  86.   
  87.     public static async Task<User> GetMeAsync(string token)  
  88.     {  
  89.         graphClient = GetGraphClient(token);  
  90.         try  
  91.         {  
  92.             // GET /me  
  93.             return await graphClient.Me  
  94.                 .Request()  
  95.                 .Select(u => new  
  96.                 {  
  97.                     u.DisplayName  
  98.                 })  
  99.                 .GetAsync();  
  100.         }  
  101.         catch (ServiceException ex)  
  102.         {  
  103.             return null;  
  104.         }  
  105.     }  
  106. }  
  107.   
  108.   public partial class Form1 : Form  
  109. {  
  110.     public static string token;  
  111.     public static GraphServiceClient graphClient;  
  112.   
  113.     public Form1()  
  114.     {  
  115.         InitializeComponent();  
  116.     }  
  117.   
  118.     private async void button1_Click(object sender, EventArgs e)  
  119.     {  
  120.         token = await GraphHelper.GetTokenForUserAsync();  
  121.         User graphUser = await GraphHelper.GetMeAsync(token);  
  122.         label4.Text = graphUser.DisplayName;  
  123.     }  
  124. }  
  125.   
  126. public partial class Form2 : Form  
  127. {  
  128.   
  129.     public Form2()  
  130.     {  
  131.         InitializeComponent();  
  132.     }  
  133. private void button2_Click(object sender, EventArgs e)  
  134.     {  
  135.         Form1 f1 = new Form1();  
  136.         this.Close();  
  137.         f1.Show();  
  138.     }  

 

Answers (2)