private async Task PerformExportEntityDescription(string folder, Guid idSdkMessage, string name)
        {
            var service = await GetService();

            if (service == null)
            {
                return;
            }

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.CreatingEntityDescription);

            var repository = new SdkMessageRepository(service);

            var message = await repository.GetByIdAsync(idSdkMessage, ColumnSetInstances.AllColumns);

            string fileName = EntityFileNameFormatter.GetMessageFileName(service.ConnectionData.Name, name, EntityFileNameFormatter.Headers.EntityDescription);
            string filePath = Path.Combine(folder, FileOperations.RemoveWrongSymbols(fileName));

            await EntityDescriptionHandler.ExportEntityDescriptionAsync(filePath, message, service.ConnectionData);

            this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionExportedEntityDescriptionFormat3
                                               , service.ConnectionData.Name
                                               , message.LogicalName
                                               , filePath
                                               );

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);

            ToggleControls(service.ConnectionData, true, Properties.OutputStrings.CreatingEntityDescriptionCompleted);
        }
        private async Task ShowExistingMessages()
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            ConnectionData connectionData = GetSelectedConnection();

            ToggleControls(connectionData, false, Properties.OutputStrings.LoadingSdkMessage);

            string textName = string.Empty;

            this.Dispatcher.Invoke(() =>
            {
                this._itemsSource.Clear();

                textName = txtBFilter.Text.Trim().ToLower();
            });

            IEnumerable <SdkMessage> list = Enumerable.Empty <SdkMessage>();

            try
            {
                var service = await GetService();

                if (service != null)
                {
                    var repository = new SdkMessageRepository(service);

                    list = await repository.GetMessagesAsync(textName
                                                             , new ColumnSet
                                                             (
                                                                 SdkMessage.Schema.Attributes.name
                                                                 , SdkMessage.Schema.Attributes.categoryname
                                                                 , SdkMessage.Schema.Attributes.autotransact
                                                                 , SdkMessage.Schema.Attributes.availability
                                                                 , SdkMessage.Schema.Attributes.customizationlevel
                                                                 , SdkMessage.Schema.Attributes.ismanaged
                                                                 , SdkMessage.Schema.Attributes.expand
                                                                 , SdkMessage.Schema.Attributes.isactive
                                                                 , SdkMessage.Schema.Attributes.isprivate
                                                                 , SdkMessage.Schema.Attributes.isreadonly
                                                                 , SdkMessage.Schema.Attributes.isvalidforexecuteasync
                                                                 , SdkMessage.Schema.Attributes.workflowsdkstepenabled
                                                                 , SdkMessage.Schema.Attributes.throttlesettings
                                                                 , SdkMessage.Schema.Attributes.template
                                                             )
                                                             );
                }
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(connectionData, ex);
            }

            LoadSdkMessages(list);

            ToggleControls(connectionData, true, Properties.OutputStrings.LoadingSdkMessageCompletedFormat1, list.Count());
        }
        public async Task <string> RegisterPluginsForAssemblyAsync(string folder, Model.Backup.PluginAssembly assembly)
        {
            if (_service.ConnectionData.IsReadOnly)
            {
                return(null);
            }

            string fileName = string.Format("{0}.Plugin Register Operation at {1}.txt"
                                            , _service.ConnectionData.Name
                                            , EntityFileNameFormatter.GetDateString()
                                            );

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

            StringBuilder log = new StringBuilder();

            var repositoryAssembly   = new PluginAssemblyRepository(_service);
            var repositoryType       = new PluginTypeRepository(_service);
            var repositoryMessage    = new SdkMessageRepository(_service);
            var repositoryFilter     = new SdkMessageFilterRepository(_service);
            var repositorySystemUser = new SystemUserRepository(_service);

            var entAssembly = await repositoryAssembly.FindAssemblyAsync(assembly.Name);

            if (entAssembly != null)
            {
                log.AppendFormat("Assembly {0} founded in CRM with ID {1}", assembly.Name, entAssembly.Id).AppendLine();

                foreach (var pluginType in assembly.PluginTypes)
                {
                    var entPluginType = await repositoryType.FindPluginTypeAsync(pluginType.TypeName);

                    if (entPluginType == null)
                    {
                        log.AppendFormat("Plugin Type {0} not founded in CRM.", pluginType.TypeName).AppendLine();
                        continue;
                    }

                    log.AppendFormat("Plugin Type {0} founded in CRM with ID {1}", pluginType.TypeName, entPluginType.Id).AppendLine();

                    foreach (var step in pluginType.PluginSteps)
                    {
                        await RegisterSingleStep(log, repositoryMessage, repositoryFilter, repositorySystemUser, entPluginType, step);
                    }
                }
            }
            else
            {
                log.AppendFormat("Assembly {0} not founded in CRM.", assembly.Name).AppendLine();
            }

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

            return(filePath);
        }
        public async Task <string> RegisterPluginsForPluginStepAsync(string folder, string assemblyName, string pluginType, Nav.Common.VSPackages.CrmDeveloperHelper.Model.Backup.PluginStep step)
        {
            if (_service.ConnectionData.IsReadOnly)
            {
                return(null);
            }

            string fileName = string.Format("{0}.Plugin Register Operation at {1}.txt"
                                            , _service.ConnectionData.Name
                                            , DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss")
                                            );

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

            StringBuilder log = new StringBuilder();

            var repositoryAssembly   = new PluginAssemblyRepository(_service);
            var repositoryType       = new PluginTypeRepository(_service);
            var repositoryMessage    = new SdkMessageRepository(_service);
            var repositoryFilter     = new SdkMessageFilterRepository(_service);
            var repositorySystemUser = new SystemUserRepository(_service);

            var entAssembly = await repositoryAssembly.FindAssemblyAsync(assemblyName);

            if (entAssembly != null)
            {
                log.AppendFormat("Assembly {0} founded in CRM with ID {1}", assemblyName, entAssembly.Id).AppendLine();

                var entPluginType = await repositoryType.FindPluginTypeAsync(pluginType);

                if (entPluginType != null)
                {
                    log.AppendFormat("Plugin Type {0} founded in CRM with ID {1}", pluginType, entPluginType.Id).AppendLine();

                    await RegisterSingleStep(log, repositoryMessage, repositoryFilter, repositorySystemUser, entPluginType, step);
                }
                else
                {
                    log.AppendFormat("Plugin Type {0} not founded in CRM.", pluginType).AppendLine();
                }
            }
            else
            {
                log.AppendFormat("Assembly {0} not founded in CRM.", assemblyName).AppendLine();
            }

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

            return(filePath);
        }
        private async Task PerformExportXmlToFile(string folder, Guid idMessage, string name, string fieldName, string fieldTitle, FileExtension extension)
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.ExportingXmlFieldToFileFormat1, fieldTitle);

            try
            {
                var repository = new SdkMessageRepository(service);

                var messageEntity = await repository.GetByIdAsync(idMessage, new ColumnSet(fieldName));

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

                string filePath = await CreateFileAsync(folder, idMessage, name, fieldTitle, extension, xmlContent);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);

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

                ToggleControls(service.ConnectionData, true, Properties.OutputStrings.ExportingXmlFieldToFileFailedFormat1, fieldName);
            }
        }
        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 CreateDescription(PluginTreeViewItem node)
        {
            if (!CanCreateDescription(node))
            {
                return;
            }

            var service = await GetService();

            if (service == null)
            {
                return;
            }

            this._iWriteToOutput.WriteToOutputStartOperation(service.ConnectionData, Properties.OperationNames.CreatingFileWithDescriptionFormat1);

            ToggleControls(service.ConnectionData, false, Properties.OutputStrings.CreatingDescription);

            StringBuilder result = new StringBuilder();

            string fileName = string.Empty;

            if (node.MessageList != null && node.MessageList.Any())
            {
                var repository = new SdkMessageRepository(service);
                List <SdkMessage> listMessages = await repository.GetMessageByIdsAsync(node.MessageList.ToArray());

                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = EntityFileNameFormatter.GetMessageFileName(service.ConnectionData.Name, node.Name, "Description");

                    if (result.Length > 0)
                    {
                        result.AppendLine().AppendLine().AppendLine();
                    }
                    result.AppendLine(service.ConnectionData.GetConnectionInfo());
                }

                foreach (var message in listMessages)
                {
                    string desc = await EntityDescriptionHandler.GetEntityDescriptionAsync(message, service.ConnectionData);

                    if (!string.IsNullOrEmpty(desc))
                    {
                        if (result.Length > 0)
                        {
                            result.AppendLine().AppendLine().AppendLine();
                        }

                        result.AppendLine(desc);
                    }
                }
            }

            if (node.MessageFilterList != null && node.MessageFilterList.Any())
            {
                var repository = new SdkMessageFilterRepository(service);
                List <SdkMessageFilter> listMessages = await repository.GetMessageFiltersByIdsAsync(node.MessageFilterList.ToArray());

                if (string.IsNullOrEmpty(fileName))
                {
                    fileName = EntityFileNameFormatter.GetMessageFilterFileName(service.ConnectionData.Name, node.Name, "Description");

                    if (result.Length > 0)
                    {
                        result.AppendLine().AppendLine().AppendLine();
                    }
                    result.AppendLine(service.ConnectionData.GetConnectionInfo());
                }

                foreach (var message in listMessages)
                {
                    string desc = await EntityDescriptionHandler.GetEntityDescriptionAsync(message, service.ConnectionData);

                    if (!string.IsNullOrEmpty(desc))
                    {
                        if (result.Length > 0)
                        {
                            result.AppendLine().AppendLine().AppendLine();
                        }

                        result.AppendLine(desc);
                    }
                }
            }

            if (!string.IsNullOrEmpty(fileName))
            {
                string filePath = Path.Combine(_commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

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

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }

            ToggleControls(service.ConnectionData, true, Properties.OutputStrings.CreatingDescriptionCompleted);

            this._iWriteToOutput.WriteToOutputEndOperation(service.ConnectionData, Properties.OperationNames.CreatingFileWithDescriptionFormat1, service.ConnectionData.Name);
        }
        private async Task RegisterSingleStep(StringBuilder log, SdkMessageRepository repositoryMessage, SdkMessageFilterRepository repositoryFilter, SystemUserRepository repositorySystemUser, Entities.PluginType entPluginType, Model.Backup.PluginStep step)
        {
            var entMessage = await repositoryMessage.FindMessageAsync(step.Message);

            if (entMessage == null)
            {
                log.AppendFormat("Message {0} not founded in CRM.", step.Message).AppendLine();
                return;
            }

            var refMessageFilter = await repositoryFilter.FindFilterAsync(entMessage.Id, step.PrimaryEntity, step.SecondaryEntity);

            EntityReference refSecure     = null;
            EntityReference refSystemUser = null;

            if (!string.IsNullOrEmpty(step.SecureConfiguration))
            {
                var entSecure = new Entity(Entities.SdkMessageProcessingStepSecureConfig.EntityLogicalName);
                entSecure.Attributes[Entities.SdkMessageProcessingStepSecureConfig.Schema.Attributes.secureconfig] = step.SecureConfiguration;

                entSecure.Id = await _service.CreateAsync(entSecure);

                refSecure = entSecure.ToEntityReference();
            }

            if (!string.IsNullOrEmpty(step.RunInUserContext) && step.RunInUserContext != "Calling User")
            {
                refSystemUser = repositorySystemUser.FindUser(step.RunInUserContext);
            }

            var entStep = new Entity(Entities.SdkMessageProcessingStep.EntityLogicalName)
            {
                Id = step.Id
            };

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.asyncautodelete] = step.AsyncAutoDelete.GetValueOrDefault();
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.name]            = step.Name;
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.description]     = step.Description;
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.rank]            = step.ExecutionOrder;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.stage] = new OptionSetValue((int)step.Stage);
            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.mode]  = new OptionSetValue((int)step.ExecutionMode);

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.supporteddeployment] = new OptionSetValue((int)step.SupportedDeploymentCode);

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.configuration] = step.UnsecureConfiguration;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.filteringattributes] = string.Join(",", step.FilteringAttributes.OrderBy(s => s));

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.plugintypeid] = entPluginType.ToEntityReference();

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.eventhandler] = entPluginType.ToEntityReference();

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.sdkmessageid] = entMessage.ToEntityReference();

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.sdkmessagefilterid] = refMessageFilter;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.sdkmessageprocessingstepsecureconfigid] = refSecure;

            entStep.Attributes[Entities.SdkMessageProcessingStep.Schema.Attributes.impersonatinguserid] = refSystemUser;

            entStep.Id = await _service.CreateAsync(entStep);

            foreach (var image in step.PluginImages)
            {
                var entImage = new Entity(Entities.SdkMessageProcessingStepImage.EntityLogicalName)
                {
                    Id = image.Id
                };

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.sdkmessageprocessingstepid] = entStep.ToEntityReference();

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.imagetype] = new OptionSetValue(image.ImageType.Value);

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.name]        = image.Name;
                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.entityalias] = image.EntityAlias;

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.customizationlevel]   = image.CustomizationLevel;
                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.relatedattributename] = image.RelatedAttributeName;
                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.messagepropertyname]  = image.MessagePropertyName;

                entImage.Attributes[Entities.SdkMessageProcessingStepImage.Schema.Attributes.attributes] = string.Join(",", image.Attributes.OrderBy(s => s));

                entImage.Id = await _service.CreateAsync(entImage);
            }

            _service.Execute(new SetStateRequest()
            {
                EntityMoniker = entStep.ToEntityReference(),

                State  = new OptionSetValue(step.StateCode.Value),
                Status = new OptionSetValue(step.StatusCode.Value),
            });
        }
        private async Task ShowExistingMessages()
        {
            if (!this.IsControlsEnabled)
            {
                return;
            }

            var service = await GetService();

            ToggleControls(service.ConnectionData, false, Properties.WindowStatusStrings.LoadingSdkMessage);

            this.Dispatcher.Invoke(() =>
            {
                _messageTree.Clear();
            });

            string entityName  = string.Empty;
            string messageName = string.Empty;

            this.Dispatcher.Invoke(() =>
            {
                entityName  = cmBEntityName.Text?.Trim();
                messageName = txtBMessageFilter.Text.Trim();
            });

            IEnumerable <SdkMessage> search = Enumerable.Empty <SdkMessage>();

            try
            {
                if (service != null)
                {
                    var repository = new SdkMessageRepository(service);

                    search = await repository.GetAllSdkMessageWithFiltersAsync(messageName, entityName);
                }
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }

            if (search != null)
            {
                this.trVMessageTree.Dispatcher.Invoke(() =>
                {
                    this.trVMessageTree.BeginInit();
                });

                switch (_currentView)
                {
                case View.ByMessage:
                    FillTreeByMessage(search);
                    break;

                case View.ByEntity:
                default:
                    FillTreeByEntity(search);
                    break;
                }

                ExpandNodes(_messageTree);

                this.trVMessageTree.Dispatcher.Invoke(() =>
                {
                    this.trVMessageTree.EndInit();
                });
            }

            ToggleControls(service.ConnectionData, true, Properties.WindowStatusStrings.LoadingSdkMessageCompleted);
        }