Thursday 22 November 2012

Code to Retrive the organization names in Dynamic CRM using c#


Right Click on the solutions --> Click Add service references


Right Click on the solutions --> Click Add service references


Then add the following references assemblies
  1. Microsoft.crm.sdk.proxy
  2. Microsoft.Xrm.Sdk
  3. System.ServiceModel




using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Crm.Sdk;

namespace Organization
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

       ClientCredentials userCredentials = new ClientCredentials();
       private void btnSrvValidate_Click(object sender, EventArgs e)
        {
            cmbOrg.Items.Clear();
            List<string> orgNames = new List<string>();

            userCredentials.UserName.UserName = txtUser.Text.Trim();
            userCredentials.UserName.Password = txtPassword.Text.Trim();
            string serverName=txtServer.Text.Trim();        
       
            string crmURI = "http://"+ serverName +"/XRMServices/2011/Discovery.svc";
            DiscoveryServiceProxy discoveryProxy = new DiscoveryServiceProxy(new Uri(crmURI),null, userCredentials,null);
            discoveryProxy.Authenticate();
     
              try
            {
                RetrieveOrganizationsRequest retrieveOrganizationsRequest = new RetrieveOrganizationsRequest();        
                RetrieveOrganizationsResponse retrieveOrganizationsResponse = discoveryProxy.Execute(retrieveOrganizationsRequest) as RetrieveOrganizationsResponse;
                if (retrieveOrganizationsResponse.Details.Count != 0)
                {
                    foreach (OrganizationDetail orgInfo in retrieveOrganizationsResponse.Details)
                        orgNames.Add(orgInfo.FriendlyName);
                }
            }        
            catch (Exception)
            {
                throw new Exception("Please check the Dynamics CRM Server URL");
            }

           cmbOrg.Items.AddRange(orgNames.ToArray());
           cmbOrg.SelectedIndex = 0;
           cmbOrg.Focus();
     }
    }
}

Result:

No comments:

Post a Comment