Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

Source Code Super Search

, 10 Mar 2009
A simple solution for searching source code directories
BSCodeGrep.zip
BSCodeGrep
branches
0.9 VS Add-In
BSCodeGrep
Classes
folder_explore copy.ico
Forms
icons
add.png
application_form.png
arrow_right.png
delete.png
find.png
folder.png
folder_explore copy.ico
folder_explore.png
folder_page.png
information.png
lightning.png
magnifier.png
note_edit.png
package_system.png
star.png
Properties
Settings.settings
CodeSearchAddIn
CodeSearchAddIn.AddIn
CodeSearchAddIn.csproj.user
tags
trunk
BSCodeGrep
bin
Classes
folder_explore copy.ico
Forms
icons
add.png
application_form.png
arrow_right.png
delete.png
find.png
folder.png
folder_explore copy.ico
folder_explore.png
folder_page.png
information.png
lightning.png
magnifier.png
note_edit.png
package_system.png
script_go.png
star.png
Properties
Settings.settings
BSCodeGrep_src.zip
Properties
Settings.settings
Classes
Forms
icons
add.png
application_form.png
arrow_right.png
BSLogo.jpg
delete.png
exclamation.png
find.png
folder.png
folder_explore copy.ico
folder_explore.png
folder_page.png
information.png
lightning.png
magnifier.png
note_edit.png
package_system.png
page_save.png
script_go.png
star.png
VS2008_Add-In.zip
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace BSCodeGrep
{
    public partial class Form1 : Form
    {
        private CAppSettings _appSettings = null;
        private IOWorker _mThreadWorker = null;
        private DateTime? _sdt = null;
        private static bool _sIsRunning = false;

        public Form1()
        {
            InitializeComponent();
            LoadUserSettings();
            InitializeBackgroundWorker();
        }

        private void LoadUserSettings()
        {
            _appSettings = new CAppSettings();
            _appSettings.Reload();

            foreach (string p in _appSettings.SearchPaths)
                comboBox1.Items.Add(p);

            foreach (string p in _appSettings.SearchFilters)
                comboBox2.Items.Add(p);

            foreach (string p in _appSettings.SearchPatterns)
                comboBox3.Items.Add(p);
        }

        private FileInfo GetSelectedNodeFile()
        {
            FileInfo fi = null;
            string f;

            if (treeView1.SelectedNode.Text.IndexOf(":\\") > -1)
            {
                f = treeView1.SelectedNode.Text;
            }
            else
            {
                f = treeView1.SelectedNode.Parent.Text;
            }

            if (File.Exists(f))
            {
                fi = new FileInfo(f);
            }
            return fi;
        }

        private void StartSearchThread()
        {
            if (ValidateAndPersistControls())
            {
                treeView1.Nodes.Clear();
                string[] filters;

                if (comboBox2.Text.IndexOf(" ") > -1)
                {
                    filters = comboBox2.Text.Split(' ');
                }
                else
                {
                    filters = new string[] { comboBox2.Text };
                }

                IOWorker.SearchSettings uso = new IOWorker.SearchSettings();
                uso.path = comboBox1.Text;
                uso.filters = filters;
                uso.pattern = comboBox3.Text;
                uso.NamesOnly = false;

                if (checkBox2.Checked)
                    uso.NamesOnly = true;

                button2.Enabled = false;
                _sdt = DateTime.Now;
                searchStatusLabel.Text = "";
                Form1._sIsRunning = true;

                backgroundWorker1.RunWorkerAsync(new IOWorker(uso));

                Thread _thread = new Thread(new ThreadStart(NotifyStatus));
                _thread.Priority = ThreadPriority.Lowest;
                _thread.Start();
            }
        }

        private bool ValidateAndPersistControls()
        {
            bool isValid = false;

            if (comboBox1.Text != "" || comboBox2.Text != "" || comboBox3.Text != "")
            {
                List<string> paths = new List<string>();
                List<string> filters = new List<string>();
                List<string> patterns = new List<string>();

                if (!comboBox1.Items.Contains(comboBox1.Text))
                    comboBox1.Items.Add(comboBox1.Text);

                if (!comboBox2.Items.Contains(comboBox2.Text))
                    comboBox2.Items.Add(comboBox2.Text);

                if (!comboBox3.Items.Contains(comboBox3.Text))
                    comboBox3.Items.Add(comboBox3.Text);

                foreach (string s in comboBox1.Items)
                    paths.Add(s);

                foreach (string s in comboBox2.Items)
                    filters.Add(s);

                foreach (string s in comboBox3.Items)
                    patterns.Add(s);

                _appSettings.SearchPaths = paths;
                _appSettings.SearchFilters = filters;
                _appSettings.SearchPatterns = patterns;
                _appSettings.Save();
                isValid = true;
            }
            else
            {
                searchStatusLabel.Text = "Path, extension, and pattern must be specified";
            }

            if (!checkBox1.Checked && !checkBox2.Checked)
            {
                searchStatusLabel.Text = "No Search Type Selected (In Files or File Names)";
                isValid = false;
            }

            //if (comboBox1.Text.Substring(comboBox1.Text.Length - 1) == "\\")
            //    comboBox1.Text = comboBox1.Text.Remove(comboBox1.Text.Length - 1);

            return isValid;
        }

        #region Threading Events
        private void InitializeBackgroundWorker()
        {
            backgroundWorker1.DoWork += new DoWorkEventHandler(OnDoWorkSearch);
            backgroundWorker1.RunWorkerCompleted += new RunWorkerCompletedEventHandler(OnWorkCompletedSearch);
        }

        private void OnDoWorkSearch(object sender, DoWorkEventArgs e)
        {
            _mThreadWorker = (IOWorker)e.Argument;
            _mThreadWorker.CreateIdx();
        }

        private void OnWorkCompletedSearch(object sender, RunWorkerCompletedEventArgs e)
        {
            Form1._sIsRunning = false;
            for (int i = 0; i < _mThreadWorker.GetSearchResults.Count; i++)
            {
                TreeNode tn;
                TreeNode stn;

                treeView1.Nodes.Add(tn = new TreeNode(_mThreadWorker.GetSearchResults[i].FilePath, 5, 5));

                for (int z = 0; z < _mThreadWorker.GetSearchResults[i].Lines.Count; z++)
                {
                    tn.Nodes.Add(stn = new TreeNode(_mThreadWorker.GetSearchResults[i].Lines[z], 7, 7));
                    stn.BackColor = Color.Yellow;
                    stn.NodeFont = new Font("Courier New", 10, FontStyle.Italic);
                }
            }
            button2.Enabled = true;
            DateTime fdt = DateTime.Now;

            searchStatusLabel.Text = String.Format("Found {0} results searching {1} files in {2} seconds",
                _mThreadWorker.GetSearchResults.Count,
                _mThreadWorker.SearchedCount.ToString(),
                (fdt - (DateTime)_sdt).Seconds.ToString());
        }

        private void NotifyStatus()
        {
            string[] status = new string[] { "S", "e", "a", "r", "c", "h", "i", "n", "g", ".", ".", "." };
            List<string> chars = new List<string>();
            chars.AddRange(status);

            while (Form1._sIsRunning)
            {
                for (int i = 0; i < chars.Count; i++)
                {
                    Thread.Sleep(100);
                    threadStatusLabel.Text += status[i];
                }
                threadStatusLabel.Text = "";
            }
            threadStatusLabel.Text = "";
        }

        #endregion

        #region Control Events

        //Browse Folder Dialog Button
        private void button1_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.RootFolder = Environment.SpecialFolder.MyComputer;
            folderBrowserDialog1.Description = "Starting Search Location";
            folderBrowserDialog1.ShowNewFolderButton = false;
            DialogResult result = folderBrowserDialog1.ShowDialog();

            if (result == DialogResult.OK)
            {
                comboBox1.Text = folderBrowserDialog1.SelectedPath;
            }
        }

        //Go Button - Create index & script
        private void button2_Click(object sender, EventArgs e)
        {
            StartSearchThread();
        }

        //Search File Names Only
        private void checkBox2_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox2.Checked)
                checkBox1.Checked = false;
        }

        //Search Inside Files
        private void checkBox1_CheckedChanged(object sender, EventArgs e)
        {
            if (checkBox1.Checked)
                checkBox2.Checked = false;
        }

        //Clear User Settings History
        private void button3_Click(object sender, EventArgs e)
        {
            _appSettings.SearchPaths.Clear();
            _appSettings.SearchFilters.Clear();
            _appSettings.SearchPatterns.Clear();
            _appSettings.Save();

            comboBox1.Items.Clear();
            comboBox2.Items.Clear();
            comboBox3.Items.Clear();

            comboBox1.Text = "";
            comboBox2.Text = "";
            comboBox3.Text = "";
        }

        //ContextMenu Open
        private void contextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (treeView1.SelectedNode != null)
            {
                contextMenuStrip1.Enabled = true;
            }
            else
            {
                contextMenuStrip1.Enabled = false;
            }
        }

        //ContextMenu Click Events
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileInfo f = GetSelectedNodeFile();

            if (f != null)
                System.Diagnostics.Process.Start(f.FullName);
        }

        private void openWithNotepadToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileInfo f = GetSelectedNodeFile();

            if (f != null)
                System.Diagnostics.Process.Start("notepad.exe", f.FullName);
        }

        private void openContainingFolderToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileInfo f = GetSelectedNodeFile();

            if (f != null)
                System.Diagnostics.Process.Start(f.Directory.FullName);
        }

        private void openProjectSLNFileToolStripMenuItem_Click(object sender, EventArgs e)
        {
            FileInfo f = GetSelectedNodeFile();

            if (f != null)
            {
                DirectoryInfo di = new DirectoryInfo(f.Directory.Parent.Parent.FullName);

                try
                {
                    string[] slnFiles = Directory.GetFiles(di.FullName, "*.sln", SearchOption.AllDirectories);

                    if (slnFiles.Length > 0)
                    {
                        System.Diagnostics.Process.Start(slnFiles[0]);
                    }
                    else
                    {
                        MessageBox.Show(" No Visual Studio Solutions Found In\r\n This Directory or 2 Directories Up ",
                                         "Alert", MessageBoxButtons.OK,
                                         MessageBoxIcon.Exclamation);
                    }
                }
                catch (UnauthorizedAccessException) { }
            }
        }

        #endregion

    }
}

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 Code Project Open License (CPOL)

About the Author

thund3rstruck
Software Developer
United States United States
I'm a typical 30 year old generation X guy that likes video games, NFL football, and comic style art. I have an insatiable passion for programming and doing what ever it takes to become a better programmer.

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 10 Mar 2009
Article Copyright 2008 by thund3rstruck
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid