Home > database >  Display all the user's files using Microsoft Graph API not working
Display all the user's files using Microsoft Graph API not working

Time:06-28

I have created one .net website application and i have added dlls and codes same like below reference video.

https://www.youtube.com/watch?v=KNJUrCHv6no&list=PLWZJrkeLOrbZ8Gl8zsxUuXTkmytyiEGSh&index=5

I have created one free Microsoft account with free subscription my id like ([email protected]) and i registered my application same in azure same as https://www.youtube.com/watch?v=k7nnvdNgfOE&list=PLWZJrkeLOrbZ8Gl8zsxUuXTkmytyiEGSh&index=4 this video.

But its not working for me. request.GetAsync().Result takes more time and request time out issue shown. i added my code below. please suggest.

default.aspx

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Microsoft.Identity.Client;
using Microsoft.Graph;
using Microsoft.Extensions.Configuration;
using Helpers;
using System.Security;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var config = LoadAppSettings();
        if (config == null)
        {
            iserror.Text = "config error";
            return;
        }
        try
        {
            var userName = ReadUsername();
            var userPassword = ReadPassword();

            var client = GetAuthenticatedGraphClient(config, userName, userPassword);

            var request = client.Me.Drive.Root.Children.Request();
            var results = request.GetAsync().Result;
            foreach (var file in results)
            {

            }
        }
        catch { iserror.Text = "config file exist. azure error"; }
    }
    private static SecureString ReadPassword()
    {
        var securePassword = "xxxxxxx";
        SecureString password = new SecureString();
        foreach (char c in securePassword)
            password.AppendChar(c);
        return password;
    }

    private static string ReadUsername()
    {
        string username;
        username = "[email protected]";
        return username;
    }
    private static GraphServiceClient GetAuthenticatedGraphClient(IConfigurationRoot config, string userName, SecureString userPassword)
    {
        var authenticationProvider = CreateAuthorizationProvider(config, userName, userPassword);
        var graphClient = new GraphServiceClient(authenticationProvider);
        return graphClient;
    }
    private static IAuthenticationProvider CreateAuthorizationProvider(IConfigurationRoot config, string userName, SecureString userPassword)
    {
        var clientId = config["applicationId"];
        var authority = "https://login.microsoftonline.com/"   config["tenantId"]   "/v2.0";

        List<string> scopes = new List<string>();
        scopes.Add("User.Read");
        scopes.Add("Files.Read");
        var cca = PublicClientApplicationBuilder.Create(clientId)
                                                .WithAuthority(authority)
                                                .Build();
        return MsalAuthenticationProvider.GetInstance(cca, scopes.ToArray(), userName, userPassword);
    }
    private static IConfigurationRoot LoadAppSettings()
    {
        try
        {
            string asas = HttpContext.Current.Server.MapPath("");
            var config = new ConfigurationBuilder()
                              .SetBasePath(asas)
                              .AddJsonFile("appsettings.json", false, true)
                              .Build();

            if (string.IsNullOrEmpty(config["applicationId"]) ||
                string.IsNullOrEmpty(config["tenantId"]))
            {
                return null;
            }

            return config;
        }
        catch (System.IO.FileNotFoundException)
        {
            return null;
        }
    }
} 

MsalAuthenticationProvider.cs

using System.Net.Http;
using System.Net.Http.Headers;
using System.Security;
using System.Threading.Tasks;
using Microsoft.Identity.Client;
using Microsoft.Graph;

namespace Helpers
{
    public class MsalAuthenticationProvider : IAuthenticationProvider
    {
        private static MsalAuthenticationProvider _singleton;
        private IPublicClientApplication _clientApplication;
        private string[] _scopes;
        private string _username;
        private SecureString _password;
        private string _userId;

        private MsalAuthenticationProvider(IPublicClientApplication clientApplication, string[] scopes, string username, SecureString password)
        {
            _clientApplication = clientApplication;
            _scopes = scopes;
            _username = username;
            _password = password;
            _userId = null;
        }

        public static MsalAuthenticationProvider GetInstance(IPublicClientApplication clientApplication, string[] scopes, string username, SecureString password)
        {
            if (_singleton == null)
            {
                _singleton = new MsalAuthenticationProvider(clientApplication, scopes, username, password);
            }

            return _singleton;
        }

        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
        {
            var accessToken = await GetTokenAsync();

            request.Headers.Authorization = new AuthenticationHeaderValue("bearer", accessToken);
        }

        public async Task<string> GetTokenAsync()
        {
            if (!string.IsNullOrEmpty(_userId))
            {
                try
                {
                    var account = await _clientApplication.GetAccountAsync(_userId);

                    if (account != null)
                    {
                        var silentResult = await _clientApplication.AcquireTokenSilent(_scopes, account).ExecuteAsync();
                        return silentResult.AccessToken;
                    }
                }
                catch (MsalUiRequiredException) { }
            }

            var result = await _clientApplication.AcquireTokenByUsernamePassword(_scopes, _username, _password).ExecuteAsync();
            _userId = result.Account.HomeAccountId.Identifier;
            return result.AccessToken;
        }
    }
}

appsettings.json*

{
  "tenantId": "xxxx",
  "applicationId": "xxxx"
}

CodePudding user response:

  1. It looks like you're running into the standard deadlock situation where async method is trying to continue thread which is blocked by the call to Result. Try using async Task test methods instead of void .

Note: And especially in user interactions one should be careful of blocking by using .Result calls on the main thread, as this type of call can lock-up your application for further user interaction.

  1. Try by avoiding the use of Result in the call.

    var results = await request.GetAsync();
    

    and do check if you need to add async to all the methods .

  2. Also check this c# - When querying drive items using Microsoft Graph- Stack Overflow that is relatable.

  3. Also if above doesn’t resolve , try also to set the Timeout to a higher value

    example:to one hour:

    graphServiceClient.HttpProvider.OverallTimeout = TimeSpan.FromHours(1);
    

Please check these below useful references:

  1. c# - 'await' works, but calling task.Result hangs/deadlocks - Stack Overflow
  2. How To Access Microsoft Graph API In Console Application (c-sharpcorner.com)
  • Related