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)

need help connecting to CRM using C# with console

(0) ShareShare
ReportReport
Posted on by

Hello,

I've never done this before, but I want to retrieve records from different entities in CRM using C# and display them in console. Can anyone show me how?

Thank you!

*This post is locked for comments

I have the same question (0)
  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    This is pretty straight forward, and I will show you two methods for this.

    First you need to add references to your project.

    You will need to add the Microsoft.Xrm.Sdk and Microsoft.Xrm.Tooling.Connector assembly references to your project.

    Within the console application, add the following to the namespace declaration area (the commented lines can be used if you need to access query, metadata or messages):

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Tooling.Connector;

    // using Microsoft.Xrm.Sdk.Metadata;

    // using Microsoft.Xrm.Sdk.Messages;

    // using Microsoft.Xrm.Sdk.Query;

    Add a global variable to your class for the Organization Service:

    // Not required if you decide to use CrmServiceClient only

    private IOrganizationService _orgService;

    Option 1 is to connect using a connection string:

    In your App.Config add the following configuration:

     <connectionStrings>

       <add name="Server=domain.com, organization=myorg, user=crmadmin@domain.local"

            connectionString="Url=crminternal.domain.com/.../Organization.svc; Username=domain\crmadmin; Password=CRM_PASSWORD; authtype=IFD"/>

     </connectionStrings>

    string connectionString = ConfigurationManager.ConnectionStrings["name"].ConnectionString;

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

    Option 2 is to connect using individual application settings:

    In your App.Config add the following application settings:

     <appSettings>

       <add key="UserName" value="domain\crmadmin"/>

       <add key="Password" value="CRM_PASSWORD" />

       <add key="InternalUrl" value="crminternal.domain.com"/>

       <add key="OrgName" value="myorg"/>

     </appSettings>

                   string userName = ConfigurationManager.AppSettings["UserName"].ToString();

                   string password = ConfigurationManager.AppSettings["Password"].ToString();

                   string internalUrl = ConfigurationManager.AppSettings["InternalUrl"].ToString();

                   string orgName = ConfigurationManager.AppSettings["OrgName"].ToString();

                   NetworkCredential creds = new NetworkCredential(userName, ConvertToSecureString(password));

                   Microsoft.Xrm.Tooling.Connector.AuthenticationType authType = Microsoft.Xrm.Tooling.Connector.AuthenticationType.IFD;

                   CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(creds, authType, internalUrl, "443", orgName, true, true, null);

    That's basically it.

    You can check if the connection is ready by using the following statement:

    if (conn.IsReady) ...

    If you want to use the Organization Service:

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

    You should be able to get it working now.

    Hope this helps.

  • Community Member Profile Picture
    on at

    Thank you for the reply but I'm having trouble understanding your solution. Can you guide me through step by step? Say I have an entity called Contact in CRM, and I want to retrieve and display a field called name in the entity Contact.

  • Verified answer
    RaviKashyap Profile Picture
    55,410 Moderator on at

    Hi Heimmu,

    You can refer the below blog -

    community.dynamics.com/.../simple-dynamics-crm-console-application

    Hope this helps.

  • Suggested answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    Hi Heimmu,

    The code above is just the connectivity to CRM, not the actual Retrieval of data.

    If you want to retrieve data, you need to query crm using a query expression after the connection:

    EntityCollection contacts = RetrieveContacts();

    if (contacts.Entities.Count > 0)

    {

      foreach (Entity contact in contacts.Entities)

      {

         Guid contactId = contact.Id;

         string firstName = contact.Contains("firstname") ? contact["firstname"].toString() : "";

         string lastName = contact.Contains("lastname") ? contact["lastname"].toString() : "";

         Console.WriteLine(firstName + " " + lastName);

      }

    }

    // function to retrieve contacts and returns Entity Collection

           private EntityCollection RetrieveContacts()

           {

               QueryExpression query = new QueryExpression()

               {

                   EntityName = "contact",

                   ColumnSet = new ColumnSet(true),

                   Criteria = new FilterExpression(LogicalOperator.And)

                   {

                       Conditions =

                       {

                           new ConditionExpression("lastname", ConditionOperator.Equal, "Smith"),

                           new ConditionExpression("statuscode", ConditionOperator.NotEqual, 1) // Active

                       }

                   }

               };

               try

               {

                   EntityCollection results = service.RetrieveMultiple(query);

                   return results;

               }

               catch (FaultException<OrganizationServiceFault> ex)

               {

                   throw new InvalidPluginExecutionException("An error occurred in the RetrieveSteps function of the plug-in.", ex);

               }

           }

    Hope this helps.

  • Community Member Profile Picture
    on at

    I got the following error message, does this mean my connection failed?

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

    System.Configuration.ConnectionStringSettingsCollection.this[string].get returned null.

    From this line

    string connectionString = ConfigurationManager.ConnectionStrings["name"].ConnectionString;

    Thank you!

  • Verified answer
    TomSmelser Profile Picture
    1,570 on at

    Make sure your "name" matches the connection name in your config file.

  • Verified answer
    Aric Levin - MVP Profile Picture
    30,190 Moderator on at

    You can also change whatever is in "name" to 0. That will mean your first connection string (or connection string at index 0).

    string connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;

    The name for the connection string in this case is long, and can be changed. It was there for show purposes. You can call it anything you want.

  • Verified answer
    Community Member Profile Picture
    on at

    hi,

    if give name Spaces:

    using Microsoft.Xrm.Tooling.Connector;

    using System.Configuration;

    using Microsoft.Xrm.Sdk;

    using Microsoft.Xrm.Sdk.Query;

    After Add to the App.config file:

    <connectionStrings>

       <add name="CRM" connectionString="AuthType=Office365;Url=organizationurl; Username=pankaj@tec.onmicrosoft.com; Password=*******"/>

     </connectionStrings>

    After add to the Console Application:

    ConnectingString:

    CrmServiceClient crmServiceClient = new CrmServiceClient(ConfigurationManager.ConnectionStrings["CRM"].ToString());

  • Community Member Profile Picture
    on at

    Thank you, I'm now connected to CRM. but I still can't display the information inside records. Suppose I just want to display 1 record

    I set the entityName to my Entity's name, id to the GUID of the record, and  columnset = new columnSet()

    Entity results = crmService.Retrieve(entityName, id, columnSet);

    //Console.WriteLine(results.GetAttributeValue(string));

    Now I have results of Entity type, does this contain all of the information of the record I specified?

    Thank you!

  • Community Member Profile Picture
    on at

    Never mind I got it figured out, Thank you everyone!

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