Ads

Wednesday, 3 April 2013

Set audience targeting programmatically

We all know that we can create our audience in central administration and then simple apply them on list items or document library items or on web parts on pages.
We can also set the same using code.

I assume that you have already created audience named “Sales” and “Finance”. I am not going in deep discussion explaining you each and every class here.

using (SPWeb objsite = (SPWeb)properties.Feature.Parent)
{
using (SPLimitedWebPartManager wpm
= objsite.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared))
{
AudienceManager am = new AudienceManager(ServerContext.Current);

wpm.WebParts[0].AuthorizationFilter
= string.Format("{0};;;;", am.GetAudience("Sales").AudienceID);

wpm.SaveChanges(wpm.WebParts[0]);
}
}

We first take our web context and then take out the default.aspx web parts. We use webpartmanager to deal with them. Then take out Audience manager class with the context, and then interesting part comes. Authorizationfilter takes argument in such way that we have to pass ;;;; in it after getting the audience target ID. Get the webpart that you want and pass its Title let’s say in wpm.WebParts[0].AuthorizationFilter line. I’ve used 0 just to get the first webpart and show you the demo.

Here we want to target sales people, so we have passed Sales and get the ID of it and finally call up the savechanges method of webpartmanager object.

As simple as that.if do the same for Finance people. Here you can set multiple audience in one go. Just change the line to.

wpm.WebParts[0].AuthorizationFilter
= string.Format("{0},{1};;;;", am.GetAudience("Sales").AudienceID, am.GetAudience("Finance").AudienceID);

No comments:

Post a Comment

Ads