title: SharePoint 2010 add a new search scope programmatically
body: <p>You can add a new search scope via powershell:
  New-SPEnterpriseSearchQueryScope -SearchApplication "Search Service Application" -Name NewSearchScope -Description "New Search Test Scope" -DisplayInAdminUI 1–OwningSiteUrl <a href="http://servername/sites/" rel="nofollow">http://servername/sites/</a> </p>
  
  <p>But does anyone know of sample code that shows how to do this via OM ? (using the Microsoft.SharePoint.Administration namespace rather than Microsoft.Office.Server.Search)</p>
  
  <p>any pointers will be great</p>
  
  <p>regards
  Mo</p>
  
  <p><em><strong></em>*Update*<em>*</em></strong>
  ignoring error handling / logging etc, is this a valid way of doing  this:</p>
  
  <p>SPSite siteColl = (SPSite)properties.Feature.Parent;</p>
  
  <pre><code>        Microsoft.SharePoint.Administration.SPServiceApplication spserviceapp = siteColl.SearchServiceInstance.Service.Applications["Search Service Application"];
  
          SearchServiceApplication searchserviceapp = (SearchServiceApplication)spserviceapp;
  
          ScopeInfo scopeInfo = new ScopeInfo(); 
          scopeInfo.Name = "Scope test1";
          scopeInfo.Description = "Scope test1";
          scopeInfo.DisplayInAdminUI = true;
          scopeInfo.CompilationType = ScopeCompilationType.AlwaysCompile;
          scopeInfo.CompilationState = ScopeCompilationState.NeedsCompile;            
          int statusCode = 0;
          int scopeId = searchserviceapp.AddScope(scopeInfo, out statusCode);
          if (scopeId &gt; 0)
          {
              RuleInfo ruleInfo;
              ruleInfo = new RuleInfo(); 
              ruleInfo.FilterBehavior = ScopeRuleFilterBehavior.Include;
              ruleInfo.RuleType = ScopeRuleType.AllContent;
              int ruleId = searchserviceapp.AddRule(ruleInfo, scopeId);
          }
          searchserviceapp.Update(true); 
  </code></pre>
  
  <hr>
  
  <p>rather then the ssp way of searchcontext?</p>
  
  <p>SearchContext searchctx = null;<br>
  searchctx = SearchContext.GetContext(web.Site);<br>
  Scopes scopes = new Scopes(searchctx);<br>
  Scope currentScope = scopes.AllScopes.Create(
          "CurrentScopeName", string.Empty, new Uri(web.Site.Url), true,
          string.Format("{0}/Search/Pages/Results.aspx", web.Site.Url),
          ScopeCompilationType.AlwaysCompile);<br>
  currentScope.Update();<br>
  currentScope.Rules.CreateUrlRule(ScopeRuleFilterBehavior.Include,
          UrlScopeRuleType.Domain, web.Site.Url);<br>
  ScopeDisplayGroup group = scopes.GetDisplayGroup(new Uri(web.Url),
          "Search Dropdown");    group.Add(currentScope);
      group.Update();<br>
  scopes.StartCompilation();</p>
  
  <pre><code>scopes.Update();
  </code></pre>