In this post, we’ll see how we can programmatically execute Search Queries for Keywords using SharePoint 2013 Client Side Object Model (CSOM).
Create a Console Application in Visual Studio 2013 and name it as KeyWordSearch
Add a reference to Microsoft.SharePoint.Client.dll
Add a reference to Microsoft.SharePoint.Client.Search.dll and it is available in the location C:Program FilesCommon FilesMicrosoft Sharedweb server extensions15ISAPI
Add a reference to Microsoft.SharePoint.Client.Runtime.dll
When I fire a Search Query using the keyword ‘Sundar’ in online portal, it gives the below results.
We’ll attempt the same by invoking the SearchQuery using manged .NET Client Side Object Model (CSOM). We’ll be leveraging SearchExecutor class and KeyWordQuery class in the Microsoft.SharePoint.Client.Search and Microsoft.SharePoint.Client.Search.Query namespaces and invoking ExecuteQuery method to get the results back.
Replace the Program.cs with the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.Search;
using Microsoft.SharePoint.Client.Search.Query;
namespace ExecuteKeywordSearch
{
class Program
{
static void Main(string[] args)
{
//Assign User Id for your SharePoint Online tenant
string UserName = “youruserid@yoursite.onmicrosoft.com”;
//Assign password for your SharePoint online tenant
string Password = “yourpassword”;
//Create a SecureString object from password string, needed for SharePointOnlineCredentials class
SecureString SecurePassword = GetSecureString(Password);
using (var oClientContext = new ClientContext(“https://yoursite.sharepoint.com/”))
{
//assign SharePoint Online Credentials to ClientContext Class
oClientContext.Credentials = new SharePointOnlineCredentials(UserName, SecurePassword);
//Create an instance of KeywordQuery Class
KeywordQuery oKeyWordQuery = new KeywordQuery(oClientContext);
//Assign the Search Query
oKeyWordQuery.QueryText = “Sundar”;
//Associate SearchExecutor with ClientContext
SearchExecutor oSearchExecutor = new SearchExecutor(oClientContext);
//Execute the Search Query
ClientResult<ResultTableCollection> oResultTables = oSearchExecutor.ExecuteQuery(oKeyWordQuery);
oClientContext.ExecuteQuery();
foreach (var oResultRow in oResultTables.Value[0].ResultRows)
{
Console.WriteLine(oResultRow[“Title”].ToString());
Console.WriteLine(“n” + oResultRow[“Path”].ToString());
}
Console.ReadLine();
}
}
private static SecureString GetSecureString(String Password)
{
SecureString oSecurePassword = new SecureString();
foreach (Char c in Password.ToCharArray())
{
oSecurePassword.AppendChar(c);
}
return oSecurePassword;
}
}
}
When we execute the above piece of code, we’ll see the following search results that matches with screenshot (manual search) illustrated above.