web
You’re offline. This is a read only version of the page.
close
Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Suggested Answer

Dynamics 365 Connection Using Console Application

(0) ShareShare
ReportReport
Posted on by 247

Hello,

I am trying to develop a simple console application which will connect to the Dynamics 365 online and will create a account or contact record within it using C# code from the console application. But I am facing an issue which runtime of a program. I am getting an exception as follows. Also I have shared a sample program which I tried to connect.


Unhandled Exception: System.NullReferenceException: Object reference not set to
an instance of an object.
at ConsoleApp.Program.Main(String[] args) in *****\ConsoleApp\Program.cs:line 44

at line 44: Guid accountId = service.Create(account);

Please let me know the solution for this. Also please note that I am using latest Dynamics 365 online environment Trial. Also for reference check my code for any issues

class Program
{
static void Main(string[] args)
{
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
string connectionString = "Url=org2a2a33f0.crm.dynamics.com/; Username=**@********.onmicrosoft.com; Password=@******** authtype=Office365";

CrmServiceClient conn = new CrmServiceClient(connectionString);

OrganizationServiceProxy service = conn.OrganizationServiceProxy;

// Create Account
Entity account = new Entity("account");
account["name"] = "ABC abc";


Guid accountId = service.Create(account);

var fetch = "<fetch {0}>" +
" <entity name='account' >" +
" <attribute name='accountid' />" +
" <attribute name='name' />" +
" </entity>" +
"</fetch>";
var accountCol = RetrieveAllRecords(service, fetch);

QueryExWithPagination(service);
}

static IOrganizationService getService()
{
IOrganizationService organizationService = null;

try
{
ClientCredentials clientCredentials = new ClientCredentials();
clientCredentials.UserName.UserName = "**@******onmicrosoft.com";
clientCredentials.UserName.Password = "@Pass";

// For Dynamics 365 Customer Engagement V9.X, set Security Protocol as TLS12
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
// Get the URL from CRM, Navigate to Settings -> Customizations -> Developer Resources
// Copy and Paste Organization Service Endpoint Address URL
organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri("https://********.api.crm.dynamics.com/XRMServices/2011/Organization.svc"),
null, clientCredentials, null);

if (organizationService != null)
{
Guid userid = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).UserId;

if (userid != Guid.Empty)
{
Console.WriteLine("Connection Established Successfully...");
}
}
else
{
Console.WriteLine("Failed to Established Connection!!!");
}
}
catch (Exception ex)
{
Console.WriteLine("Exception caught - " + ex.Message);
}
return organizationService;

}


public static List<Entity> RetrieveAllRecords(IOrganizationService service, string fetch)
{
var moreRecords = false;
int page = 1;
var cookie = string.Empty;
List<Entity> Entities = new List<Entity>();
do
{
var xml = string.Format(fetch, cookie);
var collection = service.RetrieveMultiple(new FetchExpression(xml));

if (collection.Entities.Count >= 0) Entities.AddRange(collection.Entities);

moreRecords = collection.MoreRecords;
if (moreRecords)
{
page++;
cookie = string.Format("paging-cookie='{0}' page='{1}'", System.Security.SecurityElement.Escape(collection.PagingCookie), page);
}
} while (moreRecords);

return Entities;
}

public static void QueryExWithPagination(IOrganizationService service)
{
QueryExpression qe = new QueryExpression("account");
qe.ColumnSet = new ColumnSet(new string[] { "name", "description" });
ConditionExpression con1 = new ConditionExpression("name", ConditionOperator.NotNull);
ConditionExpression con2 = new ConditionExpression("description", ConditionOperator.NotNull);
FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.AddCondition(con1);

filter.AddCondition(con2);

qe.Criteria = filter;

int recordCount = 0;
int pageNumber = 1;

int pageCount = 1000;
RetrieveMultipleRequest multiRequest = new RetrieveMultipleRequest();
RetrieveMultipleResponse multiResponse = new RetrieveMultipleResponse();
EntityCollection EntityRecords = new EntityCollection();

qe.PageInfo.Count = pageCount;
qe.PageInfo.PagingCookie = null;
qe.PageInfo.PageNumber = pageNumber;

multiRequest.Query = qe;

while (true)
{
multiResponse = (RetrieveMultipleResponse)service.Execute(multiRequest);
EntityCollection entityRecords = multiResponse.EntityCollection;

if (entityRecords.Entities.Count > 0)
{
foreach (Entity objrecord in entityRecords.Entities)
{
recordCount++;
// perform operation
EntityRecords.Entities.Add(objrecord);
}
}
if (entityRecords.MoreRecords)
{
pageNumber++;
qe.PageInfo.PageNumber = pageNumber;
qe.PageInfo.PagingCookie = multiResponse.EntityCollection.PagingCookie;
}
else
{
break;
}
}

}
}

I have the same question (0)
  • Suggested answer
    Wahaj Rashid Profile Picture
    11,321 on at

    Hi,

    When you debug, on which line it breaks? It seems like service object (OrganizationServiceProxy) is not initialized.

    I would recommend you to refer to following quick start for the latest CRM version:
    Here is sample code for your reference to create an account record using quick start guide:
    class Program
        {
            static void Main(string[] args)
            {
                // e.g. https://yourorg.crm.dynamics.com
                string url = @"";
                // e.g. you@yourorg.onmicrosoft.com
                string userName = @"";
                // e.g. y0urp455w0rd 
                string password = "";
    
                string conn = $@"
                            Url = {url};
                            AuthType = Office365;
                            UserName = {userName};
                            Password = {password};
                            RequireNewInstance = True";
    
                // Initialize Connection and Service
                using (var svc = new CrmServiceClient(conn))
                {
                    // Intialize Entity object
                    Entity newAccount = new Entity("account");
    
                    newAccount.Attributes["name"] = "John Wick 4";
    
                    Console.WriteLine("Creating Account...");
    
                    // Create Account
                    var accountId = svc.Create(newAccount);
    
                    Console.WriteLine("Account Created, ID : {0} .", accountId);
    
                    Console.WriteLine();
    
                    Console.WriteLine("Retrieving Account...");
    
                    // Retreive Account
                    var account = svc.Retrieve("account", accountId, new ColumnSet(new string[] { "name" }));
    
                    Console.WriteLine("Account '{0}' retrieved.", account.Attributes["name"]);
    
                    Console.ReadLine();
                }
            }
        }
    Let me know if you need further help.
    Best,
    Wahaj
    (if it helps, please mark it verified)
  • ARTECH Profile Picture
    247 on at

    OK. Thanks for replay. I will try your suggestion and reply soon.

    Thank You

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

Responsible AI policies

As AI tools become more common, we’re introducing a Responsible AI Use…

Neeraj Kumar – Community Spotlight

We are honored to recognize Neeraj Kumar as our Community Spotlight honoree for…

Leaderboard > Microsoft Dynamics 365 | Integration, Dataverse, and general topics

#1
Martin Dráb Profile Picture

Martin Dráb 45 Most Valuable Professional

#2
iampranjal Profile Picture

iampranjal 36

#3
Satyam Prakash Profile Picture

Satyam Prakash 31

Last 30 days Overall leaderboard

Product updates

Dynamics 365 release plans