SharePoint – Add Audience Rule Programatically

nHi,

n

nI know this is not something special I am posting in this one because this is something which is easily available on internet if you try to use our Google / bing correctly 🙂

n

nI was working (rather having a look at) Audience Targeting Feature in SharePoint 2007 and came to know that somehow we can add only six rules while creating a audience by using user interface (which you can found in SSP) here is link how you can do that

n

nbut after reading somewhere, I figured out the way to add more than six audience rules .. Yes you are right.. From code

n

nthis might be because they thought , generally one cant  make such a complex audience having more than six audience rules and I also thinks so 🙂

n

nbut still If one want to have a look at API and try to add more than six audience rules then this is how I done it (nothing special , just added a rule using API..You can concatenate such chain of rules using AND , OR)

n

n

n

ntry

n

n{

n

n  using (SPSite site = new SPSite(http://yoursite))

n

n  {

n

n    ServerContext siteContext = ServerContext.GetContext(site);

n

n    AudienceManager aManager = new AudienceManager(siteContext);

n

n    AudienceCollection audiences = aManager.Audiences;

n

n

n

n    Audience INFORMANAGEMENTUSERS = null;

n

n

n

n    if (audiences.AudienceExist(“Information Management Users”))

n

n    {

n

n      INFORMANAGEMENTUSERS = audiences[“Information Management Users”];

n

n      Console.WriteLine(string.Format(“Audience Found with Name {0}”, INFORMANAGEMENTUSERS.AudienceName));

n

n    }

n

n    else

n

n    {

n

n      INFORMANAGEMENTUSERS = audiences.Create(“Information Management Users”, “Test Audeinces”);

n

n      Console.WriteLine(“Audience Added”);

n

n    }

n

n

n

n      ArrayList aRules = INFORMANAGEMENTUSERS.AudienceRules;

n

n

n

n      if (aRules == null)

n

n      {

n

n         aRules = new ArrayList();

n

n      }

n

n      else

n

n      {

n

n        AudienceRuleComponent rule1 = new AudienceRuleComponent(null, “AND”, null);                           //Just Concatenating Previous Rule

n

n        aRules.Add(rule1);

n

n      }

n

n

n

nAudienceRuleComponent rule2 = new AudienceRuleComponent(PropertyConstants.Department, “=”, “Information Management”);

n

n

n

naRules.Add(rule2);

n

n

n

n       INFORMANAGEMENTUSERS.AudienceRules = aRules;

n

n       INFORMANAGEMENTUSERS.Commit();

n

n

n

n       Console.WriteLine(“Audience Rule Added”);

n

n

n

n   }

n

n }

n

n   catch (Exception ex)

n

n   {

n

n        Console.WriteLine(ex.Message);

n

n   }

n

n

n

n   Console.ReadLine();

n

n

Leave a Comment