HTML Dropdown

Tuesday, 19 July 2016

Retrieve records using FetchXML in CRM 2013


Write a Console Application to retrieve the following attributes from Contact record...


Demo:-

  1. Create the FetchXML via advance find in CRM

Query Like below:-


Click on Download FetchXML and Your XML Look like Below.


 

Save it as FetchXML.txt File and Open it, type Ctrl+H


And replace all the “with ‘


And your FetchXML is ready to use in the Code

2. Create a ASP.NET Empty Web Application project in Visual studio 2012.


 

3. Add the following references from the SDK\bin folder.

You can skip this step and the next by simply installing the Microsoft.CrmSdk.Extensions NuGet package.

AntiXSSLibrary.dll

Microsoft.Crm.Sdk.Proxy.dll

Microsoft.Xrm.Client.dll

Microsoft.Xrm.Portal.dll

Microsoft.Xrm.Portal.Files.dll

Microsoft.Xrm.Sdk.dll

 

4. Add the following references from .NET.

System.IdentityModel.dll

Microsoft.ServiceBus.dll

System.Data.Services.dll

System.Data.Services.Client.dll

System.Runtime.Serialization.dll

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using System.Data;

using System.ServiceModel;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Client;

using Microsoft.Xrm.Sdk.Query;

using Microsoft.Crm.Sdk.Messages;

using System.ServiceModel.Description;


5. Make sure the web application project specifies .NET Framework 4.5.2 as the target framework and not .NET Framework 4.5.2 Client Profile. Check the properties of the project by selecting the ConsoleApplication1 project in Solution Explorer and clicking Alt-Enter.

Right Click ConsoleApplication1 -> Properties

 

6. Add the following code to your Program.cs File

namespace ConsoleApplication1

    {

    class Program

        {

        static IOrganizationService _service;

        static void Main(string[] args)

            {                        

            try

               {

                ConnectToMSCRM("Username", "Password", "https://**************/XRMServices/2011/Organization.svc");

                Guid userid = ((WhoAmIResponse)_service.Execute(new WhoAmIRequest())).UserId;

                if (userid == Guid.Empty) return;//Check for CRM Connection Establishment. If Not return, other wise will proceed to next step

                string fetchXmlString = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>

                                             

                                                        <entity name='contact'>

 

                                                        <attribute name='fullname'/>

 

                                                        <attribute name='telephone1'/>

 

                                                        <attribute name='contactid'/>

 

                                                        <attribute name='donotsendmm'/>

 

                                                        <attribute name='accountrolecode'/>

 

                                                        <attribute name='defaultpricelevelid'/>

 

                                                        <attribute name='ownerid'/>

 

                                                        <attribute name='nickname'/>

 

                                                        <attribute name='familystatuscode'/>

 

                                                        <attribute name='managername'/>

 

                                                        <attribute name='jobtitle'/>

 

                                                        <attribute name='gendercode'/>

 

                                                        <attribute name='employeeid'/>

 

                                                        <attribute name='educationcode'/>

 

                                                        <attribute name='department'/>

 

                                                        <attribute name='creditlimit_base'/>

 

                                                        <attribute name='creditlimit'/>

 

                                                        <attribute name='creditonhold'/>

 

                                                        <attribute name='parentcustomerid'/>

 

                                                        <attribute name='birthdate'/>

 

                                                        <order descending='false' attribute='fullname'/>

 

 

                                                        <filter type='and'>

 

 

                                                        <filter type='or'>

 

                                                        <condition attribute='fullname' operator='not-null'/>

 

                                                        <condition attribute='contactid' operator='not-null'/>

 

                                                        <condition attribute='creditlimit' operator='not-null'/>

 

                                                        <condition attribute='birthdate' operator='this-year'/>

 

                                                        <condition attribute='accountrolecode' operator='not-null'/>

 

                                                        <condition attribute='gendercode' operator='not-null'/>

 

                                                        <condition attribute='donotsendmm' operator='not-null'/>

 

                                                        </filter>

 

                                                        </filter>

 

                                                        </entity>

                                              </fetch>";

 

                EntityCollection ec = ExecuteFetch(fetchXmlString);

                if (ec.Entities.Count > 0)

                    {

                            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 \t";

 

                                //Lookup

                                if (item.Attributes.Contains("parentcustomerid")) //Check for parentcustomerid exists or not in Entity Collection

                                    output += "Company : " + ((EntityReference)item.Attributes["parentcustomerid"]).Name + "\n \t";

 

                                //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 \t";

 

                                //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 \t";

 

                                //Currency

                                if (item.Attributes.Contains("creditlimit")) //Check for creditlimit exists or not in Entity Collection

                                    output += "Credit Limit : " + ((Money)item.Attributes["creditlimit"]).Value + "\n \t";

 

                                //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() + "\n \t";

 

                                }

 

                            Console.WriteLine(output + "\n\n \t\t");

                            Console.ReadKey();

                    }

                }

                catch (Exception ex)

                {

                    Console.WriteLine(ex.Message);

                }

            Console.ReadLine();

            }

            // retriveing values from fetchxml

            public static EntityCollection ExecuteFetch(string fetchXmlString)

            {

            return _service.RetrieveMultiple(new FetchExpression(fetchXmlString));

            }

 

            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();

                        }

                 

           

            }

 

 

 

            }

        }

   

7. Testing:-Compile and Run the console Application


9. Testing:

Query Like below in CRM


 

No comments:

Post a Comment