1. Once Create empty Console app we need to install below two NuGet Packages;
- Microsoft.CrmSdk.CoreAssemblies
- Microsoft.IdentityModel
2. Now Download and reference below Assemblies
- Microsoft.IdentityModel.Clients.ActiveDirectory.dll
- Microsoft.Xrm.Tooling.Connector.dll
3. Now create the early bound classes
For this Open the Command Prompt and go to Bin Folder of Dynamics 365 SDK. Then execute CrmSvcUtil.exe. Check given sample command line used for my scenario;
CrmSvcUtil.exe /url:https://xxxx.crm6.dynamics.com/XRMServices/2011/Organization.svc /out:Xrm.cs /username:xxxx@xxxx.onmicrosoft.com /password:xxxxx/namespace:TestConsoleDynamics365 /serviceContextName:TcServiceContext
4. Add the early bound Classes
Add a Class Library file to solution called Xrm.cs and copy relevant content from generated file in previous step. Your solution will now look like this in terms of file structure.
5. Now Open the Program.cs file and do the code as below. This sample consist of one method that uses Linq query to retrieve account name from Id.
using System; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Tooling.Connector; using System.Linq; namespace TestConsoleDynamics365 { class Program { static void Main(string[] args) { Console.WriteLine("Conncetion to Dynamics 365"); String connectionString = GetServiceConfiguration(); Console.WriteLine("Conncetion string : " + connectionString); Console.WriteLine("Press Enter to move on.."); Console.ReadLine(); CrmServiceClient conn = new Microsoft.Xrm.Tooling.Connector.CrmServiceClient(connectionString); IOrganizationService _orgService = (IOrganizationService)conn.OrganizationWebProxyClient != null ? (IOrganizationService)conn.OrganizationWebProxyClient : (IOrganizationService)conn.OrganizationServiceProxy; //TEST CODE Account acc = RetriveAccountById(_orgService, new Guid("628B3A81-CA93-E711-814F-E0071B662BF1")); string AccountName = acc != null ? acc.Name : "Nothing Found"; Console.WriteLine("Sample Account : " + AccountName); Console.ReadLine(); } internal static Account RetriveAccountById(IOrganizationService service, Guid Id) { Account account = null; using (TcServiceContext serviceContext = new TcServiceContext(service)) { account = (from c in serviceContext.CreateQuery<Account>() where c.Id == Id select c).FirstOrDefault(); } return account; } private static string GetServiceConfiguration() { return "Url = https://xxxxxx.crm6.dynamics.com; Username=xxxx@xxxxx.onmicrosoft.com; Password=xxxxxx; authtype=Office365"; } } }
6. Now Run and see. Here is my result;
Note:
My intention is to give simplest code only, though code can be improved according to best practices which I am not discussing here. Ex: storing connection string in the config file.
No comments:
Post a Comment