<commit_before>﻿using AutoFindReplace.Dtos;
using AutoFindReplace.Helpers;
using AutoFindReplace.Options;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace AutoFindReplace
{
    [ProvideAutoLoad(UIContextGuids80.SolutionExists)]
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About    
    [Guid("5e45aa4e-1a24-4edf-b10a-228b63448f70")]
    [ProvideOptionPage(typeof(GeneralOptions), Helpers.Constants.CategoryName, "General", 0, 0, true)]
    [ProvideOptionPage(typeof(RulesOptions), Helpers.Constants.CategoryName, "Rules", 0, 0, true)]
    [ProvideOptionPage(typeof(ExportRules), Helpers.Constants.CategoryName, "Export", 0, 0, true)]
    public sealed class VSPackage : Package
    {
        private bool anyRulesProcessed;
        private int changesCount;
        private DTE dte;
        private IList<string> failureMessages;
        private Dictionary<string, string> projectPaths;
        private int rulesEnabledForThisSolutionCount;
        private int rulesProcesssedSuccessfullyCount;
        private int rulesProcesssedUnsuccessfullyCount;
        private const string solutionItemsFolder = "{5B9E7010-9C34-4FA3-AED6-AD26E2C6C9CB}";

        public VSPackage()
        {
        }

        protected override void Initialize()
        {
            base.Initialize();

            IServiceContainer serviceContainer = this as IServiceContainer;
            dte = serviceContainer.GetService(typeof(SDTE)) as DTE;
            var solutionEvents = dte.Events.SolutionEvents;
            solutionEvents.Opened += OnSolutionOpened;
        }

        private void OnSolutionOpened()
        {
            var messagesHelper = new MessagesHelper();

            failureMessages = new List<string>();
            IList<string> successMessages = new List<string>();
            IEnumerable<string> summaryMessages = new List<string>();

            var generalOptionsDto = GetGeneralOptionsDtoFromStorage();
            var rulesDtos = RulesHelper.GetRulesDtos();

            if (rulesDtos != null && rulesDtos.Any())
            {
                var applyChangesMessages = ApplyChangesToSourceCode(rulesDtos, generalOptionsDto, dte.Solution.FullName);
                foreach (var applyChangesMessage in applyChangesMessages)
                {
                    successMessages.Add(applyChangesMessage);
                }

                if (anyRulesProcessed || failureMessages.Count > 0)
                {
                    summaryMessages = messagesHelper.GetSummaryMessages(rulesEnabledForThisSolutionCount, rulesProcesssedSuccessfullyCount, rulesProcesssedUnsuccessfullyCount, changesCount);
                    var userFriendlySuccessMessages = messagesHelper.GetUserFriendlySuccessMessages(successMessages);
                    var popUpMessage = messagesHelper.GetPopUpMessage(failureMessages, userFriendlySuccessMessages, summaryMessages);
                    DisplayPopUpMessage(Helpers.Constants.CategoryName + " Results", popUpMessage);
                }
            }

            PostOpenProcessing();
        }

        private IEnumerable<string> ApplyChangesToSourceCode(IEnumerable<RulesDto> rulesDtos, GeneralOptionsDto generalOptionsDto, string dteSolutionFullName)
        {
            var applyChangesMessages = new List<string>();
            var dteSolutionName = Path.GetFileName(dteSolutionFullName).ToLower();

            foreach (var rulesDto in rulesDtos.Where(x => x.Enabled && x.SolutionName.ToLower() == dteSolutionName))
            {
                try
                {
                    projectPaths = new Dictionary<string, string>();
                    SetProjectPaths();
    
                    anyRulesProcessed = true;
                    rulesEnabledForThisSolutionCount++;

                    var targetFileFullPath = GetTargetFileFullPath(rulesDto, generalOptionsDto);

                    if (!string.IsNullOrEmpty(targetFileFullPath))
                    {
                        var findReplaceMessages = PerformFindReplace(rulesDto, generalOptionsDto, targetFileFullPath);
                        applyChangesMessages.AddRange(findReplaceMessages);
                    }

                    rulesProcesssedSuccessfullyCount++;
                }
                catch (Exception ex)
                {
                    failureMessages.Add(ex.Message);
                }
            }

            rulesProcesssedUnsuccessfullyCount = rulesEnabledForThisSolutionCount - rulesProcesssedSuccessfullyCount;
           
            return applyChangesMessages;
        }

        private void SetProjectPaths()
        {
            Projects projects = dte.Solution.Projects;

            foreach (Project project in projects)
            {
                if (project.Kind != solutionItemsFolder)
                {
                    if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
                    {
                        // We've encountered a folder
                        var y = (project.ProjectItems as ProjectItems).Count;
                        for (var i = 1; i <= y; i++)
                        {
                            var x2 = project.ProjectItems.Item(i);
                            var x = x2.SubProject;
                            var subProject = x as Project;
                            if (subProject != null)
                            {
                                SetProjectPaths(x);
                            }
                        }
                    }
                    else
                    {
                        // We've encountered a project
                        SetProjectPaths(project);
                    }
                }
            }
        }

        private void SetProjectPaths(Project project)
        {
            var projectName = Path.GetFileName(project.FullName);
            var projectPath = Path.GetDirectoryName(project.FullName);

            if (!projectPaths.ContainsKey(projectName))
            {
                projectPaths.Add(projectName, projectPath);
            }
        }

        //gregt
        private string GetTargetFileFullPath(RulesDto rulesDto, GeneralOptionsDto generalOptionsDto)
        {
            var actualProjectPath = GetProjectPath(rulesDto.ProjectName);

            if (!string.IsNullOrEmpty(actualProjectPath))
            {
                var actualFilePath = GetFilePathWithinProjectDirectory(rulesDto.FileName, actualProjectPath);

                if (!string.IsNullOrEmpty(actualFilePath))
                {
                    var targetFileIsUnderSourceControl = dte.SourceControl.IsItemUnderSCC(actualFilePath);

                    if (FileIsEligibleToBeChanged(rulesDto, generalOptionsDto, actualFilePath, targetFileIsUnderSourceControl))
                    {
                        if (File.Exists(actualFilePath))
                        {
                            return actualFilePath;
                        }
                        else
                        {
                            failureMessages.Add("File " + actualFilePath + " does not exist");
                            return string.Empty;
                        }
                    }
                }
            }

            return string.Empty;
        }

        private void PostOpenProcessing()
        {
            changesCount = 0;
            rulesEnabledForThisSolutionCount = 0;
            rulesProcesssedSuccessfullyCount = 0;
            rulesProcesssedUnsuccessfullyCount = 0;
        }

        //gregt
        private string GetProjectPath(string projectName)
        {
            var projectFilePath = projectPaths.Where(x => x.Key == projectName).FirstOrDefault().Value;

            if (!string.IsNullOrEmpty(projectFilePath))
            {
                return projectFilePath;
            }
            else
            {
                return null;
            }
        }

        //gregt
        private string GetFilePathWithinProjectDirectory(string fileName, string actualProjectPath)
        {
            return FindFilePathWithinParentPath(fileName, actualProjectPath);
        }

        //gregt
        private string FindFilePathWithinParentPath(string fileToFind, string parentPath)
        {
            var matchingNameFiles = Directory.GetFiles(parentPath, fileToFind, SearchOption.AllDirectories);
            if (matchingNameFiles.Count() == 1)
            {
                return matchingNameFiles[0];
            }
            else
            {
                if (matchingNameFiles.Count() == 0)
                {
                    failureMessages.Add("File " + fileToFind + " cannot be found");
                }
                else
                {
                    failureMessages.Add("File " + fileToFind + " exists multiple times");
                }
                return null;
            }
        }

        private bool FileIsEligibleToBeChanged(RulesDto rulesDto, GeneralOptionsDto generalOptionsDto, string actualFilePath, bool targetFileIsUnderSourceControl)
        {
            bool fileIsEligibleToBeChanged;

            if (!string.IsNullOrEmpty(actualFilePath))
            {
                if (generalOptionsDto.UnderSourceControlOnly && !targetFileIsUnderSourceControl)
                {
                    failureMessages.Add("File " + rulesDto.FileName + " is not under source-control");
                    fileIsEligibleToBeChanged = false;
                }
                else
                {
                    fileIsEligibleToBeChanged = true;
                }
            }
            else
            {
                fileIsEligibleToBeChanged = false;
            }

            return fileIsEligibleToBeChanged;
        }

        //private bool HaveWeOpenedTheCorrectSolution(RulesDto rulesDto, string dteSolutionFullName)
        //{
            //var actualSolutionPathArray = dteSolutionFullName.Split('\\');
            //var actualSolutionName = actualSolutionPathArray.Last();
            //var actualSolutionName = Path.GetFileName(dteSolutionFullName);

            //return Path.GetFileName(dteSolutionFullName).ToLower() == rulesDto.SolutionName.ToLower();
        //}

        private GeneralOptionsDto GetGeneralOptionsDtoFromStorage()
        {
            var generalOptions = (GeneralOptions)GetDialogPage(typeof(GeneralOptions));

            var generalOptionsDto = new GeneralOptionsDto
            {
                UnderSourceControlOnly = generalOptions.UnderSourceControlOnly,
                KeepFileOpenAfterSave = generalOptions.KeepFileOpenAfterSave,
            };

            return generalOptionsDto;
        }

        private IEnumerable<string> PerformFindReplace(RulesDto rulesDto, GeneralOptionsDto generalOptionsDto, string targetFileFullPath)
        {
            var findReplaceMessages = new List<string>();

            dte.ItemOperations.OpenFile(targetFileFullPath);
            
            var textDocument = dte.ActiveDocument.Object("TextDocument") as TextDocument;

            if (textDocument == null)
            {
                failureMessages.Add("File " + rulesDto.FileName + " is not an editable text file");
            }
            else
            {
                var find = textDocument.DTE.Find;

                vsFindOptions vsFindOptions;

                if (rulesDto.CaseSensitive)
                {
                    vsFindOptions = vsFindOptions.vsFindOptionsMatchCase;
                }
                else
                {
                    vsFindOptions = vsFindOptions.vsFindOptionsFromStart;
                }

                var result = find.FindReplace(vsFindAction.vsFindActionReplaceAll, rulesDto.FindWhat, (int)vsFindOptions, rulesDto.ReplaceWith, vsFindTarget.vsFindTargetOpenDocuments);

                if (result == vsFindResult.vsFindResultReplaced)
                {
                    changesCount++;
                    findReplaceMessages.Add(rulesDto.FileName.ToLower() + " in " + rulesDto.ProjectName.ToLower());
                    dte.ActiveDocument.Save();
                }
            }

            if (!generalOptionsDto.KeepFileOpenAfterSave)
            {
                dte.ActiveDocument.Close();
            }

            return findReplaceMessages;
        }

        private void DisplayPopUpMessage(string title, string text)
        {
            IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
            Guid clsid = Guid.Empty;
            int result;
            uiShell.ShowMessageBox(
                0,
                ref clsid,
                title.ToUpper(),
                text,
                string.Empty,
                0,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                OLEMSGICON.OLEMSGICON_INFO,
                0,
                out result);
        }
    }
}



#region gregt to be deleted

//string projectsDetail = string.Empty;
//Projects projects = dte.Solution.Projects;
//foreach (Project project in projects)
//{
//    projectsDetail += "UniqueName=" + project.UniqueName + " Kind=" + project.Kind + Environment.NewLine;
//}
//UniqueName = a\a.csproj                                        Kind = { FAE04EC0 - 301F - 11D3 - BF4B - 00C04F79EFBC }
//UniqueName =..\b\b.csproj                                      Kind = { FAE04EC0 - 301F - 11D3 - BF4B - 00C04F79EFBC }
//UniqueName = f1{ 77DD4D22 - 73B3 - 4EB2 - 8F1C - 07F4E96A46F8} Kind = { 66A26720 - 8FB5 - 11D2 - AA7E - 00C04F688DDE }
//NAME: Solution Items{ 5B9E7010 - 9C34 - 4FA3 - AED6 - AD26E2C6C9CB}
//NAME: SiDem2.ClientWrappers{ FC3FBD6D - 58EB - 42EF - 90E4 - 6FFBC33C18FC}
//NAME: SiDem2.BL{ 89F6A61A - 834C - 42D2 - 85D3 - 6756AAE294D1}
//NAME: SiDem2.Levi9.PL{ 39EADEC9 - F559 - 49E0 - BB81 - BE1E68965593}
//NAME: SiDem2.PL{ 6DC4E2EA - F5F6 - 4296 - B7F8 - BD23886BCC5C}
//NAME: Externals{ FC6F4743 - E078 - 4071 - 859A - 75C5307DD0BB}
//NAME: Broker{ E239A8BE - 3A0D - 4723 - A559 - 03D28B3A766B}




//var sol = dte.Solution;
//var projs = sol.Projects;
////////DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
////////var sol = dte2.Solution;
////////var projs = sol.Projects;
//foreach (var proj in sol)
//{
//    var fullName = string.Empty;
//    var project = proj as Project;
//    if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
//    {
//        var innerProjects = GetSolutionFolderProjects(project);
//        foreach (var innerProject in innerProjects)
//        {
//            //carry out actions here.
//        }
//    }
//    if (!string.IsNullOrEmpty(fullName))
//    {
//        fullNames.Add(fullName);
//    }
//}



//private IEnumerable<Project> GetSolutionFolderProjects(Project project)
//{
//    List<Project> projects = new List<Project>();
//    var y = (project.ProjectItems as ProjectItems).Count;
//    for (var i = 1; i <= y; i++)
//    {
//        var x2 = project.ProjectItems.Item(i);
//        if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
//        {
//            //???
//            var innerProjects2  = GetSolutionFolderProjects2(project);
//        }
//        else
//        {
//            var x = x2.SubProject;
//            var subProject = x as Project;
//            if (subProject != null)
//            {
//                var projectPath = Path.GetDirectoryName(x.FullName);
//                var projectName = x.FullName.TrimPrefix(projectPath).TrimPrefix(@"\");
//                projectPaths.Add(projectName, projectPath);
//            }
//        }
//    }
//    return projects;
//}

//private IEnumerable<Project> GetSolutionFolderProjects2(Project project)
//{
//    List<Project> projects = new List<Project>();
//    var y = (project.ProjectItems as ProjectItems).Count;
//    for (var i = 1; i <= y; i++)
//    {
//        var x2 = project.ProjectItems.Item(i);
//        if (project.Kind != ProjectKinds.vsProjectKindSolutionFolder)
//        {
//            var x = x2.SubProject;
//            var subProject = x as Project;
//            if (subProject != null)
//            {
//                var projectPath = Path.GetDirectoryName(x.FullName);
//                var projectName = x.FullName.TrimPrefix(projectPath).TrimPrefix(@"\");
//                projectPaths.Add(projectName, projectPath);
//            }
//        }
//    }
//    return projects;
//}
#endregion<commit_msg>performance improves<commit_after>﻿using AutoFindReplace.Dtos;
using AutoFindReplace.Helpers;
using AutoFindReplace.Options;
using EnvDTE;
using EnvDTE80;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Shell.Interop;
using System;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;

namespace AutoFindReplace
{
    [ProvideAutoLoad(UIContextGuids80.SolutionExists)]
    [PackageRegistration(UseManagedResourcesOnly = true)]
    [InstalledProductRegistration("#110", "#112", "1.0", IconResourceID = 400)] // Info on this package for Help/About    
    [Guid("5e45aa4e-1a24-4edf-b10a-228b63448f70")]
    [ProvideOptionPage(typeof(GeneralOptions), Helpers.Constants.CategoryName, "General", 0, 0, true)]
    [ProvideOptionPage(typeof(RulesOptions), Helpers.Constants.CategoryName, "Rules", 0, 0, true)]
    [ProvideOptionPage(typeof(ExportRules), Helpers.Constants.CategoryName, "Export", 0, 0, true)]
    public sealed class VSPackage : Package
    {
        private bool anyRulesProcessed;
        private int changesCount;
        private DTE dte;
        private IList<string> failureMessages;
        private Dictionary<string, string> projectPaths;
        private int rulesEnabledForThisSolutionCount;
        private int rulesProcesssedSuccessfullyCount;
        private int rulesProcesssedUnsuccessfullyCount;
        private const string solutionItemsFolder = "{5B9E7010-9C34-4FA3-AED6-AD26E2C6C9CB}";

        public VSPackage()
        {
        }

        protected override void Initialize()
        {
            base.Initialize();

            IServiceContainer serviceContainer = this as IServiceContainer;
            dte = serviceContainer.GetService(typeof(SDTE)) as DTE;
            var solutionEvents = dte.Events.SolutionEvents;
            solutionEvents.Opened += OnSolutionOpened;
        }

        private void OnSolutionOpened()
        {
            var messagesHelper = new MessagesHelper();

            failureMessages = new List<string>();
            IList<string> successMessages = new List<string>();
            IEnumerable<string> summaryMessages = new List<string>();

            var generalOptionsDto = GetGeneralOptionsDtoFromStorage();
            var rulesDtos = RulesHelper.GetRulesDtos();

            if (rulesDtos != null && rulesDtos.Any())
            {
                var applyChangesMessages = ApplyChangesToSourceCode(rulesDtos, generalOptionsDto, dte.Solution.FullName);
                foreach (var applyChangesMessage in applyChangesMessages)
                {
                    successMessages.Add(applyChangesMessage);
                }

                if (anyRulesProcessed || failureMessages.Count > 0)
                {
                    summaryMessages = messagesHelper.GetSummaryMessages(rulesEnabledForThisSolutionCount, rulesProcesssedSuccessfullyCount, rulesProcesssedUnsuccessfullyCount, changesCount);
                    var userFriendlySuccessMessages = messagesHelper.GetUserFriendlySuccessMessages(successMessages);
                    var popUpMessage = messagesHelper.GetPopUpMessage(failureMessages, userFriendlySuccessMessages, summaryMessages);
                    DisplayPopUpMessage(Helpers.Constants.CategoryName + " Results", popUpMessage);
                }
            }

            PostOpenProcessing();
        }

        private IEnumerable<string> ApplyChangesToSourceCode(IEnumerable<RulesDto> rulesDtos, GeneralOptionsDto generalOptionsDto, string dteSolutionFullName)
        {
            var applyChangesMessages = new List<string>();
            var dteSolutionName = Path.GetFileName(dteSolutionFullName).ToLower();
            projectPaths = new Dictionary<string, string>();

            foreach (var rulesDto in rulesDtos.Where(x => x.Enabled && x.SolutionName.ToLower() == dteSolutionName))
            {
                try
                {
                    SetProjectPaths();
                    anyRulesProcessed = true;
                    rulesEnabledForThisSolutionCount++;

                    var targetFileFullPath = GetTargetFileFullPath(rulesDto, generalOptionsDto);

                    if (!string.IsNullOrEmpty(targetFileFullPath))
                    {
                        var findReplaceMessages = PerformFindReplace(rulesDto, generalOptionsDto, targetFileFullPath);
                        applyChangesMessages.AddRange(findReplaceMessages);
                    }

                    rulesProcesssedSuccessfullyCount++;
                }
                catch (Exception ex)
                {
                    failureMessages.Add(ex.Message);
                }
            }

            rulesProcesssedUnsuccessfullyCount = rulesEnabledForThisSolutionCount - rulesProcesssedSuccessfullyCount;
           
            return applyChangesMessages;
        }

        private void SetProjectPaths()
        {
            if (projectPaths.Count == 0)
            {
                Projects projects = dte.Solution.Projects;

                foreach (Project project in projects)
                {
                    if (project.Kind != solutionItemsFolder)
                    {
                        if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
                        {
                            // We've encountered a folder
                            var y = (project.ProjectItems as ProjectItems).Count;
                            for (var i = 1; i <= y; i++)
                            {
                                var x2 = project.ProjectItems.Item(i);
                                var x = x2.SubProject;
                                var subProject = x as Project;
                                if (subProject != null)
                                {
                                    SetProjectPaths(x);
                                }
                            }
                        }
                        else
                        {
                            // We've encountered a project
                            SetProjectPaths(project);
                        }
                    }
                }
            }
        }

        private void SetProjectPaths(Project project)
        {
            var projectName = Path.GetFileName(project.FullName);
            var projectPath = Path.GetDirectoryName(project.FullName);

            if (!projectPaths.ContainsKey(projectName))
            {
                projectPaths.Add(projectName, projectPath);
            }
        }

        //gregt
        private string GetTargetFileFullPath(RulesDto rulesDto, GeneralOptionsDto generalOptionsDto)
        {
            var actualProjectPath = GetProjectPath(rulesDto.ProjectName);

            if (!string.IsNullOrEmpty(actualProjectPath))
            {
                var actualFilePath = GetFilePathWithinProjectDirectory(rulesDto.FileName, actualProjectPath);

                if (!string.IsNullOrEmpty(actualFilePath))
                {
                    var targetFileIsUnderSourceControl = dte.SourceControl.IsItemUnderSCC(actualFilePath);

                    if (FileIsEligibleToBeChanged(rulesDto, generalOptionsDto, actualFilePath, targetFileIsUnderSourceControl))
                    {
                        if (File.Exists(actualFilePath))
                        {
                            return actualFilePath;
                        }
                        else
                        {
                            failureMessages.Add("File " + actualFilePath + " does not exist");
                            return string.Empty;
                        }
                    }
                }
            }

            return string.Empty;
        }

        private void PostOpenProcessing()
        {
            changesCount = 0;
            rulesEnabledForThisSolutionCount = 0;
            rulesProcesssedSuccessfullyCount = 0;
            rulesProcesssedUnsuccessfullyCount = 0;
        }

        //gregt
        private string GetProjectPath(string projectName)
        {
            var projectFilePath = projectPaths.Where(x => x.Key == projectName).FirstOrDefault().Value;

            if (!string.IsNullOrEmpty(projectFilePath))
            {
                return projectFilePath;
            }
            else
            {
                return null;
            }
        }

        //gregt
        private string GetFilePathWithinProjectDirectory(string fileName, string actualProjectPath)
        {
            return FindFilePathWithinParentPath(fileName, actualProjectPath);
        }

        //gregt
        private string FindFilePathWithinParentPath(string fileToFind, string parentPath)
        {
            var matchingNameFiles = Directory.GetFiles(parentPath, fileToFind, SearchOption.AllDirectories);
            if (matchingNameFiles.Count() == 1)
            {
                return matchingNameFiles[0];
            }
            else
            {
                if (matchingNameFiles.Count() == 0)
                {
                    failureMessages.Add("File " + fileToFind + " cannot be found");
                }
                else
                {
                    failureMessages.Add("File " + fileToFind + " exists multiple times");
                }
                return null;
            }
        }

        private bool FileIsEligibleToBeChanged(RulesDto rulesDto, GeneralOptionsDto generalOptionsDto, string actualFilePath, bool targetFileIsUnderSourceControl)
        {
            bool fileIsEligibleToBeChanged;

            if (!string.IsNullOrEmpty(actualFilePath))
            {
                if (generalOptionsDto.UnderSourceControlOnly && !targetFileIsUnderSourceControl)
                {
                    failureMessages.Add("File " + rulesDto.FileName + " is not under source-control");
                    fileIsEligibleToBeChanged = false;
                }
                else
                {
                    fileIsEligibleToBeChanged = true;
                }
            }
            else
            {
                fileIsEligibleToBeChanged = false;
            }

            return fileIsEligibleToBeChanged;
        }

        //private bool HaveWeOpenedTheCorrectSolution(RulesDto rulesDto, string dteSolutionFullName)
        //{
            //var actualSolutionPathArray = dteSolutionFullName.Split('\\');
            //var actualSolutionName = actualSolutionPathArray.Last();
            //var actualSolutionName = Path.GetFileName(dteSolutionFullName);

            //return Path.GetFileName(dteSolutionFullName).ToLower() == rulesDto.SolutionName.ToLower();
        //}

        private GeneralOptionsDto GetGeneralOptionsDtoFromStorage()
        {
            var generalOptions = (GeneralOptions)GetDialogPage(typeof(GeneralOptions));

            var generalOptionsDto = new GeneralOptionsDto
            {
                UnderSourceControlOnly = generalOptions.UnderSourceControlOnly,
                KeepFileOpenAfterSave = generalOptions.KeepFileOpenAfterSave,
            };

            return generalOptionsDto;
        }

        private IEnumerable<string> PerformFindReplace(RulesDto rulesDto, GeneralOptionsDto generalOptionsDto, string targetFileFullPath)
        {
            var findReplaceMessages = new List<string>();

            dte.ItemOperations.OpenFile(targetFileFullPath);
            
            var textDocument = dte.ActiveDocument.Object("TextDocument") as TextDocument;

            if (textDocument == null)
            {
                failureMessages.Add("File " + rulesDto.FileName + " is not an editable text file");
            }
            else
            {
                var find = textDocument.DTE.Find;

                vsFindOptions vsFindOptions;

                if (rulesDto.CaseSensitive)
                {
                    vsFindOptions = vsFindOptions.vsFindOptionsMatchCase;
                }
                else
                {
                    vsFindOptions = vsFindOptions.vsFindOptionsFromStart;
                }

                var result = find.FindReplace(vsFindAction.vsFindActionReplaceAll, rulesDto.FindWhat, (int)vsFindOptions, rulesDto.ReplaceWith, vsFindTarget.vsFindTargetOpenDocuments);

                if (result == vsFindResult.vsFindResultReplaced)
                {
                    changesCount++;
                    findReplaceMessages.Add(rulesDto.FileName.ToLower() + " in " + rulesDto.ProjectName.ToLower());
                    dte.ActiveDocument.Save();
                }
            }

            if (!generalOptionsDto.KeepFileOpenAfterSave)
            {
                dte.ActiveDocument.Close();
            }

            return findReplaceMessages;
        }

        private void DisplayPopUpMessage(string title, string text)
        {
            IVsUIShell uiShell = (IVsUIShell)GetService(typeof(SVsUIShell));
            Guid clsid = Guid.Empty;
            int result;
            uiShell.ShowMessageBox(
                0,
                ref clsid,
                title.ToUpper(),
                text,
                string.Empty,
                0,
                OLEMSGBUTTON.OLEMSGBUTTON_OK,
                OLEMSGDEFBUTTON.OLEMSGDEFBUTTON_FIRST,
                OLEMSGICON.OLEMSGICON_INFO,
                0,
                out result);
        }
    }
}



#region gregt to be deleted

//string projectsDetail = string.Empty;
//Projects projects = dte.Solution.Projects;
//foreach (Project project in projects)
//{
//    projectsDetail += "UniqueName=" + project.UniqueName + " Kind=" + project.Kind + Environment.NewLine;
//}
//UniqueName = a\a.csproj                                        Kind = { FAE04EC0 - 301F - 11D3 - BF4B - 00C04F79EFBC }
//UniqueName =..\b\b.csproj                                      Kind = { FAE04EC0 - 301F - 11D3 - BF4B - 00C04F79EFBC }
//UniqueName = f1{ 77DD4D22 - 73B3 - 4EB2 - 8F1C - 07F4E96A46F8} Kind = { 66A26720 - 8FB5 - 11D2 - AA7E - 00C04F688DDE }
//NAME: Solution Items{ 5B9E7010 - 9C34 - 4FA3 - AED6 - AD26E2C6C9CB}
//NAME: SiDem2.ClientWrappers{ FC3FBD6D - 58EB - 42EF - 90E4 - 6FFBC33C18FC}
//NAME: SiDem2.BL{ 89F6A61A - 834C - 42D2 - 85D3 - 6756AAE294D1}
//NAME: SiDem2.Levi9.PL{ 39EADEC9 - F559 - 49E0 - BB81 - BE1E68965593}
//NAME: SiDem2.PL{ 6DC4E2EA - F5F6 - 4296 - B7F8 - BD23886BCC5C}
//NAME: Externals{ FC6F4743 - E078 - 4071 - 859A - 75C5307DD0BB}
//NAME: Broker{ E239A8BE - 3A0D - 4723 - A559 - 03D28B3A766B}




//var sol = dte.Solution;
//var projs = sol.Projects;
////////DTE2 dte2 = Package.GetGlobalService(typeof(DTE)) as DTE2;
////////var sol = dte2.Solution;
////////var projs = sol.Projects;
//foreach (var proj in sol)
//{
//    var fullName = string.Empty;
//    var project = proj as Project;
//    if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
//    {
//        var innerProjects = GetSolutionFolderProjects(project);
//        foreach (var innerProject in innerProjects)
//        {
//            //carry out actions here.
//        }
//    }
//    if (!string.IsNullOrEmpty(fullName))
//    {
//        fullNames.Add(fullName);
//    }
//}



//private IEnumerable<Project> GetSolutionFolderProjects(Project project)
//{
//    List<Project> projects = new List<Project>();
//    var y = (project.ProjectItems as ProjectItems).Count;
//    for (var i = 1; i <= y; i++)
//    {
//        var x2 = project.ProjectItems.Item(i);
//        if (project.Kind == ProjectKinds.vsProjectKindSolutionFolder)
//        {
//            //???
//            var innerProjects2  = GetSolutionFolderProjects2(project);
//        }
//        else
//        {
//            var x = x2.SubProject;
//            var subProject = x as Project;
//            if (subProject != null)
//            {
//                var projectPath = Path.GetDirectoryName(x.FullName);
//                var projectName = x.FullName.TrimPrefix(projectPath).TrimPrefix(@"\");
//                projectPaths.Add(projectName, projectPath);
//            }
//        }
//    }
//    return projects;
//}

//private IEnumerable<Project> GetSolutionFolderProjects2(Project project)
//{
//    List<Project> projects = new List<Project>();
//    var y = (project.ProjectItems as ProjectItems).Count;
//    for (var i = 1; i <= y; i++)
//    {
//        var x2 = project.ProjectItems.Item(i);
//        if (project.Kind != ProjectKinds.vsProjectKindSolutionFolder)
//        {
//            var x = x2.SubProject;
//            var subProject = x as Project;
//            if (subProject != null)
//            {
//                var projectPath = Path.GetDirectoryName(x.FullName);
//                var projectName = x.FullName.TrimPrefix(projectPath).TrimPrefix(@"\");
//                projectPaths.Add(projectName, projectPath);
//            }
//        }
//    }
//    return projects;
//}
#endregion
{'fraction_non_alphanumeric': 0.08883678133626191, 'fraction_numerical': 0.017601139770265055, 'mean_word_length': 1.6701537486130924, 'pattern_counts': {'":': 0, '<': 47, '<?xml version=': 0, '>': 47, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 16, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '896885', 'n_tokens_mistral': 9141, 'n_tokens_neox': 8491, 'n_words': 1637}