CrmEntityPicklistControl

The next control we will create handles Lookup attributes. Instead of a CRM-style lookup control, the CrmEntityPicklistControl renders a drop-down list just like our CrmPicklistControl. However, this control doesn’t use the Microsoft Dynamics CRM metadata to populate its option list. It instead uses a query to retrieve records from an entity. The end user can then select the appropriate record from the drop-down list. The CrmEntityPicklistControl also gives you the ability to filter the results returned to populate the drop-down options.

Programming the CrmEntityPicklistControl

Adding theCrmEntityPicklist class

  1. Right-click the ProgrammingWithDynamicsCrm4.Controls Project in Solution Explorer. Under Add, click New Item.

  2. In the Visual C# Items category, select the Class template.

  3. Type CrmentityPicklist.cs in the Name box and click Add.

The CrmEntityPicklistControl inherits from the System.Web.UI.DropDownList class. Example 14-5 shows the full source code.

Example 14-5. CrmEntityPicklistControl source code

using System;
using System.Collections.Generic;
using System.Text;
using System.Web.UI.WebControls;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;
using System.ComponentModel;
using Microsoft.Crm.Sdk;
using System.Configuration;
using ProgrammingWithDynamicsCrm4.Utilities;

namespace ProgrammingWithDynamicsCrm4.Controls
{
    public class CrmEntityPicklistControl : DropDownList
    {
        public string EntityName
        {
            get
            {
                object entityName = ViewState["EntityName"];

                if (entityName != null)
                    return (string)entityName;
                else
                    return String.Empty;
            }
            set
            {
                ViewState["EntityName"] = value;
            }
        }

        public bool IncludeNullOption
        {
            get
            {
                object includeNullOption = ViewState["IncludeNullOption"];

                if (includeNullOption != null)
                    return (bool)includeNullOption;
                else
                    return false;
            }
            set
            {
                ViewState["IncludeNullOption"] = value;
            }
        }

        public FilterExpression Filter { get; set; }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override object DataSource
        {
            get
            {
                return base.DataSource;
            }
            set
            {
                base.DataSource = value;
            }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override string DataSourceID
        {
            get
            {
                return base.DataSourceID;
            }
            set
            {
                base.DataSourceID = value;
            }
        }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        public override ListItemCollection Items
        {
            get
            {
                return base.Items;
            }



        }

        protected override void OnLoad(EventArgs e)
        {
            this.DataBind();
        }

        public override void DataBind()
        {
            if (String.IsNullOrEmpty(EntityName))
                throw new Exception(

                        String.Format("{0}: Please provide a value for EntityName.",
                                       this.ID));
            if (String.IsNullOrEmpty(DataTextField))
                throw new Exception(
                     String.Format("{0}: Please provide a value for DataTextField.",
                                   this.DataTextField));
            if (String.IsNullOrEmpty(DataValueField))
                throw new Exception(
                    String.Format("{0}: Please provide a value for DataValueField.",
                                  this.DataValueField));

            QueryExpression query = new QueryExpression();
            query.EntityName = this.EntityName;

            ColumnSet columns = new ColumnSet();
            columns.Attributes.Add(this.DataValueField);
            columns.Attributes.Add(this.DataTextField);

            query.ColumnSet = columns;

            if (this.Filter != null)
                query.Criteria = this.Filter;

            CrmService service =
      CrmServiceUtility.GetCrmService(ConfigurationManager.AppSettings["CrmServer"],
                                     ConfigurationSettings.AppSettings["OrgName"]);

            RetrieveMultipleRequest request = new RetrieveMultipleRequest();
            request.Query = query;
            request.ReturnDynamicEntities = true;

            RetrieveMultipleResponse response =
                                 (RetrieveMultipleResponse)service.Execute(request);

            foreach (BusinessEntity be
                              in response.BusinessEntityCollection.BusinessEntities)
            {
                DynamicEntity de = (DynamicEntity)be;

                string text =
           DynamicEntityUtility.GetPropertyValue(de.Properties[this.DataTextField]);
                string value =
           DynamicEntityUtility.GetPropertyValue(de.Properties[this.DataValueField]);

                 ListItem newItem = new ListItem(text, value);

                 if (!this.Items.Contains(newItem))
                     this.Items.Add(newItem);
             }
        }
    }
}

Note

Note

A detailed description of the DynamicEntityUtility used in Example 14-5 can be found in Chapter 15.

CrmEntityPicklistControl Properties

Table 14-4 lists the three properties we need to add to our CrmEntityPicklistControl class.

Table 14-4. CrmEntityPicklistControl Properties

Property Name

Type

Description

EntityName

string

Name of the Microsoft Dynamics CRM entity that will be queried

IncludeNullOption

bool

Determines whether to render a null option in the select box

Filter

Filter Expression

Used to add filtering to the QueryExpression that populates the drop-down list

We use the inherited DataTextField and DataValueField properties along with our added EntityName and Filter properties to build the QueryExpression that populates our list items:

QueryExpression query = new QueryExpression();
query.EntityName = this.EntityName;
ColumnSet columns = new ColumnSet();
columns.Attributes.Add(this.DataValueField);
columns.Attributes.Add(this.DataTextField);

query.ColumnSet = columns;

if (this.Filter != null)
    query.Criteria = this.Filter;

As with our other controls that inherit from existing ASP.NET controls, we need to hide some of the inherited properties. Because we will be handling the data binding, we hide the DataSource, DataSourceID, and Items properties.

Binding the Data

We override the DataBind method to handle adding the list items. As stated earlier we build a QueryExpression based on the property values provided. Because this control works with all entities, including custom entities, we use the DynamicEntity class. This is why our RetrieveMultipleRequest has the ReturnDynamicEntities property set to true:

RetrieveMultipleRequest request = new RetrieveMultipleRequest();
request.Query = query;
request.ReturnDynamicEntities = true;

The returned dynamic entities have the attributes specified in the DataTextField and DataValueField properties populated. We can grab these values and use them to add new list items to the DropDownList Items collection.

Note

Note

The source code for the DynamicEntityUtility used in the CrmEntityPicklistControl control’s DataBind method can be found in Chapter 15.

Testing the CrmEntityPicklistControl

Adding theCrmEntityPicklistControl test page

  1. Open the ProgrammingWithDynamicsCrm4.Web project in Visual Studio.

  2. Right-click the project name in Solution Explorer, and click Add New Item.

  3. Select the Web Form template and type the name CrmEntityPicklistControlPage. aspx in the Name box. Click OK.

  4. Delete the div tag that was added by Visual Studio when the page was created.

We can test our CrmEntityPicklist control by adding <crm:CrmEntityPicklistControl ID="EntityPicklist" runat="server" EntityName="lead" DataTextField="fullname" DataValueField="leadid" /> inside of the form tag. Now if you view the CrmEntityPicklistControlPage.aspx in the browser, you can see a list of all Leads from your Microsoft Dynamics CRM system (Figure 14-4).

EntityPicklistControl unfiltered

Figure 14-4. EntityPicklistControl unfiltered

In some cases you may not want to return all of the records for your entity. We can add some filtering by setting the Filter property. Let’s set a filter so that our control only shows Leads with a company name of "Adventure Works." Add the following code block to the Page_Load method of your code-behind file. Compile your solution and view the page in the browser again. Now you can only see the Lead records that have the value "Adventure Works" in the companyname attribute (Figure 14-5).

ConditionExpression condition = new ConditionExpression();
condition.AttributeName = "companyname";
condition.Operator = ConditionOperator.Equal;
condition.Values = new object[] { "Adventure Works" };

FilterExpression filter = new FilterExpression();
filter.FilterOperator = LogicalOperator.And;
filter.Conditions.Add(condition);

this.entityPicklist.Filter = filter;
EntityPicklistControl with filtering

Figure 14-5. EntityPicklistControl with filtering

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset