private void ExecuteTransfer()
        {
            var informationPanel = InformationPanel.GetInformationPanel(this, "Starting playlist transfer...", 340, 150);

            btnCancel.Visible = true;
            bwTransferData    = new BackgroundWorker {
                WorkerReportsProgress = true, WorkerSupportsCancellation = true
            };
            bwTransferData.DoWork += (sender, e) =>
            {
                var worker       = (BackgroundWorker)sender;
                var errors       = new List <Item <string, string> >();
                var autoMappings = new List <Item <EntityReference, EntityReference> >();

                #region Auto-mappings

                OnStatusMessage?.Invoke(this, new StatusBarMessageEventArgs(1, "Retrieving root Business Units..."));
                // Add BU mappings
                var bumapping = AutoMappings.GetRootBusinessUnitMapping(sourceService, targetService);
                if (bumapping != null)
                {
                    autoMappings.Add(bumapping);
                }

                OnStatusMessage?.Invoke(this, new StatusBarMessageEventArgs(1, "Retrieving default transaction currencies..."));
                var tcmapping = AutoMappings.GetDefaultTransactionCurrencyMapping(sourceService, targetService);
                if (tcmapping != null)
                {
                    autoMappings.Add(tcmapping);
                }

                OnStatusMessage?.Invoke(this, new StatusBarMessageEventArgs(1, "Retrieving systemuser mappings..."));
                var sumapping = AutoMappings.GetSystemUsersMapping(sourceService, targetService);
                if (sumapping != null)
                {
                    autoMappings.AddRange(sumapping);
                }

                #endregion Auto-mappings

                for (int i = 0; i < list.Items.Count; i++)
                {
                    var item       = list.Items[i];
                    var entitymeta = sourceService.RetrieveEntity(item.Setting.LogicalName);
                    var attributes = entitymeta.Attributes
                                     .Where(a => (a.IsValidForCreate != null && a.IsValidForCreate.Value))// || (a.IsValidForUpdate != null && a.IsValidForUpdate.Value))
                                     .Where(a => a.IsValidForRead != null && a.IsValidForRead.Value)
                                     .Where(a => a.DisplayName != null && a.DisplayName.UserLocalizedLabel != null && !string.IsNullOrEmpty(a.DisplayName.UserLocalizedLabel.Label))
                                     .Where(a => !item.Setting.UnmarkedAttributes.Any(ua => ua.Equals(a.LogicalName)))
                                     .ToList();
                    var entity = new AppCode.EntityRecord(entitymeta, attributes, item.Actions, bwTransferData, sourceService, targetService);

                    worker.ReportProgress((i / list.Items.Count), string.Format("Transfering entity '{0}'...", entity.Name));

                    try
                    {
                        entity.Filter   = item.Setting.Filter;
                        entity.Mappings = autoMappings;
                        entity.Mappings.AddRange(item.Setting.Mappings);
                        entity.OnStatusMessage += OnStatusMessage;
                        entity.Transfer(useBulk, bulkCount);
                        errors.AddRange(entity.Messages.Select(m => new Item <string, string>(entity.Name, m)));
                    }
                    catch (FaultException <OrganizationServiceFault> error)
                    {
                        errors.Add(new Item <string, string>(entity.Name, error.Message));
                    }
                }

                e.Result = errors;
            };
            bwTransferData.RunWorkerCompleted += (sender, e) =>
            {
                btnCancel.Visible = false;
                btnCancel.Text    = @"Cancel";
                Controls.Remove(informationPanel);
                informationPanel.Dispose();
                //SendMessageToStatusBar(this, new StatusBarMessageEventArgs(string.Empty)); // keep showing transfer results afterwards

                var errors = (List <Item <string, string> >)e.Result;

                if (errors.Count > 0)
                {
                    var errorDialog = new ErrorList((List <Item <string, string> >)e.Result);
                    errorDialog.ShowDialog(ParentForm);
                }
            };
            bwTransferData.ProgressChanged += (sender, e) =>
            {
                InformationPanel.ChangeInformationPanelMessage(informationPanel, e.UserState.ToString());
                OnStatusMessage?.Invoke(this, new StatusBarMessageEventArgs(e.ProgressPercentage * 100, e.UserState.ToString()));
            };
            bwTransferData.RunWorkerAsync();
        }
Exemple #2
0
        private void TransferEntities(bool preview)
        {
            if (lvEntities.SelectedItems.Count == 0)
            {
                MessageBox.Show("You must select at least one entity to be transfered", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            // Good time to save the attributes
            SaveUnmarkedAttributes();

            if (!preview && cbDelete.Checked)
            {
                foreach (ListViewItem entityitem in lvEntities.SelectedItems)
                {
                    if (entityitem != null && entityitem.Tag != null)
                    {
                        var entity = (EntityMetadata)entityitem.Tag;

                        if (!string.IsNullOrEmpty(settings[entity.LogicalName].Filter))
                        {
                            var msg    = string.Format("You have a filter applied on \"{0}\" and checked the \"Delete\" flag. All records on the target environment which don't match the filtered soure set will be deleted! Are you sure you want to continue?", entity.LogicalName);
                            var result = MessageBox.Show(msg, "Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                            if (result.Equals(DialogResult.No))
                            {
                                return;
                            }
                        }
                    }
                }
            }

            ManageWorkingState(true);

            SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(0, "Start transfering records..."));

            var transfermode = Enumerations.TransferMode.None;

            if (preview)
            {
                transfermode |= Enumerations.TransferMode.Preview;
            }
            if (cbCreate.Checked)
            {
                transfermode |= Enumerations.TransferMode.Create;
            }
            if (cbUpdate.Checked)
            {
                transfermode |= Enumerations.TransferMode.Update;
            }
            if (cbDelete.Checked)
            {
                transfermode |= Enumerations.TransferMode.Delete;
            }

            bool useBulk    = chkUseBulk.Checked;
            int  bulkCount  = Convert.ToInt32(nudBulkCount.Value);
            var  attributes = lvAttributes.CheckedItems.Cast <ListViewItem>().Select(v => (AttributeMetadata)v.Tag).ToList();

            WorkAsync(new WorkAsyncInfo
            {
                Message       = "Transfering records...",
                AsyncArgument = lvEntities.SelectedItems.Cast <ListViewItem>().Select(v => (EntityMetadata)v.Tag).ToList(),
                IsCancelable  = true,
                Work          = (worker, evt) =>
                {
                    var entities       = (List <EntityMetadata>)evt.Argument;
                    var errors         = new List <Item <string, string> >();
                    var manualMappings = settings[organisationid].Mappings;
                    var autoMappings   = new List <Item <EntityReference, EntityReference> >();

                    if (cbBusinessUnit.Checked)
                    {
                        SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(1, "Retrieving root Business Units..."));
                        var bumapping = AutoMappings.GetRootBusinessUnitMapping(this.Service, targetService);
                        if (bumapping != null)
                        {
                            autoMappings.Add(bumapping);
                        }
                    }

                    if (cbTransactionCurrency.Checked)
                    {
                        SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(1, "Retrieving default transaction currencies..."));
                        var tcmapping = AutoMappings.GetDefaultTransactionCurrencyMapping(this.Service, targetService);
                        if (tcmapping != null)
                        {
                            autoMappings.Add(tcmapping);
                        }
                    }

                    if (cbSystemUserEntityReferences.Checked)
                    {
                        SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(1, "Retrieving systemuser mappings..."));
                        var sumapping = AutoMappings.GetSystemUsersMapping(this.Service, targetService);
                        if (sumapping != null)
                        {
                            autoMappings.AddRange(sumapping);
                        }
                    }

                    for (int i = 0; i < entities.Count; i++)
                    {
                        var entitymeta = entities[i];
                        var entity     = new AppCode.EntityRecord(entitymeta, attributes, transfermode, worker, this.Service, targetService);

                        worker.ReportProgress((i / entities.Count), string.Format("{1} entity '{0}'...", entity.Name, (preview ? "Previewing" : "Transfering")));

                        try
                        {
                            entity.Filter   = settings[entitymeta.LogicalName].Filter;
                            entity.Mappings = autoMappings;
                            entity.Mappings.AddRange(manualMappings);
                            entity.OnStatusMessage += Transfer_OnStatusMessage;
                            entity.Transfer(useBulk, bulkCount);
                            errors.AddRange(entity.Messages.Select(m => new Item <string, string>(entity.Name, m)));

                            // Show preview window
                            if (preview)
                            {
                                Invoke(new Action(() =>
                                {
                                    var prvwDialog = new Preview(entity.PreviewList);
                                    prvwDialog.ShowDialog(ParentForm);
                                }));
                            }
                        }
                        catch (FaultException <OrganizationServiceFault> error)
                        {
                            errors.Add(new Item <string, string>(entity.Name, error.Message));
                        }
                    }

                    evt.Result = errors;
                },
                PostWorkCallBack = evt =>
                {
                    tsbCancel.Text = @"Cancel";
                    //SendMessageToStatusBar(this, new StatusBarMessageEventArgs(string.Empty)); // keep showing transfer results afterwards
                    ManageWorkingState(false);

                    var errors = (List <Item <string, string> >)evt.Result;

                    if (errors.Count > 0)
                    {
                        var errorDialog = new ErrorList((List <Item <string, string> >)evt.Result);
                        errorDialog.ShowDialog(ParentForm);
                    }
                },
                ProgressChanged = evt =>
                {
                    SetWorkingMessage(evt.UserState.ToString());
                    SendMessageToStatusBar?.Invoke(this, new StatusBarMessageEventArgs(evt.ProgressPercentage * 100, evt.UserState.ToString()));
                }
            });
        }