Thursday, February 3, 2011

Using CrmDiscoveryService Web Service To Find Sales Org and Web Service End Point

Microsoft Dynamics CRM CrmDiscoveryService Web service provides a list of Web service endpoint URLs for each sales organization that you are a member of. The following sample code shows you how to use the Web service:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using CRMDiscoveryServices;
using System.Configuration;
using System.Text;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            // Get CRM Dynamics credential from web configuration
            string crmUserId = ConfigurationManager.AppSettings["CRMUSERID"];
            string crmPassword = ConfigurationManager.AppSettings["CRMPASSWORD"];
            string crmDomain = ConfigurationManager.AppSettings["CRMDOMAIN"];

            // Create and configure the CrmDiscoveryService Web service proxy.
            CrmDiscoveryService discoveryService = new CrmDiscoveryService();
            discoveryService.Credentials = new System.Net.NetworkCredential(crmUserId, crmPassword, crmDomain);

            // Retrieve the list of organizations that the logged on user belongs to.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)discoveryService.Execute(orgRequest);

            // Locate the target organization in the list.
            if (orgResponse != null && orgResponse.OrganizationDetails.Length > 0)
            {
                StringBuilder sb = new StringBuilder();
                foreach (OrganizationDetail orgDetail in orgResponse.OrganizationDetails)
                {
                    sb.AppendLine("<B>Organisation name:</B> " + orgDetail.OrganizationName
                        + " <B>CRM Web application.:</B> " + orgDetail.WebApplicationUrl
                        + " <B>CrmService Web service URL:</B> " + orgDetail.CrmServiceUrl + "<BR/>");
                }
                Response.Write(sb.ToString());
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
}

Please note that you need to add the CrmDiscoveryService web reference to your project. To add the web reference, select Add Service Reference, click Advanced, and then click Add Web Reference. In the URL field, paste the following string, replacing <server name> and <port number>:

http://<servername>:<port>/mscrmservices/2007/ad/crmdiscoveryservice.asmx?WSDL

No comments: