in

Dot Net Mafia

Group site for developer blogs dealing with (usually) .NET, SharePoint, Office 365, Mobile Development, and other Microsoft products, as well as some discussion of general programming related concepts.

This Blog

Syndication

Archives

Corey Roth [MVP]

A SharePoint MVP bringing you the latest time saving tips for SharePoint 2013, Office 365 / SharePoint Online and Visual Studio 2013.

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

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.

Published Nov 10 2009, 01:51 PM by CoreyRoth
Filed under: ,

Comments

 

Hamza Farooq said:

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.

January 4, 2010 8:22 AM
 

CoreyRoth said:

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

January 4, 2010 8:57 AM
 

CoreyRoth said:

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.

January 4, 2010 2:35 PM
 

Andrew Tam said:

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!

March 2, 2010 1:09 PM
 

CoreyRoth said:

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

March 2, 2010 1:23 PM
 

Sid said:

Hi Corey,

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

THanks,

June 25, 2010 3:52 AM
 

CoreyRoth said:

@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.

June 28, 2010 5:10 PM
 

Umbrella Corporation said:

Hi Corey,

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

Thanks in Advance,

February 9, 2011 7:56 AM
 

CoreyRoth said:

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

February 9, 2011 9:31 AM
 

Pablo said:

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

October 28, 2011 6:01 AM
 

CoreyRoth said:

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

November 7, 2011 8:35 PM
 

Venkata said:

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'.

February 7, 2012 7:57 AM
 

CoreyRoth said:

@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.

February 7, 2012 8:20 AM
 

scott said:

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?

February 28, 2012 3:30 PM
 

CoreyRoth said:

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

April 2, 2012 10:44 PM
 

Roshma said:

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

July 19, 2012 5:56 AM
 

balu said:

where we add the code

July 26, 2012 12:37 PM
 

ravi said:

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

Parameter name: serviceContext

July 26, 2012 1:09 PM
 

CoreyRoth said:

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

August 6, 2012 2:21 PM
 

Kunal said:

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

How can i do it?

February 11, 2013 3:55 AM
 

Nick Heylen said:

Hi,

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

Friendly Regards,

Nick

March 6, 2014 4:37 AM

Leave a Comment

(required)  
(optional)
(required)  
Add

About CoreyRoth

Corey Roth is an independent SharePoint consultant specializing in ECM, Apps, and Search.
2015 dotnetmafia.
Powered by Community Server (Non-Commercial Edition), by Telligent Systems