Wednesday, January 16, 2013

Use WCF to get CRM version and user name

The standard interface for interacting programmatically with CRM is to use WCF and the SDK toolkit. The following steps show how to do this. This example was derived from the SDK examples, in this case the solution located on my PC at C:\CRM\sdk\samplecode\cs\quickstart\. My preference is to remove the obfuscating (but useful another day) clutter and get to the root of what we are trying to accomplish.
  1. Download the CRM SDK from here and unzip it to your hard drive, for example at c:\crm\sdk
  2. Create a new Visual Studio windows forms project (.net 4.0).
  3. Add the following 2 references to dlls located at C:\CRM\sdk\bin:
    1. microsoft.crm.sdk.proxy.dll
    2. microsoft.xrm.sdk.dll
  4. Add the following .net references to the project:
    1. System.ServiceModel
    2. System.Runtime.Serialization
  5. Open the windows form in code view and add the following Usings to the top of the page:

    using System;
    using System.ServiceModel.Description;
    using System.Windows.Forms;
    using Microsoft.Crm.Sdk.Messages;
    using Microsoft.Xrm.Sdk;
    using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk.Query;
  6. Create a windows form with a label, button and text box:
  7. Add the following code to the Click Click event of the button:

  8. Uri OrganizationUri = new Uri(textBoxServerUrl.Text + "/" + textBoxOrg.Text + "/XRMServices/2011/Organization.svc");
    ClientCredentials Credentials = new ClientCredentials();
    Credentials.Windows.ClientCredential = new System.Net.NetworkCredential(textBoxName.Text, textBoxPassword.Text, textBoxDomain.Text);

    //INITIALIZE PIPELINE SERVICE
    OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, null, Credentials, null);
    serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
    IOrganizationService service = (IOrganizationService)serviceProxy;

    // Display information about the logged on user.
    Guid userid = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;
    Entity systemUser = service.Retrieve("systemuser", userid, new ColumnSet(new string[] { "firstname", "lastname" }));
    MessageBox.Show("Hello " + systemUser.Attributes["firstname"] + " " + systemUser.Attributes["lastname"]);

    // Retrieve the version of Microsoft Dynamics CRM.
    RetrieveVersionRequest versionRequest = new RetrieveVersionRequest();
    RetrieveVersionResponse versionResponse = (RetrieveVersionResponse)service.Execute(versionRequest);
    MessageBox.Show("You are using CRM version number " + versionResponse.Version); 
  9. Note that you will have to rename the controls on the window to match that of the code.

No comments:

Post a Comment