Friday, October 14, 2011

CRM Helper class for get CrmService object and BusinessEntityCollection in MS CRM 4.0

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.Services;
using System.Net;
using System.Configuration;
using MSDynamicsCRMHelper.CrmSdk;
using MSDynamicsCRMHelper.crmDisc;

namespace MSDynamicsCRMHelper
{
    class CRMHelper
    {
        public CrmService GetCRMService()
        {
            string _hostname = "crm";
            string _port = "5555";
            string orgname = "organization";
            DataAccess objDataAccess = new DataAccess();

            _hostname = objDataAccess.GetMessage("crmHost");
            _port = objDataAccess.GetMessage("crmPort");
            orgname = objDataAccess.GetMessage("crmOrg");
           
            CrmService service = new CrmService();

            string strCRMAuthenticationType = ConfigurationManager.AppSettings.Get("CRMAuthenticationType");
            if (strCRMAuthenticationType == "0")
            {
                service = GetOnPremiseCRMService(_hostname,_port,orgname);
            }
            else if (strCRMAuthenticationType == "2")
            {
                service = GetHostedCRMService(_port,orgname);
            }

            return service;
        }


        public CrmService GetOnPremiseCRMService( string _hostname ,string _port ,string orgname )
        {
            //Retrieve the organization name from the query string.
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Url = String.Format("http://{0}:{1}/MSCRMServices/2007/{2}/CrmDiscoveryService.asmx", _hostname, _port, "AD");

            disco.Credentials = new NetworkCredential("username", "password", "domain");
            //Retrieve a list of available organizations from the CrmDiscoveryService Web service.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            // Substitute an appropriate domain, username, and password here.

            orgRequest.UserId = "domain" + "\\" + "username";
            orgRequest.Password = "password";
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
            //Find the target organization.
            OrganizationDetail orgInfo = null;

            foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
            {
                if (orgdetail.OrganizationName.Equals(orgname))
                {
                    orgInfo = orgdetail;
                    break;
                }
            }

            // Check whether a matching organization was not found.
            if (orgInfo == null)
                throw new Exception("The specified organization was not found.");

            //Create the CrmService Web service proxy.
            CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
            sdktoken.AuthenticationType = 0;
            sdktoken.OrganizationName = orgInfo.OrganizationName;


            CrmService service = new CrmService();
            service.CrmAuthenticationTokenValue = sdktoken;
            service.Url = orgInfo.CrmServiceUrl;
            service.Credentials = new NetworkCredential("username", "password", "domain");
            return service;
        }

        public CrmService GetHostedCRMService(string _port, string orgname)
        {           
            //Retrieve the organization name from the query string.
            CrmDiscoveryService disco = new CrmDiscoveryService();
            disco.Url = "http://" + orgname + ".mycrm.in:"+_port+"/MSCRMServices/2007/SPLA/CrmDiscoveryService.asmx";           
            disco.Credentials = new NetworkCredential("username", "password", "domain");
            //Retrieve a list of available organizations from the CrmDiscoveryService Web service.
            RetrieveOrganizationsRequest orgRequest = new RetrieveOrganizationsRequest();
            // Substitute an appropriate domain, username, and password here.

            orgRequest.UserId = "domain" + "\\" + "username";
            orgRequest.Password = "password";
            RetrieveOrganizationsResponse orgResponse = (RetrieveOrganizationsResponse)disco.Execute(orgRequest);
            //Find the target organization.
            OrganizationDetail orgInfo = null;

            foreach (OrganizationDetail orgdetail in orgResponse.OrganizationDetails)
            {
                if (orgdetail.OrganizationName.Equals(orgname))
                {
                    orgInfo = orgdetail;
                    break;
                }
            }

            // Check whether a matching organization was not found.
            if (orgInfo == null)
                throw new Exception("The specified organization was not found.");

            //Retrieve a CrmTicket from the CrmDiscoveryService Web service.
            RetrieveCrmTicketRequest ticketRequest = new RetrieveCrmTicketRequest();
            ticketRequest.OrganizationName = orgInfo.OrganizationName;
            ticketRequest.UserId = "domain" + "\\" + "username";
            ticketRequest.Password = "password";

            RetrieveCrmTicketResponse ticketResponse =
                (RetrieveCrmTicketResponse)disco.Execute(ticketRequest);

            //Create the CrmService Web service proxy.
            CrmAuthenticationToken sdktoken = new CrmAuthenticationToken();
            sdktoken.AuthenticationType = 2;
            sdktoken.OrganizationName = orgInfo.OrganizationName;
            sdktoken.CrmTicket = ticketResponse.CrmTicket;

            CrmService service = new CrmService();
            service.CrmAuthenticationTokenValue = sdktoken;
            service.Url = orgInfo.CrmServiceUrl;
            service.Credentials = new NetworkCredential("username", "password", "domain");
            return service;
        }

        public BusinessEntityCollection GetSearchedEntityResult(CrmService service, EntityName EntName, string[] SearchColumns, string searchAttributeName, object searchAttributevalue, ConditionOperator searchOperator)
        {
            ColumnSet columns = new ColumnSet();
            columns.Attributes = SearchColumns;
            // Create a ConditionExpression.
            ConditionExpression conditionPrincipal = new ConditionExpression();

            // Set the ConditionExpressions properties so that the condition is true when the

            conditionPrincipal.AttributeName = searchAttributeName;
            conditionPrincipal.Operator = searchOperator;
            conditionPrincipal.Values = new object[1];
            conditionPrincipal.Values[0] = searchAttributevalue;

            // Create the FilterExpression.
            FilterExpression filterPrincipal = new FilterExpression();

            // Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = LogicalOperator.And;
            filterPrincipal.Conditions = new ConditionExpression[] { conditionPrincipal };

            QueryExpression query = new QueryExpression();
            query.ColumnSet = columns;
            query.EntityName = EntName.ToString();
            query.Criteria = filterPrincipal;

            BusinessEntityCollection result = service.RetrieveMultiple(query);
            return result;
        }

        public BusinessEntityCollection GetSearchedEntityResultMultipleAttribute(CrmService service, EntityName EntName, string[] SearchColumns, string[] searchAttributeName, object[] searchAttributevalue, ConditionOperator[] searchOperator)
        {
            ColumnSet columns = new ColumnSet();
            columns.Attributes = SearchColumns;
            // Create a ConditionExpression.

            ConditionExpression[] SetOfConditions = new ConditionExpression[searchAttributeName.Length];
            for (int Count = 0; Count < searchAttributeName.Length; Count++)
            {
                ConditionExpression conditionPrincipal = new ConditionExpression();

                // Set the ConditionExpressions properties so that the condition is true when the

                conditionPrincipal.AttributeName = searchAttributeName[Count];
                conditionPrincipal.Operator = searchOperator[Count];
                conditionPrincipal.Values = new object[1];
                conditionPrincipal.Values[0] = searchAttributevalue[Count];
                SetOfConditions[Count] = conditionPrincipal;
            }

            // Create the FilterExpression.
            FilterExpression filterPrincipal = new FilterExpression();

            // Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = LogicalOperator.And;
            filterPrincipal.Conditions = SetOfConditions;

            QueryExpression query = new QueryExpression();
            query.ColumnSet = columns;
            query.EntityName = EntName.ToString();
            query.Criteria = filterPrincipal;
            BusinessEntityCollection result = service.RetrieveMultiple(query);
            return result;
        }

        public BusinessEntityCollection GetSearchedEntityResultMultipleAttribute(CrmService service, EntityName EntName, string[] SearchColumns, string[] searchAttributeName, object[] searchAttributevalue, ConditionOperator[] searchOperator, LogicalOperator logicalOperator)
        {
            ColumnSet columns = new ColumnSet();
            columns.Attributes = SearchColumns;
            // Create a ConditionExpression.

            ConditionExpression[] SetOfConditions = new ConditionExpression[searchAttributeName.Length];
            for (int Count = 0; Count < searchAttributeName.Length; Count++)
            {
                ConditionExpression conditionPrincipal = new ConditionExpression();

                // Set the ConditionExpressions properties so that the condition is true when the

                conditionPrincipal.AttributeName = searchAttributeName[Count];
                conditionPrincipal.Operator = searchOperator[Count];
                conditionPrincipal.Values = new object[1];
                conditionPrincipal.Values[0] = searchAttributevalue[Count];
                SetOfConditions[Count] = conditionPrincipal;

            }

            // Create the FilterExpression.
            FilterExpression filterPrincipal = new FilterExpression();

            // Set the properties of the FilterExpression.
            filterPrincipal.FilterOperator = logicalOperator;
            filterPrincipal.Conditions = SetOfConditions;

            QueryExpression query = new QueryExpression();
            query.ColumnSet = columns;
            query.EntityName = EntName.ToString();
            query.Criteria = filterPrincipal;
            BusinessEntityCollection result = service.RetrieveMultiple(query);
            return result;
        }
    }
}