Thursday, June 4, 2009

How to update search scope rules programmatically

I'm changing my content sources to contain multiple web applications instead of one web application per content source. I currently have rules set up for my scopes to use the corresponding content source. I need to change this to use the new content source and add a rule for the URL. Since I have hundreds of site collections I'd rather do this programmatically.
Below is the basic outline of how I'm doing this.


  SearchContext context;
using (SPSite site = new SPSite("http://hostheader"))
{
context = SearchContext.GetContext(site);
}
Schema sspSchema = new Schema(context);
ManagedPropertyCollection properties = sspSchema.AllManagedProperties;

Scopes scopes = new Scopes(context);
ScopeCollection allscopes = scopes.AllScopes;
foreach (Scope scope in allscopes)
{
if (scope.Name == "scopethatneedstobeupdated")
{
try
{


ScopeRulesEnumerator sre = (ScopeRulesEnumerator) scope.Rules.GetEnumerator();
while (sre.MoveNext())
{

sre.Current.Delete();
sre.Reset();
scopes.Update();
}

}
catch (Exception e)
{

Console.WriteLine(e.ToString());

}



scope.Rules.CreatePropertyQueryRule(ScopeRuleFilterBehavior.Include, properties["ContentSource"], "newcontentsource");
scope.Rules.CreateUrlRule(ScopeRuleFilterBehavior.Include, UrlScopeRuleType.HostName, "http://hostheader");
scope.Rules.CreateUrlRule(ScopeRuleFilterBehavior.Exclude, UrlScopeRuleType.HostName, "http://allothers");

scope.Update();


}

}
scopes.StartCompilation();

3 comments:

  1. Mr Dude, could you provide a bit of detail of how you are adding this to your production site? The code makes sense, but what do you do if you have a SP admin that doesn't allow you to run queries directly against the prod site?

    ReplyDelete
  2. I created this as a command-line tool that I ran on the server. I don't believe that you can access these objects through web services, so your only option may be to convince your server admin to allow you to run this on the server.

    ReplyDelete
  3. I was certainly hoping to find a way to run this (well, similar) without running directly on the server. Admin won't even allow us to work in the SSP or Central Admin. Thanks for the reply.

    ReplyDelete