private async Task PublishEntityAsync(IEnumerable <string> entityNames)
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            var entityNamesOrdered = string.Join(",", entityNames.OrderBy(s => s));

            this._iWriteToOutput.WriteToOutputStartOperation(service.ConnectionData, Properties.OperationNames.PublishingEntitiesFormat2, service.ConnectionData.Name, entityNamesOrdered);

            ToggleControls(service.ConnectionData, false, Properties.WindowStatusStrings.PublishingEntitiesFormat2, service.ConnectionData.Name, entityNamesOrdered);

            try
            {
                var repository = new PublishActionsRepository(service);

                await repository.PublishEntitiesAsync(entityNames);

                ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.PublishingEntitiesCompletedFormat2, service.ConnectionData.Name, entityNamesOrdered);
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);

                ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.PublishingEntitiesFailedFormat2, service.ConnectionData.Name, entityNamesOrdered);
            }

            this._iWriteToOutput.WriteToOutputEndOperation(service.ConnectionData, Properties.OperationNames.PublishingEntitiesFormat2, service.ConnectionData.Name, entityNamesOrdered);
        }
        private async Task PerformPublishEntityAsync(string folder, Guid idSavedQueryVisualization, string entityName, string name)
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            this._iWriteToOutput.WriteToOutputStartOperation(service.ConnectionData, Properties.OperationNames.PublishingEntitiesFormat2, service.ConnectionData.Name, entityName);

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, entityName);

            try
            {
                var repository = new PublishActionsRepository(service);

                await repository.PublishEntitiesAsync(new[] { entityName });

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionPublishingEntitiesCompletedFormat2, service.ConnectionData.Name, entityName);
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionPublishingEntitiesFailedFormat2, service.ConnectionData.Name, entityName);
            }

            this._iWriteToOutput.WriteToOutputEndOperation(service.ConnectionData, Properties.OperationNames.PublishingEntitiesFormat2, service.ConnectionData.Name, entityName);
        }
        private async void btnPublishEntity_Click(object sender, RoutedEventArgs e)
        {
            PluginTreeViewItem nodeItem = GetItemFromRoutedDataContext <PluginTreeViewItem>(e);

            if (nodeItem == null ||
                !nodeItem.EntityLogicalName.IsValidEntityName()
                )
            {
                return;
            }

            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            var entityName = nodeItem.EntityLogicalName;

            this._iWriteToOutput.WriteToOutputStartOperation(service.ConnectionData, Properties.OperationNames.PublishingEntitiesFormat2, service.ConnectionData.Name, entityName);

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, entityName);

            try
            {
                var repository = new PublishActionsRepository(service);

                await repository.PublishEntitiesAsync(new[] { entityName });

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionPublishingEntitiesCompletedFormat2, service.ConnectionData.Name, entityName);
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionPublishingEntitiesFailedFormat2, service.ConnectionData.Name, entityName);
            }

            this._iWriteToOutput.WriteToOutputEndOperation(service.ConnectionData, Properties.OperationNames.PublishingEntitiesFormat2, service.ConnectionData.Name, entityName);
        }
Example #4
0
        private async Task UpdateSavedQueryXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SavedQuery savedQuery)
        {
            string fieldName  = SavedQueryRepository.GetFieldNameByXmlRoot(doc.Root.Name.ToString());
            string fieldTitle = SavedQueryRepository.GetFieldTitleByXmlRoot(doc.Root.Name.ToString());

            if (string.Equals(fieldName, SavedQuery.Schema.Attributes.layoutxml, StringComparison.InvariantCulture) &&
                !string.IsNullOrEmpty(savedQuery.ReturnedTypeCode)
                )
            {
                var entityData = service.ConnectionData.GetEntityIntellisenseData(savedQuery.ReturnedTypeCode);

                if (entityData != null && entityData.ObjectTypeCode.HasValue)
                {
                    XAttribute attr = doc.Root.Attribute("object");

                    if (attr != null)
                    {
                        attr.Value = entityData.ObjectTypeCode.ToString();
                    }
                }
            }

            {
                string xmlContent = savedQuery.GetAttributeValue <string>(fieldName);

                if (!string.IsNullOrEmpty(xmlContent))
                {
                    commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                    string fileNameBackUp = EntityFileNameFormatter.GetSavedQueryFileName(service.ConnectionData.Name, savedQuery.ReturnedTypeCode, savedQuery.Name, fieldTitle + " BackUp", FileExtension.xml);
                    string filePathBackUp = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileNameBackUp));

                    try
                    {
                        xmlContent = ContentComparerHelper.FormatXmlByConfiguration(
                            xmlContent
                            , commonConfig
                            , XmlOptionsControls.SavedQueryXmlOptions
                            , schemaName: AbstractDynamicCommandXsdSchemas.FetchSchema
                            , savedQueryId: savedQuery.Id
                            , entityName: savedQuery.ReturnedTypeCode
                            );

                        File.WriteAllText(filePathBackUp, xmlContent, new UTF8Encoding(false));

                        this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SavedQuery.Schema.EntityLogicalName, savedQuery.Name, fieldTitle, filePathBackUp);
                    }
                    catch (Exception ex)
                    {
                        this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
                    }
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SavedQuery.Schema.EntityLogicalName, savedQuery.Name, fieldTitle);
                    this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                }
            }

            var newText = doc.ToString(SaveOptions.DisableFormatting);

            if (string.Equals(fieldName, SavedQuery.Schema.Attributes.fetchxml, StringComparison.InvariantCulture))
            {
                try
                {
                    _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.ExecutingValidateSavedQueryRequest);

                    var request = new ValidateSavedQueryRequest()
                    {
                        FetchXml  = newText,
                        QueryType = savedQuery.QueryType.GetValueOrDefault()
                    };

                    service.Execute(request);
                }
                catch (Exception ex)
                {
                    this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
                }
            }

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.SavingEntityFormat1, savedQuery.LogicalName);

            _iWriteToOutput.WriteToOutputEntityInstance(service.ConnectionData, savedQuery.LogicalName, savedQuery.Id);

            var updateEntity = new SavedQuery
            {
                Id = savedQuery.Id,
            };

            updateEntity.Attributes[fieldName] = newText;

            await service.UpdateAsync(updateEntity);

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.SavingEntityCompletedFormat1, savedQuery.LogicalName);

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, savedQuery.ReturnedTypeCode);

            {
                var repositoryPublish = new PublishActionsRepository(service);

                await repositoryPublish.PublishEntitiesAsync(new[] { savedQuery.ReturnedTypeCode });
            }

            service.TryDispose();
        }
        private async Task <string> TrasnferAudit()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content, "Connection CRM Source.", "Connection CRM Target.");

            string operation = string.Format(Properties.OperationNames.TransferingAuditFormat2, ConnectionSource.Name, ConnectionTarget.Name);

            content.AppendLine(_iWriteToOutput.WriteToOutputStartOperation(null, operation));

            var repositorySource = new EntityMetadataRepository(_comparerSource.Service1);
            var repositoryTarget = new EntityMetadataRepository(_comparerSource.Service2);

            var taskSource = repositorySource.GetEntitiesWithAttributesForAuditAsync();
            var taskTarget = repositoryTarget.GetEntitiesWithAttributesForAuditAsync();

            var listEntityMetadataSource = await taskSource;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Entities in {0}: {1}", ConnectionSource.Name, listEntityMetadataSource.Count()));

            var listEntityMetadataTarget = await taskTarget;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Entities in {0}: {1}", ConnectionTarget.Name, listEntityMetadataTarget.Count()));

            var commonEntityMetadata = new List <LinkedEntities <EntityMetadata> >();

            foreach (var entityMetadata1 in listEntityMetadataSource.OrderBy(e => e.LogicalName))
            {
                {
                    var entityMetadata2 = listEntityMetadataTarget.FirstOrDefault(e => string.Equals(e.LogicalName, entityMetadata1.LogicalName, StringComparison.InvariantCultureIgnoreCase));

                    if (entityMetadata2 != null)
                    {
                        commonEntityMetadata.Add(new LinkedEntities <EntityMetadata>(entityMetadata1, entityMetadata2));
                        continue;
                    }
                }
            }

            HashSet <string> entitiesToPublish = new HashSet <string>();

            var entitiesToEnableAudit = commonEntityMetadata.Where(
                e =>
                e.Entity1.IsAuditEnabled != null &&
                e.Entity1.IsAuditEnabled.Value &&
                e.Entity2.IsAuditEnabled != null &&
                e.Entity2.IsAuditEnabled.CanBeChanged &&
                e.Entity2.IsAuditEnabled.Value == false
                ).ToList();

            if (entitiesToEnableAudit.Any())
            {
                content
                .AppendLine()
                .AppendFormat("Enabling Audit on Entities: {0}", entitiesToEnableAudit.Count)
                .AppendLine();

                foreach (var entityLink in entitiesToEnableAudit.OrderBy(e => e.Entity1.LogicalName))
                {
                    content.AppendLine(_tabSpacer + entityLink.Entity1.LogicalName);

                    entitiesToPublish.Add(entityLink.Entity1.LogicalName);

                    try
                    {
                        entityLink.Entity2.IsAuditEnabled.Value = true;

                        await repositoryTarget.UpdateEntityMetadataAsync(entityLink.Entity2);
                    }
                    catch (Exception ex)
                    {
                        var desc = DTEHelper.GetExceptionDescription(ex);

                        content.AppendLine(desc);
                    }
                }
            }

            bool first = true;

            foreach (var entityLink in commonEntityMetadata.OrderBy(e => e.Entity1.LogicalName))
            {
                var query = from source in entityLink.Entity1.Attributes
                            join target in entityLink.Entity2.Attributes on source.LogicalName equals target.LogicalName
                            where source.IsAuditEnabled != null &&
                            string.IsNullOrEmpty(source.AttributeOf) &&
                            string.IsNullOrEmpty(target.AttributeOf) &&
                            source.IsAuditEnabled.Value &&
                            target.IsAuditEnabled != null &&
                            target.IsAuditEnabled.CanBeChanged &&
                            target.IsAuditEnabled.Value == false
                            orderby target.LogicalName
                            select target;

                foreach (var attribute in query)
                {
                    if (first)
                    {
                        content
                        .AppendLine()
                        .AppendLine("Enabling Audit on Attributes:")
                        .AppendLine();

                        first = false;
                    }

                    content
                    .AppendFormat(_tabSpacer + "{0}.{1}", attribute.EntityLogicalName, attribute.LogicalName)
                    .AppendLine();

                    entitiesToPublish.Add(attribute.EntityLogicalName);

                    try
                    {
                        attribute.IsAuditEnabled.Value = true;

                        await repositoryTarget.UpdateAttributeMetadataAsync(attribute);
                    }
                    catch (Exception ex)
                    {
                        var desc = DTEHelper.GetExceptionDescription(ex);

                        content.AppendLine(desc);
                    }
                }
            }

            if (entitiesToPublish.Any())
            {
                content
                .AppendLine()
                .AppendFormat("Publish Entities: {0}", entitiesToPublish.Count)
                .AppendLine();

                foreach (var item in entitiesToPublish.OrderBy(s => s))
                {
                    content.AppendLine(_tabSpacer + item);
                }

                var repositoryPublish = new PublishActionsRepository(_comparerSource.Service2);

                try
                {
                    await repositoryPublish.PublishEntitiesAsync(entitiesToPublish);
                }
                catch (Exception ex)
                {
                    var desc = DTEHelper.GetExceptionDescription(ex);

                    content.AppendLine(desc);
                }
            }

            content.AppendLine().AppendLine().AppendLine(_iWriteToOutput.WriteToOutputEndOperation(null, operation));

            string fileName = string.Format("OrgTransfer Audit from {0} to {1} at {2}.txt"
                                            , this.ConnectionSource.Name
                                            , this.ConnectionTarget.Name
                                            , DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            string filePath = Path.Combine(_folder, FileOperations.RemoveWrongSymbols(fileName));

            File.WriteAllText(filePath, content.ToString(), new UTF8Encoding(false));

            return(filePath);
        }
        private async Task UpdateSystemFormXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SystemForm systemForm)
        {
            {
                string fieldTitle = SystemForm.Schema.Headers.formxml;

                string formXml = systemForm.FormXml;

                if (!string.IsNullOrEmpty(formXml))
                {
                    commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                    string fileNameBackUp = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, fieldTitle + " BackUp", FileExtension.xml);
                    string filePathBackUp = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileNameBackUp));

                    try
                    {
                        formXml = ContentComparerHelper.FormatXmlByConfiguration(
                            formXml
                            , commonConfig
                            , XmlOptionsControls.FormXmlOptions
                            , schemaName: AbstractDynamicCommandXsdSchemas.FormXmlSchema
                            , formId: systemForm.Id
                            , entityName: systemForm.ObjectTypeCode
                            );

                        File.WriteAllText(filePathBackUp, formXml, new UTF8Encoding(false));

                        this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SystemForm.Schema.EntitySchemaName, systemForm.Name, fieldTitle, filePathBackUp);
                    }
                    catch (Exception ex)
                    {
                        this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
                    }
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SystemForm.Schema.EntitySchemaName, systemForm.Name, fieldTitle);
                    this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                }
            }

            var newText = doc.ToString(SaveOptions.DisableFormatting);

            var updateEntity = new SystemForm
            {
                Id = systemForm.Id,
            };

            updateEntity.Attributes[SystemForm.Schema.Attributes.formxml] = newText;

            await service.UpdateAsync(updateEntity);

            var repositoryPublish = new PublishActionsRepository(service);

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingSystemFormFormat3, service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name);
            await repositoryPublish.PublishDashboardsAsync(new[] { systemForm.Id });

            if (systemForm.ObjectTypeCode.IsValidEntityName())
            {
                _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, systemForm.ObjectTypeCode);
                await repositoryPublish.PublishEntitiesAsync(new[] { systemForm.ObjectTypeCode });
            }

            service.TryDispose();
        }
        private async Task PerformUpdateEntityField(string folder, Guid idSavedQueryVisualization, string entityName, string name, string fieldName, string fieldTitle)
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.InConnectionUpdatingFieldFormat2, service.ConnectionData.Name, fieldName);

            try
            {
                var repository = new SavedQueryVisualizationRepository(service);

                var savedQueryVisualization = await repository.GetByIdAsync(idSavedQueryVisualization, new ColumnSet(fieldName));

                string xmlContent = savedQueryVisualization.GetAttributeValue <string>(fieldName);

                {
                    if (ContentComparerHelper.TryParseXml(xmlContent, out var doc))
                    {
                        xmlContent = doc.ToString();
                    }
                }

                string filePath = await CreateFileAsync(folder, entityName, name, fieldTitle + " BackUp", xmlContent);

                var  newText      = string.Empty;
                bool?dialogResult = false;

                this.Dispatcher.Invoke(() =>
                {
                    var form = new WindowTextField("Enter " + fieldTitle, fieldTitle, xmlContent);

                    dialogResult = form.ShowDialog();

                    newText = form.FieldText;
                });

                if (dialogResult.GetValueOrDefault() == false)
                {
                    ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionUpdatingFieldFailedFormat2, service.ConnectionData.Name, fieldName);
                    return;
                }

                newText = ContentComparerHelper.RemoveInTextAllCustomXmlAttributesAndNamespaces(newText);

                {
                    if (ContentComparerHelper.TryParseXml(newText, out var doc))
                    {
                        newText = doc.ToString(SaveOptions.DisableFormatting);
                    }
                }

                var updateEntity = new SavedQueryVisualization
                {
                    Id = idSavedQueryVisualization
                };
                updateEntity.Attributes[fieldName] = newText;

                await service.UpdateAsync(updateEntity);

                UpdateStatus(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingEntitiesFormat2, service.ConnectionData.Name, entityName);

                {
                    var repositoryPublish = new PublishActionsRepository(service);

                    await repositoryPublish.PublishEntitiesAsync(new[] { entityName });
                }

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionUpdatingFieldCompletedFormat2, service.ConnectionData.Name, fieldName);
            }
            catch (Exception ex)
            {
                _iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.InConnectionUpdatingFieldFailedFormat2, service.ConnectionData.Name, fieldName);
            }
        }