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

Notifications

Announcements

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Object reference not set to an instance of an object Error while Attempting to retrieve record in crm

(0) ShareShare
ReportReport
Posted on by

Hi, 
On a plugin i attempt to retrieve record in other CRM instance. 
Here is the code:

namespace TES_CRM_PLUGIN
{
    public class Class1 : IPlugin
    {
        string connstring = string.Empty;
        
        IOrganizationService _service;
        Guid fabercastel = Guid.Empty;
        string x;
        public void Execute(IServiceProvider ServiceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)ServiceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory servicefactory = (IOrganizationServiceFactory)ServiceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = servicefactory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity ent = (Entity)context.InputParameters["Target"];

                if (ent.LogicalName != "opportunity")
                    return;
                //Getting id from new field during create process in CRM On-Premise
                string idnum = ent.GetAttributeValue<String>("new_id");

                if (ent.Attributes.Contains("name"))
                {
                   
                    //Attempting to connect CRM Online
                    connstring = @"Url=office.crm5.dynamics.com; Username=admin@office.onmicrosoft.com; Password=crmoffice; authtype=Office365";
                    CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connstring);
                    _service = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;

                        if (!string.IsNullOrEmpty(idnum))
                        {
                            try{
                           
                                //Getting record from CRM Online by matching the idnum
                                QueryExpression query = new QueryExpression("opportunity");
                                string[] cols2 = { "new_presalesid", "name" };
                                query.Criteria = new FilterExpression();
                                query.Criteria.AddCondition("new_presalesid", ConditionOperator.Equal, idnum);
                                query.ColumnSet = new ColumnSet(cols2);
                                EntityCollection preid = _service.RetrieveMultiple(query);

                                foreach (Entity cloudent in preid.Entities)
                                {
                                    if (cloudent.Attributes.Contains("new_presalesid"))
                                    {
                                        x = cloudent.GetAttributeValue<String>("new_presalesid");
                                    }
                                }
                            }
                            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                            {
                                throw new InvalidPluginExecutionException(ex.Message);
                            }
                        }

                       // Fill the description field in the CRM On-premise, by value we were took from CRM Online
                        if (!string.IsNullOrEmpty(x))
                        {
                            ent["description"] = x;
                        }
                        else
                        {
                            ent["description"] = "FAK";
                        }
                  
                }

            }
        }
    }
}

The plugin throw an error like this:

Unhandled Exception: System.ServiceModel.FaultException`1[[Microsoft.Xrm.Sdk.OrganizationServiceFault, Microsoft.Xrm.Sdk, Version=8.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35]]: Error: Object reference not set to an instance of an object.Detail: 
<OrganizationServiceFault xmlns:i="www.w3.org/.../XMLSchema-instance" xmlns="schemas.microsoft.com/.../Contracts">
  <ActivityId>48b026df-da81-4eba-a075-d7f3b3b1bbc3</ActivityId>
  <ErrorCode>-2147220891</ErrorCode>
  <ErrorDetails xmlns:d2p1="schemas.datacontract.org/.../System.Collections.Generic">
    <KeyValuePairOfstringanyType>
      <d2p1:key>OperationStatus</d2p1:key>
      <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema" i:type="d4p1:string">0</d2p1:value>
    </KeyValuePairOfstringanyType>
    <KeyValuePairOfstringanyType>
      <d2p1:key>SubErrorCode</d2p1:key>
      <d2p1:value xmlns:d4p1="www.w3.org/.../XMLSchema" i:type="d4p1:string">-2146233088</d2p1:value>
    </KeyValuePairOfstringanyType>
  </ErrorDetails>
  <Message>Error: Object reference not set to an instance of an object.</Message>
  <Timestamp>2017-02-22T03:44:48.8456384Z</Timestamp>
  <ExceptionSource i:nil="true" />
  <InnerFault i:nil="true" />
  <OriginalException i:nil="true" />
  <TraceText>

[TES CRM PLUGIN: TES_CRM_PLUGIN.Class1]
[4b76457a-05f8-e611-80cb-000c2901c43a: TES_CRM_PLUGIN.Class1: Create of opportunity]
Attempting to connect CRM ONline..
Trying to get account name

</TraceText>
</OrganizationServiceFault>


The error is coming from this line:

 QueryExpression query = new QueryExpression("opportunity");
                                string[] cols2 = { "new_presalesid", "name" };
                                query.Criteria = new FilterExpression();
                                query.Criteria.AddCondition("new_presalesid", ConditionOperator.Equal, idnum);
                                query.ColumnSet = new ColumnSet(cols2);
                                EntityCollection preid = _service.RetrieveMultiple(query);


There, i used _service to retrieve queryexpression. The _service is declare in this line:

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

It's seem that _service is null. So it can't be used to retrieving data.

I have been searching on the internet how to solve this, but i am unable to find a way to solve it yet.

*This post is locked for comments

I have the same question (0)
  • Community Member Profile Picture
    on at

    Use service created in this line:

    IOrganizationService service = servicefactory.CreateOrganizationService(context.UserId);

    EntityCollection preid = service.RetrieveMultiple(query);

  • Suggested answer
    Nadeeja Bomiriya Profile Picture
    6,804 on at

    Hi Fikri,

    Your connectionstring should look like below.

    connectionString="Url=https://contoso.crm.dynamics.com; Username=someone@contoso.onmicrosoft.com; Password=password; authtype=Office365"

    Make sure the contoso in URL attribute must be replaced with the name of the CRM instance Url=contoso.crm.dynamics.com

    https://msdn.microsoft.com/en-us/library/jj602970.aspx

  • Community Member Profile Picture
    on at

    hi mohd, i can't use that. since if i used that, its mean that i retrieve record from crm onpremise where the plugin is deployed. Meanwhile i need to retrieve records in crm online

  • Community Member Profile Picture
    on at

    Hi Nadeeja, my region is in souteast asia. The  url for my region is using crm5. Also i make sure that the contoso in your example has already i changed to our crm instance.

  • Suggested answer
    Nausher Sayeed Profile Picture
    522 on at

    Hi Fikri,

    As Nadeeja said check your CRM URL.

    Cheers,

    Nausher

  • Suggested answer
    Nadeeja Bomiriya Profile Picture
    6,804 on at

    Hi Fikri,

    Can you please try the same code in a console app to see if you can get the _service with a value?

    Or try below code and see if you get a value for _orgService.

    var connectionString = "Url=contoso.crm.dynamics.com; Username=someone@contoso.onmicrosoft.com; Password=password; authtype=Office365";
    
    // Connect to the CRM web service using a connection string.
    CrmServiceClient conn = new Xrm.Tooling.Connector.CrmServiceClient(connectionString);
    
    // Cast the proxy client to the IOrganizationService interface.
    _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;


  • Community Member Profile Picture
    on at

    Using console application. i am able to retrieve record by same code. I want to try to deploy this on the different machine which has same domain with the crm on prem. i will tell the result later

  • Nausher Sayeed Profile Picture
    522 on at

    Hi,

    Can you please check your time zone.

    community.dynamics.com/.../204264

    support.microsoft.com/.../2502671

  • Community Member Profile Picture
    on at

    Hii, back again. I have tried to deploy and tested with other machine. But still no luck. Did i miss something ?

  • Nadeeja Bomiriya Profile Picture
    6,804 on at

    Did you get a chance to try the console app?

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

News and Announcements

Season of Giving Solutions is Here!

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 CRM (Archived)

#1
Shidin Haridas Profile Picture

Shidin Haridas 2

#2
Abdullah13 Profile Picture

Abdullah13 1

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans