Friday, March 11, 2016

Change search settings via client object model on SPWeb level in Sharepoint

In Sharepoint you may set search settings for whole site collection (Site settings > Site collection administration > Search settings) or for particular site (Site settings > Search > Search settings):

In search settings page you may change such settings as search center url, search results page, search navigation (tabs which are displayed on search results page):

Settings on SPWeb level have priority over site collection settings. When it may be useful to use search settings on SPWeb level? Consider the following example: we have single site collection and number of language sub sites in it:

For better user experience we may create own search center for each language version as sub site of particular language site: http://example.com/en/search and http://example.com/fi/haku (in this example we also use localized urls). In this case search requests from English site should go to English search center, and from Finnish – to Finnish one. How we can set search settings for particular SPWeb?

The following code shows how we may do it via client object model:

   1: var clientContext = new ClientContext("http://example.com/en");
   2: var secure = new SecureString();
   3: foreach (char c in "password")
   4: {
   5:     secure.AppendChar(c);
   6: }
   7: var credentials = new SharePointOnlineCredentials("user@example.com", secure);
   8: clientContext.Credentials = credentials;
   9: var web = clientContext.Web;
  10:  
  11: clientContext.Load(web, w => w.AllProperties);
  12: clientContext.ExecuteQuery();
  13:  
  14: var allProperties = web.AllProperties;
  15: allProperties["SRCH_ENH_FTR_URL_WEB"] = "~sitecollection/en/search/pages";
  16: allProperties["SRCH_SB_SET_WEB"] = "{\"Inherit\":false,\"ResultsPageAddress\":" +
  17:     "\"~sitecollection/en/search/pages/results.aspx\",\"ShowNavigation\":false}";
  18:  
  19: web.Update();
  20: clientContext.ExecuteQuery();

For Finnish sub site code will be the same, except site url and urls of search results page specified in SRCH_ENH_FTR_URL_WEB and SRCH_SB_SET_WEB property bag settings. Also let’s mention that settings on site collection level can be set by similar way with another property bag settings: SRCH_ENH_FTR_URL_SITE and SRCH_SB_SET_SITE (see e.g. this example of how to use them: Set search settings in all site collections of Sharepoint web application via PowerShell).

As we use client object model this approach can be used for setting search settings for Sharepoint Online as well.

No comments:

Post a Comment