When working on a intranet or external site in SharePoint – chances are that you are going to incorporate search in your solution. In some cases you would probably need to separate your search results based on a rule and in case of SharePoint you would use search scopes for that.
Let’s see how you can automatically provision search scopes to the site when its deployed or configured.
In my example I am using a feature with a feature receiver class.
In my solution I will need to add the following DLL references:
- Microsoft.SharePoint.dll
- Microsoft.Office.Server.dll,
- Microsoft.Office.Server.Search.dll
Also, here are the namespace references you will need to add:
- using Microsoft.Office.Server;
- using Microsoft.Office.Server.Administration;
- using Microsoft.Office.Server.Search;
- using Microsoft.Office.Server.Search.Administration;
In my FeatureActivated method I have the following code that performs scope provisioning:
using (SPWeb web = properties.Feature.Parent as SPWeb)
{
ServerContext serverctx = null;
SearchContext searchctx = null;
serverctx = ServerContext.Current;
searchctx = SearchContext.GetContext(serverctx);
Scopes scopes = new Scopes(searchctx);
Scope NewScope = scopes.AllScopes.Create(
"NewScope", string.Empty,
new Uri(SPContext.Current.Site.Url), true,
"Search/Pages/Results.aspx", ScopeCompilationType.AlwaysCompile);
NewScope.Update();
NewScope.Rules.CreateUrlRule(ScopeRuleFilterBehavior.Include,
UrlScopeRuleType.HostName, string.Empty);
ScopeDisplayGroup group = scopes.GetDisplayGroup(new
Uri(SPContext.Current.Site.Url), "All Sites");
group.Add(NewScope);
group.Update();
}
}
scopes.StartCompilation();
scopes.Update();
}
The important part is to perform a StartCompilation to actually apply your changes.
Good Luck!