Hi Experts,
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();
- }
-
- 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=\"*\"");
-
- 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 assign system admin access. can anyone please provide the code on how to achieve this?