Example #1
0
        public static string GetOptionSetValueName(string label, int value)
        {
            var result = ContentComparerHelper.RemoveDiacritics(label);

            result = Translit(result);

            result = rexReplaceNonAlpha.Replace(result, "_");
            result = rexReplaceDoubleSpace.Replace(result, "_");
            result = result.Trim(' ', '_');

            if (string.IsNullOrEmpty(result))
            {
                return("V_" + value);
            }

            if (int.TryParse(result.Substring(0, 1), out _))
            {
                result = "V_" + result;
            }

            result += "_" + value;

            result = rexReplaceNonAlpha.Replace(result, "_");
            result = rexReplaceDoubleSpace.Replace(result, "_");
            result = result.Trim(' ', '_');

            return(result);
        }
Example #2
0
        private async Task <IEnumerable <Guid> > GetDescriptionWithEntityFieldStringsInAllWorkflows(StringBuilder strFile)
        {
            var workflowsWithStrings = new Dictionary <Guid, List <WorkflowEntityFieldString> >();

            try
            {
                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty);
                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty);

                strFile.AppendLine(this._iWriteToOutput.WriteToOutputStartOperation(_service.ConnectionData, Properties.OperationNames.AnalyzingWorkflowsFormat1, _service.ConnectionData.Name));

                var repositoryWorkflow = new WorkflowRepository(_service);

                var handler = new WorkflowUsedEntitiesHandler();

                {
                    var workflowsList = await repositoryWorkflow.GetListAsync(null, null, null, null, new ColumnSet(Workflow.Schema.Attributes.xaml));

                    _descriptor.GetEntities <Workflow>((int)ComponentType.Workflow, workflowsList.Select(c => c.Id));

                    foreach (var workflow in workflowsList)
                    {
                        if (string.IsNullOrEmpty(workflow.Xaml))
                        {
                            continue;
                        }

                        var xmlContent = ContentComparerHelper.RemoveDiacritics(workflow.Xaml);

                        var doc = XElement.Parse(xmlContent);

                        List <WorkflowEntityFieldString> coll = await handler.GetWorkflowStringsEntityFieldsAsync(doc);

                        if (coll.Count > 0)
                        {
                            workflowsWithStrings.Add(workflow.Id, coll);
                        }
                    }
                }

                await FillDescriptionEntityFieldStrings(strFile, workflowsWithStrings);

                strFile.AppendLine(this._iWriteToOutput.WriteToOutputEndOperation(_service.ConnectionData, Properties.OperationNames.AnalyzingWorkflowsFormat1, _service.ConnectionData.Name));
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }

            return(workflowsWithStrings.Keys.ToArray());
        }
Example #3
0
        public static string ClearXml(string xml, params Action <XElement>[] actions)
        {
            try
            {
                xml = xml ?? string.Empty;

                xml = ContentComparerHelper.RemoveDiacritics(xml);

                if (!TryParseXml(xml, out XElement doc))
                {
                    return(xml);
                }

                RemoveEmptyXMLText(doc);
                SortXmlAttributesInternal(doc);
                SortRibbonCommandsAndRulesByIdInternal(doc);
                SortFormXmlElementsInternal(doc);

                if (actions != null)
                {
                    foreach (Action <XElement> action in actions)
                    {
                        action?.Invoke(doc);
                    }
                }

                return(doc.ToString());
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(null, ex);

#if DEBUG
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debugger.Break();
                }
#endif

                throw;
            }
        }
Example #4
0
        public async Task GetDescriptionUsedNotExistsEntitiesInWorkflowAsync(StringBuilder strFile, Guid idWorkflow)
        {
            try
            {
                var repository = new WorkflowRepository(_service);

                var workflow = await repository.GetByIdAsync(idWorkflow, ColumnSetInstances.AllColumns);

                string xmlContent = ContentComparerHelper.RemoveDiacritics(workflow.Xaml);

                var doc = XElement.Parse(xmlContent);

                HashSet <Guid> workflowsWithEntities = new HashSet <Guid>()
                {
                    idWorkflow
                };

                var handler = new WorkflowUsedEntitiesHandler();

                Dictionary <EntityReference, HashSet <Guid> > list = (await handler.GetWorkflowUsedEntitiesAsync(doc)).ToDictionary(e => e, k => new HashSet <Guid>()
                {
                    idWorkflow
                });

                strFile
                .AppendFormat("Entity:   {0}", workflow.PrimaryEntity).AppendLine()
                .AppendFormat("Category: {0}", workflow.FormattedValues[Workflow.Schema.Attributes.category]).AppendLine()
                .AppendFormat("Name:     {0}", workflow.Name).AppendLine()
                .AppendFormat("Url:      {0}", _service.UrlGenerator.GetSolutionComponentUrl(ComponentType.Workflow, idWorkflow)).AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                ;

                await FillDescriptionNotExistsEntities(strFile, workflowsWithEntities, list);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }
        }
Example #5
0
        public async Task GetDescriptionEntityFieldStringsInWorkflowAsync(StringBuilder strFile, Guid idWorkflow)
        {
            try
            {
                var repository = new WorkflowRepository(_service);

                var workflow = await repository.GetByIdAsync(idWorkflow, ColumnSetInstances.AllColumns);

                string xmlContent = ContentComparerHelper.RemoveDiacritics(workflow.Xaml);

                var doc = XElement.Parse(xmlContent);

                var handler = new WorkflowUsedEntitiesHandler();

                strFile
                .AppendFormat("Entity:   {0}", workflow.PrimaryEntity).AppendLine()
                .AppendFormat("Category: {0}", workflow.FormattedValues[Workflow.Schema.Attributes.category]).AppendLine()
                .AppendFormat("Name:     {0}", workflow.Name).AppendLine()
                .AppendFormat("Url:      {0}", _service.UrlGenerator.GetSolutionComponentUrl(ComponentType.Workflow, idWorkflow)).AppendLine()
                .AppendLine()
                .AppendLine()
                .AppendLine()
                ;

                var strings = await handler.GetWorkflowStringsEntityFieldsAsync(doc);

                Dictionary <Guid, List <WorkflowEntityFieldString> > workflowsWithStrings = new Dictionary <Guid, List <WorkflowEntityFieldString> >();

                if (strings.Any())
                {
                    workflowsWithStrings.Add(idWorkflow, strings);
                }

                await FillDescriptionEntityFieldStrings(strFile, workflowsWithStrings);
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }
        }
        public static ContentCompareResult CompareText(string text1, string text2)
        {
            text1 = text1 ?? string.Empty;
            text2 = text2 ?? string.Empty;

            text1 = ContentComparerHelper.RemoveDiacritics(text1);
            text2 = ContentComparerHelper.RemoveDiacritics(text2);

            diff_match_patch match = new diff_match_patch
            {
                Diff_Timeout = ContentComparerHelper.Diff_Timeout
            };

            if (string.IsNullOrEmpty(text1) && string.IsNullOrEmpty(text2))
            {
                return(new ContentCompareResult(true, null));
            }

            if (string.IsNullOrEmpty(text1) && !string.IsNullOrEmpty(text2))
            {
                return(new ContentCompareResult(false, match.diff_main(text1, text2, false)));
            }

            if (!string.IsNullOrEmpty(text1) && string.IsNullOrEmpty(text2))
            {
                return(new ContentCompareResult(false, match.diff_main(text1, text2, false)));
            }

            bool isEqual = string.Equals(text1, text2);

            if (isEqual)
            {
                return(new ContentCompareResult(true, null));
            }
            else
            {
                return(new ContentCompareResult(false, match.diff_main(text1, text2, false)));
            }
        }
Example #7
0
        public static string GetCorrectedXaml(string xml, LabelReplacer replacer)
        {
            try
            {
                xml = xml ?? string.Empty;

                xml = ContentComparerHelper.RemoveDiacritics(xml);

                if (!TryParseXml(xml, out XElement doc))
                {
                    return(xml);
                }

                replacer.FullfillLabelsForWorkflow(doc);

                RemoveEmptyXMLText(doc);

                RenameClasses(doc);

                WorkflowUsedEntitiesHandler.ReplaceGuids(doc);

                return(doc.ToString());
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(null, ex);

#if DEBUG
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debugger.Break();
                }
#endif

                throw;
            }
        }
Example #8
0
        public static string FormatXmlByConfiguration(
            string xml
            , CommonConfiguration commonConfig
            , XmlOptionsControls xmlOptions
            , string schemaName        = null
            , string entityName        = null
            , string siteMapUniqueName = null
            , Guid?formId            = null
            , Guid?savedQueryId      = null
            , Guid?customControlId   = null
            , Guid?workflowId        = null
            , string webResourceName = null
            )
        {
            var result = xml;

            if ((xmlOptions & XmlOptionsControls.SetIntellisenseContext) != 0 &&
                commonConfig.SetIntellisenseContext
                )
            {
                if (entityName != null)
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextEntityName, replaceIntellisenseContextEntityNameFormat3, entityName);
                }

                if (siteMapUniqueName != null)
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextSiteMapNameUnique, replaceIntellisenseContextSiteMapNameUniqueFormat3, siteMapUniqueName);
                }

                if (savedQueryId.HasValue)
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextSavedQueryId, replaceIntellisenseContextSavedQueryIdFormat3, savedQueryId.ToString());
                }

                if (formId.HasValue)
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextFormId, replaceIntellisenseContextFormIdFormat3, formId.ToString());
                }

                if (customControlId.HasValue)
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextCustomControlId, replaceIntellisenseContextCustomControlIdFormat3, customControlId.ToString());
                }

                if (workflowId.HasValue)
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextWorkflowId, replaceIntellisenseContextWorkflowIdFormat3, workflowId.ToString());
                }

                if (!string.IsNullOrEmpty(webResourceName))
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContextWebResourceName, replaceIntellisenseContextWebResourceNameFormat3, webResourceName);
                }

                if (entityName != null ||
                    siteMapUniqueName != null ||
                    savedQueryId.HasValue ||
                    formId.HasValue ||
                    customControlId.HasValue ||
                    workflowId.HasValue ||
                    !string.IsNullOrEmpty(webResourceName)
                    )
                {
                    result = ReplaceOrInsertAttribute(result, patternIntellisenseContext, replaceIntellisenseContextNamespaceFormat3, Intellisense.Model.IntellisenseContext.IntellisenseContextNamespace.NamespaceName);
                }
            }

            if ((xmlOptions & XmlOptionsControls.SetXmlSchemas) != 0 &&
                commonConfig.SetXmlSchemasDuringExport
                )
            {
                var schemasResources = AbstractDynamicCommandXsdSchemas.GetXsdSchemas(schemaName);

                if (schemasResources != null)
                {
                    result = ContentComparerHelper.SetXsdSchema(result, schemasResources);
                }
            }

            if (TryParseXml(result, out XElement doc))
            {
                var sortRibbonCommandsAndRulesById = (xmlOptions & XmlOptionsControls.SortRibbonCommandsAndRulesById) != 0 && commonConfig.SortRibbonCommandsAndRulesById;
                var sortFormXmlElements            = (xmlOptions & XmlOptionsControls.SortFormXmlElements) != 0 && commonConfig.SortFormXmlElements;
                var sortXmlAttributes = (xmlOptions & XmlOptionsControls.SortXmlAttributes) != 0 && commonConfig.SortXmlAttributes;

                if (sortRibbonCommandsAndRulesById)
                {
                    SortRibbonCommandsAndRulesByIdInternal(doc);
                }

                if (sortFormXmlElements)
                {
                    SortFormXmlElementsInternal(doc);
                }

                if (sortXmlAttributes)
                {
                    SortXmlAttributesInternal(doc);
                }

                if ((xmlOptions & XmlOptionsControls.XmlAttributeOnNewLine) != 0 && commonConfig.ExportXmlAttributeOnNewLine)
                {
                    return(FormatXmlNewLineOnAttributes(doc));
                }
                else
                {
                    return(doc.ToString());
                }
            }
            else
            {
                return(result);
            }
        }
        private async Task <string> CheckConnectionRoles()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

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

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

            var taskRole1 = _comparerSource.GetConnectionRole1Async();
            var taskRole2 = _comparerSource.GetConnectionRole2Async();



            var listRole1 = await taskRole1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRolesInConnectionFormat2, Connection1.Name, listRole1.Count));

            var listRole2 = await taskRole2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRolesInConnectionFormat2, Connection2.Name, listRole2.Count));

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



            var taskRoleAssociation1 = _comparerSource.GetConnectionRoleAssociation1Async();
            var taskRoleAssociation2 = _comparerSource.GetConnectionRoleAssociation2Async();

            var taskRoleObjectTypeCode1 = _comparerSource.GetConnectionRoleObjectTypeCode1Async();
            var taskRoleObjectTypeCode2 = _comparerSource.GetConnectionRoleObjectTypeCode2Async();



            var listRoleAssociation1 = await taskRoleAssociation1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRoleAssociationsInConnectionFormat2, Connection1.Name, listRoleAssociation1.Count));

            var listRoleAssociation2 = await taskRoleAssociation2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRoleAssociationsInConnectionFormat2, Connection2.Name, listRoleAssociation2.Count));



            var listRoleObjectTypeCode1 = await taskRoleObjectTypeCode1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRoleObjectTypeCodesInConnectionFormat2, Connection1.Name, listRoleObjectTypeCode1.Count));

            var listRoleObjectTypeCode2 = await taskRoleObjectTypeCode2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRoleObjectTypeCodesInConnectionFormat2, Connection2.Name, listRoleObjectTypeCode2.Count));



            var commonRolesList = new List <LinkedEntities <ConnectionRole> >();

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



            FormatTextTableHandler tableOnlyExistsIn1 = new FormatTextTableHandler();

            tableOnlyExistsIn1.SetHeader("Category", "Name", "Id", "IsManaged");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

            tableOnlyExistsIn2.SetHeader("Category", "Name", "Id", "IsManaged");

            foreach (var role1 in listRole1)
            {
                {
                    var role2 = listRole2.FirstOrDefault(role => role.Id == role1.Id);

                    if (role2 != null)
                    {
                        commonRolesList.Add(new LinkedEntities <ConnectionRole>(role1, role2));

                        continue;
                    }
                }

                var category1 = role1.FormattedValues[ConnectionRole.Schema.Attributes.category];
                var name1     = role1.Name;

                tableOnlyExistsIn1.AddLine(category1, name1, role1.Id.ToString(), role1.IsManaged.ToString());

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.ConnectionRole, role1.Id);
            }

            foreach (var role2 in listRole2)
            {
                {
                    var role1 = listRole1.FirstOrDefault(role => role.Id == role2.Id);

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

                var name2     = role2.Name;
                var category2 = role2.FormattedValues[ConnectionRole.Schema.Attributes.category];

                tableOnlyExistsIn2.AddLine(category2, name2, role2.Id.ToString(), role2.IsManaged.ToString());

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.ConnectionRole, role2.Id);
            }

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.ConnectionRolesCommonFormat3, Connection1.Name, Connection2.Name, commonRolesList.Count()));

            foreach (var commonItem in commonRolesList)
            {
                var diff = new List <string>();

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

                    List <string> fieldsToCompare = new List <string>()
                    {
                        ConnectionRole.Schema.Attributes.category
                        , ConnectionRole.Schema.Attributes.componentstate
                        //, ConnectionRole.Schema.Attributes.connectionroleid
                        //, ConnectionRole.Schema.Attributes.connectionroleidunique
                        //, ConnectionRole.Schema.Attributes.createdby
                        //, ConnectionRole.Schema.Attributes.createdon
                        //, ConnectionRole.Schema.Attributes.createdonbehalfby
                        , ConnectionRole.Schema.Attributes.description
                        //, ConnectionRole.Schema.Attributes.importsequencenumber
                        //, ConnectionRole.Schema.Attributes.introducedversion
                        , ConnectionRole.Schema.Attributes.iscustomizable
                        //, ConnectionRole.Schema.Attributes.ismanaged
                        //, ConnectionRole.Schema.Attributes.modifiedby
                        //, ConnectionRole.Schema.Attributes.modifiedon
                        //, ConnectionRole.Schema.Attributes.modifiedonbehalfby
                        , ConnectionRole.Schema.Attributes.name
                        //, ConnectionRole.Schema.Attributes.organizationid
                        //, ConnectionRole.Schema.Attributes.overwritetime
                        //, ConnectionRole.Schema.Attributes.solutionid
                        , ConnectionRole.Schema.Attributes.statecode
                        , ConnectionRole.Schema.Attributes.statuscode
                        //, ConnectionRole.Schema.Attributes.supportingsolutionid
                        //, ConnectionRole.Schema.Attributes.versionnumber
                    };

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

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

                    if (tabDiff.Count > 0)
                    {
                        diff.AddRange(tabDiff.GetFormatedLines(false));
                    }
                }

                {
                    var enumerable1 = listRoleObjectTypeCode1
                                      .Where(e => e.ConnectionRoleId != null && e.ConnectionRoleId.Id == commonItem.Entity1.ConnectionRoleId)
                                      .Select(e => e.AssociatedObjectTypeCode)
                                      .Distinct()
                    ;

                    var enumerable2 = listRoleObjectTypeCode2
                                      .Where(e => e.ConnectionRoleId != null && e.ConnectionRoleId.Id == commonItem.Entity2.ConnectionRoleId)
                                      .Select(e => e.AssociatedObjectTypeCode)
                                      .Distinct()
                    ;

                    CompareConnectionRoleAssociatedObjects(Properties.OrganizationComparerStrings.PrefixAssociatedObjectTypeCodes, diff, enumerable1, enumerable2);
                }

                {
                    var enumerable1 = listRoleAssociation1
                                      .Where(e => e.ConnectionRoleId != null && e.ConnectionRoleId == commonItem.Entity1.ConnectionRoleId)
                                      .Select(e => e.AssociatedConnectionRoleName)
                                      .Distinct()
                    ;

                    var enumerable2 = listRoleAssociation2
                                      .Where(e => e.ConnectionRoleId != null && e.ConnectionRoleId == commonItem.Entity2.ConnectionRoleId)
                                      .Select(e => e.AssociatedConnectionRoleName)
                                      .Distinct()
                    ;

                    CompareConnectionRoleAssociatedObjects(Properties.OrganizationComparerStrings.PrefixAssociatedConnectionRoles, diff, enumerable1, enumerable2);
                }

                if (diff.Count > 0)
                {
                    dictDifference.Add(commonItem, diff);

                    this.ImageBuilder.AddComponentDifferent((int)ComponentType.ConnectionRole, commonItem.Entity1.Id, commonItem.Entity2.Id, string.Join(Environment.NewLine, diff));
                }
            }

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

                content.AppendLine().AppendLine().AppendFormat(Properties.OrganizationComparerStrings.ConnectionRolesOnlyExistsInConnectionFormat2, 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(Properties.OrganizationComparerStrings.ConnectionRolesOnlyExistsInConnectionFormat2, 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(Properties.OrganizationComparerStrings.ConnectionRolesDifferentFormat3, Connection1.Name, Connection2.Name, dictDifference.Count);

                FormatTextTableHandler tableDifference = new FormatTextTableHandler();
                tableDifference.SetHeader(Connection1.Name, Connection2.Name, "Id");

                foreach (var item in dictDifference)
                {
                    tableDifference.CalculateLineLengths(item.Key.Entity1.Name, item.Key.Entity2.Name, item.Key.Entity1.Id.ToString());
                }

                foreach (var item in dictDifference
                         .OrderBy(w => w.Key.Entity1.Name)
                         .ThenBy(w => w.Key.Entity2.Name)
                         .ThenBy(w => w.Key.Entity1.Id.ToString())
                         )
                {
                    content.AppendLine().Append(tabSpacer + tableDifference.FormatLine(item.Key.Entity1.Name, item.Key.Entity2.Name, item.Key.Entity1.Id.ToString()));

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

            if (tableOnlyExistsIn2.Count == 0 &&
                tableOnlyExistsIn1.Count == 0 &&
                dictDifference.Count == 0
                )
            {
                content.AppendLine(Properties.OrganizationComparerStrings.ConnectionRolesNoDifference);
            }

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

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, Properties.OrganizationComparerStrings.ConnectionRolesFileName);

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
        private async Task <string> CheckDisplayStrings()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

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

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

            var task1 = _comparerSource.GetDisplayString1Async();
            var task2 = _comparerSource.GetDisplayString2Async();

            var list1 = await task1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Display Strings in {0}: {1}", Connection1.Name, list1.Count()));

            var list2 = await task2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Display Strings in {0}: {1}", Connection2.Name, list2.Count()));

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

            var taskMap1 = _comparerSource.GetDisplayStringMap1Async();
            var taskMap2 = _comparerSource.GetDisplayStringMap2Async();

            var listMap1 = await taskMap1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Display Strings Maps in {0}: {1}", Connection1.Name, listMap1.Count()));

            var listMap2 = await taskMap2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Display Strings Maps in {0}: {1}", Connection1.Name, listMap2.Count()));

            FormatTextTableHandler tableOnlyExistsIn1 = new FormatTextTableHandler();

            tableOnlyExistsIn1.SetHeader("Key", "LanguageCode", "Published", "Custom", "CustomComment", "FormatParameters");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

            tableOnlyExistsIn2.SetHeader("Key", "LanguageCode", "Published", "Custom", "CustomComment", "FormatParameters");

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

            foreach (var displayString1 in list1)
            {
                var displaystringkey1 = displayString1.DisplayStringKey;
                var languagecode1     = displayString1.LanguageCode.Value;

                {
                    var displayString2 = list2.FirstOrDefault(displayString =>
                    {
                        var displaystringkey2 = displayString.DisplayStringKey;
                        var languagecode2     = displayString.LanguageCode.Value;

                        return(displaystringkey1 == displaystringkey2 && languagecode1 == languagecode2);
                    });

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

                var customComment          = displayString1.CustomComment;
                var customDisplayString    = displayString1.CustomComment;
                var formatParameters       = displayString1.FormatParameters.Value;
                var publishedDisplayString = displayString1.PublishedDisplayString;

                tableOnlyExistsIn1.AddLine(displaystringkey1, LanguageLocale.GetLocaleName(languagecode1), publishedDisplayString, customDisplayString, customComment, formatParameters.ToString());

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.DisplayString, displayString1.Id);
            }

            foreach (var displayString2 in list2)
            {
                var displaystringkey2 = displayString2.DisplayStringKey;
                var languagecode2     = displayString2.LanguageCode.Value;

                {
                    var displayString1 = list1.FirstOrDefault(displayString =>
                    {
                        var displaystringkey1 = displayString.DisplayStringKey;
                        var languagecode1     = displayString.LanguageCode.Value;

                        return(displaystringkey1 == displaystringkey2 && languagecode1 == languagecode2);
                    });

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

                var customComment          = displayString2.CustomComment;
                var customDisplayString    = displayString2.CustomDisplayString;
                var formatParameters       = displayString2.FormatParameters.Value;
                var publishedDisplayString = displayString2.PublishedDisplayString;

                tableOnlyExistsIn2.AddLine(displaystringkey2, LanguageLocale.GetLocaleName(languagecode2), publishedDisplayString, customDisplayString, customComment, formatParameters.ToString());

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.DisplayString, displayString2.Id);
            }

            foreach (var displayString1 in list1)
            {
                var displaystringkey1 = displayString1.DisplayStringKey;
                var languagecode1     = displayString1.LanguageCode.Value;

                var displayString2 = list2.FirstOrDefault(displayString =>
                {
                    var displaystringkey2 = displayString.DisplayStringKey;
                    var languagecode2     = displayString.LanguageCode.Value;

                    return(displaystringkey1 == displaystringkey2 && languagecode1 == languagecode2);
                });

                if (displayString2 == null)
                {
                    continue;
                }

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

                var temp1 = listMap1.Where(s => s.DisplayStringId == displayString1.Id);
                var temp2 = listMap2.Where(s => s.DisplayStringId == displayString2.Id);

                if (temp1.SequenceEqual(temp2))
                {
                    tabDiff.AddLine("DisplayStringMap", Connection1.Name, "Differs");
                    tabDiff.AddLine("DisplayStringMap", Connection2.Name, "Differs");
                }

                List <string> fieldsToCompare = new List <string>()
                {
                    DisplayString.Schema.Attributes.customcomment
                    , DisplayString.Schema.Attributes.customdisplaystring
                    , DisplayString.Schema.Attributes.formatparameters
                    , DisplayString.Schema.Attributes.publisheddisplaystring
                };

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

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

                if (tabDiff.Count > 0)
                {
                    var diff = tabDiff.GetFormatedLines(false);

                    dictDifference.Add(Tuple.Create(displaystringkey1, LanguageLocale.GetLocaleName(languagecode1)), diff);

                    this.ImageBuilder.AddComponentDifferent((int)ComponentType.DisplayString, displayString1.Id, displayString2.Id, string.Join(Environment.NewLine, diff));
                }
            }

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

                content.AppendLine().AppendLine().AppendFormat("Display Strings 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("Display Strings 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("Display Strings DIFFERENT in {0} and {1}: {2}", Connection1.Name, Connection2.Name, dictDifference.Count);

                FormatTextTableHandler tableDifference = new FormatTextTableHandler();
                tableDifference.SetHeader("Key", "LanguageCode");

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

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

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

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

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

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, "Display Strings");

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
        private async Task <string> CheckSystemSavedQueryVisualizations()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

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

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

            var task1 = _comparerSource.GetSavedQueryVisualization1Async();
            var task2 = _comparerSource.GetSavedQueryVisualization2Async();

            var list1 = await task1;

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

            var list2 = await task2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.SavedQueryVisualizationsInConnectionFormat2, 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", "Name", "IsManaged", "Id");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

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

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

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

            foreach (var chart1 in list1)
            {
                {
                    var chart2 = list2.FirstOrDefault(chart => chart.Id == chart1.Id);

                    if (chart2 != null)
                    {
                        commonList.Add(new LinkedEntities <SavedQueryVisualization>(chart1, chart2));
                        continue;
                    }
                }

                var entityName1 = chart1.PrimaryEntityTypeCode;
                var name1       = chart1.Name;

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

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.SavedQueryVisualization, chart1.Id);
            }

            foreach (var chart2 in list2)
            {
                var entityName2 = chart2.PrimaryEntityTypeCode;
                var name2       = chart2.Name;

                {
                    var chart1 = list1.FirstOrDefault(chart => chart.Id == chart2.Id);

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

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

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.SavedQueryVisualization, chart2.Id);
            }

            {
                var reporter = new ProgressReporter(_iWriteToOutput, commonList.Count, 5, "Processing Common Saved Query Visualizations (Charts)");

                foreach (var chart in commonList)
                {
                    var chart1 = chart.Entity1;
                    var chart2 = chart.Entity2;

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

                    {
                        List <string> fieldsToCompare = new List <string>()
                        {
                            SavedQueryVisualization.Schema.Attributes.componentstate
                            //, SavedQueryVisualization.Schema.Attributes.createdby
                            //, SavedQueryVisualization.Schema.Attributes.createdon
                            //, SavedQueryVisualization.Schema.Attributes.createdonbehalfby
                            //, SavedQueryVisualization.Schema.Attributes.datadescription
                            , SavedQueryVisualization.Schema.Attributes.description
                            , SavedQueryVisualization.Schema.Attributes.introducedversion
                            , SavedQueryVisualization.Schema.Attributes.iscustomizable
                            , SavedQueryVisualization.Schema.Attributes.isdefault
                            //, SavedQueryVisualization.Schema.Attributes.ismanaged
                            //, SavedQueryVisualization.Schema.Attributes.modifiedby
                            //, SavedQueryVisualization.Schema.Attributes.modifiedon
                            //, SavedQueryVisualization.Schema.Attributes.modifiedonbehalfby
                            , SavedQueryVisualization.Schema.Attributes.name
                            //, SavedQueryVisualization.Schema.Attributes.organizationid
                            //, SavedQueryVisualization.Schema.Attributes.overwritetime
                            //, SavedQueryVisualization.Schema.Attributes.presentationdescription
                            , SavedQueryVisualization.Schema.Attributes.primaryentitytypecode
                            //, SavedQueryVisualization.Schema.Attributes.savedqueryvisualizationid
                            //, SavedQueryVisualization.Schema.Attributes.savedqueryvisualizationidunique
                            //, SavedQueryVisualization.Schema.Attributes.solutionid
                            //, SavedQueryVisualization.Schema.Attributes.supportingsolutionid
                            , SavedQueryVisualization.Schema.Attributes.versionnumber
                            , SavedQueryVisualization.Schema.Attributes.webresourceid
                        };

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

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

                    var entityName1 = chart1.PrimaryEntityTypeCode;
                    var name1       = chart1.Name;

                    {
                        List <string> fieldsToCompare = new List <string>()
                        {
                            SavedQueryVisualization.Schema.Attributes.datadescription
                            , SavedQueryVisualization.Schema.Attributes.presentationdescription
                        };

                        foreach (var fieldName in fieldsToCompare)
                        {
                            string xml1 = chart1.GetAttributeValue <string>(fieldName) ?? string.Empty;
                            string xml2 = chart2.GetAttributeValue <string>(fieldName) ?? string.Empty;

                            if (!ContentComparerHelper.CompareXML(xml1, xml2).IsEqual)
                            {
                                string reason = string.Empty;

                                var compare = ContentComparerHelper.CompareXML(xml1.ToLower(), xml2.ToLower(), true);

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

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

                    if (tabDiff.Count > 0)
                    {
                        var diff = tabDiff.GetFormatedLines(false);
                        this.ImageBuilder.AddComponentDifferent((int)ComponentType.SavedQueryVisualization, chart1.Id, chart2.Id, string.Join(Environment.NewLine, diff));

                        dictDifference.Add(Tuple.Create(entityName1, name1, chart1.Id.ToString()), diff);
                    }
                }
            }

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

                content.AppendLine().AppendLine().AppendFormat("System Saved Query Visualizations (Charts) 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 Saved Query Visualizations (Charts) 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 Saved Query Visualizations (Charts) DIFFERENT in {0} and {1}: {2}", Connection1.Name, Connection2.Name, dictDifference.Count);

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

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

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

                    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 Saved Query Visualizations (Charts).");
            }

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

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, "Saved Query Visualizations (Charts)");

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
        private async Task <string> CheckSystemSavedQueries()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

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

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

            var task1 = _comparerSource.GetSavedQuery1Async();
            var task2 = _comparerSource.GetSavedQuery2Async();

            var list1 = await task1;

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

            var list2 = await task2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, Properties.OrganizationComparerStrings.SavedQueriesInConnectionFormat2, 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", "Name", "QueryType", "IsUserDefined", "IsManaged", "Id");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

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

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

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

            foreach (var query1 in list1)
            {
                {
                    var query2 = list2.FirstOrDefault(query => query.Id == query1.Id);

                    if (query2 != null)
                    {
                        commonList.Add(new LinkedEntities <SavedQuery>(query1, query2));
                        continue;
                    }
                }

                var entityName1 = query1.ReturnedTypeCode;
                var name1       = query1.Name;
                var querytype1  = query1.QueryType.Value;

                var querytypeName1 = SavedQueryRepository.GetQueryTypeName(querytype1);

                tableOnlyExistsIn1.AddLine(
                    entityName1
                    , name1
                    , querytypeName1
                    , query1.IsUserDefined.ToString()
                    , query1.IsManaged.ToString()
                    , query1.Id.ToString());

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.SavedQuery, query1.Id);
            }

            foreach (var query2 in list2)
            {
                {
                    var query1 = list1.FirstOrDefault(query => query.Id == query2.Id);

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

                var entityName2 = query2.ReturnedTypeCode;
                var name2       = query2.Name;
                var querytype2  = query2.QueryType.Value;

                var querytypeName2 = SavedQueryRepository.GetQueryTypeName(querytype2);

                tableOnlyExistsIn2.AddLine(
                    entityName2
                    , name2
                    , querytypeName2
                    , query2.IsUserDefined.ToString()
                    , query2.IsManaged.ToString()
                    , query2.Id.ToString()
                    );

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.SavedQuery, query2.Id);
            }

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

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

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

                    {
                        List <string> fieldsToCompare = new List <string>()
                        {
                            SavedQuery.Schema.Attributes.advancedgroupby
                            , SavedQuery.Schema.Attributes.canbedeleted
                            //, columnsetxml
                            , SavedQuery.Schema.Attributes.componentstate
                            , SavedQuery.Schema.Attributes.conditionalformatting
                            //, SavedQuery.Schema.Attributes.createdby
                            //, SavedQuery.Schema.Attributes.createdon
                            //, SavedQuery.Schema.Attributes.createdonbehalfby
                            , SavedQuery.Schema.Attributes.description
                            //, SavedQuery.Schema.Attributes.fetchxml
                            , SavedQuery.Schema.Attributes.introducedversion
                            , SavedQuery.Schema.Attributes.iscustomizable
                            , SavedQuery.Schema.Attributes.isdefault
                            //, SavedQuery.Schema.Attributes.ismanaged
                            , SavedQuery.Schema.Attributes.isprivate
                            , SavedQuery.Schema.Attributes.isquickfindquery
                            , SavedQuery.Schema.Attributes.isuserdefined
                            //, SavedQuery.Schema.Attributes.layoutxml
                            //, SavedQuery.Schema.Attributes.modifiedby
                            //, SavedQuery.Schema.Attributes.modifiedon
                            //, SavedQuery.Schema.Attributes.modifiedonbehalfby
                            , SavedQuery.Schema.Attributes.name
                            //, SavedQuery.Schema.Attributes.organizationid
                            , SavedQuery.Schema.Attributes.organizationtaborder
                            //, SavedQuery.Schema.Attributes.overwritetime
                            , SavedQuery.Schema.Attributes.queryapi
                            , SavedQuery.Schema.Attributes.queryappusage
                            , SavedQuery.Schema.Attributes.querytype
                            , SavedQuery.Schema.Attributes.returnedtypecode
                            //, SavedQuery.Schema.Attributes.savedqueryid
                            //, SavedQuery.Schema.Attributes.savedqueryidunique
                            //, SavedQuery.Schema.Attributes.solutionid
                            , SavedQuery.Schema.Attributes.statecode
                            , SavedQuery.Schema.Attributes.statuscode
                            //, SavedQuery.Schema.Attributes.supportingsolutionid
                            , SavedQuery.Schema.Attributes.versionnumber
                        };

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

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

                    {
                        List <string> fieldsToCompare = new List <string>()
                        {
                            SavedQuery.Schema.Attributes.fetchxml
                            , SavedQuery.Schema.Attributes.layoutxml
                            , SavedQuery.Schema.Attributes.columnsetxml
                        };

                        foreach (var fieldName in fieldsToCompare)
                        {
                            Action <XElement> action = null;

                            if (string.Equals(fieldName, SavedQuery.Schema.Attributes.layoutxml))
                            {
                                action = ContentComparerHelper.RemoveLayoutObjectCode;
                            }

                            string xml1 = query.Entity1.GetAttributeValue <string>(fieldName) ?? string.Empty;
                            string xml2 = query.Entity2.GetAttributeValue <string>(fieldName) ?? string.Empty;

                            if (!ContentComparerHelper.CompareXML(xml1, xml2, false, action).IsEqual)
                            {
                                string reason = string.Empty;

                                var compare = ContentComparerHelper.CompareXML(xml1.ToLower(), xml2.ToLower(), true, action);

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

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

                    if (tabDiff.Count > 0)
                    {
                        var entityName1 = query.Entity1.ReturnedTypeCode;
                        var name1       = query.Entity1.Name;
                        var querytype1  = query.Entity1.QueryType.Value;

                        var querytypeName1 = SavedQueryRepository.GetQueryTypeName(querytype1);

                        var diff = tabDiff.GetFormatedLines(false);
                        this.ImageBuilder.AddComponentDifferent((int)ComponentType.SavedQuery, query.Entity1.Id, query.Entity2.Id, string.Join(Environment.NewLine, diff));

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

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

                content.AppendLine().AppendLine().AppendFormat("System Saved Queries 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 Saved Queries 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 Saved Queries DIFFERENT in {0} and {1}: {2}", Connection1.Name, Connection2.Name, dictDifference.Count);

                FormatTextTableHandler tableDifference = new FormatTextTableHandler();
                tableDifference.SetHeader("Entity", "Name", "QueryType", "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 Saved Queries.");
            }

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

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

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
        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);
        }
Example #14
0
        private async Task <string> CheckContractTemplates()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

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

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

            Task <List <ContractTemplate> > task1 = _comparerSource.GetContractTemplate1Async();
            Task <List <ContractTemplate> > task2 = _comparerSource.GetContractTemplate2Async();

            List <ContractTemplate> list1 = await task1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Contract Templates in {0}: {1}", Connection1.Name, list1.Count()));

            List <ContractTemplate> list2 = await task2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Contract Templates in {0}: {1}", Connection2.Name, list2.Count()));

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

            List <string> fieldsToCompare = new List <string>()
            {
                ContractTemplate.Schema.Attributes.abbreviation
                , ContractTemplate.Schema.Attributes.allotmenttypecode
                , ContractTemplate.Schema.Attributes.billingfrequencycode
                //, ContractTemplate.Schema.Attributes.componentstate
                , ContractTemplate.Schema.Attributes.contractservicelevelcode
                //, ContractTemplate.Schema.Attributes.contracttemplateid
                //, ContractTemplate.Schema.Attributes.contracttemplateidunique
                //, ContractTemplate.Schema.Attributes.createdby
                //, ContractTemplate.Schema.Attributes.createdon
                //, ContractTemplate.Schema.Attributes.createdonbehalfby
                , ContractTemplate.Schema.Attributes.description
                , ContractTemplate.Schema.Attributes.effectivitycalendar
                //, ContractTemplate.Schema.Attributes.importsequencenumber
                //, ContractTemplate.Schema.Attributes.introducedversion
                , ContractTemplate.Schema.Attributes.iscustomizable
                //, ContractTemplate.Schema.Attributes.ismanaged
                //, ContractTemplate.Schema.Attributes.modifiedby
                //, ContractTemplate.Schema.Attributes.modifiedon
                //, ContractTemplate.Schema.Attributes.modifiedonbehalfby
                , ContractTemplate.Schema.Attributes.name
                //, ContractTemplate.Schema.Attributes.organizationid
                //, ContractTemplate.Schema.Attributes.overriddencreatedon
                //, ContractTemplate.Schema.Attributes.overwritetime
                //, ContractTemplate.Schema.Attributes.solutionid
                //, ContractTemplate.Schema.Attributes.supportingsolutionid
                , ContractTemplate.Schema.Attributes.usediscountaspercentage
                //, ContractTemplate.Schema.Attributes.versionnumber
            };

            List <string> xmlFieldsToCompare = new List <string>()
            {
                //ContractTemplate.Schema.Attributes.body
                //, ContractTemplate.Schema.Attributes.presentationxml
                //, ContractTemplate.Schema.Attributes.subjectpresentationxml
            };

            FormatTextTableHandler tableOnlyExistsIn1 = new FormatTextTableHandler();

            tableOnlyExistsIn1.SetHeader("Name", "Id");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

            tableOnlyExistsIn2.SetHeader("Name", "Id");

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

            foreach (ContractTemplate template1 in list1)
            {
                {
                    ContractTemplate template2 = list2.FirstOrDefault(template => template.Id == template1.Id);

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

                string name1 = template1.Name;

                tableOnlyExistsIn1.AddLine(name1, template1.Id.ToString());

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.ContractTemplate, template1.Id);
            }

            foreach (ContractTemplate template2 in list2)
            {
                {
                    ContractTemplate template1 = list1.FirstOrDefault(template => template.Id == template2.Id);

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

                string name2 = template2.Name;

                tableOnlyExistsIn2.AddLine(name2, template2.Id.ToString());

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.ContractTemplate, template2.Id);
            }

            foreach (ContractTemplate template1 in list1)
            {
                ContractTemplate template2 = list2.FirstOrDefault(template => template.Id == template1.Id);

                if (template2 == null)
                {
                    continue;
                }

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

                foreach (string fieldName in fieldsToCompare)
                {
                    if (ContentComparerHelper.IsEntityDifferentInField(template1, template2, fieldName))
                    {
                        string str1 = EntityDescriptionHandler.GetAttributeString(template1, fieldName, Connection1);
                        string str2 = EntityDescriptionHandler.GetAttributeString(template2, fieldName, Connection2);

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

                foreach (string fieldName in xmlFieldsToCompare)
                {
                    string xml1 = template1.GetAttributeValue <string>(fieldName) ?? string.Empty;
                    string xml2 = template2.GetAttributeValue <string>(fieldName) ?? string.Empty;

                    if (!ContentComparerHelper.CompareXML(xml1, xml2).IsEqual)
                    {
                        string reason = string.Empty;

                        ContentCompareResult compare = ContentComparerHelper.CompareXML(xml1.ToLower(), xml2.ToLower(), true);

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

                        tabDiff.AddLine(fieldName, string.Empty, string.Format(Properties.OrganizationComparerStrings.FieldDifferenceReasonFormat3, Connection1.Name, Connection2.Name, reason));
                    }
                }

                if (tabDiff.Count > 0)
                {
                    string name1 = template1.Name;

                    var diff = tabDiff.GetFormatedLines(false);
                    this.ImageBuilder.AddComponentDifferent((int)ComponentType.ContractTemplate, template1.Id, template2.Id, string.Join(Environment.NewLine, diff));

                    dictDifference.Add(Tuple.Create(name1, template1.Id.ToString()), diff);
                }
            }

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

                content.AppendLine().AppendLine().AppendFormat("Contract Templates 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("Contract Templates 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("Contract Templates DIFFERENT in {0} and {1}: {2}", Connection1.Name, Connection2.Name, dictDifference.Count);

                FormatTextTableHandler tableDifference = new FormatTextTableHandler();
                tableDifference.SetHeader("Title", "Id");

                foreach (KeyValuePair <Tuple <string, string>, List <string> > template in dictDifference)
                {
                    tableDifference.CalculateLineLengths(template.Key.Item1, template.Key.Item2);
                }

                foreach (KeyValuePair <Tuple <string, string>, List <string> > template in dictDifference
                         .OrderBy(w => w.Key.Item1)
                         .ThenBy(w => w.Key.Item2)
                         )
                {
                    content.AppendLine().Append(tabSpacer + tableDifference.FormatLine(template.Key.Item1, template.Key.Item2));

                    foreach (string 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 Contract Templates.");
            }

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

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, "Contract Templates");

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
Example #15
0
        private async Task <string> CheckMailMergeTemplates()
        {
            StringBuilder content = new StringBuilder();

            await _comparerSource.InitializeConnection(_iWriteToOutput, content);

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

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

            Task <List <MailMergeTemplate> > task1 = _comparerSource.GetMailMergeTemplate1Async();
            Task <List <MailMergeTemplate> > task2 = _comparerSource.GetMailMergeTemplate2Async();

            List <MailMergeTemplate> list1 = await task1;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Mail Merge Templates in {0}: {1}", Connection1.Name, list1.Count()));

            List <MailMergeTemplate> list2 = await task2;

            content.AppendLine(_iWriteToOutput.WriteToOutput(null, "Mail Merge Templates in {0}: {1}", Connection2.Name, list2.Count()));

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

            FormatTextTableHandler tableOnlyExistsIn1 = new FormatTextTableHandler();

            tableOnlyExistsIn1.SetHeader("AssociatedEntity", "Name", "Language", "File Name", "Mail Merge Type", "Viewable By", "Owner", "Id");

            FormatTextTableHandler tableOnlyExistsIn2 = new FormatTextTableHandler();

            tableOnlyExistsIn2.SetHeader("AssociatedEntity", "Name", "Language", "File Name", "Mail Merge Type", "Viewable By", "Owner", "Id");

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

            foreach (MailMergeTemplate template1 in list1)
            {
                {
                    MailMergeTemplate template2 = list2.FirstOrDefault(template => template.Id == template1.Id);

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

                string name1       = template1.Name;
                string entityName1 = template1.TemplateTypeCode;
                int    language1   = template1.LanguageCode.Value;

                string filename   = template1.FileName;
                string reportType = template1.FormattedValues.ContainsKey(MailMergeTemplate.Schema.Attributes.mailmergetype) ? template1.FormattedValues[MailMergeTemplate.Schema.Attributes.mailmergetype] : string.Empty;

                Microsoft.Xrm.Sdk.EntityReference ownerRef = template1.OwnerId;
                string owner = string.Empty;

                if (ownerRef != null)
                {
                    owner = ownerRef.Name;
                }

                string ispersonal = template1.FormattedValues.ContainsKey(MailMergeTemplate.Schema.Attributes.ispersonal) ? template1.FormattedValues[MailMergeTemplate.Schema.Attributes.ispersonal] : string.Empty;

                tableOnlyExistsIn1.AddLine(entityName1, name1, LanguageLocale.GetLocaleName(language1), filename, reportType, ispersonal, owner, template1.Id.ToString());

                this.ImageBuilder.AddComponentSolution1((int)ComponentType.MailMergeTemplate, template1.Id);
            }

            foreach (MailMergeTemplate template2 in list2)
            {
                {
                    MailMergeTemplate template1 = list1.FirstOrDefault(template => template.Id == template2.Id);

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

                string name2       = template2.Name;
                string entityName2 = template2.TemplateTypeCode;
                int    language2   = template2.LanguageCode.Value;

                string filename     = template2.FileName;
                string templateType = template2.FormattedValues.ContainsKey(MailMergeTemplate.Schema.Attributes.mailmergetype) ? template2.FormattedValues[MailMergeTemplate.Schema.Attributes.mailmergetype] : string.Empty;

                Microsoft.Xrm.Sdk.EntityReference ownerRef = template2.OwnerId;
                string owner = string.Empty;

                if (ownerRef != null)
                {
                    owner = ownerRef.Name;
                }

                string ispersonal = template2.FormattedValues.ContainsKey(MailMergeTemplate.Schema.Attributes.ispersonal) ? template2.FormattedValues[MailMergeTemplate.Schema.Attributes.ispersonal] : string.Empty;

                tableOnlyExistsIn2.AddLine(entityName2, name2, LanguageLocale.GetLocaleName(language2), filename, templateType, ispersonal, owner, template2.Id.ToString());

                this.ImageBuilder.AddComponentSolution2((int)ComponentType.MailMergeTemplate, template2.Id);
            }

            foreach (MailMergeTemplate template1 in list1)
            {
                MailMergeTemplate template2 = list2.FirstOrDefault(template => template.Id == template1.Id);

                if (template2 == null)
                {
                    continue;
                }

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

                foreach (string fieldName in _fieldsToCompareMailMergeTemplateOrdinal)
                {
                    if (ContentComparerHelper.IsEntityDifferentInField(template1, template2, fieldName))
                    {
                        string str1 = EntityDescriptionHandler.GetAttributeString(template1, fieldName, Connection1);
                        string str2 = EntityDescriptionHandler.GetAttributeString(template2, fieldName, Connection2);

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

                foreach (string fieldName in _fieldsToCompareMailMergeTemplateXml)
                {
                    string xml1 = template1.GetAttributeValue <string>(fieldName) ?? string.Empty;
                    string xml2 = template2.GetAttributeValue <string>(fieldName) ?? string.Empty;

                    if (!ContentComparerHelper.CompareXML(xml1, xml2).IsEqual)
                    {
                        string reason = string.Empty;

                        ContentCompareResult compare = ContentComparerHelper.CompareXML(xml1.ToLower(), xml2.ToLower(), true);

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

                        tabDiff.AddLine(fieldName, string.Empty, string.Format(Properties.OrganizationComparerStrings.FieldDifferenceReasonFormat3, Connection1.Name, Connection2.Name, reason));
                    }
                }

                if (tabDiff.Count > 0)
                {
                    string name1       = template1.Name;
                    string entityName1 = template1.TemplateTypeCode;
                    int    language1   = template1.LanguageCode.Value;

                    var diff = tabDiff.GetFormatedLines(false);
                    this.ImageBuilder.AddComponentDifferent((int)ComponentType.MailMergeTemplate, template1.Id, template2.Id, string.Join(Environment.NewLine, diff));

                    dictDifference.Add(Tuple.Create(entityName1, name1, LanguageLocale.GetLocaleName(language1), template1.Id.ToString()), diff);
                }
            }

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

                content.AppendLine().AppendLine().AppendFormat("Mail Merge Templates 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("Mail Merge Templates 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("Mail Merge Templates DIFFERENT in {0} and {1}: {2}", Connection1.Name, Connection2.Name, dictDifference.Count);

                FormatTextTableHandler tableDifference = new FormatTextTableHandler();
                tableDifference.SetHeader("AssociatedEntity", "Name", "Language", "Id");

                foreach (KeyValuePair <Tuple <string, string, string, string>, List <string> > template in dictDifference)
                {
                    tableDifference.CalculateLineLengths(template.Key.Item1, template.Key.Item2, template.Key.Item3, template.Key.Item4);
                }

                foreach (KeyValuePair <Tuple <string, string, string, string>, List <string> > 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 (string 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 Mail Merge Templates.");
            }

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

            string fileName = EntityFileNameFormatter.GetDifferenceConnectionsForFieldFileName(_OrgOrgName, "Mail Merge Templates");

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

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

            await SaveOrganizationDifferenceImage();

            return(filePath);
        }
Example #16
0
        private async Task <IEnumerable <Guid> > GetDescriptionWithUsedNotExistsEntitiesInAllWorkflows(StringBuilder strFile)
        {
            HashSet <Guid> workflowsWithEntities = new HashSet <Guid>();

            try
            {
                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty);
                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty);

                strFile.AppendLine(this._iWriteToOutput.WriteToOutputStartOperation(_service.ConnectionData, Properties.OperationNames.AnalyzingWorkflowsFormat1, _service.ConnectionData.Name));

                SolutionComponentRepository repository = new SolutionComponentRepository(_service);

                Dictionary <EntityReference, HashSet <Guid> > list = new Dictionary <EntityReference, HashSet <Guid> >();

                var handler = new WorkflowUsedEntitiesHandler();

                var repositoryWorkflow = new WorkflowRepository(_service);

                {
                    var workflows = await repositoryWorkflow.GetListAsync(null, null, null, null, new ColumnSet(Workflow.Schema.Attributes.xaml));

                    _descriptor.GetEntities <Workflow>((int)ComponentType.Workflow, workflows.Select(c => c.Id));

                    foreach (var item in workflows)
                    {
                        var xmlContent = ContentComparerHelper.RemoveDiacritics(item.Xaml);

                        var doc = XElement.Parse(xmlContent);

                        var coll = await handler.GetWorkflowUsedEntitiesAsync(doc);

                        if (coll.Count > 0)
                        {
                            workflowsWithEntities.Add(item.Id);

                            foreach (var entityRef in coll)
                            {
                                HashSet <Guid> linkedWorkflows = null;

                                if (list.ContainsKey(entityRef))
                                {
                                    linkedWorkflows = list[entityRef];
                                }
                                else
                                {
                                    list[entityRef] = linkedWorkflows = new HashSet <Guid>();
                                }

                                linkedWorkflows.Add(item.Id);
                            }
                        }
                    }
                }

                await FillDescriptionNotExistsEntities(strFile, workflowsWithEntities, list);

                strFile.AppendLine(this._iWriteToOutput.WriteToOutputEndOperation(_service.ConnectionData, Properties.OperationNames.AnalyzingWorkflowsFormat1, _service.ConnectionData.Name));
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }

            return(workflowsWithEntities);
        }
Example #17
0
        private async Task GetDescriptionWithUsedEntitiesInSolutionWorkflows(StringBuilder strFile, Guid idSolution)
        {
            try
            {
                var repositorySolution = new SolutionRepository(_service);

                var solution = await repositorySolution.GetSolutionByIdAsync(idSolution);

                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty);
                this._iWriteToOutput.WriteToOutput(_service.ConnectionData, string.Empty);

                strFile.AppendLine(this._iWriteToOutput.WriteToOutputStartOperation(_service.ConnectionData, Properties.OperationNames.AnalyzingSolutionWorkflowsFormat2, _service.ConnectionData.Name, solution.UniqueName));

                SolutionComponentRepository repository = new SolutionComponentRepository(_service);

                var repositoryWorkflow = new WorkflowRepository(_service);

                HashSet <Guid> workflowsWithEntities = new HashSet <Guid>();

                Dictionary <EntityReference, HashSet <Guid> > list = new Dictionary <EntityReference, HashSet <Guid> >();

                var handler = new WorkflowUsedEntitiesHandler();

                {
                    var components = await repository.GetSolutionComponentsByTypeAsync(solution.Id, ComponentType.Workflow, new ColumnSet(SolutionComponent.Schema.Attributes.objectid));

                    _descriptor.GetEntities <Workflow>((int)ComponentType.Workflow, components.Select(c => c.ObjectId));

                    var workflows = await repositoryWorkflow.GetListByIdListAsync(components.Select(en => en.ObjectId.Value), new ColumnSet(Workflow.Schema.Attributes.xaml));

                    foreach (var item in workflows)
                    {
                        if (string.IsNullOrEmpty(item.Xaml))
                        {
                            continue;
                        }

                        var xmlContent = ContentComparerHelper.RemoveDiacritics(item.Xaml);

                        var doc = XElement.Parse(xmlContent);

                        var coll = await handler.GetWorkflowUsedEntitiesAsync(doc);

                        if (coll.Count > 0)
                        {
                            workflowsWithEntities.Add(item.Id);

                            foreach (var entityRef in coll)
                            {
                                HashSet <Guid> linkedWorkflows = null;

                                if (list.ContainsKey(entityRef))
                                {
                                    linkedWorkflows = list[entityRef];
                                }
                                else
                                {
                                    list[entityRef] = linkedWorkflows = new HashSet <Guid>();
                                }

                                linkedWorkflows.Add(item.Id);
                            }
                        }
                    }
                }

                {
                    var components = await repository.GetSolutionComponentsByTypeAsync(solution.Id, ComponentType.Entity, new ColumnSet(SolutionComponent.Schema.Attributes.objectid));

                    var listMetadata = _descriptor.MetadataSource.GetEntityMetadataList(components.Where(e => e.ObjectId.HasValue).Select(e => e.ObjectId.Value));

                    foreach (var entityMetadata in listMetadata)
                    {
                        var workflows = await repositoryWorkflow.GetListAsync(entityMetadata.LogicalName, Workflow.Schema.OptionSets.category.Business_Rule_2, null, null, new ColumnSet(Workflow.Schema.Attributes.xaml));

                        foreach (var item in workflows)
                        {
                            if (!string.IsNullOrEmpty(item.Xaml) && !workflowsWithEntities.Contains(item.Id))
                            {
                                var xmlContent = ContentComparerHelper.RemoveDiacritics(item.Xaml);

                                var doc = XElement.Parse(xmlContent);

                                var coll = await handler.GetWorkflowUsedEntitiesAsync(doc);

                                if (coll.Count > 0)
                                {
                                    workflowsWithEntities.Add(item.Id);

                                    foreach (var entityRef in coll)
                                    {
                                        HashSet <Guid> linkedWorkflows = null;

                                        if (list.ContainsKey(entityRef))
                                        {
                                            linkedWorkflows = list[entityRef];
                                        }
                                        else
                                        {
                                            list[entityRef] = linkedWorkflows = new HashSet <Guid>();
                                        }

                                        linkedWorkflows.Add(item.Id);
                                    }
                                }
                            }
                        }
                    }
                }

                await FillDescriptionUsedEntities(strFile, workflowsWithEntities, list);

                strFile.AppendLine(this._iWriteToOutput.WriteToOutputEndOperation(_service.ConnectionData, Properties.OperationNames.AnalyzingSolutionWorkflowsFormat2, _service.ConnectionData.Name, solution.UniqueName));
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }
        }
Example #18
0
        public static ContentCompareResult CompareWorkflowXAML(string xml1, string xml2, LabelReplacer rep1, LabelReplacer rep2, bool withDetails = false)
        {
            try
            {
                xml1 = xml1 ?? string.Empty;
                xml2 = xml2 ?? string.Empty;

                xml1 = ContentComparerHelper.RemoveDiacritics(xml1);
                xml2 = ContentComparerHelper.RemoveDiacritics(xml2);

                diff_match_patch match = new diff_match_patch
                {
                    Diff_Timeout = ContentComparerHelper.Diff_Timeout
                };

                if (string.IsNullOrEmpty(xml1) && string.IsNullOrEmpty(xml2))
                {
                    return(new ContentCompareResult(true, null));
                }

                if (string.IsNullOrEmpty(xml1) && !string.IsNullOrEmpty(xml2))
                {
                    return(new ContentCompareResult(false, match.diff_main(xml1, xml2, false)));
                }

                if (!string.IsNullOrEmpty(xml1) && string.IsNullOrEmpty(xml2))
                {
                    return(new ContentCompareResult(false, match.diff_main(xml1, xml2, false)));
                }

                if (!TryParseXml(xml1, out XElement doc1) || !TryParseXml(xml2, out XElement doc2))
                {
                    bool isEqual = string.Equals(xml1, xml2);

                    if (isEqual)
                    {
                        return(new ContentCompareResult(true, null));
                    }
                    else
                    {
                        if (withDetails)
                        {
                            return(new ContentCompareResult(false, match.diff_main(xml1, xml2, false)));
                        }
                        else
                        {
                            return(new ContentCompareResult(false, null));
                        }
                    }
                }

                RemoveEmptyElements(doc1);
                RemoveEmptyElements(doc2);

                RenameClasses(doc1);
                RenameClasses(doc2);

                WorkflowUsedEntitiesHandler.ReplaceGuids(doc1);
                WorkflowUsedEntitiesHandler.ReplaceGuids(doc2);

                if (rep1 != null)
                {
                    rep1.FullfillLabelsForWorkflow(doc1);
                }

                if (rep2 != null)
                {
                    rep2.FullfillLabelsForWorkflow(doc2);
                }

                {
                    bool isEqual = XNode.DeepEquals(doc1, doc2);

                    if (isEqual)
                    {
                        return(new ContentCompareResult(true, null));
                    }
                    else
                    {
                        if (withDetails)
                        {
                            return(new ContentCompareResult(false, match.diff_main(doc1.ToString(), doc2.ToString(), false)));
                        }
                        else
                        {
                            return(new ContentCompareResult(false, null));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(null, ex);

#if DEBUG
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debugger.Break();
                }
#endif

                throw;
            }
        }
Example #19
0
        public static ContentCompareResult CompareXML(string xml1, string xml2, bool withDetails = false, Action <XElement> action = null)
        {
            try
            {
                xml1 = xml1 ?? string.Empty;
                xml2 = xml2 ?? string.Empty;

                xml1 = ContentComparerHelper.RemoveDiacritics(xml1);
                xml2 = ContentComparerHelper.RemoveDiacritics(xml2);

                diff_match_patch match = new diff_match_patch
                {
                    Diff_Timeout = ContentComparerHelper.Diff_Timeout
                };

                if (string.IsNullOrEmpty(xml1) && string.IsNullOrEmpty(xml2))
                {
                    return(new ContentCompareResult(true, null));
                }

                if (string.IsNullOrEmpty(xml1) && !string.IsNullOrEmpty(xml2))
                {
                    return(new ContentCompareResult(false, match.diff_main(xml1, xml2, false)));
                }

                if (!string.IsNullOrEmpty(xml1) && string.IsNullOrEmpty(xml2))
                {
                    return(new ContentCompareResult(false, match.diff_main(xml1, xml2, false)));
                }

                if (!TryParseXml(xml1, out XElement doc1) || !TryParseXml(xml2, out XElement doc2))
                {
                    bool isEqual = string.Equals(xml1, xml2);

                    if (isEqual)
                    {
                        return(new ContentCompareResult(true, null));
                    }
                    else
                    {
                        if (withDetails)
                        {
                            return(new ContentCompareResult(false, match.diff_main(xml1, xml2, false)));
                        }
                        else
                        {
                            return(new ContentCompareResult(false, null));
                        }
                    }
                }

                RemoveEmptyXMLText(doc1);
                RemoveEmptyXMLText(doc2);

                SortXmlAttributesInternal(doc1);
                SortXmlAttributesInternal(doc2);

                SortRibbonCommandsAndRulesByIdInternal(doc1);
                SortRibbonCommandsAndRulesByIdInternal(doc2);

                SortFormXmlElementsInternal(doc1);
                SortFormXmlElementsInternal(doc2);

                if (action != null)
                {
                    action(doc1);
                    action(doc2);
                }

                {
                    bool isEqual = XNode.DeepEquals(doc1, doc2);

                    if (isEqual)
                    {
                        return(new ContentCompareResult(true, null));
                    }
                    else
                    {
                        if (withDetails)
                        {
                            return(new ContentCompareResult(false, match.diff_main(doc1.ToString(), doc2.ToString(), false)));
                        }
                        else
                        {
                            return(new ContentCompareResult(false, null));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                DTEHelper.WriteExceptionToOutput(null, ex);

#if DEBUG
                if (System.Diagnostics.Debugger.IsAttached)
                {
                    System.Diagnostics.Debugger.Break();
                }
#endif

                throw;
            }
        }
Example #20
0
        private string ParseJavaScriptCode()
        {
            JavaScriptParser parser = new JavaScriptParser();

            var prog = parser.Parse(this._javaScriptCode);

            var engine = new Engine();

            bool resultFillParameters = FillParameters(engine, prog, out var varName);

            bool executed = false;

            int count = 0;

            while (!executed && count < 1000)
            {
                try
                {
                    engine.Execute(prog);

                    executed = true;
                }
                catch (Jint.Runtime.JavaScriptException ex)
                {
                    count++;

                    bool exceptionHandled = false;

                    if (ex.Error.IsObject())
                    {
                        var obj = ex.Error.AsObject();

                        if (string.Equals(obj.Class, "Error", StringComparison.InvariantCultureIgnoreCase))
                        {
                            var name    = obj.GetOwnProperty("name");
                            var message = obj.GetOwnProperty("message");

                            if (name != null && message != null && name.Value.IsString() && message.Value.IsString())
                            {
                                var nameValue    = name.Value.AsString();
                                var messageValue = message.Value.AsString();

                                exceptionHandled = HandleException(engine, nameValue, messageValue);
                            }
                        }
                    }

                    if (!exceptionHandled)
                    {
                        _iWriteToOutput.WriteErrorToOutput(null, ex);

                        executed = false;

                        break;
                    }
                }
                catch (Exception ex)
                {
                    _iWriteToOutput.WriteErrorToOutput(null, ex);

                    executed = false;

                    break;
                }
            }

            string result = string.Empty;

            if (executed)
            {
                var lastVar = engine.Global.GetOwnProperty(varName);

                if (lastVar != null)
                {
                    result = lastVar.Value.AsString();

                    if (!string.IsNullOrEmpty(result))
                    {
                        var commonConfig = Model.CommonConfiguration.Get();

                        result = ContentComparerHelper.FormatXmlByConfiguration(
                            result
                            , commonConfig
                            , XmlOptionsControls.SavedQueryXmlOptions
                            , schemaName: Commands.AbstractDynamicCommandXsdSchemas.FetchSchema
                            );
                    }
                }
            }

            return(result);
        }
Example #21
0
        public async Task GetDescriptionEntitesAndAttributesInWorkflowAsync(StringBuilder strFile, Guid idWorkflow)
        {
            try
            {
                var repository = new WorkflowRepository(_service);

                var workflow = await repository.GetByIdAsync(idWorkflow, ColumnSetInstances.AllColumns);

                string xmlContent = ContentComparerHelper.RemoveDiacritics(workflow.Xaml);

                var doc = XElement.Parse(xmlContent);

                var handler = new WorkflowUsedEntitiesHandler();

                strFile
                .AppendFormat("Entity:   {0}", workflow.PrimaryEntity).AppendLine()
                .AppendFormat("Category: {0}", workflow.FormattedValues[Workflow.Schema.Attributes.category]).AppendLine()
                .AppendFormat("Name:     {0}", workflow.Name).AppendLine()
                .AppendFormat("Url:      {0}", _service.UrlGenerator.GetSolutionComponentUrl(ComponentType.Workflow, idWorkflow)).AppendLine()
                .AppendLine()
                ;

                WorkflowAnalysis analysis = handler.GetWorkflowAnalysis(doc);

                if (analysis.UsedEntityAttributes.Any())
                {
                    strFile
                    .AppendLine()
                    .AppendLine()
                    .AppendLine()
                    .AppendLine(new string('-', 150))
                    .AppendLine()
                    .AppendLine()
                    .AppendLine()
                    ;

                    var tableUsedAttributes = new FormatTextTableHandler();
                    tableUsedAttributes.SetHeader("Entity", "Attribute", "StepName");

                    foreach (var step in analysis.UsedEntityAttributes
                             .OrderBy(e => e.EntityName)
                             .ThenBy(e => e.Attribute)
                             .ThenBy(e => e.DisplayName)
                             )
                    {
                        tableUsedAttributes.AddLine(step.EntityName, step.Attribute, step.DisplayName);
                    }

                    strFile.AppendFormat("Used Attributes: {0}", analysis.UsedEntityAttributes.Count).AppendLine();

                    tableUsedAttributes.GetFormatedLines(false).ForEach(s => strFile.AppendLine(tabspacer + s));
                }

                if (analysis.CreateUpdateEntitySteps.Any())
                {
                    strFile
                    .AppendLine()
                    .AppendLine()
                    .AppendLine()
                    .AppendLine(new string('-', 150))
                    .AppendLine()
                    .AppendLine()
                    .AppendLine()
                    ;

                    strFile.AppendFormat("Created or Updated Entities {0}", analysis.CreateUpdateEntitySteps.Count).AppendLine();

                    foreach (var step in analysis.CreateUpdateEntitySteps)
                    {
                        strFile.AppendFormat("Entity {0}    Operation {1}    StepName {2}    With Attributes {2}", step.EntityName, step.StepType, step.DisplayName, step.SetEntityPropertySteps.Count).AppendLine()
                        ;

                        var tableUsedAttributes = new FormatTextTableHandler();
                        tableUsedAttributes.SetHeader("Attribute");

                        foreach (var stepSet in step.SetEntityPropertySteps
                                 .OrderBy(e => e.EntityName)
                                 .ThenBy(e => e.Attribute)
                                 )
                        {
                            tableUsedAttributes.AddLine(stepSet.Attribute);
                        }

                        tableUsedAttributes.GetFormatedLines(false).ForEach(s => strFile.AppendLine(tabspacer + s));

                        strFile.AppendLine().AppendLine();
                    }
                }
            }
            catch (Exception ex)
            {
                this._iWriteToOutput.WriteErrorToOutput(_service.ConnectionData, ex);
            }
        }