Tuesday, November 20, 2012

Simple CRM connection example

This post is to provide you with a simple platform for creating CRM connections and using these features of the CRM SDK within your applications.

Things you'll need to follow this post:
  1. Some IDE (I prefer VS2010)
  2. You'll need to generate your class entity files using crmSvcUtil.  I did a post on how to use this tool earlier this year
  3. You'll need the CRM2011 SDK.  This can be found here.
Assemblies you'll need to reference in your project.  (should all be included with the CRM2011 SDK)
  1. microsoft.crm.sdk.proxy
  2. microsoft.xrm.client
  3. microsoft.xrm.sdk
These are the namespaces I commonly use in dynamics CRM projects.

using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Messages;


Now that we have those. Here is the instance of the organization service proxy we need to build first.
internal static OrganizationServiceProxy GetProxy()
        {
            ClientCredentials creds = new ClientCredentials();

            creds.Windows.ClientCredential.UserName =  ConfigurationSettings.AppSettings["username"];
            creds.Windows.ClientCredential.Password = ConfigurationSettings.AppSettings["password"];
            creds.Windows.ClientCredential.Domain = ConfigurationSettings.AppSettings["domain"]; ;
            string url = ConfigurationSettings.AppSettings["orgserviceurl"];
            return new OrganizationServiceProxy(new Uri(url), null, creds, null);
        }
Now, within the methods you want to use this connection for you will need to add or have access to the following.
static void Main(string[] args)
        {
            OrganizationServiceProxy myProx = GetProxy();
            myProx.EnableProxyTypes();
            IOrganizationService myOrg = (IOrganizationService)myProx;
            //orgServiceContext from GeneratedEntities using the CRMServiceUtil
            ExampleContext orgService = new ExampleContext(myOrg);
        }
Don't forget to add this to your app.config or web.config!

  <add key="Username" value="yourUsername"/>
  <add key="Password" value="yourPassword"/>
  <add key="Domain" value="yourDomain"/>
  <add key="OrgServiceURL" value="http://MyURL/MyOrName/XrmServices/2011/Organization.svc"/>



From this point you can use LINQ to do most of the CRUD operations you want to do.
For example, you could get all the account records...
List <Account> accounts = (from a in orgService.AccountSet 
                          select a as Account).ToList();
I'll add a post later for more examples of how to use this for CRUD operations with CRM.


No comments:

Post a Comment