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 console application

(0) ShareShare
ReportReport
Posted on by 247

Hello,

I am trying to write a simple console application which will connect to the Dynamics 365 environment and will create a record in either Contact or Account entity. But I am facing an issue whenever I try to run it. It build successfully but when I run it it throws an exception.

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

Line 44 is

  Guid accountId = service.Create(account);

Also please note that I am using the latest version of Dynamics 365 online. 

The entire code of my program is as follows:

using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net;
using System.ServiceModel.Description;
using System.Text;
using System.Threading.Tasks;

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

string connectionString = "AuthType=OAuth;Username=**@**********onmicrosoft.com; Password=@Pass Url=https://********.crm.dynamics.com;AppId=51f81489-12ee-4a9e-aaae-a2591f45987d; RedirectUri=app://58145B91-0C36-4500-8554-080854F2AC97;LoginPrompt=Auto";

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;
}
}

}
}

}

Please tell me is any wrong I did with my code. Also if possible please share a blog or article regarding the about tutorial or sample.

Thanks

AR

  • Suggested answer
    Anks27 Profile Picture
    1,083 on at
    RE: Dynamics 365 connection console application

    Hello,

    The error indicates that your service object is null as it is not instantiated correctly.

    Please refer the following link for creating D365 connection from a console application.

    https://community.dynamics.com/365/b/dynamics365andazuresolutions/posts/d365-v9-x-step-by-step-guide-on-how-to-create-a-simple-console-application-for-dynamics-365

    Signed, Sealed and Delivered.

    Don't forget to help the community by Verifying the answer and Like it if your question has been answered. It will let others know that the topic has verified answer.

     

    Thanks & Regards,

    Ankit Shah(MCT-Microsoft Certified Trainer || Dynamics 365/Business Development Manager)

     

    Follow/Connect 101 on below

    LinkedIn:-   https://linkedin.com/in/dynamicpower101/

    Twitter:-     https://twitter.com/Dynamicpower101

    Facebook:- https://facebook.com/DynamicPower101/

    Telegram:- https://t.me/dynamicpower101

    Medium:-   https://medium.com/dynamicpower101

  • Suggested answer
    Pawar Pravin  Profile Picture
    5,237 on at
    RE: Dynamics 365 connection console application

    Hi,

    It looks like your were not able to retrieve the service and hence you are getting "Object reference not set to an instance of an object" error.

    Please confirm once if you are using compatible dll's with respective to your instance version, also make sure that you are using correct credentials

  • necsa Profile Picture
    3,455 on at
    RE: Dynamics 365 connection console application

    Do you have multi-factor authentication?

  • Prakash Kalimuthu Profile Picture
    on at
    RE: Dynamics 365 connection console application

    Hi,

    Please refer below link.

    https://docs.microsoft.com/en-us/powerapps/developer/common-data-service/org-service/quick-start-org-service-console-app

    Regards,

    Prakash

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

Ramesh Kumar – Community Spotlight

We are honored to recognize Ramesh Kumar as our July 2025 Community…

Congratulations to the June Top 10 Community Leaders!

These are the community rock stars!

Announcing the Engage with the Community forum!

This forum is your space to connect, share, and grow!

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

#1
Adis Profile Picture

Adis 136 Super User 2025 Season 1

#2
Sohail Ahmed Profile Picture

Sohail Ahmed 81

#3
Jonas "Jones" Melgaard Profile Picture

Jonas "Jones" Melgaard 77 Super User 2025 Season 1

Product updates

Dynamics 365 release plans