Monday, December 26, 2011

How to add custom search scope to the search drop down in sharepoint

Once you've created a custom search scope in search adminstration, you may need to add it the search drop down of a site collection. You can create a feature to add the custom search scope.

In feature activated event I'm adding the custom search scope to the search dropdown and in feature deactivating event I'm removing it.

Here is the code


public override void
FeatureActivated(SPFeatureReceiverProperties properties)
       {
           SPWebApplication webApp =
((SPWebApplication)properties.Feature.Parent);
           foreach (SPSite site in webApp.Sites)
           {
               using (SPWeb spWeb = site.OpenWeb())
               {
                   string SPsiteurl = site.Url;
                   spWeb.AllowUnsafeUpdates = true;



                   SearchContext searchContext =
SearchContext.GetContext(spWeb.Site);
                   Scopes scopes = new Scopes(searchContext);
                   Scope skillSearchScope =
scopes.GetSharedScope("MycustomScope");
                   ScopeDisplayGroupCollection
scopedisplayGroupCollection = scopes.AllDisplayGroups;
                   ScopeDisplayGroup displayGroup =
scopes.GetDisplayGroup(new Uri(spWeb.Url), "Search Dropdown");
                   displayGroup.Remove(skillSearchScope);
                   displayGroup.Add(skillSearchScope);
                   displayGroup.Update();
                   spWeb.Update();
                   spWeb.AllowUnsafeUpdates = false;
               }
           }
       }


       public override void
FeatureDeactivating(SPFeatureReceiverProperties properties)
       {
           SPWebApplication webApp =
((SPWebApplication)properties.Feature.Parent);
           foreach (SPSite site in webApp.Sites)
           {
               using (SPWeb spWeb = site.OpenWeb())
               {
                   string SPsiteurl = spWeb.Site.Url;
                   spWeb.AllowUnsafeUpdates = true;

                   Uri siteuri = new Uri(spWeb.Site.Url);
                   SearchContext searchContext =
SearchContext.GetContext(spWeb.Site);
                   Scopes scopes = new Scopes(searchContext);

                   Scope skillSearchScope =
scopes.GetSharedScope("MyCustomScope");
                   ScopeDisplayGroup displayGroup =
scopes.GetDisplayGroup(new Uri(spWeb.Url), "Search Dropdown");
                   displayGroup.Remove(skillSearchScope);
                   displayGroup.Update();

                   spWeb.Update();
                   spWeb.AllowUnsafeUpdates = false;
               }
           }
       }
       public override void
FeatureInstalled(SPFeatureReceiverProperties properties)
       { }
       public override void
FeatureUninstalling(SPFeatureReceiverProperties properties)
       { }

No comments:

Post a Comment