How to: Programmatically set the target audience on a web part

Posted Tuesday, November 10, 2009 1:51 PM by CoreyRoth

I’ve been working with audiences again, so I recently wanted to set the target audience of a web part.  Sure anyone can set it in the UI, but I want to automate my deployment, so I wanted to do it programmatically using a feature receiver.  When I first started looking for more information on how to do this, I wasn’t finding exactly what I needed and I did find some conflicting information.  To be clear about what I am talking about today, I am discussing how to target a web part to an audience in MOSS that was defined and compiled in the SSP.  Since I couldn’t find much info on the Internet, I posted something on twitter and I got a response from Randall Isenhour (@sharepointdev) on the SharePoint SDK team who referred me to Jim Crowley.  Thanks to both of them for pointing me in the right direction.

For today’s discussion, we have two audiences: Audience 1 and Audience 2 as shown below.

AudienceList

You might think that you would apply an audience to a web part using the AudienceManager class but that in fact not the case.  We actually do this by making use of the AuthorizationFilter property on the WebPart class.  The problem is that this property takes a syntax that not too many people fully understand.  Luckily, Jim pointed me to this post by Gary Lapointe where he demystifies how the string is created.  The AuthorizationFilter property can be used to specify a GUID to an audience.  However, it can also be used to specify an  LDAP distinguished name or a SharePoint group.  In this case we only care about the GUID to the audience.  All three can be specified in one string and are delimited with a double semi-colon (;;).  The first group is where you specify Audience Ids, the second is the distinguished name, and the last is the SharePoint group.  You don’t have to specify all three though, we’ll only be specifying the audience today. 

Let’s take a look at some code.  For today’s example, we can assume that we are writing code inside a FeatureActivated event handling method.  I’ll be getting a reference to an SPWeb object from there.  I am simplifying this example some because I only have one web part on my page and so I am just referencing it with an indexer value of 0.  You will want to change this to some code to find the appropriate web part on your page.  You’ll also need references to Microsoft.SharePoint, Microsoft.SharePoint.WebPartPages, and Microsoft.Office.Server.Audience.

using (SPWeb currentSite = (SPWeb)properties.Feature.Parent)

{

    using (SPLimitedWebPartManager webPartManager

        = currentSite.GetLimitedWebPartManager("default.aspx", PersonalizationScope.Shared))

    {

        AudienceManager audienceManager = new AudienceManager(ServerContext.Current);

 

        webPartManager.WebParts[0].AuthorizationFilter

            = string.Format("{0};;;;", audienceManager.GetAudience("Audience 1").AudienceID);

 

        webPartManager.SaveChanges(webPartManager.WebParts[0]);

    }

}

I then use the SPLimitedWebPartManager against the page I am working with (in my case default.aspx).  The AuthorizationFilter takes a GUID, so I need to look up the GUID for my audience using the AudienceManager.  It has a GetAudience method which takes a parameter which is the name of the audience (Audience 1).  I can then use the AudienceID property to write the GUID into the AuthorizationFilter property followed by “;;;;".  We have to specify the four semi-colons since other types of filters can be applied here in this case.  My AuthorizationFilter string would look something like this.

D2E05D3D-633F-4f0b-BA47-64E0F6A40A74;;;;

The last thing, you have to do is call SaveChanges on the SPLimitedWebPartManager object and pass a reference to your web part.  I’ll go ahead and point out now that, there is no error checking in the code above.  If you are to do this, you would want to add checks to verify that the page, web part, and audience exist to say the least.  If all goes well, when you view your page, you should be able to verify that the target audience is set like below.

TargetAudiences1

Now, I’m sure you know that you can target more than one audience on a web part, right?  It would be bad form for me not to show you how to do that, so here is what that looks like.  The key is using a comma to delimit each audience.  Here is what that code would look like.

webPartManager.WebParts[0].AuthorizationFilter = string.Format("{0},{1};;;;",

    audienceManager.GetAudience("Audience 1").AudienceID,

    audienceManager.GetAudience("Audience 2").AudienceID);

The result would then look like this.  SharePoint shows them delimited with a semi-colon when viewing them in the UI.

TargetAudiences2

As you can see, setting a target audience is actually quite easy once you know the syntax of the AuthorizationFilter string.  I have also found that sometimes when messing with audiences, that the Target Audiences property will completely disappear from the UI.  Although, I’m not sure what the cause of this is, I have found that you can bring it back by rebooting.  I have also found that you can restart the Windows SharePoint Services Administration service followed by an iisreset and it will come back as well.

Filed under: ,

Comments

# re: How to: Programmatically set the target audience on a web part

Monday, January 4, 2010 8:22 AM by Hamza Farooq

Is this applicable to SP 2010 ; I can easily enable the audience targeting but in web part i aint able to find properties to select the users. It used to be very simple and straight forward in MOSS 2007.

# re: How to: Programmatically set the target audience on a web part

Monday, January 4, 2010 8:57 AM by CoreyRoth

That I will need to confirm.  I'll take a look at it sometime on my sp2010 image.

# re: How to: Programmatically set the target audience on a web part

Monday, January 4, 2010 2:35 PM by CoreyRoth

After looking around a bit, I am thinking that this will still be applicable.  The properties for audience targeting are showing up for me on my build.  You may have some other issue or you may need to set up profile synchronization.

# re: How to: Programmatically set the target audience on a web part

Tuesday, March 2, 2010 1:09 PM by Andrew Tam

Do you know if this will work when content deployment is being used? Example, I have an authoring environment where multiple contributors can manage their own content. Upon completion of an approval workflow the published content is deployed to a read-only environment. Thanks and nice work!

# re: How to: Programmatically set the target audience on a web part

Tuesday, March 2, 2010 1:23 PM by CoreyRoth

I think it should, but you may need to put this code in the workflow itself.

# re: How to: Programmatically set the target audience on a web part

Friday, June 25, 2010 3:52 AM by Sid

Hi Corey,

Any ideas how to set SPGroup as target audience in the code in this post ???

THanks,

# re: How to: Programmatically set the target audience on a web part

Monday, June 28, 2010 5:10 PM by CoreyRoth

@Sid To do a group, I believe you would change the format string to ";;;;{0}" where {0} would be the name of the SPGroup.  It might be the Id of the group instead, but I can't remember.  Try it out and confirm.  Let us know what you get.  Thanks.

# re: How to: Programmatically set the target audience on a web part

Wednesday, February 9, 2011 7:56 AM by Umbrella Corporation

Hi Corey,

is there any way by which i can set a user (individual user) as target audience???

Thanks in Advance,

# re: How to: Programmatically set the target audience on a web part

Wednesday, February 9, 2011 9:31 AM by CoreyRoth

I think you would have to create a new audience for each individual user and target to that audience.

# re: How to: Programmatically set the target audience on a web part

Friday, October 28, 2011 6:01 AM by Pablo

Does it have a limit? For example, is it going to work if I add about 2 thousand groups?

# re: How to: Programmatically set the target audience on a web part

Monday, November 7, 2011 8:35 PM by CoreyRoth

It probably would but you may want to reconsider how many groups you add to a given site.

# re: How to: Programmatically set the target audience on a web part

Tuesday, February 7, 2012 7:57 AM by Venkata

As per above step i have created but i am getting the below error. Please help me out...

Error occurred in deployment step 'Activate Features': Unable to cast object of type 'Microsoft.SharePoint.SPSite' to type 'Microsoft.SharePoint.SPWeb'.

# re: How to: Programmatically set the target audience on a web part

Tuesday, February 7, 2012 8:20 AM by CoreyRoth

@Venkata this is a scope issue.  Your feature is scoped to site and the event receiver is looking for a web.  Change the feature scope to web and it will work.

# re: How to: Programmatically set the target audience on a web part

Tuesday, February 28, 2012 3:30 PM by scott

Is there a way to set an audience to exclude a single group. We want to target all users except those in a single group.

Is this possible?

# re: How to: Programmatically set the target audience on a web part

Monday, April 2, 2012 10:44 PM by CoreyRoth

@Scott Afraid not.  You can only check to see if a user is in a group or has a particular manager.

# re: How to: Programmatically set the target audience on a web part

Thursday, July 19, 2012 5:56 AM by Roshma

Itz really good. But I cant find Microsoft.Office.Server namespace in sharepoint 2007.How to solve it?

# re: How to: Programmatically set the target audience on a web part

Thursday, July 26, 2012 12:37 PM by balu

where we add the code

# re: How to: Programmatically set the target audience on a web part

Thursday, July 26, 2012 1:09 PM by ravi

Error occurred in deployment step 'Activate Features': Value cannot be null.

Parameter name: serviceContext

# re: How to: Programmatically set the target audience on a web part

Monday, August 6, 2012 2:21 PM by CoreyRoth

@Roshma  The assembly is present in the 14 hive \ bin folder.

# re: How to: Programmatically set the target audience on a web part

Monday, February 11, 2013 3:55 AM by Kunal

I am working in SP 2013 and want to show it to all users(general visitors or login users).

How can i do it?

# re: How to: Programmatically set the target audience on a web part

Thursday, March 6, 2014 4:37 AM by Nick Heylen

Hi,

Do you know if it's possible to add audience Programmatically in the sharepoint online version?

Friendly Regards,

Nick

# re: How to: Programmatically set the target audience on a web part

Tuesday, February 21, 2017 4:24 AM by Gautam Chawla

thanks alot, it worked smoothly for sharepoint groups as well, just use ;;;;{0} instead.

Leave a Comment

(required)
(required)
(optional)
(required)