Programmatically Set Audience to a SharePoint 2010 WebPart

To provide permission to a sharepoint web part for specific SharePoint Group, we have to use AudienceManager as shown below

SPWeb currentSite = SPContext.Current.Site.RootWeb;
SPSite spSite = currentSite.Site;

SPServiceContext sc = SPServiceContext.GetContext(spSite);

AudienceManager am = new AudienceManager(sc);

Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
mgr = currentSite.GetLimitedWebPartManager("SitePages" + "/" + page, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in mgr.WebParts)
if (webPart.Title == "WebPartTitle")
//Get the Existing Audience for the Web Part
string audWebPart = webPart.AuthorizationFilter;
//If there is no Audience for the Web Part just add it
if (audWebPart == "")
webPart.AuthorizationFilter = ";;;;" + NewAudience;

//If already Audiences are exist for the Web Part then append new Audience
webPart.AuthorizationFilter = audWebPart + "," + NewAudience;

lblMessage.Text = "Succeeded...";

If we just set the value for AuthorizationFilter property, then the existing Audiences will be overwritten.
To avoid it first we have to check whether already audiences exists for that web part. If so we have to append it.

The SharePoint Server 2010 framework requires that three kinds of values be separated by a pair of semicolons (";;"). Multiple values for global audiences and SharePoint groups are delimited by commas, and multiple values for distribution lists are delimited by newline characters ("\n"). Therefore in the above example we used ";;;;" to provide valid string to the AuthorizationFilter property.

No comments:

Post a Comment

How the transformed data is written to an output file with column headers in U-SQL...

While working with U-SQL language, I noticed that there are few ways of writing data to an output file. Let's assume the SalesDetails....