Bhoopathi

"Be Somebody Nobody Thought You could Be"

Wednesday, July 27

Retrieving Data using Query by expression in MS CRM

/** Retrieving Data using Query by expression in MS CRM **/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;

namespace estd.crmconnection
{
    class Program
    {
        static IOrganizationService _service;
        public static void Main(string[] args)
        {
            EntityCollection ec = null;
            Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;
            if (userid != Guid.Empty)
            {
                Console.WriteLine("connection successfuly established");
                Console.ReadKey();

            }
            Entity contact = new Entity("contact");
            contact.LogicalName = "contact";
            contact.Attributes.Add("firstname", "aa great");
            contact.Attributes.Add("lastname", "superrr");
            contact.Attributes.Add("jobtitle", "senior software engineer");
            _service.Create(contact);



            ec = GetEntityCollection(_service, "contact", "fullname", "Bhoopathi K", new ColumnSet("fullname", "parentcustomerid", "gendercode", "birthdate", "creditlimit", "donotsendmm"));

            if (ec.Entities.Count > 0) //Check for EntityCollection count
            {
                string output = string.Empty;
                foreach (var item in ec.Entities)
                {
                    //String
                    if (item.Attributes.Contains("fullname")) //Check for fullname value exists or not in Entity Collection
                        output += "Full Name : " + item.Attributes["fullname"] + "\n";

                    //Lookup
                    if (item.Attributes.Contains("parentcustomerid")) //Check for parentcustomerid exists or not in Entity Collection
                        output += "Company : " + ((EntityReference)item.Attributes["parentcustomerid"]).Name + "\n";

                    //OptionSet
                    if (item.Attributes.Contains("gendercode")) //Check for gendercode exists or not in Entity Collection
                        output += "Gender : Name - " + item.FormattedValues["gendercode"] + ", Value - " + ((OptionSetValue)item.Attributes["gendercode"]).Value + "\n";

                    //Date
                    if (item.Attributes.Contains("birthdate")) //Check for birthdate exists or not in Entity Collection
                        output += "Birthday : " + ((DateTime)item.Attributes["birthdate"]).ToLocalTime().ToShortDateString().ToString() + "\n";

                    //Currency
                    if (item.Attributes.Contains("creditlimit")) //Check for creditlimit exists or not in Entity Collection
                        output += "Credit Limit : " + ((Money)item.Attributes["creditlimit"]).Value + "\n";

                    //Two Options
                    if (item.Attributes.Contains("donotsendmm")) //Check for donotsendmm exists or not in Entity Collection
                        output += "Send Marketing Materials : Name - " + item.FormattedValues["donotsendmm"] + ", Value - " + ((Boolean)item.Attributes["donotsendmm"]).ToString();

                }
                Console.WriteLine(output);
                Console.ReadKey();
            }
        }
        public static void ConnectToMSCRM(string UserName, string Password, string SoapOrgServiceUri)
        {
            try
            {
                ClientCredentials credentials = new ClientCredentials();
                credentials.UserName.UserName = UserName;
                credentials.UserName.Password = Password;
                Uri serviceUri = new Uri(SoapOrgServiceUri);
                OrganizationServiceProxy proxy = new OrganizationServiceProxy(serviceUri, null, credentials, null);
                proxy.EnableProxyTypes();
                _service = (IOrganizationService)proxy;
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error while connecting to CRM " + ex.Message);
                Console.ReadKey();
            }
        }
        private static EntityCollection GetEntityCollection(IOrganizationService service, string entityName, string attributeName, string attributeValue, ColumnSet cols)
        {
            QueryExpression query = new QueryExpression { EntityName = entityName, ColumnSet = cols, Criteria = new FilterExpression { Conditions = { new ConditionExpression { AttributeName = attributeName, Operator = ConditionOperator.Equal, Values = { attributeValue } } } } };
            return service.RetrieveMultiple(query);
        }
    }
}