SharePoint - Add Audience Rule Programatically

Hi,

I 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 :)

I 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

but after reading somewhere, I figured out the way to add more than six audience rules .. yes you are right .. from code

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

but 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) 

try

{

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

  {

    ServerContext siteContext = ServerContext.GetContext(site);

    AudienceManager aManager = new AudienceManager(siteContext);

    AudienceCollection audiences = aManager.Audiences;

 

    Audience INFORMANAGEMENTUSERS = null;

 

    if (audiences.AudienceExist("Information Management Users"))

    {

      INFORMANAGEMENTUSERS = audiences["Information Management Users"];

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

    }

    else

    {

      INFORMANAGEMENTUSERS = audiences.Create("Information Management Users", "Test Audeinces");

      Console.WriteLine("Audience Added");

    }

 

      ArrayList aRules = INFORMANAGEMENTUSERS.AudienceRules;

 

      if (aRules == null)

      {

         aRules = new ArrayList();

      }

      else

      {

        AudienceRuleComponent rule1 = new AudienceRuleComponent(null, "AND", null);                           //Just Concatenating Previous Rule

        aRules.Add(rule1);

      }

 

AudienceRuleComponent rule2 = new AudienceRuleComponent(PropertyConstants.Department, "=", "Information Management");

 

aRules.Add(rule2);

 

       INFORMANAGEMENTUSERS.AudienceRules = aRules;

       INFORMANAGEMENTUSERS.Commit();

 

       Console.WriteLine("Audience Rule Added");

 

   }

 }

   catch (Exception ex)

   {

        Console.WriteLine(ex.Message);

   }

 

   Console.ReadLine();

 

Ebook Download
View all
Learn
View all