private async Task CopingToClipboardSystemFormCurrentTabsAndSections(IOrganizationServiceExtented service, CommonConfiguration commonConfig, JavaScriptObjectType jsObjectType, string entityName, Guid formId, int formType)
        {
            var repositorySystemForm = new SystemFormRepository(service);

            var systemForm = await repositorySystemForm.GetByIdAsync(formId, ColumnSetInstances.AllColumns);

            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;
            }

            try
            {
                var fileGenerationOptions = FileGenerationConfiguration.GetFileGenerationOptions();

                var config = new CreateFileJavaScriptConfiguration(fileGenerationOptions);

                var doc = XElement.Parse(formXml);

                var descriptor = new SolutionComponentDescriptor(service);

                descriptor.SetSettings(commonConfig);

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

                FormInformation formInfo = handler.GetFormInformation(doc);

                var stringBuilder = new StringBuilder();

                using (var writer = new StringWriter(stringBuilder))
                {
                    var handlerCreate = new CreateFormTabsJavaScriptHandler(writer, config, jsObjectType, service);

                    handlerCreate.WriteContentOnlyForm(formInfo);
                }

                ClipboardHelper.SetText(stringBuilder.ToString().Trim(' ', '\r', '\n'));

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, Properties.OutputStrings.CopyingEntityJavaScriptContentOnFormCompletedFormat2, systemForm.ObjectTypeCode, systemForm.Name);
                this._iWriteToOutput.ActivateOutputWindow(service.ConnectionData);

                service.TryDispose();
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(service.ConnectionData, ex);
            }
        }
        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);
            }
        }
Esempio n. 3
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);
            }
        }
        private async Task <string> CheckSystemForms()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

            string operation = string.Format(Properties.OperationNames.CheckingSystemFormsFormat2, Connection1.Name, Connection2.Name);

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

            FormDescriptionHandler handler1 = new FormDescriptionHandler(ImageBuilder.Descriptor1, new DependencyRepository(_comparerSource.Service1))
            {
                WithManagedInfo         = false,
                WithDependentComponents = false,
            };
            FormDescriptionHandler handler2 = new FormDescriptionHandler(ImageBuilder.Descriptor2, new DependencyRepository(_comparerSource.Service2))
            {
                WithManagedInfo         = false,
                WithDependentComponents = false,
            };

            var task1 = _comparerSource.GetSystemForm1Async();
            var task2 = _comparerSource.GetSystemForm2Async();

            var list1 = await task1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.SystemFormsInConnectionFormat2, Connection1.Name, list1.Count));

            var list2 = await task2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.SystemFormsInConnectionFormat2, Connection2.Name, list2.Count));

            if (!list1.Any() && !list2.Any())
            {
                _iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ThereIsNothingToCompare);
                _iWriteToOutput.WriteToOutputEndOperation(null, operation);
                return(null);
            }

            FormatTextTableHandler tableOnlyExistsIn1 = new FormatTextTableHandler();

            tableOnlyExistsIn1.SetHeader("Entity", "Type", "Name", "IsManaged", "Id");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

            tableOnlyExistsIn2.SetHeader("Entity", "Type", "Name", "IsManaged", "Id");

            var dictDifference = new Dictionary <Tuple <string, string, string, string>, List <string> >();

            var commonList = new List <LinkedEntities <SystemForm> >();

            foreach (var form1 in list1)
            {
                {
                    var form2 = list2.FirstOrDefault(form => form.Id == form1.Id);

                    if (form2 != null)
                    {
                        commonList.Add(new LinkedEntities <SystemForm>(form1, form2));
                        continue;
                    }
                }

                var entityName1 = form1.ObjectTypeCode;
                var name1       = form1.Name;

                string typeName1 = form1.FormattedValues[SystemForm.Schema.Attributes.type];

                tableOnlyExistsIn1.AddLine(entityName1, typeName1, name1, form1.IsManaged.ToString(), form1.Id.ToString());

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.SystemForm, form1.Id);
            }

            foreach (var form2 in list2)
            {
                {
                    var form1 = list1.FirstOrDefault(form => form.Id == form2.Id);

                    if (form1 != null)
                    {
                        continue;
                    }
                }

                var entityName2 = form2.ObjectTypeCode;
                var name2       = form2.Name;

                string typeName2 = form2.FormattedValues[SystemForm.Schema.Attributes.type];

                tableOnlyExistsIn2.AddLine(entityName2, typeName2, name2, form2.IsManaged.ToString(), form2.Id.ToString());

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.SystemForm, form2.Id);
            }

            {
                var reporter = new ProgressReporter(_iWriteToOutput, commonList.Count, 5, "Processing Common Forms");

                foreach (var form in commonList)
                {
                    reporter.Increase();

                    FormatTextTableHandler tabDiff = new FormatTextTableHandler();
                    tabDiff.SetHeader("Attribute", "Organization", "Value");

                    {
                        List <string> fieldsToCompare = new List <string>()
                        {
                            //SystemForm.Schema.Attributes.ancestorformid
                            SystemForm.Schema.Attributes.canbedeleted
                            , SystemForm.Schema.Attributes.componentstate
                            , SystemForm.Schema.Attributes.description
                            , SystemForm.Schema.Attributes.formactivationstate
                            , SystemForm.Schema.Attributes.formpresentation
                            //, SystemForm.Schema.Attributes.formxml
                            //, SystemForm.Schema.Attributes.formxmlmanaged
                            , SystemForm.Schema.Attributes.introducedversion
                            , SystemForm.Schema.Attributes.isairmerged
                            , SystemForm.Schema.Attributes.iscustomizable
                            , SystemForm.Schema.Attributes.isdefault
                            //, SystemForm.Schema.Attributes.ismanaged
                            , SystemForm.Schema.Attributes.istabletenabled
                            , SystemForm.Schema.Attributes.name
                            , SystemForm.Schema.Attributes.objecttypecode
                            //, SystemForm.Schema.Attributes.organizationid
                            //, SystemForm.Schema.Attributes.overwritetime
                            //, SystemForm.Schema.Attributes.publishedon
                            //, SystemForm.Schema.Attributes.solutionid
                            //, SystemForm.Schema.Attributes.supportingsolutionid
                            , SystemForm.Schema.Attributes.type
                            , SystemForm.Schema.Attributes.version
                            , SystemForm.Schema.Attributes.versionnumber
                        };

                        foreach (var fieldName in fieldsToCompare)
                        {
                            if (ContentComparerHelper.IsEntityDifferentInField(form.Entity1, form.Entity2, fieldName))
                            {
                                var str1 = EntityDescriptionHandler.GetAttributeString(form.Entity1, fieldName, Connection1);
                                var str2 = EntityDescriptionHandler.GetAttributeString(form.Entity2, fieldName, Connection2);

                                tabDiff.AddLine(fieldName, Connection1.Name, str1);
                                tabDiff.AddLine(fieldName, Connection2.Name, str2);
                            }
                        }
                    }

                    string typeName1 = form.Entity1.FormattedValues[SystemForm.Schema.Attributes.type];
                    string typeName2 = form.Entity2.FormattedValues[SystemForm.Schema.Attributes.type];

                    {
                        List <string> fieldsToCompare = new List <string>()
                        {
                            SystemForm.Schema.Attributes.formxml
                        };

                        foreach (var fieldName in fieldsToCompare)
                        {
                            string formXml1 = form.Entity1.GetAttributeValue <string>(fieldName) ?? string.Empty;
                            string formXml2 = form.Entity2.GetAttributeValue <string>(fieldName) ?? string.Empty;

                            if (!ContentComparerHelper.CompareXML(formXml1, formXml2).IsEqual)
                            {
                                string descReason = string.Empty;

                                if (ContentComparerHelper.TryParseXml(formXml1, out var doc1) && ContentComparerHelper.TryParseXml(formXml2, out var doc2))
                                {
                                    string desc1 = await handler1.GetFormDescriptionAsync(doc1, form.Entity1.ObjectTypeCode, form.Entity1.Id, form.Entity1.Name, typeName1);

                                    string desc2 = await handler2.GetFormDescriptionAsync(doc2, form.Entity2.ObjectTypeCode, form.Entity2.Id, form.Entity2.Name, typeName2);

                                    if (!string.Equals(desc1, desc2))
                                    {
                                        var compare = ContentComparerHelper.CompareText(desc1.ToLower(), desc2.ToLower());

                                        if (compare.IsEqual)
                                        {
                                            descReason = "InCase";
                                        }
                                        else
                                        {
                                            descReason = compare.GetCompareDescription();
                                        }
                                    }
                                }

                                string formReason = string.Empty;

                                {
                                    if (ContentComparerHelper.TryParseXml(formXml1, out var docCorrected1) &&
                                        ContentComparerHelper.TryParseXml(formXml2, out var docCorrected2)
                                        )
                                    {
                                        handler1.ReplaceRoleToRoleTemplates(docCorrected1);
                                        handler2.ReplaceRoleToRoleTemplates(docCorrected2);

                                        if (ContentComparerHelper.CompareXML(docCorrected1.ToString(), docCorrected2.ToString()).IsEqual)
                                        {
                                            formReason = string.Empty;
                                        }
                                        else
                                        {
                                            var compare = ContentComparerHelper.CompareXML(docCorrected1.ToString().ToLower(), docCorrected2.ToString().ToLower(), true);

                                            if (compare.IsEqual)
                                            {
                                                formReason = "InCase";
                                            }
                                            else
                                            {
                                                formReason = compare.GetCompareDescription();
                                            }
                                        }
                                    }
                                    else
                                    {
                                        var compare = ContentComparerHelper.CompareXML(formXml1.ToLower(), formXml2.ToLower(), true);

                                        if (compare.IsEqual)
                                        {
                                            formReason = "InCase";
                                        }
                                        else
                                        {
                                            formReason = compare.GetCompareDescription();
                                        }
                                    }
                                }

                                if (!string.IsNullOrEmpty(formReason))
                                {
                                    tabDiff.AddLine(fieldName, string.Empty, string.Format(Properties.OrganizationComparerStrings.FieldDifferenceReasonFormat3, Connection1.Name, Connection2.Name, formReason));
                                }

                                if (!string.IsNullOrEmpty(descReason))
                                {
                                    tabDiff.AddLine(fieldName + "Description", string.Empty, string.Format(Properties.OrganizationComparerStrings.FieldDifferenceReasonFormat3, Connection1.Name, Connection2.Name, descReason));
                                }
                            }
                        }
                    }

                    if (tabDiff.Count > 0)
                    {
                        var diff = tabDiff.GetFormatedLines(false);
                        this.ImageBuilder.AddComponentDifferent((int)ComponentType.SystemForm, form.Entity1.Id, form.Entity2.Id, string.Join(Environment.NewLine, diff));

                        var entityName1 = form.Entity1.ObjectTypeCode;
                        var name1       = form.Entity1.Name;

                        dictDifference.Add(Tuple.Create(entityName1, typeName1, name1, form.Entity1.Id.ToString()), diff);
                    }
                }
            }

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

                content.AppendLine().AppendLine().AppendFormat("System Forms ONLY EXISTS in {0}: {1}", Connection1.Name, tableOnlyExistsIn1.Count);

                tableOnlyExistsIn1.GetFormatedLines(true).ForEach(e => content.AppendLine().Append((tabSpacer + e).TrimEnd()));
            }

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

                content.AppendLine().AppendLine().AppendFormat("System Forms ONLY EXISTS in {0}: {1}", Connection2.Name, tableOnlyExistsIn2.Count);

                tableOnlyExistsIn2.GetFormatedLines(true).ForEach(e => content.AppendLine().Append((tabSpacer + e).TrimEnd()));
            }

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

                content.AppendLine().AppendLine().AppendFormat("System Forms DIFFERENT in {0} and {1}: {2}", Connection1.Name, Connection2.Name, dictDifference.Count);

                FormatTextTableHandler tableDifference = new FormatTextTableHandler();
                tableDifference.SetHeader("Entity", "Type", "Name", "Id");

                foreach (var template in dictDifference)
                {
                    tableDifference.CalculateLineLengths(template.Key.Item1, template.Key.Item2, template.Key.Item3, template.Key.Item4);
                }

                foreach (var template in dictDifference
                         .OrderBy(w => w.Key.Item1)
                         .ThenBy(w => w.Key.Item2)
                         .ThenBy(w => w.Key.Item3)
                         .ThenBy(w => w.Key.Item4)
                         )
                {
                    content.AppendLine().Append(tabSpacer + tableDifference.FormatLine(template.Key.Item1, template.Key.Item2, template.Key.Item3, template.Key.Item4));

                    foreach (var str in template.Value)
                    {
                        content.AppendLine().Append(tabSpacer + tabSpacer + str);
                    }
                }
            }

            if (tableOnlyExistsIn2.Count == 0 &&
                tableOnlyExistsIn1.Count == 0 &&
                dictDifference.Count == 0
                )
            {
                content.AppendLine("No difference in System Forms.");
            }

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

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, "System Forms");

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
        private async Task <string> CreateFormsEventsFile(IOrganizationServiceExtented service, string fileFolder, string fileNameFormat, string connectionDataName, bool onlyWithFormLibraries)
        {
            this._iWriteToOutput.WriteToOutput(service.ConnectionData, "Start analyzing System Forms.");

            var repository = new SystemFormRepository(service);

            var allForms = (await repository.GetListAsync())
                           .OrderBy(ent => ent.ObjectTypeCode)
                           .ThenBy(ent => ent.Type.Value)
                           .ThenBy(ent => ent.Name)
            ;

            SolutionComponentDescriptor descriptor = new SolutionComponentDescriptor(service);

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

            StringBuilder content = new StringBuilder();

            foreach (var systemForm in allForms)
            {
                string entityName = systemForm.ObjectTypeCode;
                string name       = systemForm.Name;

                string typeName = systemForm.FormattedValues[SystemForm.Schema.Attributes.type];

                string formXml = systemForm.FormXml;

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

                    string events = handler.GetEventsDescription(doc);

                    if (!string.IsNullOrEmpty(events))
                    {
                        string desc = handler.GetFormLibrariesDescription(doc);

                        if (onlyWithFormLibraries && string.IsNullOrEmpty(desc))
                        {
                            continue;
                        }

                        if (content.Length > 0)
                        {
                            content
                            .AppendLine()
                            .AppendLine(new string('-', 100))
                            .AppendLine()
                            ;
                        }

                        content.AppendFormat("Entity: {0}", entityName).AppendLine();
                        content.AppendFormat("Form Type: {0}", typeName).AppendLine();
                        content.AppendFormat("Form Name: {0}", name).AppendLine();

                        if (!string.IsNullOrEmpty(desc))
                        {
                            content.AppendLine("FormLibraries:");
                            content.Append(desc);
                        }

                        content.AppendLine("Events:");
                        content.AppendLine(events);
                    }
                }
            }

            string filePath = string.Empty;

            if (content.Length > 0)
            {
                string fileName = string.Format("{0}{1} {2}.txt"
                                                , (!string.IsNullOrEmpty(connectionDataName) ? connectionDataName + "." : string.Empty)
                                                , fileNameFormat.Trim()
                                                , EntityFileNameFormatter.GetDateString()
                                                );

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

                if (!Directory.Exists(fileFolder))
                {
                    Directory.CreateDirectory(fileFolder);
                }

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

                this._iWriteToOutput.WriteToOutput(service.ConnectionData, "System Forms Events were exported to {0}", filePath);
            }
            else
            {
                this._iWriteToOutput.WriteToOutput(service.ConnectionData, "No Forms Events were founded.");
            }

            return(filePath);
        }