using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Tooling.Connector;
using System;
using Microsoft.Identity.Client;
namespace Web_Jobs
{
internal class Microsoft_Identity
{
private static string GetAccessToken(string clientId, string clientSecret, string tenantId, string resource)
{
var authority = $"https://login.microsoftonline.com/{tenantId}";
var app = ConfidentialClientApplicationBuilder.Create(clientId)
.WithClientSecret(clientSecret)
.WithAuthority(new Uri(authority))
.Build();
var scopes = new string[] { $"{resource}/.default" };
var result = app.AcquireTokenForClient(scopes).ExecuteAsync();
return result.ToString();
}
private static void Run()
{
try
{
var clientId = "";
var clientSecret = "";
var tenantId = "";
var resource = "";
var accessToken = GetAccessToken(clientId, clientSecret, tenantId, resource);
// Ensure the access token is successfully acquired.
if (string.IsNullOrEmpty(accessToken))
{
Console.WriteLine("Failed to acquire access token.");
return;
}
string connectionString = $"AuthType=OAuth;Url={resource};AccessToken={accessToken};";
Console.WriteLine("*** Establishing connection to CRM... ***");
CrmServiceClient client = new CrmServiceClient(connectionString);
if (!client.IsReady)
{
Console.WriteLine(client.LastCrmException.Message);
}
else
{
Console.WriteLine("\n*** Connection Successful! ***");
// Perform client operations here.
// retrieving using fetch XML
var fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
"<entity name='contact'>" +
"<attribute name='fullname'/>" +
"<attribute name='telephone1'/>" +
"<attribute name='contactid'/>" +
"<order attribute='fullname' descending='false'/>" +
"<filter type='and'>" +
"<condition attribute='parentcustomerid' operator='eq' uitype='account' value='(83883308-7ad5-ea11-a813-000d3a33f3b4)'/>" +
"</filter>" +
"</entity>" +
"</fetch>";
EntityCollection contactRecords = client.RetrieveMultiple(new FetchExpression(fetchXML));
if (contactRecords != null)
{
foreach (var contactRecord in contactRecords.Entities)
{
contactRecord["address1_city"] = "this is from console";
client.Update(contactRecord);
Console.WriteLine(contactRecord.Attributes["fullname"]);
}
}
Console.WriteLine("\nPress any key to exit...");
Console.ReadKey(true);
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
static void Main(string[] args)
{
Run();
}
}
}