C# Graph API Call Delegate

Viewed 1118

Calling Graph API ME Request.

I am trying to call a delegate call using c# and a console application. Right now this is the error I received "Code: generalException\r\nMessage: An error occurred sending the request.\r\n"

Its a c# console trying to call graph api.

static void Main(string[] args)
        {
            try
            {
                RunAsync().GetAwaiter().GetResult();
            }
            catch(Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            Console.WriteLine("Press any key to exit");
            Console.ReadKey();
        }

        private static async Task RunAsync()
        {
            string secretKey = <secretKey>;
            string appId = <clientID>;
            string tenantId = <tenantID>;
            string tokenUrl = "https://login.microsoftonline.com/common/oauth2/v2.0/token";
            List<string> scopeURL = new List<string>();
            scopeURL.Add("https://graph.microsoft.com/.default");

            Console.WriteLine("Enter a username");
            string username = Console.ReadLine();
            Console.WriteLine("Enter a password");
            var password = GetConsoleSecurePassword();

            var httpClient = new HttpClient();

            IPublicClientApplication publicClientApplication = PublicClientApplicationBuilder
            .Create(appId)
            .WithTenantId(tenantId)
            .Build();

            UsernamePasswordProvider authProvider = new UsernamePasswordProvider(publicClientApplication, scopeURL);

            GraphServiceClient graphClient = new GraphServiceClient(authProvider);
            try
            {
                User me = await graphClient.Me.Request()
                            .WithUsernamePassword(username, password)
                            .GetAsync();

                var books = await graphClient.BookingBusinesses.Request().GetAsync();
                foreach (var book in books)
                {
                    Console.WriteLine(book.DisplayName);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }

        private static SecureString GetConsoleSecurePassword()
        {
            SecureString pwd = new SecureString();
            while (true)
            {
                ConsoleKeyInfo i = Console.ReadKey(true);
                if (i.Key == ConsoleKey.Enter)
                {
                    break;
                }
                else if (i.Key == ConsoleKey.Backspace)
                {
                    pwd.RemoveAt(pwd.Length - 1);
                    Console.Write("\b \b");
                }
                else
                {
                    pwd.AppendChar(i.KeyChar);
                    Console.Write("*");
                }
            }
            return pwd;
        }

I would really like to be able to call bookingBusiness, however I can't even read my User.

These are my permission for the application. What I am missing? enter image description here

As asked

Message: An error occurred sending the request.

 ---> Microsoft.Graph.Auth.AuthenticationException: Code: generalException
Message: Unexpected exception returned from MSAL.

 ---> MSAL.NetCore.4.19.0.0.MsalServiceException:
        ErrorCode: service_not_available
Microsoft.Identity.Client.MsalServiceException: Service is unavailable to process the request
   at Microsoft.Identity.Client.Http.HttpManager.ExecuteWithRetryAsync(Uri endpoint, IDictionary`2 headers, HttpContent body, HttpMethod method, ICoreLogger logger, Boolean doNotThrow, Boolean retry)
   at Microsoft.Identity.Client.Http.HttpManager.ExecuteWithRetryAsync(Uri endpoint, IDictionary`2 headers, HttpContent body, HttpMethod method, ICoreLogger logger, Boolean doNotThrow, Boolean retry)
   at Microsoft.Identity.Client.Http.HttpManager.SendGetAsync(Uri endpoint, IDictionary`2 headers, ICoreLogger logger)
   at Microsoft.Identity.Client.WsTrust.WsTrustWebRequestManager.GetMexDocumentAsync(String federationMetadataUrl, RequestContext requestContext)
   at Microsoft.Identity.Client.WsTrust.CommonNonInteractiveHandler.PerformWsTrustMexExchangeAsync(String federationMetadataUrl, String cloudAudienceUrn, UserAuthType userAuthType, String username, SecureString password)
   at Microsoft.Identity.Client.Internal.Requests.UsernamePasswordRequest.FetchAssertionFromWsTrustAsync()
   at Microsoft.Identity.Client.Internal.Requests.UsernamePasswordRequest.ExecuteAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.Internal.Requests.RequestBase.RunAsync(CancellationToken cancellationToken)
   at Microsoft.Identity.Client.ApiConfig.Executors.PublicClientExecutor.ExecuteAsync(AcquireTokenCommonParameters commonParameters, AcquireTokenByUsernamePasswordParameters usernamePasswordParameters, CancellationToken cancellationToken)
   at Microsoft.Graph.Auth.UsernamePasswordProvider.GetNewAccessTokenAsync(AuthenticationProviderOption msalAuthProviderOption)
        StatusCode: 500
        ResponseBody: <?xml version="1.0" encoding="utf-8" ?><s:Value xmlns:s="http://www.w3.org/2003/05/soap-envelope">s:Receiver</s:Value>
        Headers: Cache-Control: private
Server: Microsoft-IIS/10.0
X-AspNet-Version: 4.0.30319
X-Powered-By: ASP.NET
Date: Mon, 28 Sep 2020 12:48:52 GMT

   --- End of inner exception stack trace ---
   at Microsoft.Graph.Auth.UsernamePasswordProvider.GetNewAccessTokenAsync(AuthenticationProviderOption msalAuthProviderOption)
   at Microsoft.Graph.Auth.UsernamePasswordProvider.AuthenticateRequestAsync(HttpRequestMessage httpRequestMessage)
   at Microsoft.Graph.AuthenticationHandler.SendAsync(HttpRequestMessage httpRequestMessage, CancellationToken cancellationToken)
   at System.Net.Http.HttpClient.FinishSendAsyncBuffered(Task`1 sendTask, HttpRequestMessage request, CancellationTokenSource cts, Boolean disposeCts)
   at Microsoft.Graph.HttpProvider.SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---
   at Microsoft.Graph.HttpProvider.SendRequestAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
   at Microsoft.Graph.HttpProvider.SendAsync(HttpRequestMessage request, HttpCompletionOption completionOption, CancellationToken cancellationToken)
   at Microsoft.Graph.BaseRequest.SendRequestAsync(Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
   at Microsoft.Graph.BaseRequest.SendAsync[T](Object serializableObject, CancellationToken cancellationToken, HttpCompletionOption completionOption)
   at Microsoft.Graph.UserRequest.GetAsync(CancellationToken cancellationToken)
   at ConsoleGraph.Program.ClientDelegateApp(String clientId, String tenantId, String secretKey, List`1 scopes) in D:\src\ConsoleGraph\ConsoleGraph\Program.cs:line 61
0 Answers
Related