Run Giveaways at Giveaway.ly Extending the SharePoint Security Trimmed Control to support SharePoint Groups


Build Better Relationships With BPA Solutions SharePoint CRM
We all know that (SPSecurityTrimmedControl) SharePoint Security Trimmed Control comes to our rescue when we need to show role/permission based data in SharePoint. It helps you Conditionally renders the contents of the control to the current user only if the current user has permissions defined in the PermissionString.
<Sharepoint:SPSecurityTrimmedControl runat=”server” Permissions=”ManageLists”>      Place your control(s) here</SharePoint:SPSecurityTrimmedControl>
All this is good and works fine for most of the scenarios, however you may seldom find a need to be able to add a “SharePoint Group” instead of a “PermissionString”
So, let’s tell you how…
The idea is to create your wrapper control to support this feature. Let’s get started
Create a custom Web Control and write down the required logic based on your requirements. This should inherit from SPSecurityTrimmedControl
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint.WebControls;
using System.Web.UI;
using System.Web;
using Microsoft.SharePoint;

namespace SPSecurityTrimmedControlExtender
{
    public class SPUserGroupTrimmedControl : SPSecurityTrimmedControl
     {
         private List groups = new List();

         public string GroupsString
         {
             get
             {
                 return string.Join(",", groups.ToArray());
             }
             set
             {
                 groups.AddRange(
                     value.Split(new char[] { ',' },
                    System.StringSplitOptions.RemoveEmptyEntries)
                     );
             }
         }

         protected override void Render(HtmlTextWriter output)
         {
             if (!string.IsNullOrEmpty(GroupsString) && IsMember())
             {
                 base.Render(output);
             }
         }

       private bool IsMember()
       {           
           using (SPWeb web = new SPSite(SPContext.Current.Web.Url).OpenWeb())
           {
               bool isMember = false;
               foreach (string group in groups)
               {
                   isMember = web.IsCurrentUserMemberOfGroup(web.Groups[group].ID);
               }
               return isMember;
           }           
       }   
   }
}

Now, put this assembly in GAC and add a safe control entry in the web.config of you web application.


You are now ready to use this in your web page or master page by registering it.
<%@ Register TagPrefix="MyUserGroupExtender" Assembly="SPSecurityTrimmedControlExtender, Version=1.0.0.0, Culture=neutral, PublicKeyToken=121fae78165ba3d4" %>
    //your control to show to the specified group only

And you are done!!!

Comments