Exemple #1
0
        internal bool PathIsIndexed(string path)
        {
            var csm          = new CSearchManager();
            var indexManager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();

            return(indexManager.IncludedInCrawlScope(path) > 0);
        }
Exemple #2
0
        public static void InitQueryHelper(out ISearchQueryHelper queryHelper, int maxCount)
        {
            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = maxCount;

            // Set list of columns we want to display, getting the path presently
            queryHelper.QuerySelectColumns = "System.ItemUrl, System.FileName, System.FileAttributes";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // To filter based on title for now
            queryHelper.QueryContentProperties = "System.FileName";

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";
        }
Exemple #3
0
        private string GetSql(string aqs)
        {
            CSearchManager        searchManager  = new CSearchManager();
            CSearchCatalogManager catalogManager = searchManager.GetCatalog("SystemIndex");
            CSearchQueryHelper    queryHelper    = catalogManager.GetQueryHelper();

            return(queryHelper.GenerateSQLFromUserQuery(aqs));
        }
Exemple #4
0
        static void Main(string[] args)
        {
            CSearchManager        manager        = new CSearchManager();
            CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");
            CSearchQueryHelper    queryHelper    = catalogManager.GetQueryHelper();
            string sql = queryHelper.GenerateSQLFromUserQuery("text kind:music");

            Console.WriteLine(sql);
        }
Exemple #5
0
        internal CSearchQueryHelper CreateQueryHelper()
        {
            // This uses the Microsoft.Search.Interop assembly
            var manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            var catalogManager = manager.GetCatalog(SystemIndex);

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            var queryHelper = catalogManager.GetQueryHelper();

            return(queryHelper);
        }
Exemple #6
0
 internal static bool PathIsIndexed(string path)
 {
     try
     {
         var csm          = new CSearchManager();
         var indexManager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();
         return(indexManager.IncludedInCrawlScope(path) > 0);
     }
     catch (COMException)
     {
         // Occurs because the Windows Indexing (WSearch) is turned off in services and unable to be used by Explorer plugin
         return(false);
     }
 }
Exemple #7
0
        public static void RemoveSearchFolder(string strPath)
        {
            if (strPath == null || strPath.Length == 0)
            {
                return;
            }

            CSearchManager           manager            = new CSearchManager();
            CSearchCatalogManager    catalogManager     = manager.GetCatalog("SystemIndex");
            CSearchCrawlScopeManager searchScopeManager = catalogManager.GetCrawlScopeManager();

            searchScopeManager.RevertToDefaultScopes();
            searchScopeManager.RevertToDefaultScopes();
            searchScopeManager.RemoveScopeRule("file:///" + strPath);
        }
Exemple #8
0
        public void AddPathToSearchIndex(string fullPath)
        {
            Uri path = new Uri(fullPath);

            string indexingPath = path.ToString();

            CSearchManager           csm     = new CSearchManager();
            CSearchCrawlScopeManager manager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();

            if (manager.IncludedInCrawlScope(indexingPath) == 0)
            {
                manager.AddUserScopeRule(indexingPath, 1, 1, 0);
                manager.SaveAll();
            }
        }
Exemple #9
0
        public void ReIndexFolder(string strPath)
        {
            if (strPath == null || strPath.Length == 0)
            {
                return;
            }

            String                   searchPath         = "file:///" + strPath.ToLower();
            CSearchManager           manager            = new CSearchManager();
            CSearchCatalogManager    catalogManager     = manager.GetCatalog("SystemIndex");
            CSearchCrawlScopeManager searchScopeManager = catalogManager.GetCrawlScopeManager();

            // create search root
            uint             rootCnt = 0;
            CEnumSearchRoots roots   = searchScopeManager.EnumerateRoots();
            bool             exist   = false;

            do
            {
                CSearchRoot aRoot = new CSearchRoot();

                roots.Next(1, out aRoot, ref rootCnt);
                if (rootCnt != 0)
                {
                    roots.Skip(1);
                    if (aRoot.RootURL == searchPath)
                    {
                        exist = true;
                    }
                }
            } while (rootCnt != 0);

            if (!exist)
            {
                CSearchRoot r = new CSearchRoot();
                r.RootURL = searchPath;
                searchScopeManager.AddRoot(r);
                searchScopeManager.SaveAll();
            }

            searchScopeManager.RevertToDefaultScopes();
            //if (searchScopeManager.IncludedInCrawlScope(searchPath) == 0)
            //{
            searchScopeManager.AddUserScopeRule(searchPath, 1, 1, 0);
            searchScopeManager.SaveAll();
            //}
            catalogManager.ReindexSearchRoot(searchPath);
        }
Exemple #10
0
        // strPath: c:\folder\subfolder\
        public static void AddSearchFolder(string strPath)
        {
            if (strPath == null || strPath.Length == 0)
            {
                return;
            }

            CSearchManager           manager            = new CSearchManager();
            CSearchCatalogManager    catalogManager     = manager.GetCatalog("SystemIndex");
            CSearchCrawlScopeManager searchScopeManager = catalogManager.GetCrawlScopeManager();

            searchScopeManager.RevertToDefaultScopes();
            if (searchScopeManager.IncludedInCrawlScope("file:///" + strPath) == 0)
            {
                searchScopeManager.AddUserScopeRule("file:///" + strPath, 1, 1, 0);
                searchScopeManager.SaveAll();
            }
        }
        static void PerformSearch(string libPath, string query)
        {
            string                sqlQuery;
            CSearchManager        srchMgr     = null;
            CSearchCatalogManager srchCatMgr  = null;
            CSearchQueryHelper    queryHelper = null;

            try
            {
                srchMgr     = new CSearchManager();
                srchCatMgr  = srchMgr.GetCatalog("SystemIndex");
                queryHelper = srchCatMgr.GetQueryHelper();
                sqlQuery    = queryHelper.GenerateSQLFromUserQuery(query);
            }
            finally
            {
                if (queryHelper != null)
                {
                    Marshal.FinalReleaseComObject(queryHelper);
                    queryHelper = null;
                }
                if (srchCatMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchCatMgr);
                    srchCatMgr = null;
                }
                if (srchMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchMgr);
                    srchMgr = null;
                }
            }

            Console.Error.WriteLine(sqlQuery);
            Console.Error.WriteLine();

            PerformQuery(libPath, sqlQuery);
        }
Exemple #12
0
        /// <summary>
        /// Performs a full-text search against the Windows Search Index, by a given file system <paramref name="path"/>
        /// and <paramref name="query"/>. This generates an SQL query that is passed to the Windows Search query processor.
        /// <para>If you know in advance the SQL query you want to pass, use <see cref="PerformQuery"/>.</para>
        /// </summary>
        /// <param name="path">A path in the local file system.</param>
        /// <param name="query">Any full-text search string or search operators accepted by the Windows Search query engine.</param>
        /// <param name="progress">Optionally provide an <see cref="IProgress{T}"/> object to view progress output.</param>
        public static List <SearchResult> PerformSearch(string path, string query, IProgress <string> progress = null)
        {
            string                sqlQuery;
            CSearchManager        srchMgr     = null;
            CSearchCatalogManager srchCatMgr  = null;
            CSearchQueryHelper    queryHelper = null;

            try {
                srchMgr     = new CSearchManager();
                srchCatMgr  = srchMgr.GetCatalog("SystemIndex");
                queryHelper = srchCatMgr.GetQueryHelper();
                sqlQuery    = queryHelper.GenerateSQLFromUserQuery(query);
            }
            finally {
                if (queryHelper != null)
                {
                    Marshal.FinalReleaseComObject(queryHelper);
                    queryHelper = null;
                }

                if (srchCatMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchCatMgr);
                    srchCatMgr = null;
                }

                if (srchMgr != null)
                {
                    Marshal.FinalReleaseComObject(srchMgr);
                    srchMgr = null;
                }
            }

            progress?.Report($"Full query: {sqlQuery}");

            return(PerformQuery(path, sqlQuery, progress));
        }
Exemple #13
0
        //strPath: e.g. c:/disk
        public List <CSearchResultItem> SearchFolder(string strContent, string strPath)
        {
            List <CSearchResultItem> items = new List <CSearchResultItem>();

            if (strContent == null || strContent.Length == 0 || strPath == null || strPath.Length == 0)
            {
                return(items);
            }

            // Thie uses SearchAPI interop assembly
            CSearchManager manager = new CSearchManager();

            // the SystemIndex catalog is the default catalog that windows uses
            CSearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            CSearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            queryHelper.QueryContentLocale = 2052;
            queryHelper.QueryMaxResults    = 100;
            queryHelper.QueryKeywordLocale = 2052;

            //queryHelper.
            // set the columns we want,只检索文件的名字和内容,不然属性太多了,会出现狗屁不通的结果。
            queryHelper.QuerySelectColumns     = "System.ItemPathDisplay,System.Search.Rank,System.ItemNameDisplay";
            queryHelper.QueryWhereRestrictions = "AND scope='file:" + strPath + "'";
            queryHelper.QuerySorting           = "System.ItemPathDisplay ASC ";
            // queryHelper.s
            queryHelper.QueryContentProperties = "System.Search.Contents,System.ItemNameDisplay";
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(strContent);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString);

            try
            {
                // open it
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                OleDbCommand command = new OleDbCommand(sqlQuery, conn);

                // execute the command, which returns the results as an OleDbDataReader.
                OleDbDataReader WDSResults = command.ExecuteReader();

                while (WDSResults.Read())
                {
                    CSearchResultItem aResult = new CSearchResultItem();
                    aResult.FullPath = WDSResults.GetString(0);
                    aResult.Rank     = WDSResults.GetInt32(1);
                    aResult.DispName = WDSResults.GetString(2);
                    items.Add(aResult);
                }

                WDSResults.Close();
            }
            catch (Exception e)
            {
            }
            finally
            {
                conn.Close();
            }

            return(items);
        }
Exemple #14
0
 static SearchHelper()
 {
     m_results = new ThreadSafeObservableCollection <SearchResult>();
     cManager  = new CSearchManager();
 }
Exemple #15
0
        private IEnumerable <string> FindFiles(string pattern)
        {
            string userQuery = " ";

            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = 10;

            // Set list of columns we want
            queryHelper.QuerySelectColumns = "System.ItemUrl";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
            if (pattern != "*")
            {
                pattern = pattern.Replace("*", "%");
                pattern = pattern.Replace("?", "_");

                if (pattern.Contains("%") || pattern.Contains("_"))
                {
                    queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
                }
                else
                {
                    // if there are no wildcards we can use a contains which is much faster as it uses the index
                    queryHelper.QueryWhereRestrictions += " AND Contains(System.FileName, '" + pattern + "') ";
                }
            }

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";

            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(userQuery);

            Console.WriteLine(sqlQuery);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (var conn = new OleDbConnection(queryHelper.ConnectionString))
            {
                // open the connection
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                using (var command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (var results = command.ExecuteReader())
                    {
                        while (results.Read())
                        {
                            var url = results.GetString(0);

                            if (url.StartsWith("file:", StringComparison.InvariantCultureIgnoreCase))
                            {
                                yield return(url.Substring(5).Replace('/', '\\'));
                            }
                        }
                    }
                }
            }
        }
Exemple #16
0
 //        /// <summary>
 //        /// Queries the windows search index using simple keyword matching on the FileName and ItemDisplayName.
 //        /// </summary>
 //        private static string SQL_FromSimpleQuery(string keywords)
 //        {
 //            var tostrip = new List<string>
 //            {
 //                "\\",
 //                "/",
 //                ":",
 //                //"*",
 //                "?",
 //                "\"",
 //                "<",
 //                ">",
 //                "|"
 //            };
 //            foreach (var c in tostrip) {
 //                keywords = keywords.Replace(c, "");
 //            }
 //
 //            var select =
 //                string.Format(
 //                    "SELECT TOP {0} System.ItemNameDisplay, System.ItemPathDisplay, System.ItemUrl FROM SystemIndex",
 //                    MaxResults);
 //            var where = "";
 //            if (keywords != "*") {
 //                where =
 //                    string.Format(
 //                        " WHERE (System.Filename LIKE '{0}%' OR CONTAINS (System.ItemNameDisplay, '\"{0}\"'))", keywords);
 //            }
 //
 //            var order = " ORDER BY System.Search.Rank DESC";
 //            var sql = select + where + order;
 //            return sql;
 //        }
 /// <summary>
 /// Queries the windows search index from an AQS query.
 /// </summary>
 /// <remarks><see cref="https://msdn.microsoft.com/en-us/library/aa965711%28v=vs.85%29.aspx"/></remarks>
 private static string SQL_FromAQS(string aqsQuery)
 {
     var manager = new CSearchManager();
     var catalogManager = manager.GetCatalog("SystemIndex");
     var queryHelper = catalogManager.GetQueryHelper();
     queryHelper.QuerySelectColumns =
         "System.ItemNameDisplay, System.ItemPathDisplay, System.ItemUrl, System.Search.Rank";
     queryHelper.QueryWhereRestrictions = "AND scope='file:' AND System.FileAttributes <> ALL BITWISE 2";
     queryHelper.QueryContentProperties = "System.ItemNameDisplay";
     queryHelper.QueryMaxResults = MaxResults;
     queryHelper.QuerySorting = "System.Search.Rank DESC";
     var sql = queryHelper.GenerateSQLFromUserQuery(aqsQuery);
     return sql;
 }
 static VistaSearchProviderHelper()
 {
     m_results = new ThreadSafeObservableCollection<SearchResult>();
     cManager = new CSearchManagerClass();
 }
Exemple #18
0
        public List <Result> Query(Query query, bool isFullQuery)
        {
            var results = new List <Result>();

            if (!string.IsNullOrEmpty(query.Search))
            {
                var searchQuery = query.Search;
                if (_settings.MaxSearchCount <= 0)
                {
                    _settings.MaxSearchCount = 30;
                }

                var regexMatch = Regex.Match(searchQuery, reservedStringPattern);

                if (!regexMatch.Success)
                {
                    try
                    {
                        if (_driveDetection.DisplayWarning())
                        {
                            results.Add(new Result
                            {
                                Title    = Properties.Resources.Microsoft_plugin_indexer_drivedetectionwarning,
                                SubTitle = Properties.Resources.Microsoft_plugin_indexer_disable_warning_in_settings,
                                IcoPath  = WarningIconPath,
                                Action   = e =>
                                {
                                    Helper.OpenInShell("ms-settings:cortana-windowssearch");
                                    return(true);
                                },
                            });
                        }

                        // This uses the Microsoft.Search.Interop assembly
                        var searchManager     = new CSearchManager();
                        var searchResultsList = _api.Search(searchQuery, searchManager, maxCount: _settings.MaxSearchCount).ToList();

                        // If the delayed execution query is not required (since the SQL query is fast) return empty results
                        if (searchResultsList.Count == 0 && isFullQuery)
                        {
                            return(new List <Result>());
                        }

                        foreach (var searchResult in searchResultsList)
                        {
                            var path = searchResult.Path;

                            // Using CurrentCulture since this is user facing
                            var    toolTipTitle = string.Format(CultureInfo.CurrentCulture, "{0} : {1}", Properties.Resources.Microsoft_plugin_indexer_name, searchResult.Title);
                            var    toolTipText  = string.Format(CultureInfo.CurrentCulture, "{0} : {1}", Properties.Resources.Microsoft_plugin_indexer_path, path);
                            string workingDir   = null;
                            if (_settings.UseLocationAsWorkingDir)
                            {
                                workingDir = _fileSystem.Path.GetDirectoryName(path);
                            }

                            Result r = new Result();
                            r.Title       = searchResult.Title;
                            r.SubTitle    = Properties.Resources.Microsoft_plugin_indexer_subtitle_header + ": " + path;
                            r.IcoPath     = path;
                            r.ToolTipData = new ToolTipData(toolTipTitle, toolTipText);
                            r.Action      = c =>
                            {
                                bool hide = true;
                                if (!Helper.OpenInShell(path, null, workingDir))
                                {
                                    hide = false;
                                    var name = $"Plugin: {_context.CurrentPluginMetadata.Name}";
                                    var msg  = Properties.Resources.Microsoft_plugin_indexer_file_open_failed;
                                    _context.API.ShowMsg(name, msg, string.Empty);
                                }

                                return(hide);
                            };
                            r.ContextData = searchResult;

                            // If the result is a directory, then it's display should show a directory.
                            if (_fileSystem.Directory.Exists(path))
                            {
                                r.QueryTextDisplay = path;
                            }

                            results.Add(r);
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        // The connection has closed, internal error of ExecuteReader()
                        // Not showing this exception to the users
                    }
                    catch (Exception ex)
                    {
                        Log.Exception("Something failed", ex, GetType());
                    }
                }
            }

            return(results);
        }
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ds [file search pattern] [userQuery]");
                Console.WriteLine("[file search pattern] can include '*' and '?' wildcards");
                Console.WriteLine("[userQuery] query to look for inside the document (with operators of OR, AND). Optional.");
                return;
            }

            // First parameter is file name pattern
            string pattern   = args[0];
            string userQuery = " ";

            // Everything else is considered to be a search query
            for (int i = 1; i < args.Length; i++)
            {
                userQuery += args[i] + " ";
            }

            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = 10;

            // Set list of columns we want
            queryHelper.QuerySelectColumns = "System.ItemPathDisplay";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
            if (pattern != "*")
            {
                pattern = pattern.Replace("*", "%");
                pattern = pattern.Replace("?", "_");

                if (pattern.Contains("%") || pattern.Contains("_"))
                {
                    queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
                }
                else
                {
                    // if there are no wildcards we can use a contains which is much faster as it uses the index
                    queryHelper.QueryWhereRestrictions += " AND Contains(System.FileName, '" + pattern + "') ";
                }
            }

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";

            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(userQuery);

            Console.WriteLine(sqlQuery);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString))
            {
                // open the connection
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                using (OleDbCommand command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (OleDbDataReader WDSResults = command.ExecuteReader())
                    {
                        while (WDSResults.Read())
                        {
                            // col 0 is our path in display format
                            Console.WriteLine("{0}", WDSResults.GetString(0));
                        }
                    }
                }
            }
        }
 static VistaSearchProviderHelper()
 {
     m_results = new ThreadSafeObservableCollection <SearchResult>();
     cManager  = new CSearchManagerClass();
 }
Exemple #21
0
        public List <Result> Query(Query query, bool isFullQuery)
        {
            var results = new List <Result>();

            if (!string.IsNullOrEmpty(query.Search))
            {
                var searchQuery = query.Search;
                if (_settings.MaxSearchCount <= 0)
                {
                    _settings.MaxSearchCount = 30;
                }

                var regexMatch = Regex.Match(searchQuery, reservedStringPattern);

                if (!regexMatch.Success)
                {
                    try
                    {
                        if (_driveDetection.DisplayWarning())
                        {
                            results.Add(new Result
                            {
                                Title    = _context.API.GetTranslation("Microsoft_plugin_indexer_drivedetectionwarning"),
                                SubTitle = _context.API.GetTranslation("Microsoft_plugin_indexer_disable_warning_in_settings"),
                                IcoPath  = WarningIconPath,
                                Action   = e =>
                                {
                                    try
                                    {
                                        Process.Start(GetWindowsSearchSettingsProcessInfo());
                                    }
                                    catch (Exception ex)
                                    {
                                        Log.Exception("Microsoft.Plugin.Indexer", $"Unable to launch Windows Search Settings: {ex.Message}", ex, "Query");
                                    }

                                    return(true);
                                },
                            });
                        }

                        // This uses the Microsoft.Search.Interop assembly
                        var searchManager     = new CSearchManager();
                        var searchResultsList = _api.Search(searchQuery, searchManager, isFullQuery, maxCount: _settings.MaxSearchCount).ToList();

                        // If the delayed execution query is not required (since the SQL query is fast) return empty results
                        if (searchResultsList.Count == 0 && isFullQuery)
                        {
                            return(new List <Result>());
                        }

                        foreach (var searchResult in searchResultsList)
                        {
                            var    path         = searchResult.Path;
                            var    toolTipTitle = string.Format(CultureInfo.CurrentCulture, "{0} : {1}", _context.API.GetTranslation("Microsoft_plugin_indexer_name"), searchResult.Title);
                            var    toolTipText  = string.Format(CultureInfo.CurrentCulture, "{0} : {1}", _context.API.GetTranslation("Microsoft_plugin_indexer_path"), path);
                            string workingDir   = null;
                            if (_settings.UseLocationAsWorkingDir)
                            {
                                workingDir = Path.GetDirectoryName(path);
                            }

                            Result r = new Result();
                            r.Title       = searchResult.Title;
                            r.SubTitle    = "Search: " + path;
                            r.IcoPath     = path;
                            r.ToolTipData = new ToolTipData(toolTipTitle, toolTipText);
                            r.Action      = c =>
                            {
                                bool hide;
                                try
                                {
                                    Process.Start(new ProcessStartInfo
                                    {
                                        FileName         = path,
                                        UseShellExecute  = true,
                                        WorkingDirectory = workingDir,
                                    });
                                    hide = true;
                                }
                                catch (Win32Exception)
                                {
                                    var name = $"Plugin: {_context.CurrentPluginMetadata.Name}";
                                    var msg  = "Can't Open this file";
                                    _context.API.ShowMsg(name, msg, string.Empty);
                                    hide = false;
                                }

                                return(hide);
                            };
                            r.ContextData = searchResult;

                            // If the result is a directory, then it's display should show a directory.
                            if (Directory.Exists(path))
                            {
                                r.QueryTextDisplay = path;
                            }

                            results.Add(r);
                        }
                    }
                    catch (InvalidOperationException)
                    {
                        // The connection has closed, internal error of ExecuteReader()
                        // Not showing this exception to the users
                    }
                    catch (Exception ex)
                    {
                        Log.Info(ex.ToString());
                    }
                }
            }

            return(results);
        }
        static void Main(string[] args)
        {
            if (args.Length < 1)
            {
                Console.WriteLine("Usage: ds [file search pattern] [userQuery]");
                Console.WriteLine("[file search pattern] can include '*' and '?' wildcards");
                Console.WriteLine("[userQuery] query to look for inside the document (with operators of OR, AND). Optional.");
                return;
            }

            // First parameter is file name pattern
            string pattern = args[0];
            string userQuery = " ";
            // Everything else is considered to be a search query
            for (int i = 1; i < args.Length; i++)
            {
                userQuery += args[i] + " ";
            }

            // This uses the Microsoft.Search.Interop assembly
            CSearchManager manager = new CSearchManager();

            // SystemIndex catalog is the default catalog in Windows
            ISearchCatalogManager catalogManager = manager.GetCatalog("SystemIndex");

            // Get the ISearchQueryHelper which will help us to translate AQS --> SQL necessary to query the indexer
            ISearchQueryHelper queryHelper = catalogManager.GetQueryHelper();

            // Set the number of results we want. Don't set this property if all results are needed.
            queryHelper.QueryMaxResults = 10;

            // Set list of columns we want
            queryHelper.QuerySelectColumns = "System.ItemPathDisplay";

            // Set additional query restriction
            queryHelper.QueryWhereRestrictions = "AND scope='file:'";

            // convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
            if (pattern != "*")
            {
                pattern = pattern.Replace("*", "%");
                pattern = pattern.Replace("?", "_");

                if (pattern.Contains("%") || pattern.Contains("_"))
                {
                    queryHelper.QueryWhereRestrictions += " AND System.FileName LIKE '" + pattern + "' ";
                }
                else
                {
                    // if there are no wildcards we can use a contains which is much faster as it uses the index
                    queryHelper.QueryWhereRestrictions += " AND Contains(System.FileName, '" + pattern + "') ";
                }
            }

            // Set sorting order
            queryHelper.QuerySorting = "System.DateModified DESC";

            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(userQuery);
            Console.WriteLine(sqlQuery);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (System.Data.OleDb.OleDbConnection conn = new OleDbConnection(queryHelper.ConnectionString))
            {
                // open the connection
                conn.Open();

                // now create an OleDB command object with the query we built above and the connection we just opened.
                using (OleDbCommand command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (OleDbDataReader WDSResults = command.ExecuteReader())
                    {
                        while (WDSResults.Read())
                        {
                            // col 0 is our path in display format
                            Console.WriteLine("{0}", WDSResults.GetString(0));
                        }
                    }
                }
            }
        }
        public void AddPathToSearchIndex(string fullPath)
        {
            Uri path = new Uri(fullPath);

            string indexingPath = path.ToString();

            CSearchManager csm = new CSearchManager();
            CSearchCrawlScopeManager manager = csm.GetCatalog("SystemIndex").GetCrawlScopeManager();

            if (manager.IncludedInCrawlScope(indexingPath) == 0)
            {
                manager.AddUserScopeRule(indexingPath, 1, 1, 0);
                manager.SaveAll();
            }
        }