예제 #1
0
        public List <SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword)
        {
            List <SearchResult> _Result = new List <SearchResult>();

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

            // execute the command, which returns the results as an OleDBResults.
            List <OleDBResult> oleDBResults = WindowsIndexerSearch.Query(queryHelper.ConnectionString, sqlQuery);

            // Loop over all records from the database
            foreach (OleDBResult oleDBResult in oleDBResults)
            {
                if (oleDBResult.fieldData[0] == DBNull.Value || oleDBResult.fieldData[1] == DBNull.Value || oleDBResult.fieldData[2] == DBNull.Value)
                {
                    continue;
                }

                UInt32 fileAttributes = (UInt32)((Int64)oleDBResult.fieldData[2]);
                bool   isFileHidden   = (fileAttributes & FILE_ATTRIBUTE_HIDDEN) == FILE_ATTRIBUTE_HIDDEN;

                if (DisplayHiddenFiles || !isFileHidden)
                {
                    var uri_path = new Uri((string)oleDBResult.fieldData[0]);
                    var result   = new SearchResult
                    {
                        Path  = uri_path.LocalPath,
                        Title = (string)oleDBResult.fieldData[1]
                    };
                    _Result.Add(result);
                }
            }

            return(_Result);
        }
        static void doSearch(Object state)
        {
            SearchObjectState sos = (SearchObjectState)state;

            if (sos.SearchString == string.Empty)
            {
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"System.ItemNameDisplay\",\"System.ItemPathDisplay\"";

            try
            {
                using (cConnection = new OleDbConnection(
                           cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                               cHelper.GenerateSQLFromUserQuery(
                                   sos.SearchString
                                   ),
                               cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    m_results.Add(new SearchResult()
                                    {
                                        Name = reader[0].ToString(), Path = reader[1].ToString()
                                    });
                                    if (ToAbortFlag)
                                    {
                                        break;
                                    }
                                }
                                reader.Close();

                                IsWorkingFlag = false;
                            }
                        }
                    }
                    // TODO: Investigate possible RaceOnRCWCleanup exception.
                    cConnection.Close();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }
예제 #3
0
        public List <SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword, bool isFullQuery = false)
        {
            if (queryHelper == null)
            {
                throw new ArgumentNullException(paramName: nameof(queryHelper));
            }

            List <SearchResult> results = new List <SearchResult>();

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

            if (!isFullQuery)
            {
                sqlQuery = simplifiedQuery;
            }
            else if (simplifiedQuery.Equals(sqlQuery, StringComparison.CurrentCultureIgnoreCase))
            {
                // if a full query is requested but there is no difference between the queries, return empty results
                return(results);
            }

            // execute the command, which returns the results as an OleDBResults.
            List <OleDBResult> oleDBResults = windowsIndexerSearch.Query(queryHelper.ConnectionString, sqlQuery);

            // Loop over all records from the database
            foreach (OleDBResult oleDBResult in oleDBResults)
            {
                if (oleDBResult.FieldData[0] == DBNull.Value || oleDBResult.FieldData[1] == DBNull.Value || oleDBResult.FieldData[2] == DBNull.Value)
                {
                    continue;
                }

                uint fileAttributes = (uint)((long)oleDBResult.FieldData[2]);
                bool isFileHidden   = (fileAttributes & _fileAttributeHidden) == _fileAttributeHidden;

                if (DisplayHiddenFiles || !isFileHidden)
                {
                    var uri_path = new Uri((string)oleDBResult.FieldData[0]);
                    var result   = new SearchResult
                    {
                        Path  = uri_path.LocalPath,
                        Title = (string)oleDBResult.FieldData[1],
                    };

                    results.Add(result);
                }
            }

            return(results);
        }
예제 #4
0
        public List <SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword, bool isFullQuery = false)
        {
            if (queryHelper == null)
            {
                throw new ArgumentNullException(paramName: nameof(queryHelper));
            }

            List <SearchResult> results = new List <SearchResult>();

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

            if (!isFullQuery)
            {
                sqlQuery = simplifiedQuery;
            }
            else if (simplifiedQuery.Equals(sqlQuery, StringComparison.CurrentCultureIgnoreCase))
            {
                // if a full query is requested but there is no difference between the queries, return empty results
                return(results);
            }

            // execute the command, which returns the results as an OleDBResults.
            List <OleDBResult> oleDBResults = windowsIndexerSearch.Query(queryHelper.ConnectionString, sqlQuery);

            // Loop over all records from the database
            foreach (OleDBResult oleDBResult in oleDBResults)
            {
                if (oleDBResult.FieldData[0] == DBNull.Value || oleDBResult.FieldData[1] == DBNull.Value)
                {
                    continue;
                }

                // # is URI syntax for the fragment component, need to be encoded so LocalPath returns complete path
                // Using OrdinalIgnoreCase since this is internal and used with symbols
                var string_path = ((string)oleDBResult.FieldData[0]).Replace("#", "%23", StringComparison.OrdinalIgnoreCase);
                var uri_path    = new Uri(string_path);

                var result = new SearchResult
                {
                    Path  = uri_path.LocalPath,
                    Title = (string)oleDBResult.FieldData[1],
                };

                results.Add(result);
            }

            return(results);
        }
예제 #5
0
        public List <SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword)
        {
            if (queryHelper == null)
            {
                throw new ArgumentNullException(paramName: nameof(queryHelper));
            }

            List <SearchResult> results = new List <SearchResult>();

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

            // execute the command, which returns the results as an OleDBResults.
            List <OleDBResult> oleDBResults = windowsIndexerSearch.Query(queryHelper.ConnectionString, sqlQuery);

            // Loop over all records from the database
            foreach (OleDBResult oleDBResult in oleDBResults)
            {
                if (oleDBResult.FieldData[0] == DBNull.Value || oleDBResult.FieldData[1] == DBNull.Value)
                {
                    continue;
                }

                // # is URI syntax for the fragment component, need to be encoded so LocalPath returns complete path
                // Using OrdinalIgnoreCase since this is internal and used with symbols
                var string_path = ((string)oleDBResult.FieldData[0]).Replace("#", "%23", StringComparison.OrdinalIgnoreCase);

                if (!Uri.TryCreate(string_path, UriKind.RelativeOrAbsolute, out Uri uri_path))
                {
                    Log.Warn($"Failed to parse URI '${string_path}'", typeof(WindowsSearchAPI));
                    continue;
                }

                var result = new SearchResult
                {
                    Path  = uri_path.LocalPath,
                    Title = (string)oleDBResult.FieldData[1],
                };

                results.Add(result);
            }

            return(results);
        }
예제 #6
0
        public List <SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword)
        {
            if (queryHelper == null)
            {
                throw new ArgumentNullException(paramName: nameof(queryHelper));
            }

            List <SearchResult> results = new List <SearchResult>();

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

            // execute the command, which returns the results as an OleDBResults.
            List <OleDBResult> oleDBResults = windowsIndexerSearch.Query(queryHelper.ConnectionString, sqlQuery);

            // Loop over all records from the database
            foreach (OleDBResult oleDBResult in oleDBResults)
            {
                if (oleDBResult.FieldData[0] == DBNull.Value || oleDBResult.FieldData[1] == DBNull.Value || oleDBResult.FieldData[2] == DBNull.Value)
                {
                    continue;
                }

                uint fileAttributes = (uint)((long)oleDBResult.FieldData[2]);
                bool isFileHidden   = (fileAttributes & _fileAttributeHidden) == _fileAttributeHidden;

                if (DisplayHiddenFiles || !isFileHidden)
                {
                    var uri_path = new Uri((string)oleDBResult.FieldData[0]);
                    var result   = new SearchResult
                    {
                        Path  = uri_path.LocalPath,
                        Title = (string)oleDBResult.FieldData[1],
                    };

                    results.Add(result);
                }
            }

            return(results);
        }
예제 #7
0
        public List <SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword)
        {
            List <SearchResult> _Result = new List <SearchResult>();
            // Generate SQL from our parameters, converting the userQuery from AQS->WHERE clause
            string sqlQuery = queryHelper.GenerateSQLFromUserQuery(keyword);

            // --- Perform the query ---
            // create an OleDbConnection object which connects to the indexer provider with the windows application
            using (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 (command = new OleDbCommand(sqlQuery, conn))
                {
                    // execute the command, which returns the results as an OleDbDataReader.
                    using (WDSResults = command.ExecuteReader())
                    {
                        if (WDSResults.HasRows)
                        {
                            while (WDSResults.Read())
                            {
                                if (WDSResults.GetValue(0) != DBNull.Value && WDSResults.GetValue(1) != DBNull.Value)
                                {
                                    var uri_path = new Uri(WDSResults.GetString(0));
                                    var result   = new SearchResult
                                    {
                                        Path  = uri_path.LocalPath,
                                        Title = WDSResults.GetString(1)
                                    };
                                    _Result.Add(result);
                                }
                            }
                        }
                    }
                }
            }

            return(_Result);
        }
예제 #8
0
        static void doSearch(object state)
        {
            // check if user wants to show file extensions. always show on windows < 8 due to property missing
            string      displayNameColumn = "System.ItemNameDisplayWithoutExtension";
            RegistryKey hideFileExt       = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced", false);
            object      hideFileExtValue  = hideFileExt?.GetValue("HideFileExt");

            if ((hideFileExtValue != null && hideFileExtValue.ToString() == "0") || !Interop.Shell.IsWindows8OrBetter)
            {
                displayNameColumn = "System.ItemNameDisplay";
            }

            SearchObjectState sos = (SearchObjectState)state;

            if (sos.SearchString == string.Empty)
            {
                m_results.Clear();
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"" + displayNameColumn + "\",\"System.ItemUrl\",\"System.ItemPathDisplay\",\"System.DateModified\"";
            cHelper.QueryMaxResults    = MAX_RESULT;
            cHelper.QuerySorting       = "System.Search.Rank desc";

            OleDbConnection cConnection;

            try
            {
                using (cConnection = new OleDbConnection(
                           cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                               cHelper.GenerateSQLFromUserQuery(
                                   sos.SearchString
                                   ),
                               cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    if (ToAbortFlag)
                                    {
                                        break;
                                    }

                                    SearchResult result = new SearchResult()
                                    {
                                        Name = reader[0].ToString(), Path = reader[1].ToString(), PathDisplay = reader[2].ToString(), DateModified = reader[3].ToString()
                                    };

                                    if (result.Name.EndsWith(".lnk"))
                                    {
                                        result.Name = result.Name.Substring(0, result.Name.Length - 4); // Windows always hides this regardless of setting, so do it
                                    }
                                    m_results.Add(result);
                                }

                                IsWorkingFlag = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                CairoLogger.Instance.Error("Error in doSearch.", ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }
        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));
                        }
                    }
                }
            }
        }
예제 #10
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('/', '\\'));
                            }
                        }
                    }
                }
            }
        }
        static void doSearch(Object state)
        {
            SearchObjectState sos = (SearchObjectState)state;
            if (sos.SearchString == string.Empty)
            {
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"System.ItemNameDisplay\",\"System.ItemPathDisplay\"";

            try
            {
                using (cConnection = new OleDbConnection(
                            cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                            cHelper.GenerateSQLFromUserQuery(
                                sos.SearchString
                            ),
                            cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    m_results.Add(new SearchResult() { Name = reader[0].ToString(), Path = reader[1].ToString() });
                                    if (ToAbortFlag)
                                        break;
                                }
                                reader.Close();

                                IsWorkingFlag = false;
                            }
                        }

                    }
                    // TODO: Investigate possible RaceOnRCWCleanup exception.
                    cConnection.Close();
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }
예제 #12
0
        static void doSearch(Object state)
        {
            SearchObjectState sos = (SearchObjectState)state;

            if (sos.SearchString == string.Empty)
            {
                m_results.Clear();
                sos.Reset.Set();
                return;
            }
            cHelper = cManager.GetCatalog("SYSTEMINDEX").GetQueryHelper();
            cHelper.QuerySelectColumns = "\"System.ItemNameDisplay\",\"System.ItemUrl\",\"System.ItemPathDisplay\",\"System.DateModified\"";
            cHelper.QueryMaxResults    = MAX_RESULT;
            cHelper.QuerySorting       = "System.Search.Rank desc";

            OleDbConnection cConnection;

            try
            {
                using (cConnection = new OleDbConnection(
                           cHelper.ConnectionString))
                {
                    cConnection.Open();
                    using (OleDbCommand cmd = new OleDbCommand(
                               cHelper.GenerateSQLFromUserQuery(
                                   sos.SearchString
                                   ),
                               cConnection))
                    {
                        if (cConnection.State == ConnectionState.Open)
                        {
                            using (OleDbDataReader reader = cmd.ExecuteReader())
                            {
                                m_results.Clear();
                                IsWorkingFlag = true;

                                while (!reader.IsClosed && reader.Read())
                                {
                                    if (ToAbortFlag)
                                    {
                                        break;
                                    }

                                    SearchResult result = new SearchResult()
                                    {
                                        Name = reader[0].ToString(), Path = reader[1].ToString(), PathDisplay = reader[2].ToString(), DateModified = reader[3].ToString()
                                    };
                                    m_results.Add(result);
                                }

                                IsWorkingFlag = false;
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
            }

            sos.Reset.Set();
            ToAbortFlag = false;
        }