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

Notifications

Announcements

No record found.

Community site session details

Community site session details

Session Id :
Microsoft Dynamics CRM (Archived)

Retrieve Dynamics 365 Accounts with multiple columns using C# - Object reference not to an instance

(0) ShareShare
ReportReport
Posted on by

Hi everyone,

Recently we got our CRM online migrated to Dynamics 365. I have my CRM system integration with another third party system, To retrieve list of accounts with multiple column values, i was using CRM SDK via C# program. However after we migrated to Dynamics 365, my code is no longer working. Below is the code snipped which used to retrieve accounts list;

public static List<Account> GetCRMAccounts()
        {
            try
            {
                List<Account> p = new List<Account>();
                var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                string connectionString = appConfig.AppSettings.Settings["CRM"].Value.ToString().Trim();

                CrmServiceClient crmConn = new CrmServiceClient(connectionString);
                IOrganizationService crmService = crmConn.OrganizationServiceProxy;

                QueryExpression qe = new QueryExpression
                {
                    EntityName = "account",
                    ColumnSet = new ColumnSet("accountid", "name", "new_nickname")
                    
                };
                EntityCollection accounts = crmService.RetrieveMultiple(qe);

-------------------------------------------------------------------------------------------------------------------------

However the above code throw "Object reference not set to instance error" at the last line "EntityCollection accounts = crmService.RetrieveMultiple(qe);"

Not sure what has been changed upon migration.

Please can somebody help me to solve the issue?

Again i'm on Dynamics 365.

*This post is locked for comments

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

    Hi,

    Please make sure you are using latest SDK dll (v9.0).

    Mansoor

  • Community Member Profile Picture
    on at

    Hello Mansoor,

    Thanks for the reply.

    I have updated SDK dll's.  After that i started receiving below error when try to invoke;

    The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs

    Not sure what am i doing wrong?

    Thanks,

    Prajwal Shambhu

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi Prajwal,

    Which .Net framework are you using?

    Dynamics 365 (online), version 9.0,  applications using Transport Level Security (TLS) 1.2  . I would recommend update  Microsoft .NET Framework 4.6.2 or later. As TLS 1.2 is not the default protocol used by .NET Framework 4.5.2, but it is in .NET Framework 4.6.2.

    I have added security protocol in your code - 

    public static List<Account> GetCRMAccounts()
        {
            try
            {
                List<Account> p = new List<Account>();
                var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
                string connectionString = appConfig.AppSettings.Settings["CRM"].Value.ToString().Trim();
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; //  Added Security Type 
                CrmServiceClient crmConn = new CrmServiceClient(connectionString);
                IOrganizationService crmService = crmConn.OrganizationServiceProxy;
    
                QueryExpression qe = new QueryExpression
                {
                    EntityName = "account",
                    ColumnSet = new ColumnSet("accountid", "name", "new_nickname")
    
                };
                EntityCollection accounts = crmService.RetrieveMultiple(qe);


    Hope this helps.

  • Community Member Profile Picture
    on at

    Hi Goutam,

    Thanks for the response, however i have already updated my code with Security Protocol and i have .Net framework 4.7.1 installed in my machine.

    Now i'm getting different not the earlier one;

    ---------------------------------------------------------------

    The server was unable to process the request due to an internal error.  For more information about the error, either turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server in order to send the exception information back to the client, or turn on tracing as per the Microsoft .NET Framework SDK documentation and inspect the server trace logs

    Thanks,

    Prajwal Shambhu

  • Suggested answer
    gdas Profile Picture
    50,091 Moderator on at

    Hi Prajwal,

    Here is my code , its working fine for me . Please validate with this -

    Please make sure  you have  following SDK dll version
    Microsoft.Xrm.Sdk – 9.0.0.0
    Microsoft.Crm.Sdk.Proxy – 9.0.0.0

    ======================

    Program.cs

    =====================

    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Tooling.Connector;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Net;
    
    namespace OnlineLogin
    {
        class OnlineLoginSamples
        {
            private static IOrganizationService _orgService;      
            static void Main(string[] args)
            {
                //Get CRM Configuration Details 
                String connectionString = GetServiceConfiguration();
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                CrmServiceClient conn = new CrmServiceClient(connectionString);
                // Cast the proxy client to the IOrganizationService interface.
                _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy;
                Entity account = new Entity("account");
                account["name"] = "Dummy_Account_Test1";
                System.Guid _accountId = _orgService.Create(account);
            }
            private static String GetServiceConfiguration()
            {
                // Get available connection strings from app.config.
                int count = ConfigurationManager.ConnectionStrings.Count;
    
                // Create a filter list of connection strings so that we have a list of valid
                // connection strings for Microsoft Dynamics CRM only.
                List<KeyValuePair<String, String>> filteredConnectionStrings =
                    new List<KeyValuePair<String, String>>();
                for (int a = 0; a < count; a++)
                {
                    if (isValidConnectionString(ConfigurationManager.ConnectionStrings[a].ConnectionString))
                        filteredConnectionStrings.Add
                            (new KeyValuePair<string, string>
                                (ConfigurationManager.ConnectionStrings[a].Name,
                                ConfigurationManager.ConnectionStrings[a].ConnectionString));
                }
    
                // No valid connections strings found. Write out and error message.
                if (filteredConnectionStrings.Count == 0)
                {
                    Console.WriteLine("An app.config file containing at least one valid Microsoft Dynamics CRM " +
                        "connection string configuration must exist in the run-time folder.");
                    Console.WriteLine("\nThere are several commented out example connection strings in " +
                        "the provided app.config file. Uncomment one of them and modify the string according " +
                        "to your Microsoft Dynamics CRM installation. Then re-run the sample.");
                    return null;
                }
    
                // If one valid connection string is found, use that.
                if (filteredConnectionStrings.Count == 1)
                {
                    return filteredConnectionStrings[0].Value;
                }
    
                // If more than one valid connection string is found, let the user decide which to use.
                if (filteredConnectionStrings.Count > 1)
                {
                    Console.WriteLine("The following connections are available:");
                    Console.WriteLine("------------------------------------------------");
    
                    for (int i = 0; i < filteredConnectionStrings.Count; i++)
                    {
                        Console.Write("\n({0}) {1}\t",
                        i + 1, filteredConnectionStrings[i].Key);
                    }
    
                    Console.WriteLine();
    
                    Console.Write("\nType the number of the connection to use (1-{0}) [{0}] : ",
                        filteredConnectionStrings.Count);
                    String input = Console.ReadLine();
                    int configNumber;
                    if (input == String.Empty) input = filteredConnectionStrings.Count.ToString();
                    if (!Int32.TryParse(input, out configNumber) || configNumber > count ||
                        configNumber == 0)
                    {
                        Console.WriteLine("Option not valid.");
                        return null;
                    }
    
                    return filteredConnectionStrings[configNumber - 1].Value;
    
                }
                return null;
    
            }
    
            /// <summary>
            /// Verifies if a connection string is valid for Microsoft Dynamics CRM.
            /// </summary>
            /// <returns>True for a valid string, otherwise False.</returns>
            private static Boolean isValidConnectionString(String connectionString)
            {
                // At a minimum, a connection string must contain one of these arguments.
                if (connectionString.Contains("Url=") ||
                    connectionString.Contains("Server=") ||
                    connectionString.Contains("ServiceUri="))
                    return true;
    
                return false;
            }
        }
    }
    

    ===========================
    App.Config

    ==========================

    <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <connectionStrings>
    <add name="Server=CRM Online, organization=XXXXXX, user=goutam" connectionString="Url=xxxxxx.crm8.dynamics.com; Username=XXXXXXX@XXXXXX.onmicrosoft.com; Password=XXXXXX; authtype=Office365"/>
    </connectionStrings>
    <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
    </startup>
    <system.diagnostics>
    <trace autoflush="true"/>
    <sources>
    <source name="Microsoft.Xrm.Tooling.Connector.CrmServiceClient" switchName="Microsoft.Xrm.Tooling.Connector.CrmServiceClient" switchType="System.Diagnostics.SourceSwitch">
    <listeners>
    <add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
    <add name="fileListener"/>
    </listeners>
    </source>
    <source name="Microsoft.Xrm.Tooling.CrmConnectControl" switchName="Microsoft.Xrm.Tooling.CrmConnectControl" switchType="System.Diagnostics.SourceSwitch">
    <listeners>
    <add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
    <add name="fileListener"/>
    </listeners>
    </source>
    <source name="CrmSvcUtil" switchName="CrmSvcUtil" switchType="System.Diagnostics.SourceSwitch">
    <listeners>
    <add name="console" type="System.Diagnostics.ConsoleTraceListener"/>
    <add name="fileListener"/>
    </listeners>
    </source>
    </sources>
    <switches>

    <!--Possible values for switches: Off, Error, Warning, Information, Verbose
    Verbose: includes Error, Warning, Info, Trace levels
    Information: includes Error, Warning, Info levels
    Warning: includes Error, Warning levels
    Error: includes Error level-->

    <add name="Microsoft.Xrm.Tooling.CrmConnectControl" value="Off"/>
    <add name="Microsoft.Xrm.Tooling.Connector.CrmServiceClient" value="Error"/>
    <add name="CrmSvcUtil" value="Off"/>
    </switches>

    <sharedListeners>
    <add name="fileListener" type="System.Diagnostics.TextWriterTraceListener" initializeData="CrmSvcUtil.log"/>
    </sharedListeners>

    </system.diagnostics>
    <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Xrm.Sdk" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Xrm.Sdk.Deployment" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-7.0.0.0" newVersion="8.0.0.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.ServiceBus" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-2.4.0.0" newVersion="2.4.0.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.Crm.Sdk.Proxy" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0"/>
    </dependentAssembly>
    <dependentAssembly>
    <assemblyIdentity name="Microsoft.IdentityModel.Clients.ActiveDirectory" publicKeyToken="31bf3856ad364e35" culture="neutral"/>
    <bindingRedirect oldVersion="0.0.0.0-3.19.2.6005" newVersion="3.19.2.6005"/>
    </dependentAssembly>
    </assemblyBinding>
    </runtime>
    </configuration>

  • Community Member Profile Picture
    on at
    Hello, try to execute the code that you share and show the following error when getting the connection string of the App.config:
    
     int count = ConfigurationManager.ConnectionStrings.Count;
    
    Error CS1061
    'object' does not contain a definition for 'ConnectionStrings' nor is there any
    Extension method 'ConnectionStrings' that accepts a first argument of type 'object'
    (Missing any using directive or an assembly reference?)
    
    
    Could you tell me the cause of the error?
    
    I appreciate your support.
    
    regards!

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

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
SA-08121319-0 Profile Picture

SA-08121319-0 4

#1
Calum MacFarlane Profile Picture

Calum MacFarlane 4

#3
Alex Fun Wei Jie Profile Picture

Alex Fun Wei Jie 2

Last 30 days Overall leaderboard

Featured topics

Product updates

Dynamics 365 release plans