The requirement is to extract regional and language settings for the signed in user. I have explored the Internet and found that we have to use Graph API Beta version to achieve this. I have used the same. I can see the result in "Graph Explorer" web application, but it throwing "Null" values in my local c# application.
internal class Program {
private static IConfiguration _configuration;
private static string _tenantDomain;
private static string[] _graphScopes = new string[] { $"user.read", "user.readwrite.all", "user.read.all" };
/// <summary>
/// The access token for MS Graph
/// </summary>
/// NOTE: Do not use in prod apps as-is. you should be using a cached token obtained via MSAL. See aka.ms/aadcodesamples for a sample matching your app type and authN scenario
private static string _GraphAccessToken = string.Empty;
private static async Task Main(string[] args)
{
LoadConfig();
// Prepare an authenticated MS Graph SDK client
GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient();
// Call Graph APIs
// Get information from Graph about the currently signed-In user
Console.WriteLine("--Fetching details of the currently signed-in user--");
await GetMeAsync(graphServiceClient);
Console.WriteLine("---------");
/*Console.WriteLine("--Listing all groups this user is a member of--");
var groups = await GetUserGroupMemberships(graphServiceClient);
groups.ForEach(u => Console.WriteLine(u.DisplayName));
Console.WriteLine("---------");
Console.WriteLine("--Listing all directory roles this user is a member of--");
var roles = await GetUsersDirectoryRoles(graphServiceClient);
roles.ForEach(u => Console.WriteLine(u.DisplayName));
Console.WriteLine("---------");
//The delta query example
await GraphDeltaQueryExample(graphServiceClient);
// Batching
BatchRequestExample(graphServiceClient).GetAwaiter().GetResult();*/
Console.WriteLine("Press any key to exit");
Console.ReadKey();
}
/// <summary>Calls the /me and /me/directreports endpoints of Microsoft Graph using the MS Graph SDK.</summary>
/// <param name="graphServiceClient">The graph service client.</param>
private static async Task GetMeAsync(GraphServiceClient graphServiceClient)
{
// Call /me Api
Console.WriteLine($"GET {graphServiceClient.Me.Request().RequestUrl}");
var me = await graphServiceClient.Me.Settings.RegionalAndLanguageSettings.Request().GetAsync();
LocaleInfo local = me.DefaultRegionalFormat;
Console.WriteLine($"Default Regional from /me->{local.DisplayName}");
// /me/directReports
Console.WriteLine($"GET {graphServiceClient.Me.DirectReports.Request().RequestUrl}");
var directreports = await graphServiceClient.Me.DirectReports.Request().GetAsync();
foreach (User user in directreports.CurrentPage)
{
Console.WriteLine($"Direct report's Display Name ->{user.DisplayName}");
}
}
private static void LoadConfig()
{
// Using appsettings.json as our configuration settings
var builder = new ConfigurationBuilder()
.SetBasePath(System.IO.Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json");
_configuration = builder.Build();
_tenantDomain = _configuration.GetValue<string>("TenantDomain");
}
/// <summary>
/// An example of how to authenticate the Microsoft Graph SDK using the MSAL library
/// </summary>
/// <returns></returns>
private static GraphServiceClient GetAuthenticatedGraphClient()
{
string GraphApiEndpoint = _configuration.GetValue<string>("GraphApiEndpoint");
IPublicClientApplication app = BuildPublicClientApp();
GraphServiceClient graphServiceClient =
new GraphServiceClient(GraphApiEndpoint, new DelegateAuthenticationProvider(async (requestMessage) =>
{
// Retrieve an access token for Microsoft Graph (gets a fresh token if needed).
await AuthenticateUsingMsalAsync(app);
// Add the access token in the Authorization header of the API request.
requestMessage.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", _GraphAccessToken);
}));
return graphServiceClient;
}
/// <summary>
/// Initializes the MSAL's IPublicClientApplication from the configuration
/// </summary>
/// <returns></returns>
private static IPublicClientApplication BuildPublicClientApp()
{
PublicClientApplicationOptions appConfiguration = _configuration.Get<PublicClientApplicationOptions>();
string authority = string.Concat(appConfiguration.Instance, appConfiguration.TenantId);
// Building a public client application
IPublicClientApplication app = PublicClientApplicationBuilder.Create(appConfiguration.ClientId)
.WithAuthority(authority)
.WithRedirectUri(appConfiguration.RedirectUri)
.Build();
return app;
}
/// <summary>
/// Acquiring token for Graph using the MSAL SDK
/// </summary>
/// <param name="app">The IPublicClientApplication instance.</param>
/// <returns></returns>
/// <exception cref="InvalidOperationException">Failed to obtain the JWT token for Graph</exception>
private static async Task<string> AuthenticateUsingMsalAsync(IPublicClientApplication app)
{
// Warning: This does not check for expired token and other relevant conditions.
// In production apps, you will always use token cache instead of using variables like below here.
// Use code samples ajaka.ms/aadcodesamples for your applicable app scenario
if (!string.IsNullOrWhiteSpace(_GraphAccessToken))
{
return _GraphAccessToken;
}
var GraphResult = await app.AcquireTokenInteractive(_graphScopes).ExecuteAsync();
if (GraphResult == null)
{
throw new InvalidOperationException("Failed to obtain the JWT token for Graph");
}
_GraphAccessToken = GraphResult.AccessToken;
return _GraphAccessToken;
}
}
Error Iam getting in Code:
*System.NullReferenceException: 'Object reference not set to an instance of an object.'
local was null.*
In actual the value is not Null. When I open it via Graph API explorer I get response attached in image: URL: https://graph.microsoft.com/beta/me/settings/regionalAndLanguageSettings
I was trying to Fetch the Regional Language Settings but it doesn't shows in my C# application. Iam using Graph Beta API.
Taken help from below URL:
https://gist.github.com/kalyankrishna1/997f7ca1af1f73f8107c1c8cebfbaf3f`