Tuesday, September 8, 2020

LinPadQuery to connect to an org with username, password

 <Query Kind="Program">

  <NuGetReference>Microsoft.CrmSdk.CoreAssemblies</NuGetReference>
  <NuGetReference>Microsoft.CrmSdk.Deployment</NuGetReference>
  <NuGetReference>Microsoft.CrmSdk.Workflow</NuGetReference>
  <NuGetReference>Microsoft.CrmSdk.XrmTooling.CoreAssembly</NuGetReference>
  <NuGetReference>Microsoft.CrmSdk.XrmTooling.PackageDeployment</NuGetReference>
  <Namespace>Microsoft.Xrm.Sdk</Namespace>
  <Namespace>Microsoft.Xrm.Sdk.Messages</Namespace>
  <Namespace>Microsoft.Xrm.Sdk.Query</Namespace>
</Query>
 
string orgUrl = "https://.crm.dynamics.com/";
string authType = "Office365"; // AD, IFD, OAuth, Office365
string user = ".com";
string password = "#########";
string domain = ""; //not required
Microsoft.Xrm.Sdk.IOrganizationService _orgService;
Microsoft.Xrm.Sdk.ITracingService _tracer;
 
void Main()
{
    _orgService = CreateOrgService();
    var account = _orgService.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression($@"<fetch>
          <entity name='account'>
            <attribute name='name' />
            <attribute name='accountid' />
          </entity>
        </fetch>"));
 
    account[0].Id.Dump();
}
 
// Define other methods and classes here
Microsoft.Xrm.Sdk.IOrganizationService CreateOrgService()
{
    var connectionString = $"Url={orgUrl};AuthType={authType};RequireNewInstance=true";
    if (!string.IsNullOrEmpty(user))
    {
        connectionString += $";UserName={user}";
    }
    if (!string.IsNullOrEmpty(password))
    {
        connectionString += $";Password={password}";
    }
    if (!string.IsNullOrEmpty(domain))
    {
        connectionString += $";Domain={domain}";
    }
    connectionString.Dump();
    return new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);
}

No comments:

Post a Comment