Click here to Skip to main content
15,891,777 members
Articles / Desktop Programming / Windows Forms

C# and VB.NET Code Searcher - Using Roslyn

Rate me:
Please Sign up or sign in to vote.
4.84/5 (51 votes)
7 Mar 2013LGPL314 min read 201.4K   5.6K   130  
A fast C# and VB.NET code searcher using Roslyn.
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using Roslyn.Services;
using Roslyn.Compilers.Common;
using Roslyn.Compilers.CSharp;
using System.Windows.Forms;

namespace RoslynCodeSearcher
{
    public static class CodeRepository
    {
        private static List<string> _solutions = new List<string>();
        private static List<IWorkspace> _workspaces = new List<IWorkspace>();
        private static string _startingPath;
        public delegate void ProgressBarMaxUpdateHandler(int max);
        public delegate void ProgressBarProgressUpdateHandler(int max);
        private static readonly object _syncObject = new object();

        public static ProgressBarProgressUpdateHandler _progressBarProgressUpdateHandler;

        #region Properties

        /// <summary>
        /// The startingpath for the coderepository to search for solutions
        /// </summary>
        public static string StartingPath
        {
            get { return CodeRepository._startingPath; }
            set { CodeRepository._startingPath = value; }
        }

        public static int SolutionProgressCount { get; set; }

        public static int SolutionCount { get; set; }

        public static List<IWorkspace> Workspaces
        {
            get
            {
                return _workspaces;
            }
            set
            {
                _workspaces = value;
            }
        }

        public static List<string> Solutions
        {
            get
            {
                return _solutions;
            }
            set
            {
                _solutions = value;
            }
        }

        #endregion Properties

        #region Methods

        ///http://social.msdn.microsoft.com/Forums/eu/parallelextensions/thread/dbb4e493-7b12-4a9c-b500-b567dce0eca8
        /// <summary>
        /// From a list of paths to solution (.sln) files, create a list of IWorkspace objects.
        /// </summary>
        /// <param name="solutions"></param>
        /// <returns></returns>
        public static List<IWorkspace> GetWorkspacesParallel(List<string> solutions, ProgressBarMaxUpdateHandler progressBarMaxUpdateHandler, ProgressBarProgressUpdateHandler progressBarProgressUpdateHandler)
        {
            _progressBarProgressUpdateHandler = progressBarProgressUpdateHandler;

            SolutionCount = solutions.Count;
            if (progressBarMaxUpdateHandler != null)
            {
                progressBarMaxUpdateHandler(SolutionCount);
            }
            
            List<IWorkspace> workspaces = solutions.AsParallel().Select(path => GetWorkspace(path)).ToList<IWorkspace>();

            return workspaces;
        }

        private static IWorkspace GetWorkspace(string solutionPath)
        {
            lock (_syncObject)
            {
                SolutionProgressCount++;
                if (_progressBarProgressUpdateHandler != null)
                {
                    _progressBarProgressUpdateHandler(SolutionProgressCount);
                }
            }

            try
            {
                IWorkspace workspace = Workspace.LoadSolution(solutionPath);
                foreach (IProject project in workspace.CurrentSolution.Projects)
                {
                    CommonCompilation compil = project.GetCompilation();
                }
                return workspace;
            }
            catch (NotSupportedException nse)
            {
                Logger.Log(solutionPath);
            }
            catch (Exception exc)
            {
                Logger.Log("====================");
                Logger.Log(exc.Message);
                Logger.Log(exc.StackTrace);
                if (exc.InnerException != null)
                {
                    Logger.Log(exc.InnerException.Message);
                }
            }

            return null;
        }

        /// <summary>
        /// Get paths to solution files from a "solutions.txt" file.
        /// Put them in a list of strings.
        /// </summary>
        /// <returns></returns>
        public static List<string> GetSolutions(string solutionsTxtFilePath)
        {
            List<string> solutions = new List<string>();
            using (StreamReader file = new StreamReader(solutionsTxtFilePath))
            {
                string line = "";
                while ((line = file.ReadLine()) != null)
                {
                    if (!String.IsNullOrEmpty(line))
                    {
                        solutions.Add(line);
                    }
                }
            }

            return solutions;
        }

        /// <summary>
        /// Search recursively through directories for .sln files, starting with startDir
        /// </summary>
        /// <param name="sDir"></param>
        public static void DirSearch(string startDir, bool firstTime)
        {
            try
            {
                if (firstTime)
                {
                    foreach (string f in Directory.GetFiles(startDir, "*.sln"))
                    {
                        _solutions.Add(f);
                    }
                    firstTime = false;
                }
                foreach (string d in Directory.GetDirectories(startDir))
                {
                    foreach (string f in Directory.GetFiles(d, "*.sln"))
                    {
                        _solutions.Add(f);
                    }
                    DirSearch(d, firstTime);
                }
            }
            catch (System.Exception excpt)
            {
                throw excpt;
            }
        }

        /// <summary>
        /// Search for solutions and create a list of Workspaces for the solutions.
        /// </summary>
        /// <param name="startingPath"></param>
        /// <returns></returns>
        public static List<IWorkspace> RefreshWorkspaces()
        {
            Solutions = new List<string>();
            //After this call the Util.Solutions property is filled.
            DirSearch(_startingPath, true);

            //Load the solutions into workspaces. Non-compatible solution files 
            //(solution files < Visual Studio 2010,2008) will be discarded.
            return GetWorkspacesParallel(_solutions, null, null);
        }

        /// <summary>
        /// Create a solutions.txt file with the provided workspaces list
        /// and write it to the provided baseDirectorySolutionsTxtPath.
        /// </summary>
        /// <param name="workspaces"></param>
        /// <param name="baseDirectorySolutionsTxtPath"></param>
        public static void CreateSolutionsTxtFile(List<IWorkspace> workspaces, string baseDirectorySolutionsTxtPath)
        {
            using (StreamWriter writer = new StreamWriter(baseDirectorySolutionsTxtPath))
            {
                foreach (IWorkspace w in workspaces)
                {
                    //FilePath is the full path to the solution file.
                    writer.WriteLine(w.CurrentSolution.FilePath);
                }
            }
        }

        #endregion Methods

    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU Lesser General Public License (LGPLv3)


Written By
Software Developer (Senior)
Netherlands Netherlands
Languages: C#, ASP.NET, HTML, VB, Javascript.
Tools: Visual Studio 2010, 2012.
Databases: MS SQL Server, Oracle, SQLite.
Skills: MCPD Web Developer 4.0, MCSD 2.0
Likes: Solving problems at projecteuler.net. at #66 now.
Technologies:C#, Azure, Xamarin.iOS, Web API, T/SQL, PL/SQL, MSBuild, WIX, XSLT, WPF, WCF, JavaScript

I have been a programmer since 1995. At first at school where we had a computer club with nice Aster CT-80 (TRS-80 clone) computers and 1 MSX computer where I learned to program in BASIC. Later I had my own 8086 XT computer.
My first experience with programming was way before that when I was about 8. A friend of mine had a Commodore 64. He typed over a BASIC game from a computing magazine. The program worked but it contained an error. The thing he did was go to the source line that caused the error, deleted the line, and restarted the program. It worked every time he got an error...

Comments and Discussions