How to get organization id with organization name in CRM 2011

Posted on Posted in CRM 2011 SDK, MS CRM 2011, MS Dynamics

How to get organization id with organization name in CRM 2011

To get an organization id with organization name in CRM 4.0 we used below

static public string OrganizationId(string orgName)
{
if (organizationIds == null)
organizationIds = new Dictionary<string, string>();
string organizationId = string.Empty;
if (organizationIds.ContainsKey(orgName))
organizationId = organizationIds[orgName];
if (string.IsNullOrEmpty(organizationId))
{
using (CrmService mscrm = CrmServices.MscrmService(orgName))
{
mscrm.Credentials = System.Net.CredentialCache.DefaultCredentials;

ColumnSet cols = new ColumnSet();
cols.Attributes.Add(“organizationid”);
QueryExpression query = new QueryExpression();
query.ColumnSet = cols;
query.EntityName = EntityName.organization.ToString();
BusinessEntityCollection bec = mscrm.RetrieveMultiple(query);

organization org = (organization)bec.BusinessEntities[0];

organizationId = org.organizationid.Value.ToString();
organizationIds[orgName] = organizationId;
}
}
return organizationId;
}


This has changed in CRM 2011 API and we can use query below to get an organization id by passing an organization name

static public string OrganizationId(string orgName)
{
if (organizationIds == null)
organizationIds = new Dictionary<string, string>();
string organizationId = string.Empty;
if (organizationIds.ContainsKey(orgName))
organizationId = organizationIds[orgName];
if (string.IsNullOrEmpty(organizationId))
{
using (OrganizationServiceProxy service = CrmServerConnection.GetOrganisationProxy(orgName))
{
QueryExpression qe=new QueryExpression(“organization”);
qe.ColumnSet =new ColumnSet(new string[]{“organizationid”});
qe.Criteria.AddCondition(“name”, ConditionOperator.Equal, orgName);

EntityCollection orgs = service.RetrieveMultiple(qe);

if (orgs !=null && orgs.Entities.Count>0)
{
var org = orgs[0];
organizationId = org[“organizationid”].ToString();
organizationIds[orgName] = organizationId;
}

}
}
return organizationId;
}