Call Sharepoint Search service from Console Applicaton

26/03/2015 11:25

When we need to call Search.asmx service from other sites, we can use following code:

(first Add Web Service Reference to your console application project and name it e. g. SearchWS)

Update your site collection url and your credentials if needed

(If you get an error, check if Web application is not in anonymous access mode)

input xml format for soap is described in Protocol examples page

msdn.microsoft.com/en-us/library/dd927255(v=office.12).aspx


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SPSearchWebServiceCall.SearchWS;
using System.Net;
using System.Data;

namespace SPSearchWebServiceCall
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                string queryTerm = "test";

                QueryService service = new QueryService();
                service.Url = "https://yourSiteCollection/_vti_bin/search.asmx";
                NetworkCredential credential = new NetworkCredential();
               
                //credential.UserName = "testUser";
                //credential.Password = "yourPassword";
                //credential.Domain = "yourDomain";

                //service.Credentials = credential;

                service.Credentials = CredentialCache.DefaultCredentials;
                service.UseDefaultCredentials = true;

                System.Data.DataSet queryResults = service.QueryEx(GetXmlString(queryTerm));

                DataRowCollection resultRows = queryResults.Tables[0].Rows;
                foreach (DataRow row in resultRows)
                {
                    Console.WriteLine(GetColumnValue(row, "Title"));
                    Console.WriteLine(GetColumnValue(row, "Description"));
                    Console.WriteLine("");
                }

       //to get suggestions, result is in string array

         string inputXmlSug = BuildXmlForQuerySuggestions(queryTerm);
         string[] queryResults = service.GetQuerySuggestions(inputXmlSug);
                
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
            }
            finally {
                Console.ReadLine();
            }
        }

        /// <summary>
        /// Internal method, get empty string or value to string
        /// </summary>
        /// <param></param>
        /// <param></param>
        /// <returns></returns>
        private static string GetColumnValue(System.Data.DataRow _row, string _columnName)
        {
            return _row[_columnName] == null ? String.Empty : _row[_columnName].ToString();
        }

        private static string GetXmlString(string queryTerm)
        {
            /*
               The proceeding six lines of code is actually one line of code.
               It is separated into four lines here for readability.
               You will need to remove the line breaks when you copy the code to your project.
            */
               StringBuilder xmlString = new StringBuilder(@"<QueryPacket xmlns='urn:Microsoft.Search.Query'>
            <Query><SupportedFormats><Format revision='1'> urn:Microsoft.Search.Response.Document:Document
            </Format></SupportedFormats><Context><QueryText language='en-US' type='STRING'>");
               xmlString.Append(queryTerm);
               xmlString.Append("</QueryText></Context></Query></QueryPacket>");
            return xmlString.ToString();
        }


private static string BuildXmlForQuerySuggestions(string queryTerm)
        {
            string xmlString = string.Format("<QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1000'><Query><PreQuerySuggestions>true</PreQuerySuggestions><SupportedFormats><Format>urn:Microsoft.Search.Response.Document.Document</Format></SupportedFormats><Context><QueryText language='en-US' type='STRING'>{0}</QueryText></Context><Range><Count>10</Count></Range></Query></QueryPacket>", queryTerm);
            //string xmlString = "<?xml version='1.0' encoding='utf-8' ?><QueryPacket xmlns='urn:Microsoft.Search.Query' Revision='1'><Query domain='DEV'><PreQuerySuggestions>true</PreQuerySuggestions><Context><QueryText language='En-Us' type='STRING'>test</QueryText></Context><Range><StartAt>1</StartAt><Count>8</Count></Range><HighlightQuerySuggestions>true</HighlightQuerySuggestions></Query></QueryPacket>";
            return xmlString;
        }

    }
}