Compiling audiences in SharePoint 2010

Compiling audiences from code has always been a bit troublesome to do. The things you need aren’t that well documented so it takes some Googling to get everything into place. But for some reason, the articles I found didn’t seem to work in my SharePoint 2010 installation. The result of my job was always 4: AUDIENCEJOB_NOPORTALSITE_ERROR. I tried numerous options, untill I found at that:

1) You need to set the first argument to RunAudienceJob to the ID of the webapplication
2) You cannot use the ID of the Search Service, but you need to get the ID of the User Profile Service Application. You can find this by opening up the User Profile application in Central Administration and copy/paste it from the URL.

But what if you need to get the User Profile Application ID dynamically in code? Well there doesn’t seem to be an out of the box way of doing this, so I used Reflector to find the classes and properties need it to get there. The code snippet below will let you compile an audience for a given site with a given name. If you want to compile all audiences, just omit the 4th argument.


public static void CompileAudience(string audienceName, bool fullCompile, Guid siteId)
{
SPServiceContext serviceContext;
using (SPSite site = new SPSite(siteId))
{
serviceContext = SPServiceContext.GetContext(site);

// get the assembly which hosts the UserProfile class
Assembly userProfilesAssembly = typeof(UserProfile).Assembly;

// get the type of the UserProfileApplicationProxy
Type userProfileApplicationProxyType = userProfilesAssembly.GetType("Microsoft.Office.Server.Administration.UserProfileApplicationProxy");

// get the proxy object
object proxy = serviceContext.GetDefaultProxy(userProfileApplicationProxyType);
// get the UserProfileApplication property which holds the actual application
object profile = proxy.GetType().GetProperty("UserProfileApplication", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(proxy, null);
// get the Id of the application
Guid applicationId = ((Microsoft.SharePoint.Administration.SPPersistedObject)(profile)).Id;

string[] args = new string[4];
args[0] = applicationId.ToString();
args[1] = "1";
args[2] = fullCompile ? "1" : "0";
args[3] = audienceName;

int result = Microsoft.Office.Server.Audience.AudienceJob.RunAudienceJob(args);
AudienceJobReturnCode returnCode = (AudienceJobReturnCode)Enum.Parse(typeof(AudienceJobReturnCode), result.ToString());
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *