serving the solutions day and night

Pages

Monday, November 26, 2012

CRM Dynamics 2011 - Dynamic Entity

Using C# and IOrganizationService Web Service - A Simple Application will display, add, modify and delete Entity records.

Form design

<div>
        <strong>Contact Form - <asp:Button ID="Insert" runat="server" OnClick="Insert_Click" Text="Insert" /><br /></strong>
        <asp:Literal ID="litViewAll" runat="server"></asp:Literal><br />
        <asp:Panel runat="server" ID="panDetails" Visible="false">
        First Name<asp:TextBox ID="txtFirstName" runat="server"></asp:TextBox><br />
        Last Name<asp:TextBox ID="txtLastName" runat="server"></asp:TextBox><br />
        Address<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox><br />
        City<asp:TextBox ID="txtCity" runat="server"></asp:TextBox><br />
        Zip<asp:TextBox ID="txtZip" runat="server"></asp:TextBox><br />
        State<asp:DropDownList ID="ddlSList" runat="server" AppendDataBoundItems="true">
            <asp:ListItem Selected="True" Text="Select SList" Value="00000000-0000-0000-0000-000000000000"/>
        </asp:DropDownList><br />
        Municipality Name<asp:DropDownList ID="ddlJList" runat="server" AppendDataBoundItems="true">
            <asp:ListItem Selected="True" Text="Select MList" Value="00000000-0000-0000-0000-000000000000"/>
        </asp:DropDownList><br/>      
        <asp:Button ID="CreateNew" runat="server" OnClick="CreateNew_Click" Text="Create" />
        <asp:Button ID="Delete" runat="server" OnClick="Delete_Click" Text="Delete" />
        <asp:Button ID="Update" runat="server" OnClick="Update_Click" Text="Update" /><br />
        </asp:Panel>
        </div>


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ServiceModel.Description;
using Microsoft.Xrm.Sdk.Client;
using System.Net;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;

namespace CreateContactDataEntry
{
    public partial class _default : System.Web.UI.Page
    {
        //This URL needs to be updated to match the servername and Organization for the environment.
        Uri OrganizationUri = new Uri("http://<Server_Name>/<Organization_Name>/XRMServices/2011/Organization.svc");
        Uri HomeRealmUri = null;
        String eid = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            ViewAll();
            panDetails.Visible = false;
            if (Request.QueryString["id"] != null && Request.QueryString["id"].Length > 1)
            {
                eid = Request.QueryString["id"];
            }
            if (!IsPostBack)
            {
                BindList(ddlState, "g_state", "g_sid", "g_name", "","");
                BindList(ddlJurisdiction, "g_jurisdiction", "g_jid", "g_name", "g_jtype","2");
                if (eid.Length > 0)
                {
                    panDetails.Visible = true;
                    CreateNew.Visible = false;
                    View();
                }
            }
        }

Bind List
        private void BindList(DropDownList ddl, String entityName, String fieldID, String fieldName, String filterName, String filterValue)
        {
            ListItemCollection listColl = new ListItemCollection();
            listColl = GetListValue(entityName, fieldID, fieldName, filterName, filterValue);
            ddl.DataSource = listColl;
            ddl.DataTextField = "Text";
            ddl.DataValueField = "Value";
            ddl.DataBind();
        }

        private ListItemCollection GetListValue(String entityName, String fieldID, String fieldName, String filterName, String filterValue)
        {
            ListItemCollection  liCol = new ListItemCollection();
            ListItem lItem;
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                QueryExpression qryExp = new QueryExpression(entityName);
                qryExp.ColumnSet = new ColumnSet(fieldName);

                if (filterName.Length > 0)
                {
                    ConditionExpression conExp = new ConditionExpression();
                    conExp.AttributeName = filterName;
                    conExp.Operator = ConditionOperator.Equal;
                    //to test for a null value
                    //conExp.Operator = ConditionOperator.Null;
                    conExp.Values.Add(filterValue);

                    FilterExpression filExp = new FilterExpression();
                    filExp.FilterOperator = LogicalOperator.And;
                    filExp.Conditions.Add(conExp);

                    qryExp.Criteria = filExp;
                }

                EntityCollection entCollection = service.RetrieveMultiple(qryExp);
                foreach (var c in entCollection.Entities)
                {
                    lItem = new ListItem();
                    lItem.Text = c.Attributes[fieldName].ToString();
                    lItem.Value = c.Attributes[fieldID].ToString();
                    liCol.Add(lItem);
                }
            }
            return liCol;
        }

        protected void Insert_Click(object sender, EventArgs e)
        {
            panDetails.Visible = true;
            CreateNew.Visible = true;
            Delete.Visible = false;
            Update.Visible = false;
            ClearAll();
            //Response.Redirect("default.aspx?id=");
        }

        protected void CreateNew_Click(object sender, EventArgs e)
        {
            CreateUpdate("C");
        }

Insert and update
        private void CreateUpdate(String type)
        {
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                //Instantiate the contact object and populate the attributes.

                Entity contact = new Entity("g_bpres");
                contact["g_fname"] = txtFirstName.Text.ToString();
                contact["g_lname"] = txtLastName.Text.ToString();
                contact["g_add"] = txtAddress.Text.ToString();
                contact["g_cit"] = txtCity.Text.ToString();
                if (ddlSList.SelectedValue == "00000000-0000-0000-0000-000000000000")
                {
                    contact["g_sta"] = "";
                }
                else
                {
                    EntityReference stateID = new EntityReference("g_slist", new Guid(ddlSList.SelectedValue));
                    contact["g_sta"] = stateID;
                }
                if (ddlJList.SelectedValue == "00000000-0000-0000-0000-000000000000")
                {
                    contact["g_mname"] = "";
                }
                else
                {
                    EntityReference mnID = new EntityReference("g_jlist", new Guid(ddlJList.SelectedValue));
                    contact["g_mname"] = mnID;
                }
              
                contact["g_zcode"] = txtZip.Text.ToString();
                if (type == "C")
                {
                    Guid newContactId = service.Create(contact);
                }
                else
                {
                    contact["g_bpid"] = new Guid(eid);
                    service.Update(contact);
                }
               
                ClearAll();
            }
            ViewAll();
        }

        private void ClearAll()
        {
            //This code will clear the textboxes after the contact is created.
            txtFirstName.Text = "";
            txtLastName.Text = "";
            txtAddress.Text = "";
            txtCity.Text = "";
            ddlSList.SelectedValue = "00000000-0000-0000-0000-000000000000";
            ddlJList.SelectedValue = "00000000-0000-0000-0000-000000000000";
            txtZip.Text = "";
        }

View
        private void View()
        {
            Entity contact = new Entity("g_bpres");
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                ColumnSet cols = new ColumnSet(new string[] { "g_zcode", "g_add", "g_cit", "g_fname", "g_lname", "g_sta", "g_mname" });
                contact = service.Retrieve("g_bpres", new Guid(eid), cols);
                txtFirstName.Text = contact["g_fname"].ToString();
                txtLastName.Text = contact["g_lname"].ToString();
                txtZip.Text = contact["g_zcode"].ToString();
                txtAddress.Text = contact["g_add"].ToString();
                txtCity.Text = contact["g_cit"].ToString();
                ddlSList.SelectedValue = ((EntityReference)contact["g_sta"]).Id.ToString();
                //lblSList.Text = ((EntityReference)contact["g_sta"]).Id.ToString();
                ddlJList.SelectedValue = ((EntityReference)contact["g_mname"]).Id.ToString();
            }
        }

Delete
        protected void Delete_Click(object sender, EventArgs e)
        {
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                service.Delete("g_bpres", new Guid(eid));
            }
            panDetails.Visible = false;
            ViewAll();
        }

        protected void Update_Click(object sender, EventArgs e)
        {
            CreateUpdate("U");
        }

        private void ViewAll()
        {
            ViewAll_QryExpression();
        }

        //IOrganizationService.RetrieveMultiple - use managed code.

        //the RetrieveMultiple method performs faster than the Fetch method because it does not have to parse the query.
        //Use the QueryExpression class to build complex queries for use with the RetrieveMultiple method or the RetrieveMultiple message.

        //The ColumnSet class is used to specify which attributes are to be retrieved in the results of a query.
        //To reduce the data that is passed from the server to the client, the default column set returns only the primary key.
        //To retrieve all columns, pass a new instance of the AllColumns class.
        //However, notice that retrieving all the attributes for an entity will affect the performance of your code.
Query Expression
        private void ViewAll_QryExpression()
        {
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                QueryExpression qryExp = new QueryExpression("g_bpres");
                qryExp.ColumnSet = new ColumnSet("g_fname", "g_lname", "g_sta", "g_mname");
                //qryExp.ColumnSet.AllColumns=true;
                EntityCollection entCollection = service.RetrieveMultiple(qryExp);
                DisplayResults(entCollection);
            }
        }

FetchXML
        private void ViewAll_FetchXML()
        {
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                string fetchXML = "";

                //Reterive all attributes
                fetchXML = @"<fetch mapping='logical'>
                                <entity name='g_bpres'><all-attributes/>
                            </entity></fetch>";

                fetchXML = @"<fetch mapping='logical'>
                                <entity name='g_bpres'>
                                    <attribute name='g_bpres'/>
                                    <attribute name='g_fname'/>
                                    <attribute name='g_lname'/>
                                    <filter type='and'>
                                        <condition attribute='g_zcode' operator='eq' value='68123' />
                                    </filter>
                                </entity>
                            </fetch> ";
                EntityCollection entCollection = service.RetrieveMultiple(new FetchExpression(fetchXML));
                DisplayResults(entCollection);
            }
        }


        //the RetrieveMultiple method performs faster than the Fetch method because it does not have to parse the query.
        //The QueryByAttribute class provides an easy way to build queries that test a set of attributes against a set of values. Use this class together with the RetrieveMultiple method or the RetrieveMultiple message.
QueryByAttribute
        private void ViewAll_QueryByAttribute()
        {
            using (OrganizationServiceProxy serviceProxy = new OrganizationServiceProxy(OrganizationUri, HomeRealmUri, PassCredentials(), null))
            {
                IOrganizationService service = (IOrganizationService)serviceProxy;
                QueryByAttribute qryExp = new QueryByAttribute("g_bpres");
                qryExp.ColumnSet = new ColumnSet("g_fname", "g_lname", "g_sta", "g_mname");
                //qryExp.ColumnSet.AllColumns=true;

                //Error Will thorw - QueryByAttribute must specify a non-empty attribute array.
                //Because we haven’t specified Attributes and Values property. So we need to specify those properties.
                qryExp.Attributes.Add("g_zcode"); //qryExp.Attributes.Add("g_zcode","g_sta");
                qryExp.Values.Add("68123"); //qryExp.Values.Add("68123","NE");
               
                EntityCollection entCollection = service.RetrieveMultiple(qryExp);
                DisplayResults(entCollection);
            }
        }

Display Entity List
        private void DisplayResults(EntityCollection entCollection)
        {
            String strHtml = "<table rules='all' border='1'><tr><td></td><td>Name</td><td>State</td><td>M Name</td></tr>";
            foreach (var c in entCollection.Entities)
            {
                strHtml += "<tr><td>";
                if (c.Attributes.Contains("g_bpid"))
                {
                    strHtml += "<a href=default.aspx?id=" + c.Attributes["g_bpid"] + ">Edit</a>";
                }
                strHtml += "</td><td>";
                if (c.Attributes.Contains("g_fname") && c.Attributes.Contains("g_lname"))
                {
                    strHtml += c.Attributes["g_fname"] + "," + c.Attributes["g_lname"];
                }
                strHtml += "</td><td>";
                if (c.Attributes.Contains("g_sta"))
                {
                    //strHtml += ((EntityReference)c.Attributes["g_sta"]).Id.ToString() + " - ";
                    strHtml += ((EntityReference)c.Attributes["g_sta"]).Name.ToString();
                }
                strHtml += "</td><td>";
                if (c.Attributes.Contains("g_mname"))
                {
                    //strHtml += ((EntityReference)c.Attributes["g_mname"]).Id.ToString() + " - ";
                    strHtml += ((EntityReference)c.Attributes["g_mname"]).Name.ToString();
                }
                strHtml += "</td></tr>";
            }
            litViewAll.Text = strHtml + "</table>";
        }

Pass Credentials
        private ClientCredentials PassCredentials()
        {
            //Authenticate using credentials of the logged in user;      
            ClientCredentials cntCredentials = new ClientCredentials();
            cntCredentials.UserName.UserName = "userid";
            cntCredentials.UserName.Password = "pwd";
            //cntCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

            return cntCredentials;
        }
    }
}
Reference CrmService Web Service - http://msdn.microsoft.com/en-us/library/bb887784.aspx

No comments: