示例#1
0
        private async Task AddPluginTypeStepsToSolution(bool withSelect, string solutionUniqueName)
        {
            var entity = GetSelectedEntity();

            if (entity == null)
            {
                return;
            }

            var service = await GetService();

            var repository = new SdkMessageProcessingStepRepository(service);

            var steps = await repository.GetAllStepsByPluginTypeAsync(entity.Id);

            if (!steps.Any())
            {
                return;
            }

            _commonConfig.Save();

            try
            {
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);

                await SolutionController.AddSolutionComponentsGroupToSolution(_iWriteToOutput, service, null, _commonConfig, solutionUniqueName, ComponentType.SdkMessageProcessingStep, steps.Select(s => s.Id), null, withSelect);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
示例#2
0
        protected override List <string> GetDescriptionValues(Entity entityInput, string behavior, bool withManaged, bool withSolutionInfo, bool withUrls, Action <List <string>, Entity, bool, bool, bool> action)
        {
            var entity = entityInput.ToEntity <SdkMessageProcessingStep>();

            List <string> values = new List <string>();

            values.AddRange(new[]
            {
                entity.EventHandler?.Name ?? "Unknown"
                , entity.PrimaryObjectTypeCodeName
                , entity.SecondaryObjectTypeCodeName
                , entity.SdkMessageId?.Name ?? "Unknown"
                , SdkMessageProcessingStepRepository.GetStageName(entity.Stage.Value, entity.Mode.Value)
                , entity.Rank.ToString()
                , entity.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                , entity.IsCustomizable?.Value.ToString()
                , behavior
            });

            AppendIntoValues(values, entity, false, withManaged, withSolutionInfo);

            values.Add(entity.FilteringAttributesStringsSorted);

            return(values);
        }
        protected override List <string> GetDescriptionValues(Entity entityInput, string behavior, bool withManaged, bool withSolutionInfo, bool withUrls, Action <List <string>, Entity, bool, bool, bool> action)
        {
            var entity = entityInput.ToEntity <SdkMessageProcessingStepImage>();

            List <string> values = new List <string>();

            int stage = entity.Contains("sdkmessageprocessingstep.stage") ? (entity.GetAttributeValue <AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0;
            int mode  = entity.Contains("sdkmessageprocessingstep.mode") ? (entity.GetAttributeValue <AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0;

            values.AddRange(new[]
            {
                EntityDescriptionHandler.GetAttributeString(entity, "sdkmessageprocessingstep.eventhandler")
                , entity.PrimaryObjectTypeCodeName
                , entity.SecondaryObjectTypeCodeName
                , EntityDescriptionHandler.GetAttributeString(entity, "sdkmessageprocessingstep.sdkmessageid")
                , SdkMessageProcessingStepRepository.GetStageName(stage, mode)
                , EntityDescriptionHandler.GetAttributeString(entity, "sdkmessageprocessingstep.rank")
                , EntityDescriptionHandler.GetAttributeString(entity, "sdkmessageprocessingstep.statuscode")
                , entity.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype]
                , entity.Name
                , entity.EntityAlias
                , entity.IsManaged.ToString()
                , entity.IsCustomizable?.Value.ToString()
                , behavior
            });

            AppendIntoValues(values, entity, false, withManaged, withSolutionInfo);

            values.Add(entity.Attributes1StringsSorted);

            return(values);
        }
        protected override List <T> GetEntitiesByQuery <T>(QueryExpression query)
        {
            var result = base.GetEntitiesByQuery <T>(query);

            SdkMessageProcessingStepRepository.FullfillEntitiesSteps(result);

            return(result);
        }
        public PluginAssemblyDescriptionHandler(IOrganizationServiceExtented service, string connectionInfo)
        {
            this._service        = service;
            this._connectionInfo = connectionInfo;

            this._repType   = new PluginTypeRepository(service);
            this._repStep   = new SdkMessageProcessingStepRepository(service);
            this._repImage  = new SdkMessageProcessingStepImageRepository(service);
            this._repSecure = new SdkMessageProcessingStepSecureConfigRepository(service);
        }
示例#6
0
        private async Task AddAssemblyStepsToSolution(bool withSelect, string solutionUniqueName)
        {
            var entitiesList = GetSelectedEntitiesList()
                               .Select(e => e.Id);

            if (!entitiesList.Any())
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            var steps = new List <SdkMessageProcessingStep>();

            var repository = new SdkMessageProcessingStepRepository(service);

            foreach (var id in entitiesList)
            {
                steps.AddRange(await repository.GetAllStepsByPluginAssemblyAsync(id));
            }

            if (!steps.Any())
            {
                return;
            }

            if (!steps.Any())
            {
                return;
            }

            _commonConfig.Save();

            try
            {
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);

                await SolutionController.AddSolutionComponentsGroupToSolution(_iWriteToOutput, service, null, _commonConfig, solutionUniqueName, ComponentType.SdkMessageProcessingStep, steps.Select(s => s.Id), null, withSelect);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
示例#7
0
        private async Task PerformExportPluginTypeDescription(string folder, Guid idPluginType, string name)
        {
            var service = await GetService();

            if (service == null)
            {
                return;
            }

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.CreatingPluginTypeDescriptionFormat1, name);

            string fileName = EntityFileNameFormatter.GetPluginTypeFileName(service.ConnectionData.Name, name, "Description");
            string filePath = Path.Combine(folder, FileOperations.RemoveWrongSymbols(fileName));

            var repStep   = new SdkMessageProcessingStepRepository(service);
            var repImage  = new SdkMessageProcessingStepImageRepository(service);
            var repSecure = new SdkMessageProcessingStepSecureConfigRepository(service);

            var allSteps = await repStep.GetAllStepsByPluginTypeAsync(idPluginType);

            var queryImage = await repImage.GetImagesByPluginTypeAsync(idPluginType);

            var listSecure = await repSecure.GetAllSdkMessageProcessingStepSecureConfigAsync();

            bool hasDescription = await PluginTypeDescriptionHandler.CreateFileWithDescriptionAsync(
                service.ConnectionData.GetConnectionInfo()
                , filePath
                , idPluginType
                , name
                , allSteps
                , queryImage
                , listSecure
                );

            if (hasDescription)
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, PluginType.EntitySchemaName, name, "Description", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
            else
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, PluginType.EntitySchemaName, name, "Description");
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
            }

            ToggleControls(service.ConnectionData, true, Properties.OutputStrings.CreatingPluginTypeDescriptionCompletedFormat1, name);
        }
        private async Task CheckingPluginImagesRequiredComponents(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);
            var repositoryImage = new SdkMessageProcessingStepImageRepository(service);

            var listImages = await repositoryImage.GetAllImagesAsync();

            var queryImages = listImages
                            .OrderBy(image => image.Contains("sdkmessageprocessingstep.eventhandler") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.eventhandler").Value as EntityReference).Name : "Null")
                            .ThenBy(image => image.PrimaryObjectTypeCodeName)
                            .ThenBy(image => image.SecondaryObjectTypeCodeName)
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.sdkmessageid") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.sdkmessageid").Value as EntityReference).Name : "Null", new MessageComparer())
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.stage") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0)
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.mode") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0)
                            .ThenBy(image => image.Contains("sdkmessageprocessingstep.rank") ? (int)image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.rank").Value : 0)
                            .ThenBy(image => image.FormattedValues.ContainsKey("sdkmessageprocessingstep.statuscode") ? image.FormattedValues["sdkmessageprocessingstep.statuscode"] : "")
                            .ThenBy(image => image.FormattedValues.ContainsKey(SdkMessageProcessingStepImage.Schema.Attributes.imagetype) ? image.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype] : "")
                            .ThenBy(image => image.Name)
                            .ThenBy(image => image.EntityAlias)
                            .ThenBy(image => image.Attributes1StringsSorted)
                            ;

            EntityMetadataRepository repositoryMetadata = new EntityMetadataRepository(service);
            var dependencyRepository = new DependencyRepository(service);

            var listMetaData = await repositoryMetadata.GetEntitiesWithAttributesAsync();

            var dictEntity = new Dictionary<Guid, EntityMetadata>();
            var dictAttribute = new Dictionary<Guid, AttributeMetadata>();

            foreach (var metaEntity in listMetaData)
            {
                dictEntity.Add(metaEntity.MetadataId.Value, metaEntity);

                foreach (var metaAttribute in metaEntity.Attributes)
                {
                    dictAttribute.Add(metaAttribute.MetadataId.Value, metaAttribute);
                }
            }

            bool hasInfo = false;

            foreach (var image in queryImages)
            {
                var listRequired = await dependencyRepository.GetRequiredComponentsAsync((int)ComponentType.SdkMessageProcessingStepImage, image.Id);

                var stepEntities = GetSetEntites(image);
                var stepAttributes = GetSetImageAttributes(image);

                var componentsEntities = GetSetComponentsEntites(listRequired, dictEntity);
                var componentsAttributes = GetSetComponentsAttributes(listRequired, dictAttribute);

                bool entitiesIsSame = stepEntities.SequenceEqual(componentsEntities);
                bool attributesIsSame = stepAttributes.SequenceEqual(componentsAttributes);

                string pluginType = image.Contains("sdkmessageprocessingstep.eventhandler") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.eventhandler").Value as EntityReference).Name : "Null";

                string sdkMessage = image.Contains("sdkmessageprocessingstep.sdkmessageid") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.sdkmessageid").Value as EntityReference).Name : "Null";
                int stage = image.Contains("sdkmessageprocessingstep.stage") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.stage").Value as OptionSetValue).Value : 0;
                int mode = image.Contains("sdkmessageprocessingstep.mode") ? (image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.mode").Value as OptionSetValue).Value : 0;
                int rank = image.Contains("sdkmessageprocessingstep.rank") ? (int)image.GetAttributeValue<AliasedValue>("sdkmessageprocessingstep.rank").Value : 0;
                string status = image.FormattedValues.ContainsKey("sdkmessageprocessingstep.statuscode") ? image.FormattedValues["sdkmessageprocessingstep.statuscode"] : "";

                if (!entitiesIsSame || !attributesIsSame)
                {
                    hasInfo = true;

                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine().AppendLine();
                    }

                    //handler.SetHeader("PluginType", "Primary Entity", "Secondary Entity", "Message", "Stage", "Rank", "Status", "ImageType", "Name", "EntityAlias", "Attributes");

                    content.AppendFormat("{0}   Primary {1}   Secondary {2}   Message {3}   Stage {4}   Rank {5}   Status {6}   ImageType {7}   Name {8}   EntityAlias {9}   Attributes {10}"
                        , pluginType
                        , image.PrimaryObjectTypeCodeName
                        , image.SecondaryObjectTypeCodeName
                        , sdkMessage
                        , SdkMessageProcessingStepRepository.GetStageName(stage, mode)
                        , rank.ToString()
                        , status
                        , image.FormattedValues[SdkMessageProcessingStepImage.Schema.Attributes.imagetype]
                        , image.Name
                        , image.EntityAlias
                        , image.Attributes1StringsSorted
                    ).AppendLine();

                    if (!entitiesIsSame)
                    {
                        content.AppendLine("Conflict in entites.");

                        content.Append("Entities in plugin step description");

                        if (stepEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }


                        content.Append("Entities in required components");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }

                    if (!attributesIsSame)
                    {
                        content.AppendLine("Conflict in attributes.");

                        content.Append("Attributes in plugin step description");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }

                        content.Append("Attributes in required components");

                        if (componentsAttributes.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }
                }
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No conflicts were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Images Required Components at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Images Required Components: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
        private async Task CheckingPluginStepsRequiredComponents(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);

            var search = await repository.FindAllAsync(new List<PluginStage>(), string.Empty, string.Empty, string.Empty);

            var querySteps = search.SdkMessageProcessingStep
                            .OrderBy(ent => ent.EventHandler.Name)
                            .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                            .ThenBy(ent => ent.SdkMessageId.Name, new MessageComparer())
                            .ThenBy(ent => ent.Stage.Value)
                            .ThenBy(ent => ent.Mode.Value)
                            .ThenBy(ent => ent.Rank)
                            .ThenBy(ent => ent.Name)
                            ;

            EntityMetadataRepository repositoryMetadata = new EntityMetadataRepository(service);

            DependencyRepository dependencyRepository = new DependencyRepository(service);

            var listMetaData = await repositoryMetadata.GetEntitiesWithAttributesAsync();

            var dictEntity = new Dictionary<Guid, EntityMetadata>();
            var dictAttribute = new Dictionary<Guid, AttributeMetadata>();

            bool hasInfo = false;

            foreach (var metaEntity in listMetaData)
            {
                dictEntity.Add(metaEntity.MetadataId.Value, metaEntity);

                foreach (var metaAttribute in metaEntity.Attributes)
                {
                    dictAttribute.Add(metaAttribute.MetadataId.Value, metaAttribute);
                }
            }

            foreach (var step in querySteps)
            {
                var listRequired = await dependencyRepository.GetRequiredComponentsAsync((int)ComponentType.SdkMessageProcessingStep, step.Id);

                var stepEntities = GetSetEntites(step);
                var stepAttributes = GetSetStepAttributes(step);

                var componentsEntities = GetSetComponentsEntites(listRequired, dictEntity);
                var componentsAttributes = GetSetComponentsAttributes(listRequired, dictAttribute);

                bool entitiesIsSame = stepEntities.SequenceEqual(componentsEntities);
                bool attributesIsSame = stepAttributes.SequenceEqual(componentsAttributes);

                if (!entitiesIsSame || !attributesIsSame)
                {
                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine().AppendLine();
                    }

                    content.AppendFormat("{0}   Primary {1}   Secondary {2}   Message {3}   Stage {4}   Rank {5}   Status {6}   FilteringAttributes {7}",
                        step.EventHandler?.Name ?? "Unknown"
                        , step.PrimaryObjectTypeCodeName
                        , step.SecondaryObjectTypeCodeName
                        , step.SdkMessageId?.Name ?? "Unknown"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        , step.FilteringAttributesStringsSorted
                    ).AppendLine();

                    if (!entitiesIsSame)
                    {
                        hasInfo = true;

                        content.AppendLine("Conflict in entites.");

                        content.Append("Entities in plugin step description");

                        if (stepEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }


                        content.Append("Entities in required components");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsEntities)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }

                    if (!attributesIsSame)
                    {
                        hasInfo = true;

                        content.AppendLine("Conflict in attributes.");

                        content.Append("Attributes in plugin step description");

                        if (componentsEntities.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in stepAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }

                        content.Append("Attributes in required components");

                        if (componentsAttributes.Count > 0)
                        {
                            content.AppendLine(":");

                            foreach (var item in componentsAttributes)
                            {
                                content.AppendFormat("    {0}", item).AppendLine();
                            }
                        }
                        else
                        {
                            content.AppendLine(" are empty.");
                        }
                    }
                }
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No conflicts were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Steps Required Components at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Steps Required Components: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
        private async Task CheckingPluginSteps(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);

            var search = await repository.FindAllAsync(null, string.Empty, string.Empty, string.Empty);

            var querySteps = search.SdkMessageProcessingStep
                            .OrderBy(ent => ent.EventHandler?.Name ?? "Unknown")
                            .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                            .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                            .ThenBy(ent => ent.Stage.Value)
                            .ThenBy(ent => ent.Mode.Value)
                            .ThenBy(ent => ent.Rank)
                            .ThenBy(ent => ent.Name)
                            ;

            var pluginTypesWithConflicts = querySteps.GroupBy(step => new
            {
                EventHandlerId = step.EventHandler.Id,
                Stage = step.Stage.Value,

                EntityName = step.PrimaryObjectTypeCodeName,
                Message = step.SdkMessageId?.Name ?? "Unknown",

                EventHandlerName = step.EventHandler?.Name ?? "Unknown",
                step.Configuration,
            }).Where(gr => gr.Count() > 1);

            int pluginTypeNumber = 1;

            bool hasInfo = false;

            foreach (var gr in pluginTypesWithConflicts)
            {
                hasInfo = true;

                if (content.Length > 0)
                {
                    content.AppendLine().AppendLine();
                }

                content.AppendFormat("{0}. {1}", pluginTypeNumber, gr.Key.EventHandlerName).AppendLine();

                content.AppendFormat("Entity '{0}',   Message '{1}',   Stage '{2}'"
                    , gr.Key.EntityName
                    , gr.Key.Message
                    , SdkMessageProcessingStepRepository.GetStageName(gr.Key.Stage, null)
                    ).AppendLine();

                if (!string.IsNullOrEmpty(gr.Key.Configuration))
                {
                    content.AppendFormat("Configuration: {0}", gr.Key.Configuration).AppendLine();
                }

                foreach (var step in gr)
                {
                    content.AppendFormat("Stage '{0}',   Rank {1},   Statuscode {2}"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        ).AppendLine();

                    var queryImage = from image in search.SdkMessageProcessingStepImage
                                     where image.SdkMessageProcessingStepId != null
                                     where image.SdkMessageProcessingStepId.Id == step.Id
                                     orderby image.ImageType.Value, image.CreatedOn, image.Name
                                     select image;

                    int numberImage = 1;

                    foreach (var image in queryImage)
                    {
                        string imageDescription = GetImageDescription(numberImage.ToString(), image);

                        var coll = imageDescription.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                        foreach (var item in coll)
                        {
                            content.AppendLine(tabSpacer + tabSpacer + item);
                        }

                        numberImage++;
                    }
                }

                pluginTypeNumber++;
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No duplicates were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Steps Duplicates at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Steps Duplicates: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
        private async Task CheckingPluginImages(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            StringBuilder content = new StringBuilder();

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM));

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription()));

            // Подключаемся к CRM.
            var service = await QuickConnection.ConnectAsync(connectionData);

            if (service == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionFailedFormat1, connectionData.Name);
                return;
            }

            content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint));

            var repository = new PluginSearchRepository(service);

            var search = await repository.FindAllAsync(null, string.Empty, string.Empty, string.Empty);

            var querySteps = search.SdkMessageProcessingStep
                            .OrderBy(ent => ent.EventHandler?.Name ?? "Unknown")
                            .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                            .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                            .ThenBy(ent => ent.Stage.Value)
                            .ThenBy(ent => ent.Mode.Value)
                            .ThenBy(ent => ent.Rank)
                            .ThenBy(ent => ent.Name)
                            ;

            int stepNumber = 1;

            bool hasInfo = false;

            foreach (var step in querySteps)
            {
                var queryImage = from image in search.SdkMessageProcessingStepImage
                                 where image.SdkMessageProcessingStepId != null
                                 where image.SdkMessageProcessingStepId.Id == step.Id
                                 orderby image.ImageType.Value, image.CreatedOn, image.Name
                                 select image;

                var preImages = queryImage.Where(im => im.ImageType.Value == 0 || im.ImageType.Value == 2);
                var postImages = queryImage.Where(im => im.ImageType.Value == 1 || im.ImageType.Value == 2);

                var preImagesByEntityAlias = preImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);
                var preImagesByName = preImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);

                var postImagesByEntityAlias = postImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);
                var postImagesByName = postImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);

                var hasDuplicatesPreImagesByEntityAlias = preImagesByEntityAlias.Count() > 0;
                var hasDuplicatesPreImagesByName = preImagesByName.Count() > 0;

                var hasDuplicatesPostImagesByEntityAlias = postImagesByEntityAlias.Count() > 0;
                var hasDuplicatesPostImagesByName = postImagesByName.Count() > 0;

                if (hasDuplicatesPreImagesByEntityAlias
                    || hasDuplicatesPreImagesByName
                    || hasDuplicatesPostImagesByEntityAlias
                    || hasDuplicatesPostImagesByName
                    )
                {
                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine();
                    }

                    hasInfo = true;

                    content.AppendFormat("{0}. {1}", stepNumber, step.EventHandler?.Name ?? "Unknown").AppendLine();

                    content.AppendFormat("Entity '{0}',   Message '{1}',   Stage '{2}',   Rank {3},   Statuscode {4}"
                        , step.PrimaryObjectTypeCodeName
                        , step.SdkMessageId?.Name ?? "Unknown"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        ).AppendLine();

                    DescribeImages(content, stepNumber, hasDuplicatesPreImagesByEntityAlias, preImagesByEntityAlias, "Pre images duplicates by EntityAlias:");

                    DescribeImages(content, stepNumber, hasDuplicatesPreImagesByName, preImagesByName, "Pre images duplicates by Name:");

                    DescribeImages(content, stepNumber, hasDuplicatesPostImagesByEntityAlias, postImagesByEntityAlias, "Post images duplicates by EntityAlias:");

                    DescribeImages(content, stepNumber, hasDuplicatesPostImagesByName, postImagesByName, "Post images duplicates by Name:");

                    stepNumber++;
                }
            }

            if (!hasInfo)
            {
                content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No duplicates were found."));
            }

            string fileName = string.Format("{0}.Checking Plugin Images Duplicates at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

            if (string.IsNullOrEmpty(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportIsEmpty);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }
            else if (!Directory.Exists(commonConfig.FolderForExport))
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FolderForExportDoesNotExistsFormat1, commonConfig.FolderForExport);
                commonConfig.FolderForExport = FileOperations.GetDefaultFolderForExportFilePath();
            }

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Images Duplicates: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
        private async Task <string> TrasnferPluginStepsStates()
        {
            StringBuilder content = new StringBuilder();

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

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

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

            var taskSource = _comparerSource.GetSdkMessageProcessingStep1Async();
            var taskTarget = _comparerSource.GetSdkMessageProcessingStep2Async();

            List <SdkMessageProcessingStep> listSource = await taskSource;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.PluginStepsInConnectionFormat2, ConnectionSource.Name, listSource.Count()));

            List <SdkMessageProcessingStep> listTarget = await taskTarget;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.PluginStepsInConnectionFormat2, ConnectionTarget.Name, listTarget.Count()));

            List <LinkedEntities <SdkMessageProcessingStep> > commonList = new List <LinkedEntities <SdkMessageProcessingStep> >();

            foreach (SdkMessageProcessingStep stepSource in listSource)
            {
                SdkMessageProcessingStep stepTarget = listTarget.FirstOrDefault(st => st.Id == stepSource.Id);

                if (stepTarget != null)
                {
                    commonList.Add(new LinkedEntities <SdkMessageProcessingStep>(stepSource, stepTarget));
                    continue;
                }
            }

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.PluginStepsCommonFormat3, ConnectionSource.Name, ConnectionTarget.Name, commonList.Count()));

            List <SdkMessageProcessingStep> pluginStepsToActivate   = new List <SdkMessageProcessingStep>();
            List <SdkMessageProcessingStep> pluginStepsToDeactivate = new List <SdkMessageProcessingStep>();

            foreach (LinkedEntities <SdkMessageProcessingStep> step in commonList
                     .OrderBy(s => s.Entity1.EventHandler?.Name ?? "Unknown")
                     .ThenBy(s => s.Entity1.PrimaryObjectTypeCodeName)
                     .ThenBy(s => s.Entity1.SecondaryObjectTypeCodeName)
                     .ThenBy(s => s.Entity1.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                     .ThenBy(s => s.Entity1.Stage.Value)
                     .ThenBy(s => s.Entity1.Mode.Value)
                     )
            {
                if (step.Entity1.StatusCode?.Value != step.Entity2.StatusCode?.Value)
                {
                    List <SdkMessageProcessingStep> list = null;

                    if (step.Entity1.StatusCode.Value == (int)SdkMessageProcessingStep.Schema.OptionSets.statuscode.Enabled_0_Enabled_1)
                    {
                        list = pluginStepsToActivate;
                    }
                    else if (step.Entity1.StatusCode.Value == (int)SdkMessageProcessingStep.Schema.OptionSets.statuscode.Disabled_1_Disabled_2)
                    {
                        list = pluginStepsToDeactivate;
                    }

                    if (list != null)
                    {
                        list.Add(step.Entity2);
                    }
                }
            }

            var orderedDeactivate = pluginStepsToDeactivate
                                    .OrderBy(s => s.EventHandler?.Name ?? "Unknown")
                                    .ThenBy(s => s.PrimaryObjectTypeCodeName)
                                    .ThenBy(s => s.SecondaryObjectTypeCodeName)
                                    .ThenBy(s => s.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                                    .ThenBy(s => s.Stage.Value)
                                    .ThenBy(s => s.Mode.Value)
            ;

            var orderedActivate = pluginStepsToActivate
                                  .OrderBy(s => s.EventHandler?.Name ?? "Unknown")
                                  .ThenBy(s => s.PrimaryObjectTypeCodeName)
                                  .ThenBy(s => s.SecondaryObjectTypeCodeName)
                                  .ThenBy(s => s.SdkMessageId?.Name ?? "Unknown", new MessageComparer())
                                  .ThenBy(s => s.Stage.Value)
                                  .ThenBy(s => s.Mode.Value)
            ;

            FormatTextTableHandler tableDeactivatePluginSteps = new FormatTextTableHandler();

            tableDeactivatePluginSteps.SetHeader("PluginType", "Primary Entity", "Secondary Entity", "Message", "Stage", "Rank", "Status", "IsHidden", "IsManaged", "FilteringAttributes");

            FormatTextTableHandler tableActivatePluginSteps = new FormatTextTableHandler();

            tableActivatePluginSteps.SetHeader("PluginType", "Primary Entity", "Secondary Entity", "Message", "Stage", "Rank", "Status", "IsHidden", "IsManaged", "FilteringAttributes");

            foreach (var step in orderedDeactivate)
            {
                tableDeactivatePluginSteps.AddLine(
                    step.EventHandler?.Name ?? "Unknown"
                    , step.PrimaryObjectTypeCodeName
                    , step.SecondaryObjectTypeCodeName
                    , step.SdkMessageId?.Name ?? "Unknown"
                    , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                    , step.Rank.ToString()
                    , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                    , step.IsHidden?.Value.ToString()
                    , step.IsManaged.ToString()
                    , step.FilteringAttributesStringsSorted
                    );
            }

            foreach (var step in orderedActivate)
            {
                tableActivatePluginSteps.AddLine(
                    step.EventHandler?.Name ?? "Unknown"
                    , step.PrimaryObjectTypeCodeName
                    , step.SecondaryObjectTypeCodeName
                    , step.SdkMessageId?.Name ?? "Unknown"
                    , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                    , step.Rank.ToString()
                    , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                    , step.IsHidden?.Value.ToString()
                    , step.IsManaged.ToString()
                    , step.FilteringAttributesStringsSorted
                    );
            }

            if (tableDeactivatePluginSteps.Count > 0)
            {
                content
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(new string('-', 150))
                .AppendLine()
                .AppendLine();

                content.AppendLine().AppendLine().AppendFormat(Properties.OrganizationComparerStrings.PluginStepsToDeactivationInConnectionFormat2, ConnectionTarget.Name, tableDeactivatePluginSteps.Count);

                tableDeactivatePluginSteps.GetFormatedLines(false).ForEach(e => content.AppendLine().Append((_tabSpacer + e).TrimEnd()));
            }

            if (tableActivatePluginSteps.Count > 0)
            {
                content
                .AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine(new string('-', 150))
                .AppendLine()
                .AppendLine();

                content.AppendLine().AppendLine().AppendFormat(Properties.OrganizationComparerStrings.PluginStepsToActivationInConnectionFormat2, ConnectionTarget.Name, tableActivatePluginSteps.Count);

                tableActivatePluginSteps.GetFormatedLines(false).ForEach(e => content.AppendLine().Append((_tabSpacer + e).TrimEnd()));
            }

            foreach (var step in orderedDeactivate)
            {
                try
                {
                    await _comparerSource.Service2.ExecuteAsync <SetStateResponse>(new SetStateRequest()
                    {
                        EntityMoniker = step.ToEntityReference(),

                        State  = new Microsoft.Xrm.Sdk.OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.statecode.Disabled_1),
                        Status = new Microsoft.Xrm.Sdk.OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.statuscode.Disabled_1_Disabled_2),
                    });
                }
                catch (Exception ex)
                {
                    var desc = DTEHelper.GetExceptionDescription(ex);

                    var stepDescription = tableDeactivatePluginSteps.FormatLineWithHeadersInLine(
                        step.EventHandler?.Name ?? "Unknown"
                        , step.PrimaryObjectTypeCodeName
                        , step.SecondaryObjectTypeCodeName
                        , step.SdkMessageId?.Name ?? "Unknown"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        , step.IsHidden?.Value.ToString()
                        , step.IsManaged.ToString()
                        , step.FilteringAttributesStringsSorted
                        );

                    string operationLocal = string.Format(Properties.OperationNames.DeactivatingEntityFormat2, step.LogicalName, ConnectionTarget.Name, stepDescription);

                    content.AppendLine().AppendLine().AppendLine();
                    content.AppendLine(new string('-', 150)).AppendLine();
                    content.AppendFormat(Properties.OutputStrings.ExceptionWhileOperationFormat1, operationLocal).AppendLine();
                    content.AppendLine(desc);
                    content.AppendLine(new string('-', 150)).AppendLine();
                }
            }

            foreach (var step in orderedActivate)
            {
                try
                {
                    await _comparerSource.Service2.ExecuteAsync <SetStateResponse>(new SetStateRequest()
                    {
                        EntityMoniker = step.ToEntityReference(),

                        State  = new Microsoft.Xrm.Sdk.OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.statecode.Enabled_0),
                        Status = new Microsoft.Xrm.Sdk.OptionSetValue((int)SdkMessageProcessingStep.Schema.OptionSets.statuscode.Enabled_0_Enabled_1),
                    });
                }
                catch (Exception ex)
                {
                    var desc = DTEHelper.GetExceptionDescription(ex);

                    var stepDescription = tableActivatePluginSteps.FormatLineWithHeadersInLine(
                        step.EventHandler?.Name ?? "Unknown"
                        , step.PrimaryObjectTypeCodeName
                        , step.SecondaryObjectTypeCodeName
                        , step.SdkMessageId?.Name ?? "Unknown"
                        , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                        , step.Rank.ToString()
                        , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                        , step.IsHidden?.Value.ToString()
                        , step.IsManaged.ToString()
                        , step.FilteringAttributesStringsSorted
                        );

                    string operationLocal = string.Format(Properties.OperationNames.ActivatingEntityFormat3, step.LogicalName, ConnectionTarget.Name, stepDescription);

                    content.AppendLine().AppendLine().AppendLine();
                    content.AppendLine(new string('-', 150)).AppendLine();
                    content.AppendFormat(Properties.OutputStrings.ExceptionWhileOperationFormat1, operationLocal).AppendLine();
                    content.AppendLine(desc);
                    content.AppendLine(new string('-', 150)).AppendLine();
                }
            }

            if (tableActivatePluginSteps.Count == 0 &&
                tableDeactivatePluginSteps.Count == 0
                )
            {
                content.AppendLine(Properties.OrganizationComparerStrings.PluginStepsStatesNoDifference);
            }

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

            string fileName = string.Format("OrgTransfer Plugin Steps States 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 <Model.Backup.PluginDescription> GetPluginDescription(IOrganizationServiceExtented service)
        {
            var repositoryAssembly = new PluginAssemblyRepository(service);
            var repositoryType     = new PluginTypeRepository(service);

            var repositoryMessage = new SdkMessageRepository(service);
            var repositoryFilter  = new SdkMessageFilterRepository(service);
            var repositorySecure  = new SdkMessageProcessingStepSecureConfigRepository(service);
            var repositoryImage   = new SdkMessageProcessingStepImageRepository(service);

            var repositoryStep = new SdkMessageProcessingStepRepository(service);

            var result = new Model.Backup.PluginDescription();

            result.CreatedOn = DateTime.Now;

            var listAssemblies = await repositoryAssembly.GetAllPluginAssemblisWithStepsAsync();

            var listMessage = await repositoryMessage.GetAllSdkMessageWithStepsAsync();

            var listFilter = await repositoryFilter.GetAllSdkMessageFilterWithStepsAsync();

            var listSecure = await repositorySecure.GetAllSdkMessageProcessingStepSecureConfigAsync();

            foreach (var entAssembly in listAssemblies)
            {
                var assembly = Model.Backup.PluginAssembly.GetObject(entAssembly);

                result.PluginAssemblies.Add(assembly);

                var listTypes = await repositoryType.GetPluginTypesAsync(entAssembly.Id);

                foreach (var entPluginType in listTypes)
                {
                    var pluginType = Model.Backup.PluginType.GetObject(entPluginType);

                    assembly.PluginTypes.Add(pluginType);

                    var listSteps = await repositoryStep.GetPluginStepsByPluginTypeIdAsync(entPluginType.Id);

                    var listStepsToAdd = new List <Model.Backup.PluginStep>();

                    foreach (var entStep in listSteps)
                    {
                        Entities.SdkMessage       entMessage = null;
                        Entities.SdkMessageFilter entFilter  = null;
                        Entities.SdkMessageProcessingStepSecureConfig entSecure = null;

                        var refMessage = entStep.SdkMessageId;
                        if (refMessage != null)
                        {
                            entMessage = listMessage.FirstOrDefault(m => m.SdkMessageId == refMessage.Id);
                        }

                        var refFilter = entStep.SdkMessageFilterId;
                        if (refFilter != null)
                        {
                            entFilter = listFilter.FirstOrDefault(f => f.SdkMessageFilterId == refFilter.Id);
                        }

                        var refSecure = entStep.SdkMessageProcessingStepSecureConfigId;
                        if (refSecure != null)
                        {
                            entSecure = listSecure.FirstOrDefault(s => s.SdkMessageProcessingStepSecureConfigId == refSecure.Id);
                        }

                        var step = Model.Backup.PluginStep.GetObject(entStep, entMessage, entFilter, entSecure);

                        listStepsToAdd.Add(step);

                        var listImages = await repositoryImage.GetStepImagesAsync(entStep.Id);

                        foreach (var entImage in listImages)
                        {
                            var image = Model.Backup.PluginImage.GetObject(entImage);

                            step.PluginImages.Add(image);
                        }
                    }

                    pluginType.PluginSteps.AddRange(
                        listStepsToAdd
                        .OrderBy(step => step.PrimaryEntity)
                        .ThenBy(step => step.SecondaryEntity)
                        .ThenBy(step => step.Message, MessageComparer.Comparer)
                        .ThenBy(step => step.Stage)
                        .ThenBy(step => step.ExecutionOrder)
                        .ThenBy(step => step.Name)
                        .ThenBy(step => step.CreatedOn)
                        );
                }
            }

            return(result);
        }
        private async Task CheckingPluginSteps(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            using (service.Lock())
            {
                var content = new StringBuilder();

                content.AppendLine(Properties.OutputStrings.ConnectingToCRM);
                content.AppendLine(connectionData.GetConnectionDescription());
                content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine();

                var repositoryStep      = new SdkMessageProcessingStepRepository(service);
                var repositoryStepImage = new SdkMessageProcessingStepImageRepository(service);

                var stepEnum = await repositoryStep.FindSdkMessageProcessingStepWithEntityNameAsync(null, null, null, null, null);

                var imagesList = await repositoryStepImage.GetAllSdkMessageProcessingStepImageAsync(null, ColumnSetInstances.AllColumns);

                var imagesDictionary = imagesList.GroupBy(e => e.SdkMessageProcessingStepId.Id).ToDictionary(g => g.Key, g => g.ToList());

                var querySteps = stepEnum
                                 .OrderBy(ent => ent.EventHandler?.Name ?? "Unknown")
                                 .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                                 .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", MessageComparer.Comparer)
                                 .ThenBy(ent => ent.Stage.Value)
                                 .ThenBy(ent => ent.Mode.Value)
                                 .ThenBy(ent => ent.Rank)
                                 .ThenBy(ent => ent.Name)
                ;

                var pluginTypesWithConflicts = querySteps.GroupBy(step => new
                {
                    EventHandlerId = step.EventHandler.Id,
                    Stage          = step.Stage.Value,

                    EntityName = step.PrimaryObjectTypeCodeName,
                    Message    = step.SdkMessageId?.Name ?? "Unknown",

                    EventHandlerName = step.EventHandler?.Name ?? "Unknown",
                    step.Configuration,
                }).Where(gr => gr.Count() > 1);

                int pluginTypeNumber = 1;

                bool hasInfo = false;

                foreach (var gr in pluginTypesWithConflicts)
                {
                    hasInfo = true;

                    if (content.Length > 0)
                    {
                        content.AppendLine().AppendLine();
                    }

                    content.AppendFormat("{0}. {1}", pluginTypeNumber, gr.Key.EventHandlerName).AppendLine();

                    content.AppendFormat("Entity '{0}',   Message '{1}',   Stage '{2}'"
                                         , gr.Key.EntityName
                                         , gr.Key.Message
                                         , SdkMessageProcessingStepRepository.GetStageName(gr.Key.Stage, null)
                                         ).AppendLine();

                    if (!string.IsNullOrEmpty(gr.Key.Configuration))
                    {
                        content.AppendFormat("Configuration: {0}", gr.Key.Configuration).AppendLine();
                    }

                    foreach (var step in gr)
                    {
                        content.AppendFormat("Stage '{0}',   Rank {1},   Statuscode {2}"
                                             , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                                             , step.Rank.ToString()
                                             , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                                             ).AppendLine();

                        var queryImage = Enumerable.Empty <SdkMessageProcessingStepImage>();

                        if (imagesDictionary.TryGetValue(step.Id, out var listImages))
                        {
                            queryImage = from image in listImages
                                         orderby image.ImageType.Value, image.CreatedOn, image.Name
                            select image;
                        }

                        int numberImage = 1;

                        foreach (var image in queryImage)
                        {
                            string imageDescription = GetImageDescription(numberImage.ToString(), image);

                            var coll = imageDescription.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                            foreach (var item in coll)
                            {
                                content.Append(_tabSpacer).Append(_tabSpacer).AppendLine(item);
                            }

                            numberImage++;
                        }
                    }

                    pluginTypeNumber++;
                }

                if (!hasInfo)
                {
                    content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No duplicates were found."));
                }

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                string fileName = string.Format("{0}.Checking Plugin Steps Duplicates at {1}.txt", connectionData.Name, EntityFileNameFormatter.GetDateString());

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

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

                this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Steps Duplicates: {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
        }
        private async Task CheckingPluginImages(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            using (service.Lock())
            {
                var content = new StringBuilder();

                content.AppendLine(Properties.OutputStrings.ConnectingToCRM);
                content.AppendLine(connectionData.GetConnectionDescription());
                content.AppendFormat(Properties.OutputStrings.CurrentServiceEndpointFormat1, service.CurrentServiceEndpoint).AppendLine();

                var repositoryStep      = new SdkMessageProcessingStepRepository(service);
                var repositoryStepImage = new SdkMessageProcessingStepImageRepository(service);

                var stepEnum = await repositoryStep.FindSdkMessageProcessingStepWithEntityNameAsync(null, null, null, null, null);

                var imagesList = await repositoryStepImage.GetAllSdkMessageProcessingStepImageAsync(null, ColumnSetInstances.AllColumns);

                var imagesDictionary = imagesList.GroupBy(e => e.SdkMessageProcessingStepId.Id).ToDictionary(g => g.Key, g => g.ToList());

                var querySteps = stepEnum
                                 .OrderBy(ent => ent.EventHandler?.Name ?? "Unknown")
                                 .ThenBy(ent => ent.PrimaryObjectTypeCodeName)
                                 .ThenBy(ent => ent.SdkMessageId?.Name ?? "Unknown", MessageComparer.Comparer)
                                 .ThenBy(ent => ent.Stage.Value)
                                 .ThenBy(ent => ent.Mode.Value)
                                 .ThenBy(ent => ent.Rank)
                                 .ThenBy(ent => ent.Name)
                ;

                int stepNumber = 1;

                bool hasInfo = false;

                foreach (var step in querySteps)
                {
                    var queryImage = Enumerable.Empty <SdkMessageProcessingStepImage>();

                    if (imagesDictionary.TryGetValue(step.Id, out var listImages))
                    {
                        queryImage = from image in listImages
                                     orderby image.ImageType.Value, image.CreatedOn, image.Name
                        select image;
                    }

                    var preImages  = queryImage.Where(im => im.ImageType.Value == 0 || im.ImageType.Value == 2);
                    var postImages = queryImage.Where(im => im.ImageType.Value == 1 || im.ImageType.Value == 2);

                    var preImagesByEntityAlias = preImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);
                    var preImagesByName        = preImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);

                    var postImagesByEntityAlias = postImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);
                    var postImagesByName        = postImages.GroupBy(im => im.EntityAlias).Where(gr => gr.Count() > 1);

                    var hasDuplicatesPreImagesByEntityAlias = preImagesByEntityAlias.Count() > 0;
                    var hasDuplicatesPreImagesByName        = preImagesByName.Count() > 0;

                    var hasDuplicatesPostImagesByEntityAlias = postImagesByEntityAlias.Count() > 0;
                    var hasDuplicatesPostImagesByName        = postImagesByName.Count() > 0;

                    if (hasDuplicatesPreImagesByEntityAlias ||
                        hasDuplicatesPreImagesByName ||
                        hasDuplicatesPostImagesByEntityAlias ||
                        hasDuplicatesPostImagesByName
                        )
                    {
                        if (content.Length > 0)
                        {
                            content.AppendLine().AppendLine();
                        }

                        hasInfo = true;

                        content.AppendFormat("{0}. {1}", stepNumber, step.EventHandler?.Name ?? "Unknown").AppendLine();

                        content.AppendFormat("Entity '{0}',   Message '{1}',   Stage '{2}',   Rank {3},   Statuscode {4}"
                                             , step.PrimaryObjectTypeCodeName
                                             , step.SdkMessageId?.Name ?? "Unknown"
                                             , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                                             , step.Rank.ToString()
                                             , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                                             ).AppendLine();

                        DescribeImages(content, stepNumber, hasDuplicatesPreImagesByEntityAlias, preImagesByEntityAlias, "Pre images duplicates by EntityAlias:");

                        DescribeImages(content, stepNumber, hasDuplicatesPreImagesByName, preImagesByName, "Pre images duplicates by Name:");

                        DescribeImages(content, stepNumber, hasDuplicatesPostImagesByEntityAlias, postImagesByEntityAlias, "Post images duplicates by EntityAlias:");

                        DescribeImages(content, stepNumber, hasDuplicatesPostImagesByName, postImagesByName, "Post images duplicates by Name:");

                        stepNumber++;
                    }
                }

                if (!hasInfo)
                {
                    content.AppendLine(this._iWriteToOutput.WriteToOutput(connectionData, "No duplicates were found."));
                }

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                string fileName = string.Format("{0}.Checking Plugin Images Duplicates at {1}.txt", connectionData.Name, EntityFileNameFormatter.GetDateString());

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

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

                this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Checking Plugin Images Duplicates: {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
        }
        private static string GetStepDescription(
            SdkMessageProcessingStep step
            , SdkMessageProcessingStepSecureConfig entSecure
            , IEnumerable <SdkMessageProcessingStepImage> stepImages
            )
        {
            StringBuilder description = new StringBuilder();

            var messageName             = step.SdkMessageId?.Name ?? "Unknown";
            var primaryObjectTypeCode   = step.PrimaryObjectTypeCodeName;
            var secondaryObjectTypeCode = step.SecondaryObjectTypeCodeName;

            description.AppendFormat("Primary Entity '{0}',   Secondary Entity '{1}'"
                                     , primaryObjectTypeCode
                                     , secondaryObjectTypeCode
                                     ).AppendLine();

            description.AppendFormat("Message '{0}',    Stage '{1}',    Mode '{2}',    Rank {3},    Status {4}"
                                     , messageName
                                     , SdkMessageProcessingStepRepository.GetStageName(step.Stage.Value, step.Mode.Value)
                                     , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.mode]
                                     , step.Rank.ToString()
                                     , step.FormattedValues[SdkMessageProcessingStep.Schema.Attributes.statuscode]
                                     ).AppendLine();

            string contextUser = "******";

            if (step.ImpersonatingUserId != null)
            {
                contextUser = step.ImpersonatingUserId.Name;
            }

            description.AppendFormat("RunInUserContext: {0}", contextUser).AppendLine();
            description.AppendFormat("AsyncAutoDelete: {0}", step.AsyncAutoDelete.GetValueOrDefault()).AppendLine();

            if (!string.IsNullOrEmpty(step.FilteringAttributes))
            {
                description.AppendFormat("Filtering Attributes: {0}", step.FilteringAttributesStringsSorted).AppendLine();
            }

            if (!string.IsNullOrEmpty(step.Name))
            {
                description.AppendFormat("Name: {0}", step.Name).AppendLine();
            }

            if (!string.IsNullOrEmpty(step.Description))
            {
                description.AppendFormat("Description: {0}", step.Description).AppendLine();
            }

            if (!string.IsNullOrEmpty(step.Configuration))
            {
                description.AppendFormat("Unsecure Configuration: {0}", step.Configuration).AppendLine();
            }

            if (entSecure != null)
            {
                if (!string.IsNullOrEmpty(entSecure.SecureConfig))
                {
                    description.AppendFormat("Secure Configuration: {0}", entSecure.SecureConfig).AppendLine();
                }
            }

            //{
            //    string dateStr = GetDateString(step.CreatedBy, step.CreatedOn, step.ModifiedBy, step.ModifiedOn, step.OverwriteTime);

            //    if (!string.IsNullOrEmpty(dateStr))
            //    {
            //        description.AppendLine(dateStr);
            //    }
            //}

            int numberImage = 1;

            foreach (var image in stepImages
                     .OrderBy(im => im.ImageType.Value)
                     .ThenBy(im => im.CreatedOn.Value)
                     .ThenBy(im => im.Name)
                     )
            {
                string imageDescription = GetImageDescription(numberImage, image);

                var coll = imageDescription.Split(new string[] { "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);

                foreach (var item in coll)
                {
                    description.AppendLine(tabSpacer + item);
                }

                numberImage++;
            }

            return(description.ToString());
        }