Monday, May 31, 2010

Adding a new federated location to search service applicaitons.

As we know the Shared services provider is gone in SharePoint 2010 and instead we have a nice SharePoint service application model. I do not try to explain the difference in details as I found some nice well written article readily available and hit easily by googling. The way I understand, in brief, the consumers can access the service application using the service application proxy which knows how to find out where the application is running. I think that is enough here and my focus is to tell you how to add a new federated location to a search service application.

I recently played with the search service application and I had to add a federated location to the search application automatically, we did that in SharePoint 2007 using SearchContext but it is not an option here in SharePoint 2010, SearchContext is still available but that is marked as obsolete.

So way to do is, by getting all the search service application and iterating through them and adding the new federated location if it is not already existing.

The challenge is how to get all the search service application in the farm.

First get all the services using the SPFarm.Local.Services, and iterate through all the services and find the services of type SearchQueryAndSiteSettingsService. The search applications can be found there.

//Get all the services in this farm
services = Microsoft.SharePoint.Administration.SPFarm.Local.Services;

//Iterate through all the services to find the SearchQueryAndSiteSettingsServices
foreach (SPService service in services)
{
//All Search service applicaitons are under SearchQueryAndSiteSettingsService
if (service is SearchQueryAndSiteSettingsService)
{
//Get all the search service application.
serviceApplicaiton = service.Applications;

foreach (SPServiceApplication applicaiton in serviceApplicaiton)
{

//Check whether the application is a search service application
if (applicaiton is SearchServiceApplication)
{

//This is a search service applicaiton
searchApplication = (SearchServiceApplication)applicaiton;

//Check whether the new location is already added.
if (!IsLocationExists(searchApplication.LocationConfigurations))
{
//Create a new locaiton
federatedLocation = new LocationConfiguration();

//Import the federated location
GetStream(ref filestream);

federatedLocation.Import(filestream);

searchApplication.AddNewLocationConfiguration(federatedLocation);
}
}
}
}
}