Skip to main content

Inserting or updating bulk records in CRM 365 through C#

For some scenarios we would be having some requirements where multiple records needs to be created which can take number of iterations. To user service.create() method would affect the performance significantly. So we need to executemultiple request.

Below is the code for the executemultiple() method usage. To create contact.
Same can be used for other entities as well.
Here i am selecting record from grid and looping through the selected records.


            Entity                                    contact = new Entity();
            EntityReferenceCollection   relatedEntities = new EntityReferenceCollection();
            Relationship                          relationship = new Relationship("account_primary_contact");
            String                                    bdate;
            Int32                                     rowcount = dataGrid.SelectedItems.Count;
            DataRowView                      rw;         
            AccountManager                  selectedVal;
            EntityCollection                   val1;
            EntityCollection                   chkContact;
            String                                   name;
            Guid                                     value;
            OptionSetValueCollection   mul = new OptionSetValueCollection();


            ExecuteMultipleRequest request = new ExecuteMultipleRequest()
            {
                Settings = new ExecuteMultipleSettings()
                {
                    ContinueOnError = false,
                    ReturnResponses = false
                },
                Requests = new OrganizationRequestCollection()
            };

            int i = 0;
            while (i < rowcount)
            {
                var currentRowIndex = dataGrid.Items.IndexOf(dataGrid.SelectedItems[i]);
                rw = (DataRowView)dataGrid.SelectedItems[i];
                object item = dataGrid.Items[i];
               
                contact.LogicalName = "contact";
                contact["firstname"] = rw["Firstname"].ToString();
                contact["middlename"] = rw["Middlename"].ToString();
                contact["lastname"] = rw["Lastname"].ToString();
                contact["emailaddress1"] = rw["EmailId"].ToString();
                contact["telephone1"] = rw["TelePhone"].ToString();
                contact["mobilephone"] = rw["Mobile"].ToString();
                bdate = rw["BirthDate"].ToString();
                contact["birthdate"] = Convert.ToDateTime(bdate);
                mul.Add(new OptionSetValue(100000001));

                selectedVal = cmbAccount.SelectedItem as AccountManager;                       
               
                if ((Boolean)rw["AccountFlag"])
                {
                    int k = 0;
                    val1 = GetAccount(true);
                    foreach (Entity j in val1.Entities)
                    {
                        name = val1.Entities[k].Attributes["name"].ToString();
                        value = (Guid)val1.Entities[k].Attributes["accountid"];
                        selectedVal = new AccountManager() { Name = name, Value = value };
                        k++;
                    }                 
                }

                contact["new_datasource"] = mul;
                Guid accountId = selectedVal.Value;
                contact["parentcustomerid"] = new EntityReference("account", accountId);
                chkContact = ValidateContact(rw["Firstname"].ToString(), rw["Lastname"].ToString(),                        rw["EmailId"].ToString());

                if (chkContact.Entities.Count > 0)
                {
                    var boundItem = dataGrid.CurrentCell.Item;
                    Entity contactUpdate = new Entity("contact");
                    contactUpdate.Id = chkContact.Entities[0].Id;
                    contactUpdate["telephone1"] = rw["TelePhone"].ToString();
                    contactUpdate["mobilephone"] = rw["Mobile"].ToString();

                    mul.Add(new OptionSetValue(100000001));
                    mul.Add(new OptionSetValue(100000002));
                    contactUpdate["new_datasource"] = mul;

                    UpdateRequest ur = new UpdateRequest { Target = contact };
                    request.Requests.Add(ur);                   
                }
                else
                {
                    CreateRequest cr = new CreateRequest { Target = contact };
                    request.Requests.Add(cr);                 
                }
                i++;
            }
            _service.Execute(request);

Comments

Popular posts from this blog

Error 500 on the server for D365 finance and operations

While working on D365 finance and operations one fine day i came across the error 500. There are many reasons for this server. Below link can help you if encounter the same issue. https://community.dynamics.com/ax/f/33/t/195422 If any of solutions does not work for you then you might need to check if there are any newly added objects through code and they might be causing the issue. Try to remove them build and synchronize them with the database. https://community.dynamics.com/ax/b/axdilip/archive/2017/01/05/dynamics-365-for-operations-troubleshooting-http-500-httpcompileexception-error To debug more you can use solution provided in below link. https://www.linkedin.com/pulse/ax7-500-error-shashi-kant-yadav In my case the issue was related to the certificate expiration. To check the expired certificate on the server we can go to "Certificate Management Console" and see the certificates expiration date. To check this is power shell open "Windows PowerS

A reference to 'Dynamics.AX.XXXXX, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is required to compile this module.

The error "A reference to 'Dynamics.AX.Directory, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null' is required to compile this module." came on when i was building the project in visual studio. This error is thrown when the model is missing any reference which are needed to build the project. To update rectify this error we need to update the model. To do that go to "Dynamics 365 > Model Management > Update model parameter" A new window will open the model you want to update. Here i am selecting "Development" which i have created. Then click on next. On "Select referenced packages" select the missing packages which ones is throwing error. Here i have selected the "Directory" packages as they are the once throwing error. Select the packages. After selecting the packages click on "Next". And Click on "Finish". Rebuild the project and you are good to go.

D365 Month end and year end process

Period Closing Accounts Payable a.          Post invoices for all open/received purchase orders. b.          Post all pending invoices if received from Vendor. c.          Post and settle all payments. d.          Run Currency revaluation e.          Reconcile Vendor balance and trial balance for control accounts. f.           Set fiscal period on-hold for Vendor. Accounts Receivable a.          Post invoices for all open/delivered sales orders. b.          Post all pending free text invoices. c.          Post and settle all received payments. d.          Run Currency revaluation e.          Reconcile Vendor balance and trial balance for control accounts. f.           Set fiscal period on-hold for Customer. Cash and Bank a.          Perform Bank reconciliation b.          Set fiscal period on-hold for Bank. Procurement / Sales a.          Review and Close all open purchase/sales orders/Requisition if require. b.          Perform sort cl