How to retreive CRM records from an Entity using Fetch XML in Dynamics CRM and show on Grid view using c#. How to Bulk delete records from CRM using c#

In this blog I am going to explain how we could retrive/ delete all records from an entity in CRM using C#. For this demo I have taken a windows application, check the below steps and use the code as it is. This code also includes code how we could show Entity data in Gridview.



1. First of all take two different buttons. First button for retreiving records and 2nd button is for deleting records from an entity in CRM.

2. Place a Gridview control too in your form.

3. Now place code as below on Browse, Bulk_Upload button::

        OrganizationService _orgservice = new OrganizationService(CrmConnection.Parse("Url=https://yourSolution.crm5.dynamics.com; Username=admin@yourSolution.onmicrosoft.com; Password=pass@word1;"));
     
            //Retrive All records from an Entity in CRM using ExecuteMultipleRequest
        private void btnRtvMultiple_Click(object sender, EventArgs e)
        {
            DataTable dt = new DataTable();
            EntityCollection ecContacts = getAllContacts();

            if (ecContacts.Entities.Count > 0)
            {
                foreach (var entity in ecContacts.Entities)
                {
                    DataRow dr = dt.NewRow();

                    for (int i = 0; i < entity.Attributes.Count; i++)
                    {
                        string colName = entity.Attributes.Keys.ElementAt(i);
                        if (!dt.Columns.Contains(colName))
                        {
                            dt.Columns.Add(colName);
                        }

                        //String
                        if (entity.Attributes.Keys.ElementAt(i).ToString() == "fullname")                //Check for fullname value exists or not in Entity Collection
                            dr[colName] = entity.Attributes["fullname"];

                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "telephone1")         //Check for telephone1 exists or not in Entity Collection
                            dr[colName] = entity.Attributes["telephone1"].ToString();

                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "emailaddress1")      //Check for emailaddress1 exists or not in Entity Collection
                            dr[colName] = entity.Attributes["emailaddress1"].ToString();

                        //Lookup
                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "parentcustomerid")   //Check for parentcustomerid exists or not in Entity Collection
                            dr[colName] = ((EntityReference)entity.Attributes["parentcustomerid"]).Name;

                        //OptionSet
                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "gendercode")         //Check for gendercode exists or not in Entity Collection
                            dr[colName] = entity.FormattedValues["gendercode"];                          // Value - ((OptionSetValue)entity.Attributes["gendercode"]).Value;

                        //Date
                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "birthdate")          //Check for birthdate exists or not in Entity Collection
                            dr[colName] = ((DateTime)entity.Attributes["birthdate"]).ToLocalTime().ToShortDateString().ToString();

                        //Currency
                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "creditlimit")        //Check for creditlimit exists or not in Entity Collection
                            dr[colName] = ((Money)entity.Attributes["creditlimit"]).Value;

                        //Two Options
                        else if (entity.Attributes.Keys.ElementAt(i).ToString() == "donotsendmm")         //Check for donotsendmm exists or not in Entity Collection
                            dr[colName] = ((Boolean)entity.Attributes["donotsendmm"]).ToString();
                    }
                    dt.Rows.Add(dr);
                }
                dataGridView1.DataSource = dt;
            }
            else
            {
                MessageBox.Show("No records found in CRM for fetching data in grdiview", "Warning", MessageBoxButtons.RetryCancel, MessageBoxIcon.Warning);
            }
        }

        //Get data from CRM Entity using Fetch XML
        private EntityCollection getAllContacts()
        {

                             EntityCollection ecContacts = _orgservice.RetrieveMultiple(new FetchExpression(fetchXMl));
            return ecContacts;
        }

        //Delete All records from an Entity in CRM using ExecuteMultipleRequest
        private void btnBulk_Delete_Click(object sender, EventArgs e)
        {
            EntityCollection ecContact = getAllContacts();
            if (ecContact.Entities.Count > 0)
            {
                try
                {
                    var mulReq = new ExecuteMultipleRequest
                       {
                           Settings = new ExecuteMultipleSettings
                           {
                               ContinueOnError = false,
                               ReturnResponses = true
                           },
                           Requests = new OrganizationRequestCollection()
                       };

                    foreach (var entity in ecContact.Entities)
                    {
                        EntityReference oldEntRef = new EntityReference(entity.LogicalName, entity.Id);
                        DeleteRequest delReq = new DeleteRequest { Target = oldEntRef };
                        mulReq.Requests.Add(delReq);
                    }
                    ExecuteMultipleResponse mulResp = (ExecuteMultipleResponse)_orgservice.Execute(mulReq);
                    MessageBox.Show("All records deleted successfully from Contacts :: ", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Some error occured while deleteing records from Contacts :: " + ex, "Error", MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("No records found in Contact entity. Please try again later", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }




Comments

  1. hello
    can u send me all class file like datagridview

    ReplyDelete

Post a Comment

Popular posts from this blog

Search data in Gridview on Textbox Key press event using JQuery in Asp.Net- C#

StateCode and StatusCode Values for mostly used entities in Microsoft Dynamics CRM 2013

Dumps for Microsoft Dynamics CRM MB2-703 Practice Exam Questions Free

How to import CSV files into DataTable in C#

How to show enlarge image when mouse hover on image or link in Asp.Net(c#) using JavaScript

go to top image