private async Task GetCurrentEntityDescription(IOrganizationServiceExtented service, CommonConfiguration commonConfig, SystemForm systemForm)
        {
            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string fileName = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, EntityFileNameFormatter.Headers.EntityDescription, FileExtension.txt);
            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            try
            {
                await EntityDescriptionHandler.ExportEntityDescriptionAsync(filePath, systemForm, service.ConnectionData);

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionExportedEntityDescriptionFormat3
                                                   , service.ConnectionData.Name
                                                   , systemForm.LogicalName
                                                   , filePath
                                                   );
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }

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

            service.TryDispose();
        }
        private void GetCurrentSystemFormJson(IOrganizationServiceExtented service, CommonConfiguration commonConfig, SystemForm systemForm)
        {
            string formJson = systemForm.FormJson;

            if (string.IsNullOrEmpty(formJson))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, SystemForm.Schema.Headers.formjson);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            formJson = ContentComparerHelper.FormatJson(formJson);

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string currentFileName = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, SystemForm.Schema.Headers.formjson, FileExtension.json);
            string currentFilePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(currentFileName));

            try
            {
                File.WriteAllText(currentFilePath, formJson, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, SystemForm.Schema.Headers.formjson, currentFilePath);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }

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

            service.TryDispose();
        }
示例#3
0
        private void GetCurrentSavedQueryXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SavedQuery savedQuery)
        {
            string fieldName  = SavedQueryRepository.GetFieldNameByXmlRoot(doc.Root.Name.ToString());
            string fieldTitle = SavedQueryRepository.GetFieldTitleByXmlRoot(doc.Root.Name.ToString());

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

            if (string.IsNullOrEmpty(xmlContent))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SavedQuery.Schema.EntityLogicalName, savedQuery.Name, fieldTitle);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string currentFileName = EntityFileNameFormatter.GetSavedQueryFileName(service.ConnectionData.Name, savedQuery.ReturnedTypeCode, savedQuery.Name, fieldTitle, FileExtension.xml);
            string currentFilePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(currentFileName));

            try
            {
                File.WriteAllText(currentFilePath, xmlContent, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SavedQuery.Schema.EntityLogicalName, savedQuery.Name, fieldTitle, currentFilePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, currentFilePath);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);

                service.TryDispose();
            }
        }
示例#4
0
        private async Task UpdateWebResourceDependencyXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, WebResource webResource)
        {
            {
                string fieldTitle = WebResource.Schema.Headers.dependencyxml;

                string dependencyXml = webResource.DependencyXml;

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

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

                    try
                    {
                        dependencyXml = ContentComparerHelper.FormatXmlByConfiguration(
                            dependencyXml
                            , commonConfig
                            , XmlOptionsControls.WebResourceDependencyXmlOptions
                            , schemaName: AbstractDynamicCommandXsdSchemas.WebResourceDependencyXmlSchema
                            , webResourceName: webResource.Name
                            );

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

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

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

            var updateEntity = new WebResource
            {
                Id = webResource.Id
            };

            updateEntity.Attributes[WebResource.Schema.Attributes.dependencyxml] = newText;

            await service.UpdateAsync(updateEntity);

            var repositoryPublish = new PublishActionsRepository(service);

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingWebResourceFormat2, service.ConnectionData.Name, webResource.Name);

            await repositoryPublish.PublishWebResourcesAsync(new[] { webResource.Id });

            service.TryDispose();
        }
        private async Task UpdateSiteMapXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SiteMap siteMap)
        {
            string fieldTitle = SiteMap.Schema.Headers.sitemapxml;

            {
                string siteMapXml = siteMap.SiteMapXml;

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

                    string fileNameBackUp = EntityFileNameFormatter.GetSiteMapFileName(service.ConnectionData.Name, siteMap.SiteMapNameUnique, siteMap.Id, fieldTitle + " BackUp", FileExtension.xml);
                    string filePathBackUp = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileNameBackUp));

                    try
                    {
                        siteMapXml = ContentComparerHelper.FormatXmlByConfiguration(
                            siteMapXml
                            , commonConfig
                            , XmlOptionsControls.SiteMapXmlOptions
                            , schemaName: AbstractDynamicCommandXsdSchemas.SiteMapXmlSchema
                            , siteMapUniqueName: siteMap.SiteMapNameUnique ?? string.Empty
                            );

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

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

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

            var updateEntity = new SiteMap
            {
                Id = siteMap.Id
            };

            updateEntity.Attributes[SiteMap.Schema.Attributes.sitemapxml] = newText;

            await service.UpdateAsync(updateEntity);

            _iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionPublishingSiteMapFormat3, service.ConnectionData.Name, siteMap.SiteMapName, siteMap.Id.ToString());

            var repositoryPublish = new PublishActionsRepository(service);

            await repositoryPublish.PublishSiteMapsAsync(new[] { siteMap.Id });

            service.TryDispose();
        }
示例#6
0
        private async Task CheckingEntitiesOwnership(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            EntityMetadataRepository repositoryEntity = new EntityMetadataRepository(service);

            var allEntities = await repositoryEntity.GetEntitiesDisplayNameAsync();

            var groups = allEntities.GroupBy(ent => ent.OwnershipType).OrderBy(gr => gr.Key);

            foreach (var gr in groups)
            {
                content.AppendLine();

                int count = gr.Count();

                string name = "Null";

                if (gr.Key.HasValue)
                {
                    name = gr.Key.Value.ToString();
                }

                content.AppendFormat(Properties.OutputStrings.EntitiesWithOwnershipFormat2, name, count).AppendLine();

                gr.OrderBy(ent => ent.LogicalName).ToList().ForEach(ent => content.AppendLine(_tabSpacer + ent.LogicalName));
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithEntitiesOwnershipFormat1, filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
示例#7
0
        private async Task ComparingAssemblyAndCrmSolution(ConnectionData connectionData, CommonConfiguration commonConfig, string projectName, string defaultOutputFilePath)
        {
            if (string.IsNullOrEmpty(projectName))
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.AssemblyNameIsEmpty);
                return;
            }

            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            var repositoryAssembly = new PluginAssemblyRepository(service);

            var assembly = await repositoryAssembly.FindAssemblyAsync(projectName);

            if (assembly == null)
            {
                assembly = await repositoryAssembly.FindAssemblyByLikeNameAsync(projectName);
            }

            if (assembly == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.PluginAssemblyNotFoundedByNameFormat1, projectName);

                WindowHelper.OpenPluginAssemblyExplorer(
                    this._iWriteToOutput
                    , service
                    , commonConfig
                    , projectName
                    );

                return;
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string filePath = await CreateFileWithAssemblyComparing(commonConfig.FolderForExport, service, assembly.Id, assembly.Name, defaultOutputFilePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
        private async Task GetCurrentFormDescription(IOrganizationServiceExtented service, CommonConfiguration commonConfig, SystemForm systemForm)
        {
            string formXml = systemForm.FormXml;

            if (string.IsNullOrEmpty(formXml))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, SystemForm.Schema.Headers.formxml);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            var descriptor = new SolutionComponentDescriptor(service);

            descriptor.SetSettings(commonConfig);

            var handler = new FormDescriptionHandler(descriptor, new DependencyRepository(service));

            string fileName = EntityFileNameFormatter.GetSystemFormFileName(service.ConnectionData.Name, systemForm.ObjectTypeCode, systemForm.Name, "FormDescription", FileExtension.txt);
            string filePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileName));

            try
            {
                XElement doc = XElement.Parse(formXml);

                string desc = await handler.GetFormDescriptionAsync(doc, systemForm.ObjectTypeCode, systemForm.Id, systemForm.Name, systemForm.FormattedValues[SystemForm.Schema.Attributes.type]);

                File.WriteAllText(filePath, desc, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, SystemForm.Schema.EntityLogicalName, systemForm.Name, "FormDescription", filePath);

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

                service.TryDispose();
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
示例#9
0
        private void GetCurrentWorkflowXaml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, Workflow workflow)
        {
            string workflowXaml = workflow.Xaml;

            if (string.IsNullOrEmpty(workflowXaml))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, Workflow.Schema.EntityLogicalName, workflow.Name, Workflow.Schema.Headers.xaml);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            workflowXaml = ContentComparerHelper.FormatXmlByConfiguration(
                workflowXaml
                , commonConfig
                , XmlOptionsControls.WorkflowXmlOptions
                , workflowId: workflow.Id
                );

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string fieldTitle = Workflow.Schema.Headers.xaml;

            string currentFileName = EntityFileNameFormatter.GetWorkflowFileName(service.ConnectionData.Name, workflow.PrimaryEntity, workflow.FormattedValues[Workflow.Schema.Attributes.category], workflow.Name, fieldTitle, FileExtension.xml);
            string currentFilePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(currentFileName));

            try
            {
                File.WriteAllText(currentFilePath, workflowXaml, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, Workflow.Schema.EntityLogicalName, workflow.Name, Workflow.Schema.Headers.xaml, currentFilePath);

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

                service.TryDispose();
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
示例#10
0
        private async Task CheckingWorkflowsNotExistingUsedEntities(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string fileName = string.Format("{0}.Workflows Used Not Existing Entities at {1}.txt", connectionData.Name, DateTime.Now.ToString("yyyy.MM.dd HH-mm-ss"));

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

            var descriptor = new SolutionComponentDescriptor(service);

            descriptor.WithUrls          = true;
            descriptor.WithManagedInfo   = true;
            descriptor.WithSolutionsInfo = true;

            var workflowDescriptor = new WorkflowUsedEntitiesDescriptor(_iWriteToOutput, service, descriptor);

            var stringBuider = new StringBuilder();

            await workflowDescriptor.GetDescriptionWithUsedNotExistsEntitiesInAllWorkflowsAsync(stringBuider);

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

            this._iWriteToOutput.WriteToOutput(connectionData, "Created file with Workflows Used Not Existing Entities: {0}", filePath);

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
示例#11
0
        private void GetCurrentWebResourceDependencyXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, WebResource webResource)
        {
            string dependencyXml = webResource.DependencyXml;

            if (string.IsNullOrEmpty(dependencyXml))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, WebResource.Schema.EntityLogicalName, webResource.Name, WebResource.Schema.Headers.dependencyxml);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            dependencyXml = ContentComparerHelper.FormatXmlByConfiguration(
                dependencyXml
                , commonConfig
                , XmlOptionsControls.WebResourceDependencyXmlOptions
                , schemaName: AbstractDynamicCommandXsdSchemas.WebResourceDependencyXmlSchema
                , webResourceName: webResource.Name
                );

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string currentFileName = EntityFileNameFormatter.GetWebResourceFileName(service.ConnectionData.Name, webResource.Name, WebResource.Schema.Headers.dependencyxml, FileExtension.xml);
            string currentFilePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(currentFileName));

            try
            {
                File.WriteAllText(currentFilePath, dependencyXml, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, WebResource.Schema.EntityLogicalName, webResource.Name, WebResource.Schema.Headers.dependencyxml, currentFilePath);

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

                service.TryDispose();
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
        private void GetCurrentPluginTypeCustomWorkflowActivityInfo(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, PluginType pluginType)
        {
            string customWorkflowActivityInfo = pluginType.CustomWorkflowActivityInfo;

            if (string.IsNullOrEmpty(customWorkflowActivityInfo))
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldIsEmptyFormat4, service.ConnectionData.Name, PluginType.Schema.EntitySchemaName, pluginType.TypeName, PluginType.Schema.Headers.customworkflowactivityinfo);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);
                return;
            }

            customWorkflowActivityInfo = ContentComparerHelper.FormatXmlByConfiguration(
                customWorkflowActivityInfo
                , commonConfig
                , XmlOptionsControls.PluginTypeCustomWorkflowActivityInfoXmlOptions
                , schemaName: AbstractDynamicCommandXsdSchemas.PluginTypeCustomWorkflowActivityInfoSchema
                );

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

            string currentFileName = EntityFileNameFormatter.GetPluginTypeFileName(service.ConnectionData.Name, pluginType.TypeName, PluginType.Schema.Headers.customworkflowactivityinfo, FileExtension.xml);
            string currentFilePath = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(currentFileName));

            try
            {
                File.WriteAllText(currentFilePath, customWorkflowActivityInfo, new UTF8Encoding(false));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionEntityFieldExportedToFormat5, service.ConnectionData.Name, PluginType.Schema.EntitySchemaName, pluginType.TypeName, PluginType.Schema.Headers.customworkflowactivityinfo, currentFilePath);

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

                service.TryDispose();
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
示例#13
0
        private async Task CheckingUnknownFormControlType(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            Dictionary <string, FormatTextTableHandler> dictUnknownControls = new Dictionary <string, FormatTextTableHandler>(StringComparer.InvariantCultureIgnoreCase);

            var descriptor = new SolutionComponentDescriptor(service);
            var handler    = new FormDescriptionHandler(descriptor, new DependencyRepository(service));

            var repositorySystemForm = new SystemFormRepository(service);

            var formList = await repositorySystemForm.GetListAsync(null, null, new ColumnSet(true));

            foreach (var systemForm in formList
                     .OrderBy(f => f.ObjectTypeCode)
                     .ThenBy(f => f.Type?.Value)
                     .ThenBy(f => f.Name)
                     )
            {
                string formXml = systemForm.FormXml;

                if (!string.IsNullOrEmpty(formXml))
                {
                    XElement doc = XElement.Parse(formXml);

                    var tabs = handler.GetFormTabs(doc);

                    var unknownControls = tabs.SelectMany(t => t.Sections).SelectMany(s => s.Controls).Where(c => c.GetControlType() == FormControl.FormControlType.UnknownControl);

                    foreach (var control in unknownControls)
                    {
                        if (!dictUnknownControls.ContainsKey(control.ClassId))
                        {
                            FormatTextTableHandler tableUnknownControls = new FormatTextTableHandler();
                            tableUnknownControls.SetHeader("Entity", "FormType", "Form", "State", "Attribute", "Form Url");

                            dictUnknownControls[control.ClassId] = tableUnknownControls;
                        }

                        dictUnknownControls[control.ClassId].AddLine(
                            systemForm.ObjectTypeCode
                            , systemForm.FormattedValues[SystemForm.Schema.Attributes.type]
                            , systemForm.Name
                            , systemForm.FormattedValues[SystemForm.Schema.Attributes.formactivationstate]
                            , control.Attribute
                            , service.UrlGenerator.GetSolutionComponentUrl(ComponentType.SystemForm, systemForm.Id)
                            );
                    }
                }
            }

            if (dictUnknownControls.Count > 0)
            {
                content.AppendLine().AppendLine();

                content.AppendFormat("Unknown Form Control Types: {0}", dictUnknownControls.Count);

                foreach (var classId in dictUnknownControls.Keys.OrderBy(s => s))
                {
                    content.AppendLine().AppendLine();

                    content.AppendLine(classId);

                    var tableUnknownControls = dictUnknownControls[classId];

                    foreach (var str in tableUnknownControls.GetFormatedLines(false))
                    {
                        content.AppendLine(_tabSpacer + str);
                    }
                }

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

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

                this._iWriteToOutput.WriteToOutput(connectionData, "Unknown Form Control Types were exported to {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
            else
            {
                this._iWriteToOutput.WriteToOutput(connectionData, "No Unknown Form Control Types in CRM were founded.");
                this._iWriteToOutput.ActivateOutputWindow(connectionData);
            }
        }
示例#14
0
        private async Task CreatingAllDependencyNodesDescription(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            var hash = new HashSet <Tuple <int, Guid> >();

            {
                var repository = new DependencyNodeRepository(service);

                var components = await repository.GetDistinctListAsync();

                foreach (var item in components.Where(en => en.ComponentType != null && en.ObjectId.HasValue))
                {
                    hash.Add(Tuple.Create(item.ComponentType.Value, item.ObjectId.Value));
                }
            }

            if (hash.Any())
            {
                content.AppendLine().AppendLine();

                var solutionComponents = hash.Select(e => new SolutionComponent
                {
                    ComponentType = new OptionSetValue(e.Item1),
                    ObjectId      = e.Item2,
                }).ToList();

                var descriptor = new SolutionComponentDescriptor(service);
                descriptor.WithUrls          = true;
                descriptor.WithManagedInfo   = true;
                descriptor.WithSolutionsInfo = true;

                descriptor.MetadataSource.DownloadEntityMetadata();

                var desc = await descriptor.GetSolutionComponentsDescriptionAsync(solutionComponents);

                content.AppendLine(desc);

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

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

                this._iWriteToOutput.WriteToOutput(connectionData, "Dependency Nodes Description were exported to {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
        }
示例#15
0
        private async Task CheckingComponentTypeEnum(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            var hash = new HashSet <Tuple <int, Guid> >();

            {
                var repository = new SolutionComponentRepository(service);

                var components = await repository.GetDistinctSolutionComponentsAsync();

                foreach (var item in components.Where(en => en.ComponentType != null && en.ObjectId.HasValue))
                {
                    if (!item.IsDefinedComponentType())
                    {
                        hash.Add(Tuple.Create(item.ComponentType.Value, item.ObjectId.Value));
                    }
                }
            }

            {
                var repository = new DependencyNodeRepository(service);

                var components = await repository.GetDistinctListUnknownComponentTypeAsync();

                foreach (var item in components.Where(en => en.ComponentType != null && en.ObjectId.HasValue))
                {
                    if (!item.IsDefinedComponentType())
                    {
                        hash.Add(Tuple.Create(item.ComponentType.Value, item.ObjectId.Value));
                    }
                }
            }

            {
                var repository = new InvalidDependencyRepository(service);

                var components = await repository.GetDistinctListAsync();

                foreach (var item in components.Where(en => en.MissingComponentType != null && en.MissingComponentId.HasValue))
                {
                    if (!item.IsDefinedMissingComponentType())
                    {
                        hash.Add(Tuple.Create(item.MissingComponentType.Value, item.MissingComponentId.Value));
                    }
                }

                foreach (var item in components.Where(en => en.ExistingComponentType != null && en.ExistingComponentId.HasValue))
                {
                    if (!item.IsDefinedExistingComponentType())
                    {
                        hash.Add(Tuple.Create(item.ExistingComponentType.Value, item.ExistingComponentId.Value));
                    }
                }
            }

            if (hash.Any())
            {
                var groups = hash.GroupBy(e => e.Item1);

                content.AppendLine().AppendLine();

                content.AppendFormat("ComponentTypes not founded in Enum: {0}", groups.Count());

                foreach (var gr in groups.OrderBy(e => e.Key))
                {
                    content.AppendLine().AppendLine();

                    foreach (var item in gr.OrderBy(e => e.Item2))
                    {
                        content.AppendFormat(_tabSpacer + item.Item1.ToString() + _tabSpacer + item.Item2.ToString()).AppendLine();
                    }
                }

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

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

                this._iWriteToOutput.WriteToOutput(connectionData, "New ComponentTypes were exported to {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
            else
            {
                this._iWriteToOutput.WriteToOutput(connectionData, "No New ComponentTypes in CRM were founded.");
                this._iWriteToOutput.ActivateOutputWindow(connectionData);
            }
        }
示例#16
0
        private async Task CheckingGlobalOptionSetDuplicates(ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            var entityMetadataSource = new SolutionComponentMetadataSource(service);

            var descriptor = new SolutionComponentDescriptor(service);

            descriptor.WithUrls          = true;
            descriptor.WithManagedInfo   = true;
            descriptor.WithSolutionsInfo = true;

            var dependencyRepository = new DependencyRepository(service);
            var descriptorHandler    = new DependencyDescriptionHandler(descriptor);

            RetrieveAllOptionSetsRequest request = new RetrieveAllOptionSetsRequest();

            RetrieveAllOptionSetsResponse response = (RetrieveAllOptionSetsResponse)service.Execute(request);

            bool hasInfo = false;

            foreach (var optionSet in response.OptionSetMetadata.OfType <OptionSetMetadata>().OrderBy(e => e.Name))
            {
                var coll = await dependencyRepository.GetDependentComponentsAsync((int)ComponentType.OptionSet, optionSet.MetadataId.Value);

                if (coll.Any())
                {
                    var filter = coll
                                 .Where(c => c.DependentComponentType.Value == (int)ComponentType.Attribute)
                                 .Select(c => new { Dependency = c, Attribute = entityMetadataSource.GetAttributeMetadata(c.DependentComponentObjectId.Value) })
                                 .Where(c => c.Attribute != null)
                                 .GroupBy(c => c.Attribute.EntityLogicalName)
                                 .Where(gr => gr.Count() > 1)
                                 .SelectMany(gr => gr.Select(c => c.Dependency))
                                 .ToList()
                    ;

                    if (filter.Any())
                    {
                        var desc = await descriptorHandler.GetDescriptionDependentAsync(filter);

                        if (!string.IsNullOrEmpty(desc))
                        {
                            if (content.Length > 0)
                            {
                                content
                                .AppendLine(new string('-', 150))
                                .AppendLine();
                            }

                            hasInfo = true;

                            content.AppendFormat("Global OptionSet Name {0}       IsCustomOptionSet {1}      IsManaged {2}", optionSet.Name, optionSet.IsCustomOptionSet, optionSet.IsManaged).AppendLine();

                            content.AppendLine(desc);
                        }
                    }
                }
            }

            if (!hasInfo)
            {
                content.AppendLine("No duplicates were found.");
            }

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithCheckingGlobalOptionSetDuplicatesOnEntityFormat1, filePath);

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

                string formXml = systemForm.FormXml;

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

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

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

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

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

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

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

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

            await service.UpdateAsync(updateEntity);

            var repositoryPublish = new PublishActionsRepository(service);

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

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

            service.TryDispose();
        }
        private async Task CheckingPluginImagesRequiredComponents(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 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", MessageComparer.Comparer)
                                  .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."));
                }

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                string fileName = string.Format("{0}.Checking Plugin Images Required Components 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 Required Components: {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
        }
        private async Task CheckingPluginStepsRequiredComponents(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 stepEnum = await repositoryStep.FindSdkMessageProcessingStepWithEntityNameAsync(null, null, null, null, null);

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

                var 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>();

                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."));
                }

                commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

                string fileName = string.Format("{0}.Checking Plugin Steps Required Components 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 Required Components: {0}", filePath);

                this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
            }
        }
示例#20
0
        private async Task UpdateWorkflowXaml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, Workflow workflow)
        {
            string fieldTitle = Workflow.Schema.Headers.xaml;

            {
                string workflowXaml = workflow.Xaml;

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

                    string fileNameBackUp = EntityFileNameFormatter.GetWorkflowFileName(service.ConnectionData.Name, workflow.PrimaryEntity, workflow.FormattedValues[Workflow.Schema.Attributes.category], workflow.Name, fieldTitle + " BackUp", FileExtension.xml);
                    string filePathBackUp = Path.Combine(commonConfig.FolderForExport, FileOperations.RemoveWrongSymbols(fileNameBackUp));

                    try
                    {
                        workflowXaml = ContentComparerHelper.FormatXmlByConfiguration(
                            workflowXaml
                            , commonConfig
                            , XmlOptionsControls.WorkflowXmlOptions
                            , workflowId: workflow.Id
                            );

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

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

            if (workflow.StateCodeEnum == Workflow.Schema.OptionSets.statecode.Activated_1)
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionDeactivatingWorkflowFormat2, service.ConnectionData.Name, workflow.Name);

                await service.ExecuteAsync <SetStateResponse>(new SetStateRequest()
                {
                    EntityMoniker = workflow.ToEntityReference(),
                    State         = new OptionSetValue((int)Workflow.Schema.OptionSets.statecode.Draft_0),
                    Status        = new OptionSetValue((int)Workflow.Schema.OptionSets.statuscode.Draft_0_Draft_1),
                });
            }

            this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionUpdatingFieldFormat2, service.ConnectionData.Name, Workflow.Schema.Headers.xaml);

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

            var updateEntity = new Workflow
            {
                Id = workflow.Id,
            };

            updateEntity.Attributes[Workflow.Schema.Attributes.xaml] = newText;

            await service.UpdateAsync(updateEntity);

            if (workflow.StateCodeEnum == Workflow.Schema.OptionSets.statecode.Activated_1)
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.InConnectionActivatingWorkflowFormat2, service.ConnectionData.Name, workflow.Name);

                await service.ExecuteAsync <SetStateResponse>(new SetStateRequest()
                {
                    EntityMoniker = workflow.ToEntityReference(),
                    State         = new OptionSetValue((int)Workflow.Schema.OptionSets.statecode.Activated_1),
                    Status        = new OptionSetValue((int)Workflow.Schema.OptionSets.statuscode.Activated_1_Activated_2),
                });
            }

            service.TryDispose();
        }
        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);
            }
        }
示例#22
0
        private async Task UpdateSavedQueryXml(IOrganizationServiceExtented service, CommonConfiguration commonConfig, XDocument doc, string filePath, SavedQuery savedQuery)
        {
            string fieldName  = SavedQueryRepository.GetFieldNameByXmlRoot(doc.Root.Name.ToString());
            string fieldTitle = SavedQueryRepository.GetFieldTitleByXmlRoot(doc.Root.Name.ToString());

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            updateEntity.Attributes[fieldName] = newText;

            await service.UpdateAsync(updateEntity);

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

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

            {
                var repositoryPublish = new PublishActionsRepository(service);

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

            service.TryDispose();
        }
        private async Task 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);
            }
        }
示例#24
0
        private async Task ShowingWebResourcesDependentComponents(ConnectionData connectionData, CommonConfiguration commonConfig, List <SelectedFile> selectedFiles)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            var descriptor = new SolutionComponentDescriptor(service);

            descriptor.WithUrls          = true;
            descriptor.WithManagedInfo   = true;
            descriptor.WithSolutionsInfo = true;

            var descriptorHandler = new DependencyDescriptionHandler(descriptor);

            var dependencyRepository = new DependencyRepository(service);

            bool isconnectionDataDirty = false;

            List <string> listNotExistsOnDisk        = new List <string>();
            List <string> listNotFoundedInCRMNoLink  = new List <string>();
            List <string> listLastLinkEqualByContent = new List <string>();

            List <SolutionComponent> webResourceNames = new List <SolutionComponent>();

            Dictionary <SolutionComponent, string> webResourceDescriptions = new Dictionary <SolutionComponent, string>();

            WebResourceRepository repositoryWebResource = new WebResourceRepository(service);

            FormatTextTableHandler tableWithoutDependenComponents = new FormatTextTableHandler();

            tableWithoutDependenComponents.SetHeader("FilePath", "Web Resource Name", "Web Resource Type");

            var groups = selectedFiles.GroupBy(sel => sel.Extension);

            foreach (var gr in groups)
            {
                var names = gr.Select(sel => sel.FriendlyFilePath).ToArray();

                var dict = repositoryWebResource.FindMultiple(gr.Key, names);

                foreach (var selectedFile in gr)
                {
                    if (File.Exists(selectedFile.FilePath))
                    {
                        string name = selectedFile.FriendlyFilePath.ToLower();

                        var webresource = WebResourceRepository.FindWebResourceInDictionary(dict, name, gr.Key);

                        if (webresource == null)
                        {
                            Guid?webId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                            if (webId.HasValue)
                            {
                                webresource = await repositoryWebResource.GetByIdAsync(webId.Value);

                                if (webresource != null)
                                {
                                    listLastLinkEqualByContent.Add(selectedFile.FriendlyFilePath);
                                }
                            }
                        }

                        if (webresource != null)
                        {
                            // Запоминается файл
                            isconnectionDataDirty = true;
                            connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                            var coll = await dependencyRepository.GetDependentComponentsAsync((int)ComponentType.WebResource, webresource.Id);

                            var desc = await descriptorHandler.GetDescriptionDependentAsync(coll);

                            if (!string.IsNullOrEmpty(desc))
                            {
                                var component = new SolutionComponent()
                                {
                                    ComponentType = new OptionSetValue((int)ComponentType.WebResource),
                                    ObjectId      = webresource.Id,
                                };

                                webResourceNames.Add(component);

                                webResourceDescriptions.Add(component, desc);
                            }
                            else
                            {
                                tableWithoutDependenComponents.AddLine(selectedFile.FriendlyFilePath, webresource.Name, "'" + webresource.FormattedValues[WebResource.Schema.Attributes.webresourcetype] + "'");
                            }
                        }
                        else
                        {
                            connectionData.RemoveMapping(selectedFile.FriendlyFilePath);

                            listNotFoundedInCRMNoLink.Add(selectedFile.FriendlyFilePath);
                        }
                    }
                    else
                    {
                        listNotExistsOnDisk.Add(selectedFile.FilePath);
                    }
                }
            }

            if (isconnectionDataDirty)
            {
                //Сохранение настроек после публикации
                connectionData.Save();
            }

            FindsController.WriteToContentList(listNotFoundedInCRMNoLink, content, "File NOT FOUNDED in CRM: {0}");

            FindsController.WriteToContentList(listLastLinkEqualByContent, content, "Files NOT FOUNDED in CRM, but has Last Link: {0}");

            FindsController.WriteToContentList(listNotExistsOnDisk, content, Properties.OutputStrings.FileNotExistsFormat1);

            FindsController.WriteToContentList(tableWithoutDependenComponents.GetFormatedLines(true), content, "Files without dependent components: {0}");

            FindsController.WriteToContentDictionary(descriptor, content, webResourceNames, webResourceDescriptions, "WebResource dependent components: {0}");

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

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

            this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatedFileWithWebResourcesDependentComponentsFormat1, filePath);

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