Monday, December 26, 2011

Create Search scope programmatically in Sharepoint

In order to create a search scope programmatically, you need to get instance of Search context.

Here is the code

SearchContext searchContext = SearchContext.GetContext(
context);
               Scopes scopes = new Scopes(searchContext);
               Scope newScope =
scopes.AllScopes.Create("MycustomScope",
"This is a sample scope for testing purpose", null, true,
"Resultpage.aspx", ScopeCompilationType.AlwaysCompile);
               Schema sspSchema = new Schema(searchContext);

newScope.Rules. CreatePropertyQueryRule(ScopeRuleFilterBehavior.Include,
sspSchema.AllManagedProperties["contentclass"],
"urn:content-class:SPSPeople");
               scopes.StartCompilation();
 


You can deploy it via feature. Here is the complete code.


public override void
FeatureActivated(
SPFeatureReceiverProperties properties)
       {
           ServerContext context = ServerContext.Current;
           if (context != null)
           {
               SearchContext searchContext = SearchContext.GetContext(context);
               Scopes scopes = new Scopes(searchContext);
               Scope newScope =
scopes.AllScopes.Create(GetConfigValue("DropDownText"),
GetConfigValue("Description"), null, true,
GetConfigValue("ResultPage"), ScopeCompilationType.AlwaysCompile);
               Schema sspSchema = new Schema(searchContext);

newScope.Rules.CreatePropertyQueryRule(ScopeRuleFilterBehavior.Include,
sspSchema.AllManagedProperties["contentclass"],
"urn:content-class:SPSPeople");
               scopes.StartCompilation();
           }

       }
       public override void
FeatureDeactivating(SPFeatureReceiverProperties properties)
       {
           ServerContext context = ServerContext.Current;
           if (context != null)
           {
               SearchContext searchContext = SearchContext.GetContext(context);
               Scopes scopes = new Scopes(searchContext);
               Scope newScope = null;

               try
               {
                   newScope = scopes.GetScope(null,
"MycustomScope");
               }
               catch (Exception ex)//For Scope Not Found Exception
               { }
               if (newScope != null)
               {
                   scopes.GetScope(null,"MycustomScoe").Delete();
                   scopes.Update();
               }

           }


       }
       public override void
FeatureInstalled(SPFeatureReceiverProperties properties)
       {
           //throw new NotImplementedException();
       }
       public override void
FeatureUninstalling(SPFeatureReceiverProperties properties)
       {
           //throw new NotImplementedException();
       }

1 comment:

  1. Follow this link. I achieved with this

    http://vamshikrishnabudarapu.wordpress.com/2013/12/16/creating-search-scopes-programatically-using-spnavigation-class/

    ReplyDelete