Monday, April 27, 2009

WebParts and Audiences - Part 1: Show or hide a Web Part based on audiences

This is part 1 of a series I will write on how to deal with audiences in your custom SharePoint WebParts.

Some of the standard SharePoint WebParts implement audience filtering. I was wondering, what it takes to make my custom WebParts as well audience "sensitive". I wanted to apply the audience filtering at 2 different levels:

  • Show or hide the WebPart depending on audiences
  • Show or hide data items the WebPart displays depending on audiences.

As well, I wanted to enable administrators / power users to configure the WebPart to filter for audiences, which meant to create a custom ToolPart/EditorPart.

In this first part of the series, we will look at how hide a custom WebPart if the user is not in one of the necessary audiences that are allowed to see the WebPart.

In order to store the audiences that are allowed to see the WebPart, we must create a shared-property that will be configured using our custom ToolPart/EditorPart which I will describe in Part 2 of my series.

[WebBrowsable(false), FriendlyName("WebPart target audiences"), Description(""),
Category("Presentation"), DefaultValue(""), WebPartStorage(Storage.Shared), Personalizable(PersonalizationScope.Shared)]
public string TargetAudiences
{
get
{
return this._targetAudiences;
}
set
{
this._targetAudiences = value;
}
}

This property stores the value given back by the standard-SharePoint AudienceEditor control Text-property as I will describe in part 2. Given this WebPart-property, all we need to do is to override the OnPreRender-method of our WebPart with the following:

protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);

this.Hidden = false;

if (!string.IsNullOrEmpty(TargetAudiences))
{
if (ServerContext.Current == null)
return;

AudienceLoader audienceLoader = AudienceLoader.GetAudienceLoader();
if (!AudienceManager.IsCurrentUserInAudienceOf(audienceLoader, this.TargetAudiences, false))
{
this.Hidden = true;
}
}
}

Try it :) If the current user is not in one of the audiences that are configured for your WebPart - the whole WebPart will be hidden.

Post a Comment

Blog Popularty Partners

  ©All Right Reserved.

Back to TOP