Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM (Archived)

Object reference not set to an instance of an object.

Posted on by Microsoft Employee

Dear All,

I'm trying to insert couple of records for Entity person 

here is the code I wrote:

Entity account  = new Entity("contact");

            account.Attributes["firstname"] = "Test";

            account.Attributes["lastname"] = "Test";

            account.Attributes["datatel_prospectsourceid"] = "Beacardinal Website";

            account.Attributes["preferredcontactmethodcode"] = new OptionSetValue(2);

            account.Attributes["address1_telephone1"] = "3333333333";

But I keep getting this error message: "Object reference not set to an instance of an object." .

Any suggestions?

Regards

*This post is locked for comments

  • tw0sh3ds Profile Picture
    tw0sh3ds 5,600 on at
    RE: Object reference not set to an instance of an object.

    You are having this issue because of error with connecting to Dynamics 365. You can enable tracing for XrmTooling, like described here:

    docs.microsoft.com/.../configure-tracing-xrm-tooling

    In trace you should get more detailed information why you cannot connect (9 out of 10 times it's because you have bad connection string)

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Object reference not set to an instance of an object.

    Hi Nadeeja,

    I'm still getting the same error - 'Object reference not set to an instance of an object.' after making all the changes you suggested still stucked!! I also added a new line for calling the Organization service to create an entity for me which is accountId = _orgService.Create(account); and its throwing an exception on that line see below: Please assist.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Client;

    using Microsoft.Crm.Sdk.Messages;

    using System.Data;

    using System.Data.SqlClient;

    using System.Data.SqlTypes;

    using Microsoft.Xrm.Client;

    using Microsoft.Xrm.Client.Services;

    using Microsoft.Xrm.Tooling.Connector;

    using NUnit.Framework;

    using System.Configuration.Assemblies;

    using System.ServiceModel.Description;

    public class CRM

       {

           private OrganizationServiceProxy _serviceProxy;

           private IOrganizationService _orgService;

           // Define the IDs needed for this sample.

           private Guid _accountId;

           public static void Main(string[] args)

           {

               CRM crm = new CRM();

               crm.Run();

           }

           public void Run()

           {

               //try

               //{

               string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString;

               string strOrganizationUri = System.Configuration.ConfigurationManager.AppSettings["MyUrI"];

               var credentials = new ClientCredentials();

               credentials.UserName.UserName = System.Configuration.ConfigurationManager.AppSettings["UserName"];

               credentials.UserName.Password = System.Configuration.ConfigurationManager.AppSettings["Password"];

               var organizationUriIFD = new Uri(strOrganizationUri);

               //In-case I have organization service issue being null

               System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

               //Use the connection string named "MyCRMServer from the configuration file "  

               CrmServiceClient crmSvc = new CrmServiceClient(System.Configuration.ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString);

               Console.WriteLine("Connection String Found on App.Config!!");

               //Wrapping connString to the CrmServiceClient Object

               CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);

               _orgService = crmSvc.OrganizationWebProxyClient != null ? crmSvc.OrganizationWebProxyClient :(IOrganizationService)crmSvc.OrganizationServiceProxy;

               _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

               Console.WriteLine("Succesfully Connected to the IOrganization Service!!");

               CreateRequiredRecords();

               //Account account = new Account { Name = "Tester Account" };

               Entity account = new Entity("account");

               account.Attributes["AccountId"] = "141da83-3ee7-e811-80f3-005056b546bz";

               account.Attributes["RoleTypeId"] = "2";

               account.Attributes["RoleStatusId"] = "2";

               // Create an account record named Tester Account.

           _accountId = _orgService.Create(account);

               Console.Write(_accountId);

               //Console.WriteLine("{0} {1} {2} created,", account.LogicalName);

               Console.Write("Account created succesfully");

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Object reference not set to an instance of an object.

    Hi Nadeeja,

    I'm still getting the same error - 'Object reference not set to an instance of an object.' after making all the changes you suggested still stucked!! I also added a new line for calling the Organization service to create an entity for me which is accountId = _orgService.Create(account); and its throwing an exception on that line see below: Please assist.

    using System;

    using System.Collections.Generic;

    using System.Linq;

    using System.Text;

    using System.Threading.Tasks;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    using Microsoft.Xrm.Sdk.Client;

    using Microsoft.Crm.Sdk.Messages;

    using System.Data;

    using System.Data.SqlClient;

    using System.Data.SqlTypes;

    using Microsoft.Xrm.Client;

    using Microsoft.Xrm.Client.Services;

    using Microsoft.Xrm.Tooling.Connector;

    using NUnit.Framework;

    using System.Configuration.Assemblies;

    using System.ServiceModel.Description;

    public class CRM

       {

           private OrganizationServiceProxy _serviceProxy;

           private IOrganizationService _orgService;

           // Define the IDs needed for this sample.

           private Guid _accountId;

           public static void Main(string[] args)

           {

               CRM crm = new CRM();

               crm.Run();

           }

           public void Run()

           {

               //try

               //{

               string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString;

               string strOrganizationUri = System.Configuration.ConfigurationManager.AppSettings["MyUrI"];

               var credentials = new ClientCredentials();

               credentials.UserName.UserName = System.Configuration.ConfigurationManager.AppSettings["UserName"];

               credentials.UserName.Password = System.Configuration.ConfigurationManager.AppSettings["Password"];

               var organizationUriIFD = new Uri(strOrganizationUri);

               //In-case I have organization service issue being null

               System.Net.ServicePointManager.SecurityProtocol = System.Net.SecurityProtocolType.Tls12;

               //Use the connection string named "MyCRMServer from the configuration file "  

               CrmServiceClient crmSvc = new CrmServiceClient(System.Configuration.ConfigurationManager.ConnectionStrings["MyCRMServer"].ConnectionString);

               Console.WriteLine("Connection String Found on App.Config!!");

               //Wrapping connString to the CrmServiceClient Object

               CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString);

               _orgService = crmSvc.OrganizationWebProxyClient != null ? crmSvc.OrganizationWebProxyClient :(IOrganizationService)crmSvc.OrganizationServiceProxy;

               _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

               Console.WriteLine("Succesfully Connected to the IOrganization Service!!");

               CreateRequiredRecords();

               //Account account = new Account { Name = "Tester Account" };

               Entity account = new Entity("account");

               account.Attributes["AccountId"] = "141da83-3ee7-e811-80f3-005056b546bz";

               account.Attributes["RoleTypeId"] = "2";

               account.Attributes["RoleStatusId"] = "2";

               // Create an account record named Tester Account.

           _accountId = _orgService.Create(account);

               Console.Write(_accountId);

               //Console.WriteLine("{0} {1} {2} created,", account.LogicalName);

               Console.Write("Account created succesfully");

  • Suggested answer
    tw0sh3ds Profile Picture
    tw0sh3ds 5,600 on at
    RE: Object reference not set to an instance of an object.

    Well you are now providing string from code, so I can't tell you that. It depends from where you have this information. You are now setting "Beacardinal Website" which is hardcoded, so I can't see any difference in providing hardcoded Guid. Of course it would be better to put in some kind of configuration dictionary in CRM or whatever, but this is another story.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Object reference not set to an instance of an object.

    Thx fo the answer,

    There is a field for states and it's look up , so is there better way to just provide state value and it get guid instead of providing guid from code ?

    Thx alot

  • Suggested answer
    tw0sh3ds Profile Picture
    tw0sh3ds 5,600 on at
    RE: Object reference not set to an instance of an object.

    Hi,

    The problem is not CRM related, it's C# related. This code:

    using (var serviceProxy = new OrganizationServiceProxy(config, credentials))
               {
                   // This statement is required to enable early-bound type support.
                   serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                   service = serviceProxy;
                   var who = new WhoAmIRequest();
                   //retreive user data from the server.
                   var whoResponse = (WhoAmIResponse)service.Execute(who);
                   System.Diagnostics.Debug.WriteLine(whoResponse.UserId);
                   return service;
               }


    makes no sense. You are creating serviceProxy in using {} block so it will be disposed when you exit using block. So returning this service makes no sense, you will be then trying to call a disposed object.

    If you want to use Using statement, you should wrap it around code that is using your service, so remove Using from CRMService method and do the Using statement inside submitInoRequestFormDataToCRM method.

    Also I'm not sure if this line is correct:

     account.Attributes["datatel_prospectsourceid"] = "Beacardinal Website";

    usually when the field is called like that it is EntityReference and you are assigning String to it. Assign EntityReference instead.

  • Suggested answer
    Pramod M Profile Picture
    Pramod M 1,445 on at
    RE: Object reference not set to an instance of an object.

    Hi Mohammed,

    In order to set the lookup you need to use EntityReference. Below please find the sample for lookup to contact. The field is primarycontactid.

    EntityReference primaryContactId = new EntityReference("contact", contactId);

    account["primarycontactid"] = primaryContactId;

  • Verified answer
    Nadeeja Bomiriya Profile Picture
    Nadeeja Bomiriya 6,804 on at
    RE: Object reference not set to an instance of an object.

    Hi mohammed,

    It should be something like below.

    account.Attributes["originsource"] = new EntityReference("source", sourceId);

    Where:

    originsource = Name of the lookup

    source = Entity name of the Source entity

    sourceId = GUID of the Source record you are associating with contact.

  • Community Member Profile Picture
    Community Member Microsoft Employee on at
    RE: Object reference not set to an instance of an object.

    Thx for the answer, It's contact and I found the issue which is , we have afield called origin source whcih has this setup:

    Data type:lookup

    target record type:Source

    So hwo can I add valeu for such field?

  • Suggested answer
    Nadeeja Bomiriya Profile Picture
    Nadeeja Bomiriya 6,804 on at
    RE: Object reference not set to an instance of an object.

    Hi mohammed,

    As Pawel mentioned, please provide the StackTrace.

    I noticed the first line is a bit strange.

    Entity account  = new Entity("contact");

    Which entity are you using? Account or Contact?  If it's Account record you are creating, change the code as below.

    Entity account  = new Entity("account");

    Also double check the attribute names you are using.  Maybe you have a typo.  Comment out the below three lines temporarily and just leave the mandatory fields and see if it works.

    account.Attributes["datatel_prospectsourceid"] = "Beacardinal Website";

    account.Attributes["preferredcontactmethodcode"] = new OptionSetValue(2);

    account.Attributes["address1_telephone1"] = "3333333333";

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

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Tips for Writing Effective Suggested Answers

Best practices for providing successful forum answers ✍️

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,253 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,188 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans