Tuesday, September 16, 2014

Set Target Audience for a webpart programmatically

Introduction

As all we now SharePoint webpart properties having an option to set Target Audience. If we set this to particular member/group, the webpart will show to them. Let we see how to set this by programmatically

Customization

At First, we need to create a site page and add a webpart in it programmatically using visual studio. Refer this URL to add an webpart in sitepages. Then add an Event receiver to Feature. call  the below method in Feature Activating method

 private void SetTargetAudienceToAdmin(SPFeatureReceiverProperties properties, string relativeUrlOfPage)
        {
            
            try
            {
                var web = properties.Feature.Parent as SPWeb;
                
                    using (web)
                    {
                        web.AllowUnsafeUpdates = true;
                        SPFile page = web.GetFile(web.Url + "/" + relativeUrlOfPage);
                        if (page.Exists)
                        {
                            SPServiceContext serviceContext = SPServiceContext.GetContext(web.Site);
                            AudienceManager audienceManager = new AudienceManager(serviceContext);
                            SPLimitedWebPartManager wpManager = web.GetLimitedWebPartManager(page.Url, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                            foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpManager.WebParts)
                            {
                                if (wp.Title.ToLower().Equals("YourWebpartTitle"))
                                {

                                        wp.AuthorizationFilter = string.Format("{0};;;;", Your GroupName/UserName);
                                        wpManager.SaveChanges(wp);
                                   
                                }

                            }
                        }
                        web.Update();
                        web.AllowUnsafeUpdates = false;
                    }

            }
            catch (Exception ex)
            { throw ex; }
        }

Tha's all. Audience has set to Your webpart.


No comments:

Post a Comment