As developers, sometimes we need to execute CRUD operations outside CRM to validate certain components or a specific behavior. Hence, a console application is needed. To create a console app that connects to CRM, you need to follow the next steps:
- Open Visual Studio
- Create a new console application. Make sure your target framework is 4.5.2 or higher
- Open App.config file. Here, we’ll need to configure our target organization and user credentials. For MS Dynamics CRM Online, add the following XML:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <connectionStrings> <add name="CRM_String_Connection" connectionString="AuthType=Office365;Url=YOUR_ORGANIZATION_URL; Username=YOUR_USER_NAME; Password=YOUR_PASSWORD" /> </connectionStrings> </configuration>
For MS Dynamics CRM On premises, the XML connection changes, please find it below:
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" /> </startup> <connectionStrings> <add name="CRM_String_Connection" connectionString="AuthType=AD;Url=YOUR_ORGANIZATION_URL; Domain=YOUR_DOMAIN; Username=YOUR_USER_NAME; Password=YOUR_PASSWORD" /> </connectionStrings> </configuration>
The most important part of the XML above is in connectionString attribute. Here, you’ll need to set the following parameters:
- AuthType – Authentication Type(Active Directory or Office 365).
- Url – URL of the organization you want to connect to.
- Username – The User name you use to log in the target organization.
- Password – The user password
- Domain – Only required for On premises, define the domain in the Active Directory.
4. Click on save to save the changes you did on App.config file.
5. Open Program.cs file
6. Add the following Using lines:
using Microsoft.Xrm.Tooling.Connector; using Microsoft.Crm.Sdk; using System.Configuration;
7. Go to Main method. Here, we’ll need to create three objects:
// Get the connection string saved in App.config. string CRM_String_Connection = ConfigurationManager.ConnectionStrings["CRM_String_Connection"].ConnectionString; // Do the actual connection to CRM using a CRM Service Client object, sending user credentials as parameter. CrmServiceClient crmConn = new CrmServiceClient(CRM_String_Connection); // Get Organization Service Proxy. This is needed to excecute any CRUD operation in CRM. IOrganizationService crmService = crmConn.OrganizationServiceProxy;
crmService will be the key object to do any CRUD Operation in CRM, same as “service” in plugins. Execute the console and you are ready to go!
Let me know any question or doubt!