
Hi Expects,
I am new to console app . using OAuth, I am trying to connect to crm and retrieve all accounts records as show in below code.
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
using System.Net.Sockets;
namespace CRMConnection
{
class Program
{
static void Main(string[] args)
{
var accounts = CrmRequest(HttpMethod.Get,"crmurl/api/data/v9.1/accounts").Result.Content.ReadAsStringAsync();
}
/// Method-to-generate-Access-Token
public static async Task<string> AccessTokenGenerator()
{
string clientId = "ID";
string clientSecret = "Secret code";
string authority = "login.microsoft.com/tenantID/oauth2/v2.0/token";
string resourceUrl = "CRMUrl";
var credentials = new ClientCredential(clientId, clientSecret);
var authContext = new Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext(authority);
var result = await authContext.AcquireTokenAsync(resourceUrl, credentials);
return result.AccessToken;
}
public static async Task<HttpResponseMessage> CrmRequest(HttpMethod httpMethod, string requestUri, string body = null)
{
var accessToken = await AccessTokenGenerator();
var client = new HttpClient();
var msg = new HttpRequestMessage(httpMethod, requestUri);
msg.Headers.Add("OData-MaxVersion", "4.0");
msg.Headers.Add("OData-Version", "4.0");
msg.Headers.Add("Prefer", "odata.include-annotations=\"*\"");
// Passing AccessToken in Authentication header
msg.Headers.Add("Authorization", $"Bearer {accessToken}");
if (body != null)
msg.Content = new StringContent(body, UnicodeEncoding.UTF8, "application/json");
return await client.SendAsync(msg);
}
}
}
I am getting below error : The program '[24580] CRMConnection.exe' has exited with code 0 (0x0).
Reason : I need to check the roles in another call and assgin system admin access . can any one please provide the code how to acheive this ?
Hello,
In order this Achieve this you will need to follow these documentations from starting to register an application and end with the sample code
https://docs.microsoft.com/en-us/azure/active-directory/develop/quickstart-register-app
https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/authenticate-oauth
if you still don't able to connect , I would recommend to open a support ticket as it will need an online session with screen sharing to check the azure configurations and user account in CRM and the code as well as a first step in troubleshooting.