Skip to main content

Notifications

Announcements

No record found.

Microsoft Dynamics CRM forum
Answered

NullReferenceException Thrown using Organization Service RetrieveMultiple Method

Posted on by 55

My company uses Field Service and I have a single webpage our company uses to allow 3rd Party contractors to accept or decline work order assignments. No changes have been made to our processes or to the code for this app, but yesterday we began getting errors on the webpage. 

The error is that an "Object reference not set to an instance of an object." The thing is I'm having trouble finding any null objects where this error is being thrown.

On Page_Load I have a method that instantiates a private IOrganizationService variable. This method executes successfully and returns a connection. I updated this method a few months ago when WS-TRUST was deprecated and it seems to have been working with no issues:

public IOrganizationService GetOrganizationService()
{
    string serverUrl = ConfigurationManager.AppSettings["ServerUrl"];
    string userName = ConfigurationManager.AppSettings["UserName"];
    string password = ConfigurationManager.AppSettings["Password"];
    string errorMsg = String.Empty;
    try
    {
        ClientCredentials clientCredentials = new ClientCredentials();
        clientCredentials.UserName.UserName = userName;
        clientCredentials.UserName.Password = password;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        this.organizationService = new CrmServiceClient("AuthType=OAuth;Username=CREDUSER;Password=CREDPWD;Url=ORGURL;AppId=AZUREAPPID;RedirectUri=AZUREREDIRECTURI;LoginPrompt=Auto");
    }
    catch (Exception exception)
    {
        errorMsg = exception.Message;
    }

    return this.organizationService;
}

Then, based on a querystring variable in the URL there is a lookup to retrieve the Work Order record in CE:

public void RetrieveWorkOrder()
{
    if (base.Request.QueryString["workorder"] != null)
    {
        string QEmsdyn_workorder_msdyn_name = Convert.ToString(base.Request.QueryString["workorder"]).Trim();
        this.hdn_workOrderNumber.Value = QEmsdyn_workorder_msdyn_name;
        QueryExpression QEmsdyn_workorder = new QueryExpression("msdyn_workorder");
        QEmsdyn_workorder.ColumnSet.AddColumns(new string[] { "dxc_primarytechnician", "dxc_backuptechnician", "msdyn_name", "createdon", "dxc_scheduledbooking", "dxc_assignedtechnician", "msdyn_substatus" });
        QEmsdyn_workorder.Criteria.AddCondition("msdyn_name", 0, new object[] { QEmsdyn_workorder_msdyn_name });

        // debugging NullReferenceException
        string msg = String.Empty;
        if (Object.ReferenceEquals(QEmsdyn_workorder, null))
        {
             msg = "QEmsdyn_workorder is null";
        }
        if (Object.ReferenceEquals(this.organizationService, null))
        {
            msg = "organizationService is null";
        }
        if (Object.ReferenceEquals(QEmsdyn_workorder_msdyn_name, null))
        {
            msg = "QEmsdyn_workorder_msdyn_name is null";
        }

        // try calling a method of organizationservice just as an extra step
        msg = this.organizationService.ToString();
        // end debuggin

        EntityCollection workOrderCollection = this.organizationService.RetrieveMultiple(QEmsdyn_workorder); // <--- ERROR THROWN HERE

        if (workOrderCollection.Entities.Count > 0)
        {
            this.workOrderEntity = workOrderCollection.Entities[0];
            this.hdn_workOrderCreatedOn.Value = Convert.ToString(this.workOrderEntity["createdon"]);
            this.hdn_scheduledBooking.Value = Convert.ToString(this.workOrderEntity["dxc_scheduledbooking"]);
            this.hdn_assignedTechnician.Value = Convert.ToString(((OptionSetValue)this.workOrderEntity["dxc_assignedtechnician"]).Value);
        }
    }
}

The organizationService object is not null, the QEmsdyn_workorder QueryExpression object is not null, the ColumnSet and Criteria members of the QueryExpression are not null, yet this line continues to produce the error:

EntityCollection workOrderCollection = this.organizationService.RetrieveMultiple(QEmsdyn_workorder);

I've also checked the ColumnSet values just to make sure they are correct, although in my head I know they are correct and also again this has been working for over a year with the only change being to change authentication when WS-TRUST was deprecated a few months ago. But even after that change this app has been used daily for months with no issues. 

I'm feel like I've hit a wall with this for the moment so wanted to reach out to see if anyone else has any ideas or are experiencing a similar issue. The answer may be right in front of my eyes but I've looked at this long enough that I can't see it.

  • Jeremy Ginn Profile Picture
    Jeremy Ginn 55 on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    Yes very helpful Bipin, thank you again!

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,962 Moderator on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    Hi,

    Cool.

    Now instead of just throwing static error , you can try below code which will throw an actual error .

    throw new Exception ($"Connection unsuccessful {client.LastCrmException}");

    Hope this helps!

    Thanks,

    Bipin

  • Jeremy Ginn Profile Picture
    Jeremy Ginn 55 on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    Hi Bipin, I had actually tried to perform that check before but I see now I was mistakenly looking for the property on the IOrganizationService object where it does not exist. I see now that I need to do as you suggest and create a CrmServiceClient object, check the property and if true assign to my local IOrganizationService variable. Hopefully this will prevent this type of issue going forward. Thanks again for your help and replies.

                   

    //this.organizationService = new CrmServiceClient("AuthType=OAuth;Username=USER;Password=PWD...");
    
                   var client = new CrmServiceClient("AuthType=OAuth;Username=USER;Password=PWD...");
    
                   if (client.IsReady)
    
                   {
    
                       this.organizationService = client;
    
                   }
    
                   else
    
                   {
    
                       throw new Exception("Connection unsuccessful");
    
                   }

  • Verified answer
    Bipin D365 Profile Picture
    Bipin D365 28,962 Moderator on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    Hi,

    You should first check is ready property in your code to know if connection is success

    Var client= new CrmServiceClient(connectionString):

    if(client.isReady)

    {

    Do your operation

    }

    else

    Log error

    Thanks,

    Bipin

  • Suggested answer
    Jeremy Ginn Profile Picture
    Jeremy Ginn 55 on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    This was an interesting scenario but it is resolved now. The issue ended up being with the service account we were using to authenticate using OAuth. Connections were being rejected for this user, possibly related to an issue we had earlier in the week with our Azure AD where our network admin had to rebuild the Azure AD Connector. Either way, even though the connection was being refused the IOrganizationService object was still being instantiated and no error was being thrown to the catch block by the CrmServiceClient.  

  • Jeremy Ginn Profile Picture
    Jeremy Ginn 55 on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    Hi Bipin, thank you for your reply. I did update the project nuget packages but that made no difference.

    I believe I have narrowed down the issue to having to do with my connection using the IOrganizationService interface, because I have one other project that updates customer assets in Dynamics CE from our ERP that uses the same connection method, and that is the only commonality between the two projects. That service is also producing the same error when trying to retrieve and update a customer asset in CE. I'm just unsure of how to troubleshoot a null reference exception when I can't find any null references, and both projects have been working for quite a while with no issues until very recently while no changes have been made.

  • Suggested answer
    Bipin D365 Profile Picture
    Bipin D365 28,962 Moderator on at
    RE: NullReferenceException Thrown using Organization Service RetrieveMultiple Method

    Hi,

    Have you tried updating nuget package to use latest version for crm SDK dll?

    Thanks,

    Bipin

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

Anton Venter – Community Spotlight

Kudos to our October Community Star of the month!

Announcing Our 2024 Season 2 Super Users!

A new season of Super Users has arrived, and we are so grateful for the daily…

Dynamics 365 Community Newsletter - September 2024

Check out the latest community news

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 290,558 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 228,647 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,148

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans