Custom Audience Targeting SharePoint 2010

Today I will  show how to create , compile Audiences using code and as well will show how to find whether a logged in user belongs to the Audience or not
1. Creating a new audience
First thing we'll do is creating a custom audience, giving it two rules, joined with an OR operator.
public void CreateNewAudience()
string audienceName = "Test and temp"; //audience name
string audienceDesc = "Only the test and temp users."; //audience description
SPServiceContext  context = SPServiceContext.GetContext(SPContext.Current.Site);
AudienceManager audManager = newAudienceManager(context);
AudienceCollection audCollection = audManager.Audiences;
Audience audience = null;
AudienceRuleComponent audRule = null;
        audience = audCollection.Create(audienceName, audienceDesc);
        audience.AudienceRules = new ArrayList();//initialize the collection
/* An AudienceRuleComponent exists of:
        * a left part: the property to look at
        * an operator: the operator to perform (=, <>, Contains, …)
        * a right part: the value to search for */
        audRule = new AudienceRuleComponent("UserName","Contains", "test");
        audRule = new AudienceRuleComponent(null, "OR",null);
//to use an operator (AND, OR, …) set the left and the right part to NULL !
        audRule = new AudienceRuleComponent("UserName","Contains", "temp");
        audience.Commit(); //commit the changes
Doing this, a new audience named "Test and Temp" will be created, which in the end will contain all users with user names containing "test" or "temp".
2. Compiling the new audience
To compile the new audience, we have to run an AudienceJob, and give it 4 parameters in a string array:
  1. The application id
  2. "1" = start job, "0" = stop job
  3. "1" = full compilation, "0" = incremental compilation (optional, default = 0)
  4. Audience name (optional, if null is supplied, all audiences are run!
public void CompileAudience(string audienceName, bool fullCompile)
SPServiceContext context = SPServiceContext.GetContext(SPContext.Current.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 = context.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());
So in this case, it means we will perform a START of the operation, doing a FULL compilation.

3. Validating logged in user in a webpart
Okay, so now our audience has been compiled, we can go for the next step: of validating whether logged in user is part of the audience or not.
private bool validateUser(string dlName)
           bool result = true;
           if (!string.IsNullOrEmpty(dlName))
               Guid audienceID = Guid.Empty;
               string[] dlnames;
               SPServiceContext context = SPServiceContext.GetContext(SPContext.Current.Site);
               AudienceManager amManager = new AudienceManager(context);
               AudienceCollection ac = amManager.Audiences;
               Audience ad;
               if (dlName.Contains("="))
                   string[] token = dlName.Split('=');
                   dlnames = token[1].Split(',');
                   ad = amManager.Audiences[dlnames[0]];
                   dlnames = dlName.Split(';');
                   audienceID = new Guid(dlnames[0]);
                   ad = amManager.Audiences[audienceID];
               result = (ad.IsMember(SPContext.Current.Web.CurrentUser.LoginName));
           return result;


Popular Posts