Tuesday, May 29, 2007

Compiling SharePoint 2007 audiences using the SharePoint object model (C# code sample)

A while ago I was looking for a way to start audience compilation using code. While I was looking in the SDK I stumbled upon this little phrase which was quite annoying - "Compiling audiences is not supported in the object model. " on
http://msdn2.microsoft.com/en-us/library/microsoft.office.server.audience.audiencemanager.aspx .

Fortunately, it does seem to be possible - here's what you need to do  (I added the code in a SharePoint application page - you know one of those pages that you add in the _layouts folder).

  • First add a reference to Microsoft.Office.Server.Search.dll (which you can find in the ISAPI folder in 12 Hive).
  • Audience compilation can take a while so you might want to show the user one of those new nice "Operation in progress" pages - you can do this using the SPLongOperation class
  • Next add the next code sample in your code behind:


SPLongOperation operation = new SPLongOperation(this.Page);
SearchContext searchcontext = SearchContext.GetContext(SPControl.GetContextSite(this.Context));

string[] args = new string[4];
args[0] = searchcontext.Name;
args[1] = "1"; //1= start compile, 0=stop
args[2] = "1"; //1=Full, 0=Incremental
args[3] = "Marketing"; //Audience name
Int32 runjob = Microsoft.Office.Server.Audience.AudienceJob.RunAudienceJob(args);



For more information about RunAudienceJob check out the SDK. I left out the code which checks the AudienceJobReturnCode for simplicity sake and you might also want to include some impersonation since the user might not have sufficient rights to run an audience job.

Other resources:

No comments: