Sep 19, 2009

Creating Search scopes programmatically

Requirement:Creating the scopes programmatically and creating the rule for it

We can create search scopes in two ways ,one is through providing the content source as scope rule and another is by providing the web address and then providing the url of the folder as the rule.

Through second way we can provide any list or document libraryy as the content source for the scope

We will go through each of them in detail .

Before creating scope check if scope already exists or not

To Check if scope already exists

Create one console application

and in it add Microsoft.Sharepoint.dll and Microsoft.Sharepoint.Office.Server.dll as reference and paste this code snippet in the main method

foreach (Microsoft.Office.Server.Search.Administration.Scope sspScope in

sspScopes)

{

if (sspScope.Name == ''ScopeName")

{

isValidScope = true;

break;

}

}

Create Using content source

//Add these references in the code

using Microsoft.Office.Server.Search.Administration;
using Microsoft.SharePoint;

SearchContext context;
using (SPSite site = new SPSite(”http://<SSPsite>”))
{
context = SearchContext.GetContext(site);
}
Schema sspSchema = new Schema(context);
ManagedPropertyCollection properties = sspSchema.AllManagedProperties;
Scopes scopes = new Scopes(context);
ScopeCollection sspScopes = scopes.AllScopes;
Scope newScope = sspScopes.Create(”Name”, “Description”,
null, // System.Uri object representing the owning site URL
true, // True to display the scope in the SSP Administrator UI
null, // A string specifying the alternate results page for the scope
ScopeCompilationType.AlwaysCompile); // Includes your content sources to the created Scope
foreach (string ContentSourceName in YourContentSourcesNames)
{
newScope.Rules.CreatePropertyQueryRule(ScopeRuleFilterBehavior.Include,
properties["ContentSource"], // Managed Property
ContentSourceName);
}
// Update Scopes
scopes.StartCompilation();

2)using scope rule as WebAdress and specify the url of folder

as scope.In this Scope is limited to a particular list.

This way we can include as many urls in the the scope rule

//Create the new scope

Scope newScope = sspScopes.Create(“Scope Title”, Scope Description, null, true, null, ScopeCompilationType.AlwaysCompile);

SPList ListName = site.RootWeb.Lists.GetByName("ListName");

if (ListName!= null)

{

//Scope Url is the PodCast List url.

string scopeUrl = ListName.ParentWeb.Url.ToString() + "/" + ListName.RootFolder.Url.ToString();

newScope.Rules.CreateUrlRule(ScopeRuleFilterBehavior.Include, UrlScopeRuleType.Folder, scopeUrl);

scopes.StartCompilation();

}

Thus scope is ready to use.

If you feel this content is of some use then please post your comments.

Enjoy coding!!!

No comments:

Post a Comment