0

Here I want to retrieve data from CRM and have registered it in Azure to to get Client Credentials and using it in below code:

using Microsoft.Crm.Sdk.Messages;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.WebServiceClient;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace CRM_WebAPI_Test1
{
    class Program
    {
        static void Main(string[] atrgs)
        {
            MainAsync();
        }
        static async void MainAsync()
        {
            try
            {
                string organizationUrl = "https://OrgName<<URL>>.com";
                string clientId = "xxxxxxxxx-xxxx-xxxx-b7ca-xxxx";
                string clientSecret = "key received from Azure App Registration";
                string aadInstance = "https://login.microsoftonline.com/";
                string tenantID = "orgname";

                ClientCredential clientCredentials = new ClientCredential(clientId, clientSecret);
                AuthenticationContext authenticationContext = new AuthenticationContext(aadInstance + tenantID);
                AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientCredentials);
                var requestedToken = authenticationResult.AccessToken;

                using (var sdkService = new OrganizationWebProxyClient(GetServiceUrl(organizationUrl), false))
                {
                    sdkService.HeaderToken = requestedToken;

                    OrganizationRequest request = new OrganizationRequest()
                    {
                        RequestName = "WhoAmI"
                    };

                    WhoAmIResponse response = sdkService.Execute(new WhoAmIRequest()) as WhoAmIResponse;
                    Console.WriteLine(response.UserId);

                    Console.WriteLine("Press any key to exit...");
                    Console.ReadLine();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());

                Console.WriteLine("Press any key to exit...");
                Console.ReadLine();
            }
        }
        static private Uri GetServiceUrl(string organizationUrl)
        {
            return new Uri(organizationUrl + @"/xrmservices/2011/organization.svc/web?SdkClientVersion=8.2");
        }
    }
}

But when it come to line:

AuthenticationResult authenticationResult = await authenticationContext.AcquireTokenAsync(organizationUrl, clientCredentials);

It directly exists the program and not giving any output, not even hitting the catch exception part. Is there anything I am missing here?

Also, how to know the tenant name while registering the application in Azure AD?

UPDATE: [Updating in question because not able to write down whole error in comment section so please bare with it.] After applying code changes as suggestion it is throwing error as below:

Microsoft.IdentityModel.Clients.ActiveDirectory.AdalServiceException: AADSTS50001: The application named https://orgname.com was not found in the tenant named mydirectory.onmicrosoft.com. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant. Trace ID: 58b1b994-eac3-4209-b553-4cea6a120500 Correlation ID: fb8a3f3a-8b0c-4cea-90fa-88ea6e9a7208 Timestamp: 2017-11-29 09:09:37Z ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 400 (BadRequest). ---> Microsoft.IdentityModel.Clients.ActiveDirectory.AdalException: {"error":"invalid_resource","error_description":"AADSTS50001: The application named https://orgname.com was not found in the tenant named mydirectory.onmicrosoft.com. This can happen if the application has not been installed by the administrator of the tenant or consented to by any user in the tenant. You might have sent your authentication request to the wrong tenant.\r\nTrace ID: 58b1b994-eac3-4209-b553-4cea6a120500\r\nCorrelation ID: fb8a3f3a-8b0c-4cea-90fa-88ea6e9a7208\r\nTimestamp: 2017-11-29 09:09:37Z","error_codes":[50001],"timestamp":"2017-11-29 09:09:37Z","trace_id":"58b1b994-eac3-4209-b553-4cea6a120500","correlation_id":"fb8a3f3a-8b0c-4cea-90fa-88ea6e9a7208"}: Unknown error --- End of inner exception stack trace --- at Microsoft.IdentityModel.Clients.ActiveDirectory.HttpClientWrapper.d__31.MoveNext() --- End of inner exception stack trace --- at Microsoft.IdentityModel.Clients.ActiveDirectory.AdalHttpClient.d__221.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AdalHttpClient.<GetResponseAsync>d__211.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__71.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__68.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__59.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at Microsoft.IdentityModel.Clients.ActiveDirectory.AcquireTokenHandlerBase.d__57.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__33.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext.d__58.MoveNext() --- End of stack trace from previous location where exception was thrown --- at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at CRM_WebAPI_Test1.Program.d__1.MoveNext() in E:\VS_2015\CRM Projects\CRM_WebAPI_Test1\CRM_WebAPI_Test1\Program.cs:line 31 ErrorCode: invalid_resource StatusCode: 400

4

1 回答 1

1

首先,你正在使用一个async void你不应该做的函数(除了在你不能影响方法签名的事件处理程序中)。

所以它应该是这样的:

static void Main(string[] atrgs)
{
    MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
}

基本上在您的代码中,当它遇到等待时,它会返回到 Main 并且程序退出。

在 C# 7.2 中,您还可以声明 main 方法,async Task这样您就可以只声明await该方法。

您可以从 Azure 门户获取租户ID 。

  1. 打开 Azure AD 刀片
  2. 转到属性
  3. 您可以找到租户 ID

另一种选择是使用任何经过验证的域名(例如 mydirectory.onmicrosoft.com)。

于 2017-11-29T07:55:33.633 回答