Beispiel #1
0
        private async Task ShowingWebResourcesDependentComponents(ConnectionData connectionData, CommonConfiguration commonConfig, List <SelectedFile> selectedFiles)
        {
            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            StringBuilder content = new StringBuilder();

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

            var descriptor = new SolutionComponentDescriptor(service);

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

            var descriptorHandler = new DependencyDescriptionHandler(descriptor);

            var dependencyRepository = new DependencyRepository(service);

            bool isconnectionDataDirty = false;

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

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

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

            WebResourceRepository repositoryWebResource = new WebResourceRepository(service);

            FormatTextTableHandler tableWithoutDependenComponents = new FormatTextTableHandler();

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

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

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

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

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

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

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

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

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

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

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

                            var desc = await descriptorHandler.GetDescriptionDependentAsync(coll);

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

                                webResourceNames.Add(component);

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

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

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

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

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

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

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

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

            commonConfig.CheckFolderForExportExists(this._iWriteToOutput);

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

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

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

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

            this._iWriteToOutput.PerformAction(service.ConnectionData, filePath);
        }
Beispiel #2
0
        private async Task UpdatingReport(SelectedFile selectedFile, ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            if (connectionData.IsReadOnly)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionIsReadOnlyFormat1, connectionData.Name);
                return;
            }

            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            bool isconnectionDataDirty = false;

            // Репозиторий для работы с веб-ресурсами
            ReportRepository reportRepository = new ReportRepository(service);

            if (File.Exists(selectedFile.FilePath))
            {
                Report reportEntity = null;

                reportEntity = await reportRepository.FindAsync(selectedFile.FileName);

                if (reportEntity != null)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Report founded by name.");

                    isconnectionDataDirty = true;
                    connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);
                }
                else
                {
                    Guid?lastReportId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                    this._iWriteToOutput.WriteToOutput(connectionData, "Starting Custom Report selection form.");

                    bool?dialogResult     = null;
                    Guid?selectedReportId = null;

                    string selectedPath = string.Empty;
                    var    t            = new Thread((ThreadStart)(() =>
                    {
                        try
                        {
                            var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, lastReportId);

                            dialogResult = form.ShowDialog();
                            selectedReportId = form.SelectedReportId;
                        }
                        catch (Exception ex)
                        {
                            DTEHelper.WriteExceptionToOutput(connectionData, ex);
                        }
                    }));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();

                    t.Join();

                    if (dialogResult.GetValueOrDefault())
                    {
                        if (selectedReportId.HasValue)
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "Custom report is selected.");

                            reportEntity = await reportRepository.GetByIdAsync(selectedReportId.Value);

                            isconnectionDataDirty = true;
                            connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. Report not exists. name: {0}.", selectedFile.Name);
                        }
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Updating was cancelled.");
                        return;
                    }
                }

                if (reportEntity != null)
                {
                    var update = new Entity(Report.EntityLogicalName);
                    update.Id = reportEntity.Id;

                    update.Attributes[Report.Schema.Attributes.bodytext] = File.ReadAllText(selectedFile.FilePath);

                    await service.UpdateAsync(update);

                    this._iWriteToOutput.WriteToOutput(connectionData, "Report updated in CRM: {0} - {1} - {2}", reportEntity.Name, reportEntity.FileName, reportEntity.ReportNameOnSRS);
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ReportNotFoundedInConnectionFormat2, connectionData.Name, selectedFile.FileName);
                }
            }
            else
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
            }

            if (isconnectionDataDirty)
            {
                //Сохранение настроек после публикации
                connectionData.Save();
            }
        }
        private async Task ThreeFileDifferenceReport(SelectedFile selectedFile, string fieldName, string fieldTitle, ConnectionData connectionData1, ConnectionData connectionData2, ShowDifferenceThreeFileType differenceType, CommonConfiguration commonConfig)
        {
            if (differenceType == ShowDifferenceThreeFileType.ThreeWay)
            {
                if (!File.Exists(selectedFile.FilePath))
                {
                    this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                    return;
                }
            }

            var doubleConnection = await ConnectAndWriteToOutputDoubleConnectionAsync(connectionData1, connectionData2);

            if (doubleConnection == null)
            {
                return;
            }

            var service1 = doubleConnection.Item1;
            var service2 = doubleConnection.Item2;

            if (string.IsNullOrEmpty(fieldName))
            {
                fieldName  = Report.Schema.Attributes.originalbodytext;
                fieldTitle = Report.Schema.Headers.originalbodytext;
            }

            // Репозиторий для работы с веб-ресурсами
            ReportRepository reportRepository1 = new ReportRepository(service1);
            ReportRepository reportRepository2 = new ReportRepository(service2);

            var taskReport1 = reportRepository1.FindAsync(selectedFile.FileName);
            var taskReport2 = reportRepository2.FindAsync(selectedFile.FileName);

            Report reportEntity1 = await taskReport1;
            Report reportEntity2 = await taskReport2;

            if (reportEntity1 != null)
            {
                this._iWriteToOutput.WriteToOutput(null, "{0}: Report founded by name.", connectionData1.Name);

                connectionData1.AddMapping(reportEntity1.Id, selectedFile.FriendlyFilePath);

                connectionData1.Save();
            }
            else
            {
                Guid?reportId = connectionData1.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                if (reportId.HasValue)
                {
                    reportEntity1 = await reportRepository1.GetByIdAsync(reportId.Value);

                    if (reportEntity1 != null)
                    {
                        this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded by name. Last link report is selected for difference.", connectionData1.Name);

                        connectionData1.AddMapping(reportEntity1.Id, selectedFile.FriendlyFilePath);

                        connectionData1.Save();
                    }
                }
            }

            if (reportEntity2 != null)
            {
                this._iWriteToOutput.WriteToOutput(null, "{0}: Report founded by name.", connectionData2.Name);

                connectionData2.AddMapping(reportEntity2.Id, selectedFile.FriendlyFilePath);

                connectionData2.Save();
            }
            else
            {
                Guid?reportId = connectionData2.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                if (reportId.HasValue)
                {
                    reportEntity2 = await reportRepository2.GetByIdAsync(reportId.Value);

                    if (reportEntity2 != null)
                    {
                        this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded by name. Last link report is selected for difference.", connectionData2.Name);

                        connectionData2.AddMapping(reportEntity2.Id, selectedFile.FriendlyFilePath);

                        connectionData2.Save();
                    }
                }
            }

            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
            }

            if (reportEntity1 == null)
            {
                this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded in CRM: {1}", connectionData1.Name, selectedFile.FileName);
            }

            if (reportEntity2 == null)
            {
                this._iWriteToOutput.WriteToOutput(null, "{0}: Report not founded in CRM: {1}", connectionData2.Name, selectedFile.FileName);
            }

            string fileLocalPath  = selectedFile.FilePath;
            string fileLocalTitle = selectedFile.FileName;

            string filePath1  = string.Empty;
            string fileTitle1 = string.Empty;

            string filePath2  = string.Empty;
            string fileTitle2 = string.Empty;

            if (reportEntity1 != null)
            {
                var textReport = reportEntity1.GetAttributeValue <string>(fieldName);

                if (ContentComparerHelper.TryParseXml(textReport, out var doc))
                {
                    textReport = doc.ToString();
                }

                var reportName = EntityFileNameFormatter.GetReportFileName(connectionData1.Name, reportEntity1.Name, reportEntity1.Id, fieldTitle, selectedFile.Extension);

                filePath1  = FileOperations.GetNewTempFilePath(Path.GetFileNameWithoutExtension(reportName), selectedFile.Extension);
                fileTitle1 = connectionData1.Name + "." + selectedFile.FileName + " - " + filePath1;

                File.WriteAllText(filePath1, textReport, new UTF8Encoding(false));
            }

            if (reportEntity2 != null)
            {
                var textReport = reportEntity2.GetAttributeValue <string>(fieldName);

                if (ContentComparerHelper.TryParseXml(textReport, out var doc))
                {
                    textReport = doc.ToString();
                }

                var reportName = EntityFileNameFormatter.GetReportFileName(connectionData2.Name, reportEntity2.Name, reportEntity2.Id, fieldTitle, selectedFile.Extension);

                filePath2  = FileOperations.GetNewTempFilePath(Path.GetFileNameWithoutExtension(reportName), selectedFile.Extension);
                fileTitle1 = connectionData2.Name + "." + selectedFile.FileName + " - " + filePath2;

                File.WriteAllText(filePath2, textReport, new UTF8Encoding(false));
            }

            switch (differenceType)
            {
            case ShowDifferenceThreeFileType.OneByOne:
                ShowDifferenceOneByOne(commonConfig, connectionData1, connectionData2, fileLocalPath, fileLocalTitle, filePath1, fileTitle1, filePath2, fileTitle2);
                break;

            case ShowDifferenceThreeFileType.TwoConnections:
                await this._iWriteToOutput.ProcessStartProgramComparerAsync(connectionData1, filePath1, filePath2, fileTitle1, fileTitle2, connectionData2);

                break;

            case ShowDifferenceThreeFileType.ThreeWay:
                ShowDifferenceThreeWay(commonConfig, connectionData1, connectionData2, fileLocalPath, fileLocalTitle, filePath1, fileTitle1, filePath2, fileTitle2);
                break;

            default:
                break;
            }
        }
        private async Task OpeningReport(CommonConfiguration commonConfig, ConnectionData connectionData, SelectedFile selectedFile, ActionOnComponent actionOnComponent)
        {
            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                return;
            }

            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            // Репозиторий для работы с веб-ресурсами
            ReportRepository reportRepository = new ReportRepository(service);

            Report reportEntity = await reportRepository.FindAsync(selectedFile.FileName);

            if (reportEntity != null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ReportFoundedByNameFormat2, reportEntity.Id.ToString(), reportEntity.Name);

                connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                connectionData.Save();
            }
            else
            {
                Guid?reportId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                if (reportId.HasValue)
                {
                    reportEntity = await reportRepository.GetByIdAsync(reportId.Value);
                }

                if (reportEntity != null)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Report not founded by name. Last link report is selected for opening.");

                    connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                    connectionData.Save();
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Report not founded by name and has not Last link.");
                    this._iWriteToOutput.WriteToOutput(connectionData, "Starting Custom Report selection form.");

                    bool?dialogResult     = null;
                    Guid?selectedReportId = null;

                    string selectedPath = string.Empty;
                    var    thread       = new Thread(() =>
                    {
                        try
                        {
                            var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, reportId);

                            dialogResult     = form.ShowDialog();
                            selectedReportId = form.SelectedReportId;
                        }
                        catch (Exception ex)
                        {
                            DTEHelper.WriteExceptionToOutput(connectionData, ex);
                        }
                    });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();

                    thread.Join();

                    if (dialogResult.GetValueOrDefault())
                    {
                        if (selectedReportId.HasValue)
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "Custom report is selected.");

                            reportEntity = await reportRepository.GetByIdAsync(selectedReportId.Value);

                            connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                            connectionData.Save();
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. Report not exists. name: {0}.", selectedFile.Name);
                        }
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Opening was cancelled.");
                        return;
                    }
                }
            }

            if (reportEntity == null)
            {
                service.TryDispose();

                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ReportNotFoundedByNameFormat1, selectedFile.FileName);
                return;
            }

            if (actionOnComponent == ActionOnComponent.OpenInWeb)
            {
                service.UrlGenerator.OpenSolutionComponentInWeb(Entities.ComponentType.Report, reportEntity.Id);
                service.TryDispose();
            }
            else if (actionOnComponent == ActionOnComponent.OpenDependentComponentsInWeb)
            {
                connectionData.OpenSolutionComponentDependentComponentsInWeb(Entities.ComponentType.Report, reportEntity.Id);
                service.TryDispose();
            }
            else if (actionOnComponent == ActionOnComponent.OpenDependentComponentsInExplorer)
            {
                WindowHelper.OpenSolutionComponentDependenciesExplorer(
                    _iWriteToOutput
                    , service
                    , null
                    , commonConfig
                    , (int)ComponentType.Report
                    , reportEntity.Id
                    , null);
            }
            else if (actionOnComponent == ActionOnComponent.OpenSolutionsListWithComponentInExplorer)
            {
                WindowHelper.OpenExplorerSolutionExplorer(
                    _iWriteToOutput
                    , service
                    , commonConfig
                    , (int)ComponentType.Report
                    , reportEntity.Id
                    , null
                    );
            }
        }
Beispiel #5
0
        private async Task OpeningWebResource(CommonConfiguration commonConfig, ConnectionData connectionData, SelectedFile selectedFile, ActionOpenComponent action)
        {
            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                return;
            }

            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

            WebResource webresource = await webResourceRepository.FindByNameAsync(selectedFile.FriendlyFilePath, selectedFile.Extension);

            if (webresource != null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.WebResourceFoundedByNameFormat2, webresource.Id.ToString(), webresource.Name);

                connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                connectionData.Save();
            }
            else
            {
                Guid?webId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

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

                if (webresource != null)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Web-resource not founded by name. Last link web-resource is selected for opening.");

                    connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                    connectionData.Save();
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Web-resource not founded by name and has not Last link.");
                    this._iWriteToOutput.WriteToOutput(connectionData, "Starting Custom Web-resource selection form.");

                    bool?dialogResult          = null;
                    Guid?selectedWebResourceId = null;

                    string selectedPath = string.Empty;
                    var    t            = new Thread((ThreadStart)(() =>
                    {
                        try
                        {
                            var form = new Views.WindowWebResourceSelectOrCreate(this._iWriteToOutput, service, selectedFile, webId);

                            dialogResult = form.ShowDialog();
                            selectedWebResourceId = form.SelectedWebResourceId;
                        }
                        catch (Exception ex)
                        {
                            DTEHelper.WriteExceptionToOutput(connectionData, ex);
                        }
                    }));
                    t.SetApartmentState(ApartmentState.STA);
                    t.Start();

                    t.Join();

                    if (dialogResult.GetValueOrDefault())
                    {
                        if (selectedWebResourceId.HasValue)
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "Custom Web-resource is selected.");

                            webresource = await webResourceRepository.GetByIdAsync(selectedWebResourceId.Value);

                            connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                            connectionData.Save();
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. WebResource not exists. name: {0}.", selectedFile.Name);
                        }
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Opening was cancelled.");
                        return;
                    }
                }
            }

            if (webresource == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.WebResourceNotFoundedByNameFormat1, selectedFile.FileName);
                return;
            }

            if (action == ActionOpenComponent.OpenInWeb)
            {
                service.UrlGenerator.OpenSolutionComponentInWeb(Entities.ComponentType.WebResource, webresource.Id);
            }
            else if (action == ActionOpenComponent.OpenDependentComponentsInWeb)
            {
                connectionData.OpenSolutionComponentDependentComponentsInWeb(Entities.ComponentType.WebResource, webresource.Id);
            }
            else if (action == ActionOpenComponent.OpenDependentComponentsInExplorer)
            {
                WindowHelper.OpenSolutionComponentDependenciesExplorer(
                    _iWriteToOutput
                    , service
                    , null
                    , commonConfig
                    , (int)ComponentType.WebResource
                    , webresource.Id
                    , null);
            }
            else if (action == ActionOpenComponent.OpenSolutionsContainingComponentInExplorer)
            {
                WindowHelper.OpenExplorerSolutionExplorer(
                    _iWriteToOutput
                    , service
                    , commonConfig
                    , (int)ComponentType.WebResource
                    , webresource.Id
                    , null
                    );
            }
        }
        private async Task DifferenceReport(ConnectionData connectionData, CommonConfiguration commonConfig, SelectedFile selectedFile, string fieldName, string fieldTitle, bool withSelect)
        {
            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                return;
            }

            var service = await ConnectAndWriteToOutputAsync(connectionData);

            if (service == null)
            {
                return;
            }

            if (string.IsNullOrEmpty(fieldName))
            {
                fieldName  = Report.Schema.Attributes.originalbodytext;
                fieldTitle = Report.Schema.Headers.originalbodytext;
            }

            Report reportEntity = null;

            using (service.Lock())
            {
                // Репозиторий для работы с веб-ресурсами
                var reportRepository = new ReportRepository(service);

                if (withSelect)
                {
                    Guid?reportId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                    bool?dialogResult     = null;
                    Guid?selectedReportId = null;

                    string selectedPath = string.Empty;
                    var    thread       = new Thread(() =>
                    {
                        try
                        {
                            var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, reportId);

                            dialogResult     = form.ShowDialog();
                            selectedReportId = form.SelectedReportId;
                        }
                        catch (Exception ex)
                        {
                            DTEHelper.WriteExceptionToOutput(connectionData, ex);
                        }
                    });
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();

                    thread.Join();

                    if (dialogResult.GetValueOrDefault())
                    {
                        if (selectedReportId.HasValue)
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "Custom report is selected.");

                            reportEntity = await reportRepository.GetByIdAsync(selectedReportId.Value);

                            connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                            connectionData.Save();
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. Report not exists. name: {0}.", selectedFile.Name);
                        }
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.DifferenceWasCancelled);
                        return;
                    }
                }
                else
                {
                    reportEntity = await reportRepository.FindAsync(selectedFile.FileName);

                    if (reportEntity != null)
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Report founded by name.");

                        connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                        connectionData.Save();
                    }
                    else
                    {
                        Guid?reportId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                        if (reportId.HasValue)
                        {
                            reportEntity = await reportRepository.GetByIdAsync(reportId.Value);
                        }

                        if (reportEntity != null)
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "Report not founded by name. Last link report is selected for difference.");

                            connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                            connectionData.Save();
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "Report not founded by name and has not Last link.");
                            this._iWriteToOutput.WriteToOutput(connectionData, "Starting Custom Report selection form.");

                            bool?dialogResult     = null;
                            Guid?selectedReportId = null;

                            string selectedPath = string.Empty;
                            var    thread       = new Thread(() =>
                            {
                                try
                                {
                                    var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, reportId);

                                    dialogResult     = form.ShowDialog();
                                    selectedReportId = form.SelectedReportId;
                                }
                                catch (Exception ex)
                                {
                                    DTEHelper.WriteExceptionToOutput(connectionData, ex);
                                }
                            });
                            thread.SetApartmentState(ApartmentState.STA);
                            thread.Start();

                            thread.Join();

                            if (dialogResult.GetValueOrDefault())
                            {
                                if (selectedReportId.HasValue)
                                {
                                    this._iWriteToOutput.WriteToOutput(connectionData, "Custom report is selected.");

                                    reportEntity = await reportRepository.GetByIdAsync(selectedReportId.Value);

                                    connectionData.AddMapping(reportEntity.Id, selectedFile.FriendlyFilePath);

                                    connectionData.Save();
                                }
                                else
                                {
                                    this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. Report not exists. name: {0}.", selectedFile.Name);
                                }
                            }
                            else
                            {
                                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.DifferenceWasCancelled);
                                return;
                            }
                        }
                    }
                }
            }

            if (reportEntity == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.InConnectionReportWasNotFoundFormat2, connectionData.Name, selectedFile.FileName);
                return;
            }

            var reportName = EntityFileNameFormatter.GetReportFileName(connectionData.Name, reportEntity.Name, reportEntity.Id, fieldTitle, selectedFile.Extension);

            string temporaryFilePath = FileOperations.GetNewTempFilePath(Path.GetFileNameWithoutExtension(reportName), selectedFile.Extension);

            var textReport = reportEntity.GetAttributeValue <string>(fieldName);

            if (ContentComparerHelper.TryParseXml(textReport, out var doc))
            {
                textReport = doc.ToString();
            }

            File.WriteAllText(temporaryFilePath, textReport, new UTF8Encoding(false));

            //DownloadReportDefinitionRequest rdlRequest = new DownloadReportDefinitionRequest
            //{
            //    ReportId = reportEntity.Id
            //};

            //DownloadReportDefinitionResponse rdlResponse = (DownloadReportDefinitionResponse)service.Execute(rdlRequest);

            //using (XmlTextWriter reportDefinitionFile = new XmlTextWriter(temporaryFilePath, System.Text.Encoding.UTF8))
            //{
            //    reportDefinitionFile.WriteRaw(rdlResponse.BodyText);
            //    reportDefinitionFile.Close();
            //}

            this._iWriteToOutput.WriteToOutput(connectionData, "Starting Compare Program for {0} and {1}", selectedFile.FriendlyFilePath, reportName);

            string fileLocalPath  = selectedFile.FilePath;
            string fileLocalTitle = selectedFile.FileName;

            string filePath2  = temporaryFilePath;
            string fileTitle2 = connectionData.Name + "." + selectedFile.FileName + " - " + temporaryFilePath;

            await this._iWriteToOutput.ProcessStartProgramComparerAsync(connectionData, fileLocalPath, filePath2, fileLocalTitle, fileTitle2);
        }
        private async Task ThreeFileDifferenceWebResources(SelectedFile selectedFile, ConnectionData connectionData1, ConnectionData connectionData2, ShowDifferenceThreeFileType differenceType, CommonConfiguration commonConfig)
        {
            if (connectionData1 == null)
            {
                this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.NoCRMConnection1);
                return;
            }

            if (connectionData2 == null)
            {
                this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.NoCRMConnection2);
                return;
            }

            if (differenceType == ShowDifferenceThreeFileType.ThreeWay)
            {
                if (!File.Exists(selectedFile.FilePath))
                {
                    this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                    return;
                }
            }

            this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.ConnectingToCRM);
            this._iWriteToOutput.WriteToOutput(null, string.Empty);
            this._iWriteToOutput.WriteToOutput(null, connectionData1.GetConnectionDescription());
            this._iWriteToOutput.WriteToOutput(null, string.Empty);
            this._iWriteToOutput.WriteToOutput(null, connectionData2.GetConnectionDescription());

            var task1 = QuickConnection.ConnectAsync(connectionData1);
            var task2 = QuickConnection.ConnectAsync(connectionData2);

            var service1 = await task1;
            var service2 = await task2;

            if (service1 == null)
            {
                _iWriteToOutput.WriteToOutput(connectionData1, Properties.OutputStrings.ConnectionFailedFormat1, connectionData1.Name);
                return;
            }

            if (service2 == null)
            {
                _iWriteToOutput.WriteToOutput(connectionData2, Properties.OutputStrings.ConnectionFailedFormat1, connectionData2.Name);
                return;
            }

            this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.CurrentServiceEndpointConnectionFormat2, connectionData1.Name, service1.CurrentServiceEndpoint);
            this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.CurrentServiceEndpointConnectionFormat2, connectionData2.Name, service2.CurrentServiceEndpoint);

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository1 = new WebResourceRepository(service1);
            WebResourceRepository webResourceRepository2 = new WebResourceRepository(service2);

            var taskWebResource1 = webResourceRepository1.FindByNameAsync(selectedFile.FriendlyFilePath, selectedFile.Extension);
            var taskWebResource2 = webResourceRepository2.FindByNameAsync(selectedFile.FriendlyFilePath, selectedFile.Extension);

            WebResource webresource1 = await taskWebResource1;
            WebResource webresource2 = await taskWebResource2;

            if (webresource1 != null)
            {
                this._iWriteToOutput.WriteToOutput(null, "{0}: WebResource founded by name.", connectionData1.Name);

                connectionData1.AddMapping(webresource1.Id, selectedFile.FriendlyFilePath);

                connectionData1.Save();
            }
            else
            {
                Guid?webId = connectionData1.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                if (webId.HasValue)
                {
                    webresource1 = await webResourceRepository1.GetByIdAsync(webId.Value);

                    if (webresource1 != null)
                    {
                        this._iWriteToOutput.WriteToOutput(null, "{0}: WebResource not founded by name. Last link WebResource is selected for difference.", connectionData1.Name);

                        connectionData1.AddMapping(webresource1.Id, selectedFile.FriendlyFilePath);

                        connectionData1.Save();
                    }
                }
            }

            if (webresource2 != null)
            {
                this._iWriteToOutput.WriteToOutput(null, "{0}: WebResource founded by name.", connectionData2.Name);

                connectionData2.AddMapping(webresource2.Id, selectedFile.FriendlyFilePath);

                connectionData2.Save();
            }
            else
            {
                Guid?webId = connectionData2.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                if (webId.HasValue)
                {
                    webresource2 = await webResourceRepository2.GetByIdAsync(webId.Value);

                    if (webresource2 != null)
                    {
                        this._iWriteToOutput.WriteToOutput(null, "{0}: WebResource not founded by name. Last link WebResource is selected for difference.", connectionData2.Name);

                        connectionData2.AddMapping(webresource2.Id, selectedFile.FriendlyFilePath);

                        connectionData2.Save();
                    }
                }
            }

            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
            }

            if (webresource1 == null)
            {
                this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.WebResourceNotFoundedInConnectionFormat2, connectionData1.Name, selectedFile.FileName);
            }

            if (webresource2 == null)
            {
                this._iWriteToOutput.WriteToOutput(null, Properties.OutputStrings.WebResourceNotFoundedInConnectionFormat2, connectionData2.Name, selectedFile.FileName);
            }

            // string fileLocalPath, string fileLocalTitle, string filePath1, string fileTitle1, string filePath2, string fileTitle2,
            string fileLocalPath  = selectedFile.FilePath;
            string fileLocalTitle = selectedFile.FileName;

            string filePath1  = string.Empty;
            string fileTitle1 = string.Empty;

            string filePath2  = string.Empty;
            string fileTitle2 = string.Empty;

            if (webresource1 != null)
            {
                var contentWebResource1 = webresource1.Content ?? string.Empty;

                var array = Convert.FromBase64String(contentWebResource1);

                filePath1  = FileOperations.GetNewTempFilePath(webresource1.Name, selectedFile.Extension);
                fileTitle1 = connectionData1.Name + "." + selectedFile.FileName + " - " + filePath1;

                File.WriteAllBytes(filePath1, array);
            }

            if (webresource2 != null)
            {
                var contentWebResource2 = webresource2.Content ?? string.Empty;

                var array = Convert.FromBase64String(contentWebResource2);

                filePath2  = FileOperations.GetNewTempFilePath(webresource2.Name, selectedFile.Extension);
                fileTitle2 = connectionData2.Name + "." + selectedFile.FileName + " - " + filePath2;

                File.WriteAllBytes(filePath2, array);
            }

            switch (differenceType)
            {
            case ShowDifferenceThreeFileType.OneByOne:
                ShowDifferenceOneByOne(commonConfig, fileLocalPath, fileLocalTitle, filePath1, fileTitle1, filePath2, fileTitle2);
                break;

            case ShowDifferenceThreeFileType.TwoConnections:
                this._iWriteToOutput.ProcessStartProgramComparer(filePath1, filePath2, fileTitle1, fileTitle2);
                break;

            case ShowDifferenceThreeFileType.ThreeWay:
                ShowDifferenceThreeWay(commonConfig, fileLocalPath, fileLocalTitle, filePath1, fileTitle1, filePath2, fileTitle2);
                break;

            default:
                break;
            }
        }
        private async Task DifferenceWebResources(SelectedFile selectedFile, bool isCustom, ConnectionData connectionData, CommonConfiguration commonConfig)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                return;
            }

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

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

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

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

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

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

            WebResource webresource = null;

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

                bool?dialogResult          = null;
                Guid?selectedWebResourceId = null;

                string selectedPath = string.Empty;
                var    t            = new Thread(() =>
                {
                    try
                    {
                        var form = new Views.WindowWebResourceSelectOrCreate(this._iWriteToOutput, service, connectionData, selectedFile, webId);

                        dialogResult          = form.ShowDialog();
                        selectedWebResourceId = form.SelectedWebResourceId;
                    }
                    catch (Exception ex)
                    {
                        DTEHelper.WriteExceptionToOutput(connectionData, ex);
                    }
                });
                t.SetApartmentState(ApartmentState.STA);
                t.Start();

                t.Join();

                if (dialogResult.GetValueOrDefault() == false)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.DifferenceWasCancelled);
                    return;
                }

                if (selectedWebResourceId.HasValue)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Custom Web-resource is selected.");

                    webresource = await webResourceRepository.GetByIdAsync(selectedWebResourceId.Value);

                    connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                    connectionData.Save();
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. WebResource not exists. name: {0}.", selectedFile.Name);
                }
            }
            else
            {
                webresource = await webResourceRepository.FindByNameAsync(selectedFile.FriendlyFilePath, selectedFile.Extension);

                if (webresource != null)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, "Web-resource founded by name.");

                    connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                    connectionData.Save();
                }
                else
                {
                    Guid?webId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

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

                    if (webresource != null)
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Web-resource not founded by name. Last link web-resource is selected for difference.");

                        connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                        connectionData.Save();
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Web-resource not founded by name and has not Last link.");
                        this._iWriteToOutput.WriteToOutput(connectionData, "Starting Custom Web-resource selection form.");

                        bool?dialogResult          = null;
                        Guid?selectedWebResourceId = null;

                        string selectedPath = string.Empty;
                        var    t            = new Thread(() =>
                        {
                            try
                            {
                                var form = new Views.WindowWebResourceSelectOrCreate(this._iWriteToOutput, service, connectionData, selectedFile, webId);

                                dialogResult          = form.ShowDialog();
                                selectedWebResourceId = form.SelectedWebResourceId;
                            }
                            catch (Exception ex)
                            {
                                DTEHelper.WriteExceptionToOutput(connectionData, ex);
                            }
                        });
                        t.SetApartmentState(ApartmentState.STA);
                        t.Start();

                        t.Join();

                        if (dialogResult.GetValueOrDefault())
                        {
                            if (selectedWebResourceId.HasValue)
                            {
                                this._iWriteToOutput.WriteToOutput(connectionData, "Custom Web-resource is selected.");

                                webresource = await webResourceRepository.GetByIdAsync(selectedWebResourceId.Value);

                                connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                                connectionData.Save();
                            }
                            else
                            {
                                this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. WebResource not exists. name: {0}.", selectedFile.Name);
                            }
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.DifferenceWasCancelled);
                            return;
                        }
                    }
                }
            }

            if (webresource == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, "Web-resource not founded in CRM: {0}", selectedFile.FileName);
                return;
            }

            string filePath1  = selectedFile.FilePath;
            string fileTitle1 = selectedFile.FileName;

            string filePath2  = string.Empty;
            string fileTitle2 = string.Empty;

            {
                var contentWebResource = webresource.Content ?? string.Empty;

                var array = Convert.FromBase64String(contentWebResource);

                filePath2 = FileOperations.GetNewTempFilePath(webresource.Name, selectedFile.Extension);

                File.WriteAllBytes(filePath2, array);

                fileTitle2 = connectionData.Name + "." + selectedFile.FileName + " - " + filePath2;
            }

            this._iWriteToOutput.ProcessStartProgramComparer(filePath1, filePath2, fileTitle1, fileTitle2);
        }
                                          > > FindFilesNotExistsInCrm(
            IWriteToOutput _iWriteToOutput
            , List <SelectedFile> selectedFiles
            , ConnectionData connectionData)
        {
            if (connectionData == null)
            {
                _iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return(null);
            }

            _iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM);

            _iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription());

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

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

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

            bool isconnectionDataDirty = false;

            var listNotFoundedInCrmNoLink   = new List <SelectedFile>();
            var listNotFoundedInCrmWithLink = new List <Tuple <SelectedFile, WebResource> >();

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

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

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

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

                var dict = webResourceRepository.FindMultiple(gr.Key, names
                                                              , new ColumnSet(
                                                                  WebResource.Schema.EntityPrimaryIdAttribute
                                                                  , WebResource.Schema.Attributes.name
                                                                  , WebResource.Schema.Attributes.webresourcetype
                                                                  ));

                foreach (var selectedFile in gr)
                {
                    if (!File.Exists(selectedFile.FilePath))
                    {
                        listNotExistsOnDisk.Add(selectedFile.FilePath);
                        continue;
                    }

                    string name = selectedFile.FriendlyFilePath.ToLower();

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

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

                        if (webId.HasValue)
                        {
                            webresource = await webResourceRepository.GetByIdAsync(webId.Value, new ColumnSet(true));

                            if (webresource != null)
                            {
                                listNotFoundedInCrmWithLink.Add(Tuple.Create(selectedFile, webresource));

                                isconnectionDataDirty = true;
                                connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);
                            }
                            else
                            {
                                connectionData.RemoveMapping(selectedFile.FriendlyFilePath);

                                listNotFoundedInCrmNoLink.Add(selectedFile);
                            }
                        }
                        else
                        {
                            listNotFoundedInCrmNoLink.Add(selectedFile);
                        }
                    }
                }
            }

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

            var tabSpacer = "    ";

            if (listNotFoundedInCrmNoLink.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM: {0}", listNotFoundedInCrmNoLink.Count);

                listNotFoundedInCrmNoLink.Sort();

                listNotFoundedInCrmNoLink.ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (listNotFoundedInCrmWithLink.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link: {0}", listNotFoundedInCrmWithLink.Count);

                FormatTextTableHandler tableLastLinkDifferent = new FormatTextTableHandler();
                tableLastLinkDifferent.SetHeader("FriendlyFilePath", "WebResourceName");

                listNotFoundedInCrmWithLink.ForEach(i => tableLastLinkDifferent.AddLine(i.Item1.FriendlyFilePath, i.Item2.Name));

                tableLastLinkDifferent.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (listNotExistsOnDisk.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, listNotExistsOnDisk.Count);

                listNotExistsOnDisk.Sort();

                listNotExistsOnDisk.ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (listNotFoundedInCrmNoLink.Count + listNotFoundedInCrmWithLink.Count == 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "No files not exists in Crm");
            }

            return(Tuple.Create(service, listNotFoundedInCrmNoLink, listNotFoundedInCrmWithLink));
        }
                                          > > ComparingFilesAndWebResources(
            IWriteToOutput _iWriteToOutput
            , List <SelectedFile> selectedFiles
            , ConnectionData connectionData
            , bool withDetails)
        {
            if (connectionData == null)
            {
                _iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return(null);
            }

            var dictFilesEqualByTextNotContent = new List <Tuple <SelectedFile, WebResource> >();
            var dictFilesNotEqualByText        = new List <Tuple <SelectedFile, WebResource, ContentCopareResult> >();

            _iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectingToCRM);

            _iWriteToOutput.WriteToOutput(connectionData, connectionData.GetConnectionDescription());

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

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

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

            bool isconnectionDataDirty = false;

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

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

            int countEqualByContent = 0;

            FormatTextTableHandler tableEqualByText = new FormatTextTableHandler();

            tableEqualByText.SetHeader("FriendlyFilePath", "WebResourceName");

            FormatTextTableHandler tableDifferent = new FormatTextTableHandler();

            if (withDetails)
            {
                tableDifferent.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");
            }
            else
            {
                tableDifferent.SetHeader("FriendlyFilePath", "WebResourceName");
            }

            FormatTextTableHandler tableDifferentOnlyInserts = new FormatTextTableHandler();

            tableDifferentOnlyInserts.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)");

            FormatTextTableHandler tableDifferentOnlyDeletes = new FormatTextTableHandler();

            tableDifferentOnlyDeletes.SetHeader("FriendlyFilePath", "WebResourceName", "-Deletes", "(-Length)");

            FormatTextTableHandler tableDifferentComplexChanges = new FormatTextTableHandler();

            tableDifferentComplexChanges.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableDifferentMirror = new FormatTextTableHandler();

            tableDifferentMirror.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableDifferentMirrorWithInserts = new FormatTextTableHandler();

            tableDifferentMirrorWithInserts.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableDifferentMirrorWithDeletes = new FormatTextTableHandler();

            tableDifferentMirrorWithDeletes.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableLastLinkEqualByContent = new FormatTextTableHandler();

            tableLastLinkEqualByContent.SetHeader("FriendlyFilePath", "WebResourceName");

            FormatTextTableHandler listLastLinkEqualByText = new FormatTextTableHandler();

            listLastLinkEqualByText.SetHeader("FriendlyFilePath", "WebResourceName");

            FormatTextTableHandler tableLastLinkDifferent = new FormatTextTableHandler();

            if (withDetails)
            {
                tableLastLinkDifferent.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");
            }
            else
            {
                tableLastLinkDifferent.SetHeader("FriendlyFilePath", "WebResourceName");
            }

            FormatTextTableHandler tableLastLinkDifferentOnlyInserts = new FormatTextTableHandler();

            tableLastLinkDifferentOnlyInserts.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)");

            FormatTextTableHandler tableLastLinkDifferentOnlyDeletes = new FormatTextTableHandler();

            tableLastLinkDifferentOnlyDeletes.SetHeader("FriendlyFilePath", "WebResourceName", "-Deletes", "(-Length)");

            FormatTextTableHandler tableLastLinkDifferentComplexChanges = new FormatTextTableHandler();

            tableLastLinkDifferentComplexChanges.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableLastLinkDifferentMirror = new FormatTextTableHandler();

            tableLastLinkDifferentMirror.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableLastLinkDifferentMirrorWithInserts = new FormatTextTableHandler();

            tableLastLinkDifferentMirrorWithInserts.SetHeader("FriendlyFilePath", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            FormatTextTableHandler tableLastLinkDifferentMirrorWithDeletes = new FormatTextTableHandler();

            tableLastLinkDifferentMirrorWithDeletes.SetHeader("FriendlyFilePath", "WebResourceName", "+Inserts", "(+Length)", "-Deletes", "(-Length)");

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

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

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

                var dict = webResourceRepository.FindMultiple(gr.Key, names
                                                              , new ColumnSet(
                                                                  WebResource.Schema.EntityPrimaryIdAttribute
                                                                  , WebResource.Schema.Attributes.name
                                                                  , WebResource.Schema.Attributes.webresourcetype
                                                                  , WebResource.Schema.Attributes.content
                                                                  ));

                foreach (var selectedFile in gr)
                {
                    if (!File.Exists(selectedFile.FilePath))
                    {
                        listNotExistsOnDisk.Add(selectedFile.FilePath);
                        continue;
                    }

                    string urlShowDifference = string.Format("{0}:///{1}?ConnectionId={2}", UrlCommandFilter.PrefixShowDifference, selectedFile.FilePath.Replace('\\', '/'), connectionData.ConnectionId.ToString());

                    string name = selectedFile.FriendlyFilePath.ToLower();

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

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

                        var contentWebResource = webresource.Content ?? string.Empty;

                        var arrayFile = File.ReadAllBytes(selectedFile.FilePath);

                        var contentFile = Convert.ToBase64String(arrayFile);

                        if (string.Equals(contentFile, contentWebResource))
                        {
                            countEqualByContent++;
                        }
                        else
                        {
                            var arrayWebResource = Convert.FromBase64String(contentWebResource);

                            var nameWebResource = webresource.Name;

                            var compare = ContentCoparerHelper.CompareByteArrays(selectedFile.Extension, arrayFile, arrayWebResource, withDetails);

                            if (compare.IsEqual)
                            {
                                tableEqualByText.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource);

                                dictFilesEqualByTextNotContent.Add(Tuple.Create(selectedFile, webresource));
                            }
                            else
                            {
                                dictFilesNotEqualByText.Add(Tuple.Create(selectedFile, webresource, compare));

                                if (withDetails)
                                {
                                    string[] values = new string[]
                                    {
                                        selectedFile.UrlFriendlyFilePath, nameWebResource
                                        , string.Format("+{0}", compare.Inserts)
                                        , string.Format("(+{0})", compare.InsertLength)
                                        , string.Format("-{0}", compare.Deletes)
                                        , string.Format("(-{0})", compare.DeleteLength)
                                        , urlShowDifference
                                    };

                                    tableDifferent.AddLine(values);

                                    if (compare.IsOnlyInserts)
                                    {
                                        tableDifferentOnlyInserts.AddLine(selectedFile.UrlFriendlyFilePath
                                                                          , string.Format("+{0}", compare.Inserts)
                                                                          , string.Format("(+{0})", compare.InsertLength)
                                                                          , urlShowDifference
                                                                          );
                                    }

                                    if (compare.IsOnlyDeletes)
                                    {
                                        tableDifferentOnlyDeletes.AddLine(selectedFile.UrlFriendlyFilePath
                                                                          , string.Format("-{0}", compare.Deletes)
                                                                          , string.Format("(-{0})", compare.DeleteLength)
                                                                          , urlShowDifference
                                                                          );
                                    }

                                    if (compare.IsComplexChanges)
                                    {
                                        tableDifferentComplexChanges.AddLine(values);
                                    }

                                    if (compare.IsMirror)
                                    {
                                        tableDifferentMirror.AddLine(values);
                                    }

                                    if (compare.IsMirrorWithInserts)
                                    {
                                        tableDifferentMirrorWithInserts.AddLine(values);
                                    }

                                    if (compare.IsMirrorWithDeletes)
                                    {
                                        tableDifferentMirrorWithDeletes.AddLine(values);
                                    }
                                }
                                else
                                {
                                    tableDifferent.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource, urlShowDifference);
                                }
                            }
                        }
                    }
                    else
                    {
                        Guid?webId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

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

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

                                var contentWebResource = webresource.Content ?? string.Empty;
                                var nameWebResource    = webresource.Name;

                                var arrayFile = File.ReadAllBytes(selectedFile.FilePath);

                                var contentFile = Convert.ToBase64String(arrayFile);

                                if (string.Equals(contentFile, contentWebResource))
                                {
                                    tableLastLinkEqualByContent.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource);
                                }
                                else
                                {
                                    var arrayWebResource = Convert.FromBase64String(contentWebResource);

                                    var compare = ContentCoparerHelper.CompareByteArrays(selectedFile.Extension, arrayFile, arrayWebResource);

                                    if (compare.IsEqual)
                                    {
                                        listLastLinkEqualByText.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource);

                                        dictFilesEqualByTextNotContent.Add(Tuple.Create(selectedFile, webresource));
                                    }
                                    else
                                    {
                                        dictFilesNotEqualByText.Add(Tuple.Create(selectedFile, webresource, compare));

                                        if (withDetails)
                                        {
                                            string[] values = new string[]
                                            {
                                                selectedFile.UrlFriendlyFilePath, nameWebResource
                                                , string.Format("+{0}", compare.Inserts)
                                                , string.Format("(+{0})", compare.InsertLength)
                                                , string.Format("-{0}", compare.Deletes)
                                                , string.Format("(-{0})", compare.DeleteLength)
                                                , urlShowDifference
                                            };

                                            tableLastLinkDifferent.AddLine(values);


                                            if (compare.IsOnlyInserts)
                                            {
                                                tableLastLinkDifferentOnlyInserts.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource
                                                                                          , string.Format("+{0}", compare.Inserts)
                                                                                          , string.Format("(+{0})", compare.InsertLength)
                                                                                          , urlShowDifference
                                                                                          );
                                            }

                                            if (compare.IsOnlyDeletes)
                                            {
                                                tableLastLinkDifferentOnlyDeletes.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource
                                                                                          , string.Format("-{0}", compare.Deletes)
                                                                                          , string.Format("(-{0})", compare.DeleteLength)
                                                                                          , urlShowDifference
                                                                                          );
                                            }

                                            if (compare.IsComplexChanges)
                                            {
                                                tableLastLinkDifferentComplexChanges.AddLine(values);
                                            }

                                            if (compare.IsMirror)
                                            {
                                                tableLastLinkDifferentMirror.AddLine(values);
                                            }

                                            if (compare.IsMirrorWithInserts)
                                            {
                                                tableLastLinkDifferentMirrorWithInserts.AddLine(values);
                                            }

                                            if (compare.IsMirrorWithDeletes)
                                            {
                                                tableLastLinkDifferentMirrorWithDeletes.AddLine(values);
                                            }
                                        }
                                        else
                                        {
                                            tableLastLinkDifferent.AddLine(selectedFile.UrlFriendlyFilePath, nameWebResource, urlShowDifference);
                                        }
                                    }
                                }
                            }
                            else
                            {
                                connectionData.RemoveMapping(selectedFile.FriendlyFilePath);

                                listNotFoundedInCRMNoLink.Add(selectedFile.UrlFriendlyFilePath);
                            }
                        }
                        else
                        {
                            listNotFoundedInCRMNoLink.Add(selectedFile.UrlFriendlyFilePath);
                        }
                    }
                }
            }

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

            var tabSpacer = "    ";

            if (tableDifferent.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content: {0}", tableDifferent.Count);

                tableDifferent.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableDifferentOnlyInserts.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content WITH ONLY INSERTS: {0}", tableDifferentOnlyInserts.Count);

                tableDifferentOnlyInserts.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableDifferentOnlyDeletes.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content WITH ONLY DELETES: {0}", tableDifferentOnlyDeletes.Count);

                tableDifferentOnlyDeletes.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableDifferentComplexChanges.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content WITH COMPLEX CHANGES: {0}", tableDifferentComplexChanges.Count);

                tableDifferentComplexChanges.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableDifferentMirror.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content WITH MIRROR CHANGES: {0}", tableDifferentMirror.Count);

                tableDifferentMirror.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableDifferentMirrorWithInserts.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content WITH MIRROR CHANGES AND INSERTS: {0}", tableDifferentMirrorWithInserts.Count);

                tableDifferentMirrorWithInserts.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableDifferentMirrorWithDeletes.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource are DIFFERENT by content WITH MIRROR CHANGES AND DELETES: {0}", tableDifferentMirrorWithDeletes.Count);

                tableDifferentMirrorWithDeletes.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (listNotFoundedInCRMNoLink.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM: {0}", listNotFoundedInCRMNoLink.Count);

                listNotFoundedInCRMNoLink.Sort();

                listNotFoundedInCRMNoLink.ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkDifferent.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT: {0}", tableLastLinkDifferent.Count);

                tableLastLinkDifferent.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }


            if (tableLastLinkDifferentOnlyInserts.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT WITH ONLY INSERTS: {0}", tableLastLinkDifferentOnlyInserts.Count);

                tableLastLinkDifferentOnlyInserts.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkDifferentOnlyDeletes.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT WITH ONLY DELETES: {0}", tableLastLinkDifferentOnlyDeletes.Count);

                tableLastLinkDifferentOnlyDeletes.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkDifferentComplexChanges.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT WITH COMPLEX CHANGES: {0}", tableLastLinkDifferentComplexChanges.Count);

                tableLastLinkDifferentComplexChanges.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkDifferentMirror.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT WITH MIRROR CHANGES: {0}", tableLastLinkDifferentMirror.Count);

                tableLastLinkDifferentMirror.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkDifferentMirrorWithInserts.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT WITH MIRROR CHANGES AND INSERTS: {0}", tableLastLinkDifferentMirrorWithInserts.Count);

                tableLastLinkDifferentMirrorWithInserts.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkDifferentMirrorWithDeletes.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files DIFFERENT WITH MIRROR CHANGES AND DELETES: {0}", tableLastLinkDifferentMirrorWithDeletes.Count);

                tableLastLinkDifferentMirrorWithDeletes.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (listLastLinkEqualByText.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files EQUALS BY TEXT: {0}", listLastLinkEqualByText.Count);

                listLastLinkEqualByText.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableLastLinkEqualByContent.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File NOT FOUNDED in CRM, but has Last Link, files EQUALS BY CONTENT: {0}", tableLastLinkEqualByContent.Count);

                tableLastLinkEqualByContent.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (listNotExistsOnDisk.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, listNotExistsOnDisk.Count);

                listNotExistsOnDisk.Sort();

                listNotExistsOnDisk.ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (tableEqualByText.Count > 0)
            {
                _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource EQUALS BY TEXT: {0}", tableEqualByText.Count);

                tableEqualByText.GetFormatedLines(true).ForEach(item => _iWriteToOutput.WriteToOutput(connectionData, tabSpacer + item));
            }

            if (countEqualByContent > 0)
            {
                if (countEqualByContent == selectedFiles.Count)
                {
                    _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                    _iWriteToOutput.WriteToOutput(connectionData, "All files and web-resources EQUALS BY CONTENT: {0}", countEqualByContent);
                }
                else
                {
                    _iWriteToOutput.WriteToOutput(connectionData, string.Empty);
                    _iWriteToOutput.WriteToOutput(connectionData, "File and web-resource EQUALS BY CONTENT: {0}", countEqualByContent);
                }
            }

            return(Tuple.Create(service, dictFilesEqualByTextNotContent, dictFilesNotEqualByText));
        }
        private async Task CreatingLastLinkWebResourceMultiple(List <SelectedFile> selectedFiles, ConnectionData connectionData)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

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

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

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

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

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

            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

            foreach (var selectedFile in selectedFiles)
            {
                if (!File.Exists(selectedFile.FilePath))
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                    continue;
                }

                var idLastLink = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                bool?dialogResult          = null;
                Guid?selectedWebResourceId = null;

                bool showNext = false;

                var t = new Thread((ThreadStart)(() =>
                {
                    try
                    {
                        var form = new Views.WindowWebResourceSelectOrCreate(this._iWriteToOutput, service, connectionData, selectedFile, idLastLink);
                        form.ShowSkipButton();

                        dialogResult = form.ShowDialog();
                        selectedWebResourceId = form.SelectedWebResourceId;
                        showNext = form.ShowNext;
                    }
                    catch (Exception ex)
                    {
                        DTEHelper.WriteExceptionToOutput(connectionData, ex);
                    }
                }));
                t.SetApartmentState(ApartmentState.STA);
                t.Start();

                t.Join();

                if (dialogResult.GetValueOrDefault())
                {
                    if (selectedWebResourceId.HasValue)
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.WebResourceIsSelected);

                        var webresource = await webResourceRepository.GetByIdAsync(selectedWebResourceId.Value);

                        connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                        connectionData.Save();
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.WebResourceNotFoundedByNameFormat1, selectedFile.Name);
                    }
                }
                else if (!showNext)
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatingLastLinkWasCanceled);
                    return;
                }
            }
        }
        private async Task CreatingLastLinkReport(SelectedFile selectedFile, ConnectionData connectionData)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            if (!File.Exists(selectedFile.FilePath))
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.FileNotExistsFormat1, selectedFile.FilePath);
                return;
            }

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

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

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

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

            Guid?idLastLink = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

            bool?dialogResult     = null;
            Guid?selectedReportId = null;

            string selectedPath = string.Empty;
            var    t            = new Thread((ThreadStart)(() =>
            {
                try
                {
                    var form = new Views.WindowReportSelect(this._iWriteToOutput, service, selectedFile, idLastLink);

                    dialogResult = form.ShowDialog();
                    selectedReportId = form.SelectedReportId;
                }
                catch (Exception ex)
                {
                    DTEHelper.WriteExceptionToOutput(connectionData, ex);
                }
            }));

            t.SetApartmentState(ApartmentState.STA);
            t.Start();

            t.Join();

            if (dialogResult.GetValueOrDefault())
            {
                if (selectedReportId.HasValue)
                {
                    ReportRepository reportRepository = new ReportRepository(service);

                    this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ReportIsSelected);

                    var webresource = await reportRepository.GetByIdAsync(selectedReportId.Value);

                    connectionData.AddMapping(webresource.Id, selectedFile.FriendlyFilePath);

                    connectionData.Save();
                }
                else
                {
                    this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ReportNotFoundedByNameFormat1, selectedFile.Name);
                }
            }
            else
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.CreatingLastLinkWasCanceled);
                return;
            }
        }
        private async Task UpdateContentAndPublish(List <SelectedFile> selectedFiles, ConnectionData connectionData)
        {
            if (connectionData == null)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.NoCurrentCRMConnection);
                return;
            }

            if (connectionData.IsReadOnly)
            {
                this._iWriteToOutput.WriteToOutput(connectionData, Properties.OutputStrings.ConnectionIsReadOnlyFormat1, connectionData.Name);
                return;
            }

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

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

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

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

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

            // Менеджер для публикации в CRM.
            PublishManager publishHelper = new PublishManager(this._iWriteToOutput, service);

            // Репозиторий для работы с веб-ресурсами
            WebResourceRepository webResourceRepository = new WebResourceRepository(service);

            bool allForOther = false;

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

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

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

                foreach (var selectedFile in gr)
                {
                    if (File.Exists(selectedFile.FilePath))
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "Try to find web-resource by name: {0}. Searching...", selectedFile.Name);

                        string key = selectedFile.FriendlyFilePath.ToLower();

                        var contentFile = Convert.ToBase64String(File.ReadAllBytes(selectedFile.FilePath));

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

                        if (webresource != null)
                        {
                            var webName = webresource.Name;

                            this._iWriteToOutput.WriteToOutput(connectionData, "WebResource founded by name. WebResourceId: {0} Name: {1}", webresource.Id, webName);
                        }
                        else
                        {
                            this._iWriteToOutput.WriteToOutput(connectionData, "WebResource not founded by name. FileName: {0}. Open linking dialog...", selectedFile.Name);

                            Guid?webId = connectionData.GetLastLinkForFile(selectedFile.FriendlyFilePath);

                            bool?dialogResult          = null;
                            Guid?selectedWebResourceId = null;

                            var t = new Thread(() =>
                            {
                                try
                                {
                                    var form = new Views.WindowWebResourceSelectOrCreate(this._iWriteToOutput, service, connectionData, selectedFile, webId);
                                    form.ShowCreateButton(allForOther);

                                    dialogResult = form.ShowDialog();

                                    allForOther = form.ForAllOther;

                                    selectedWebResourceId = form.SelectedWebResourceId;
                                }
                                catch (Exception ex)
                                {
                                    DTEHelper.WriteExceptionToOutput(connectionData, ex);
                                }
                            });
                            t.SetApartmentState(ApartmentState.STA);
                            t.Start();

                            t.Join();

                            if (string.IsNullOrEmpty(connectionData?.LastSelectedSolutionsUniqueName?.FirstOrDefault()))
                            {
                                allForOther = false;
                            }

                            connectionData.Save();

                            if (dialogResult.GetValueOrDefault())
                            {
                                if (selectedWebResourceId.HasValue)
                                {
                                    webresource = await webResourceRepository.GetByIdAsync(selectedWebResourceId.Value);
                                }
                                else
                                {
                                    this._iWriteToOutput.WriteToOutput(connectionData, "!Warning. WebResource not linked. name: {0}.", selectedFile.Name);
                                }
                            }
                            else
                            {
                                this._iWriteToOutput.WriteToOutput(connectionData, "Updating Content and Publishing was cancelled.");
                                return;
                            }
                        }

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

                            publishHelper.Add(new ElementForPublish(selectedFile, webresource));
                        }
                    }
                    else
                    {
                        this._iWriteToOutput.WriteToOutput(connectionData, "File not founded: {0}", selectedFile.FilePath);
                    }
                }
            }

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

            publishHelper.UpdateContentAndPublish();
        }