Fixing stylecop violations (#5629)

This commit is contained in:
Clint Rutkas
2020-08-06 10:10:44 -07:00
committed by GitHub
parent 0f90af3c7d
commit ed36447bdf
13 changed files with 653 additions and 607 deletions

View File

@@ -1,8 +1,8 @@
using System;
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Collections.Generic;
using System.Data.Common;
using System.Data.OleDb;
using System.Text;
namespace Microsoft.Plugin.Indexer.SearchHelper
{

View File

@@ -1,83 +1,89 @@
using System;
using System.Collections.Generic;
using System.Data.OleDb;
namespace Microsoft.Plugin.Indexer.SearchHelper
{
public class OleDBSearch : ISearch, IDisposable
{
private OleDbCommand command;
private OleDbConnection conn;
private OleDbDataReader WDSResults;
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Data.OleDb;
namespace Microsoft.Plugin.Indexer.SearchHelper
{
public class OleDBSearch : ISearch, IDisposable
{
private OleDbCommand command;
private OleDbConnection conn;
private OleDbDataReader wDSResults;
private bool disposedValue;
[System.Diagnostics.CodeAnalysis.SuppressMessage("Security", "CA2100:Review SQL queries for security vulnerabilities",
Justification = "sqlQuery does not come from user input but is generated via the ISearchQueryHelper::GenerateSqlFromUserQuery " +
" see: https://docs.microsoft.com/en-us/windows/win32/search/-search-3x-wds-qryidx-searchqueryhelper#using-the-generatesqlfromuserquery-method")]
public List<OleDBResult> Query(string connectionString, string sqlQuery)
{
List<OleDBResult> result = new List<OleDBResult>();
using (conn = new OleDbConnection(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))
{
using (WDSResults = command.ExecuteReader())
{
if (WDSResults.HasRows)
{
while (WDSResults.Read())
{
List<Object> fieldData = new List<object>();
for (int i = 0; i < WDSResults.FieldCount; i++)
{
fieldData.Add(WDSResults.GetValue(i));
}
result.Add(new OleDBResult(fieldData));
}
}
}
}
}
return result;
}
/// Checks if all the variables related to database connection have been properly disposed
public bool HaveAllDisposableItemsBeenDisposed()
{
bool commandDisposed = false;
bool connDisposed = false;
bool resultDisposed = false;
try
{
command.ExecuteReader();
}
catch (InvalidOperationException)
{
commandDisposed = true;
}
try
{
WDSResults.Read();
}
catch (InvalidOperationException)
{
resultDisposed = true;
}
if (conn.State == System.Data.ConnectionState.Closed)
{
connDisposed = true;
}
return commandDisposed && resultDisposed && connDisposed;
[System.Diagnostics.CodeAnalysis.SuppressMessage(
"Security",
"CA2100:Review SQL queries for security vulnerabilities",
Justification = "sqlQuery does not come from user input but is generated via the ISearchQueryHelper::GenerateSqlFromUserQuery see: https://docs.microsoft.com/en-us/windows/win32/search/-search-3x-wds-qryidx-searchqueryhelper#using-the-generatesqlfromuserquery-method")]
public List<OleDBResult> Query(string connectionString, string sqlQuery)
{
List<OleDBResult> result = new List<OleDBResult>();
using (conn = new OleDbConnection(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))
{
using (wDSResults = command.ExecuteReader())
{
if (wDSResults.HasRows)
{
while (wDSResults.Read())
{
List<object> fieldData = new List<object>();
for (int i = 0; i < wDSResults.FieldCount; i++)
{
fieldData.Add(wDSResults.GetValue(i));
}
result.Add(new OleDBResult(fieldData));
}
}
}
}
}
return result;
}
// Checks if all the variables related to database connection have been properly disposed
public bool HaveAllDisposableItemsBeenDisposed()
{
bool commandDisposed = false;
bool connDisposed = false;
bool resultDisposed = false;
try
{
command.ExecuteReader();
}
catch (InvalidOperationException)
{
commandDisposed = true;
}
try
{
wDSResults.Read();
}
catch (InvalidOperationException)
{
resultDisposed = true;
}
if (conn.State == System.Data.ConnectionState.Closed)
{
connDisposed = true;
}
return commandDisposed && resultDisposed && connDisposed;
}
protected virtual void Dispose(bool disposing)
@@ -88,7 +94,7 @@ namespace Microsoft.Plugin.Indexer.SearchHelper
{
command?.Dispose();
conn?.Dispose();
WDSResults?.Dispose();
wDSResults?.Dispose();
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
@@ -97,18 +103,11 @@ namespace Microsoft.Plugin.Indexer.SearchHelper
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~OleDBSearch()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose()
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose(disposing: true);
GC.SuppressFinalize(this);
}
}
}
}
}

View File

@@ -1,8 +1,6 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
namespace Microsoft.Plugin.Indexer.SearchHelper
{
@@ -13,6 +11,5 @@ namespace Microsoft.Plugin.Indexer.SearchHelper
// Contains the Title of the file or folder
public string Title { get; set; }
}
}

View File

@@ -1,68 +1,72 @@
using System;
using System.Collections.Generic;
using Microsoft.Search.Interop;
namespace Microsoft.Plugin.Indexer.SearchHelper
{
public class WindowsSearchAPI
{
public bool DisplayHiddenFiles { get; set; }
private readonly ISearch WindowsIndexerSearch;
private readonly object _lock = new object();
private readonly UInt32 FILE_ATTRIBUTE_HIDDEN = 0x2;
public WindowsSearchAPI(ISearch windowsIndexerSearch, bool displayHiddenFiles = false)
{
this.WindowsIndexerSearch = windowsIndexerSearch;
this.DisplayHiddenFiles = displayHiddenFiles;
}
public List<SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword)
{
if(queryHelper == null)
// Copyright (c) Microsoft Corporation
// The Microsoft Corporation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using Microsoft.Search.Interop;
namespace Microsoft.Plugin.Indexer.SearchHelper
{
public class WindowsSearchAPI
{
public bool DisplayHiddenFiles { get; set; }
private readonly ISearch windowsIndexerSearch;
private readonly object _lock = new object();
private const uint _fileAttributeHidden = 0x2;
public WindowsSearchAPI(ISearch windowsIndexerSearch, bool displayHiddenFiles = false)
{
this.windowsIndexerSearch = windowsIndexerSearch;
DisplayHiddenFiles = displayHiddenFiles;
}
public List<SearchResult> ExecuteQuery(ISearchQueryHelper queryHelper, string keyword)
{
if (queryHelper == null)
{
throw new ArgumentNullException(paramName: nameof(queryHelper));
}
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;
}
public static void ModifyQueryHelper(ref ISearchQueryHelper queryHelper, string pattern)
{
if(pattern == null)
}
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;
}
public static void ModifyQueryHelper(ref ISearchQueryHelper queryHelper, string pattern)
{
if (pattern == null)
{
throw new ArgumentNullException(paramName: nameof(pattern));
}
@@ -70,62 +74,62 @@ namespace Microsoft.Plugin.Indexer.SearchHelper
if (queryHelper == null)
{
throw new ArgumentNullException(paramName: nameof(queryHelper));
}
// convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
if (pattern != "*")
{
pattern = pattern.Replace("*", "%", StringComparison.InvariantCulture);
pattern = pattern.Replace("?", "_", StringComparison.InvariantCulture);
if (pattern.Contains("%", StringComparison.InvariantCulture) || pattern.Contains("_", StringComparison.InvariantCulture))
{
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 + "') ";
}
}
}
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";
}
public IEnumerable<SearchResult> Search(string keyword, string pattern = "*", int maxCount = 30)
{
lock (_lock)
{
ISearchQueryHelper queryHelper;
InitQueryHelper(out queryHelper, maxCount);
ModifyQueryHelper(ref queryHelper, pattern);
return ExecuteQuery(queryHelper, keyword);
}
}
}
}
}
// convert file pattern if it is not '*'. Don't create restriction for '*' as it includes all files.
if (pattern != "*")
{
pattern = pattern.Replace("*", "%", StringComparison.InvariantCulture);
pattern = pattern.Replace("?", "_", StringComparison.InvariantCulture);
if (pattern.Contains("%", StringComparison.InvariantCulture) || pattern.Contains("_", StringComparison.InvariantCulture))
{
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 + "') ";
}
}
}
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";
}
public IEnumerable<SearchResult> Search(string keyword, string pattern = "*", int maxCount = 30)
{
lock (_lock)
{
ISearchQueryHelper queryHelper;
InitQueryHelper(out queryHelper, maxCount);
ModifyQueryHelper(ref queryHelper, pattern);
return ExecuteQuery(queryHelper, keyword);
}
}
}
}