Skip to main content

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics 365 | Integration, Dataverse...
Answered

System.NullReferenceException: 'Object reference not set to an instance of an object.'

(0) ShareShare
ReportReport
Posted on by 25

I am pulling a set of records to use the CrmServiceClient to upload them into a custom entity in our instance of CRM.

The query is returning results and seems to be setting the fields in sms properly. 

The error is being thrown at this line:   Guid NewActid = crmService.Create(sms);

Any idea what is causing this?

ERROR Details:

System.NullReferenceException
HResult=0x80004003
Message=Object reference not set to an instance of an object.
Source=UploadLeads_toCRM
StackTrace:
at UpdateCRM.Program.HMtoCRM() in C:\...\UploadLeads_toCRM\Program.cs:line 149
at UpdateCRM.Program.Main(String[] args) in C:\...\UploadLeads_toCRM\Program.cs:line 32   

CODE:

using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader r = command.ExecuteReader();

var p = 0;

while (r.Read())
{
Console.WriteLine(r["contactid"].ToString());
Console.WriteLine(r["date"].ToString());
Console.WriteLine(r["messages"].ToString());


var messages = r["messages"].ToString();

var sms = new ksl_sms
{
ActualStart = DateTime.Parse(r["date"].ToString()),
ActualEnd = DateTime.Parse(r["date"].ToString()),
ksl_Contact = new EntityReference("contact", Guid.Parse(r["contactid"].ToString())),
RegardingObjectId = new EntityReference("contact", Guid.Parse(r["contactid"].ToString())),
OwnerId = new EntityReference("systemuser", Guid.Parse(r["ownerid"].ToString())),
ksl_completeby = new EntityReference("systemuser", Guid.Parse(r["ownerid"].ToString())),
StatusCode = new OptionSetValue(1),
ksl_TextsReceived = Convert.ToInt16(r["totalreceived"]),
ksl_TextsSent = Convert.ToInt16(r["totalsent"].ToString()),
Description = r["messages"].ToString(),
Subject = "Text Conversation"
};

Guid NewActid = crmService.Create(sms);

  • Verified answer
    JonathanKisco Profile Picture
    25 on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    I ended up going a totally different route and got it to work using the below to ClientCredentials method to connect.  Hope it's helpful if anyone else runs into this issue.

           public static IOrganizationService ConnectD35OnlineUsingOrgSvc()

           {

               IOrganizationService organizationService = null;

               String username = "***";

               String password = "***";

               String url = "kisco.api.crm.dynamics.com/.../Organization.svc";

               try

               {

                   ClientCredentials clientCredentials = new ClientCredentials();

                   clientCredentials.UserName.UserName = username;

                   clientCredentials.UserName.Password = password;

                   // For Dynamics 365 Customer Engagement V9.X, set Security Protocol as TLS12

                   ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

                   organizationService = (IOrganizationService)new OrganizationServiceProxy(new Uri(url), null, clientCredentials, null);

                   if (organizationService != null)

                   {

                       Guid gOrgId = ((WhoAmIResponse)organizationService.Execute(new WhoAmIRequest())).OrganizationId;

                       if (gOrgId != Guid.Empty)

                       {

                           Console.WriteLine("Connection Established Successfully...");

                       }

                   }

                   else

                   {

                       Console.WriteLine("Failed to Established Connection!!!");

                   }

               }

               catch (Exception ex)

               {

                   Console.WriteLine("Exception occured - " + ex.Message);

               }

               return organizationService;

           }

     IOrganizationService service = ConnectD35OnlineUsingOrgSvc();

    Guid NewActid = service.Create(sms);

  • a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    You can find the version of the tooling in the version of the NuGet package used.

  • JonathanKisco Profile Picture
    25 on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    These are the directions I used for setting things up.

    docs.microsoft.com/.../quickstart-register-app

    Because of our AD set up I haven't been able to add a user in Dynamics for this app.  But I have been trying to use the service account I was using previously with the Office365 authentication I was using.

    How do I tell which version of XRMTooling I have?

  • a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    I had issues with customer's production this morning so Iconfigured new App User and fixed the integration. So... I'm pretty sure the connection string approach works.

    What XrmTooling/Xrm.Sdk version do you use? My recommendation - update it to the latest.

    Can you please provide the step by step details how you configured App Registration in Azure and created App User in dataverse?

  • JonathanKisco Profile Picture
    25 on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    Yes, sorry I forgot to say I tried it with the ClientSecret string/parameters with no luck either.

  • a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    I checked the article you mentioned and your connection string is not even close to what is written over there.

    AuthType is ClientSecret, no user id, and password and clientid/clientsecret instead of it.

  • JonathanKisco Profile Picture
    25 on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    No change :/

    I also verified that I could log in to GUI with the user so all the permissions there are correct.

  • a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    Instead of using

    IOrganizationService crmService = crmConn.OrganizationServiceProxy;

    Guid NewActid = crmService.Create(sms);

    try to use

    Guid NewActid = crmConn.Create(sms);

  • JonathanKisco Profile Picture
    25 on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    I tried that, but still no luck.   Here is my connection string, I am pulling the appid from Application (client) ID in Azure.  

    I tried following these directions, but I was unable to create an application user in Dynamics, I think because we currently pull our users from our on prim instance of AD. https://optimallogics.com/connect-to-ms-dynamics-365-crm-using-oauth-in-c-sharp/

    Is there anything I should be doing in the AD set up of the app?   Also do you know any instructions for how to see the Oauth connection attempt response? I couldn't find anything, but it seems that might help give a clue on the issue. 

    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

               CrmServiceClient crmConn = new CrmServiceClient("AuthType = OAuth; " +

                                               "Url = https://kis.crm.dynamics.com; " +

                                               "Username=[user]@kis.onmicrosoft.com; Password=*****" +

                                               "AppId=33a****;  " +

                                               "RedirectUri = app://33a****;  " +

                                               "LoginPrompt = Auto ");

               IOrganizationService crmService = crmConn.OrganizationServiceProxy;

    Guid NewActid = crmService.Create(sms);  <--- Fail point


  • a33ik Profile Picture
    84,331 Most Valuable Professional on at
    RE: System.NullReferenceException: 'Object reference not set to an instance of an object.'

    You can check this video - nishantrana.me/.../

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