Role Enabled Custom Controls

So we did all this work to a membership provider and a role provider for ASP.NET and it was a lesson in patients as we figured out how it was all suppose to work.  However, now we have it I found out that the ASP.NET controls are not enabled for roles.  It works well with our Forms authentication for blocking access to pages where the user doesn't have the right role.  However, I want to display controls and not display controls based on the user's role.  I love to create custom controls that work just like we want them to work.  So I subclassed the Panel control and "roles" enabled it.  Code:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace WebUtility
    [ToolboxData("<{0}:RolePanel runat=server></{0}:RolePanel>")]
    public class RolePanel : Panel
        /// <summary>
        /// Gets or sets the roles
        /// </summary>
        /// <value>The on click.</value>
        public string Roles
                String s = (String)ViewState["Roles"];
                return s ?? string.Empty;
                ViewState["Roles"] = value;

        protected override void OnLoad(EventArgs e)
            Boolean bFound = false;
            foreach (String role in Roles.Split(','))
                if (Page.User.IsInRole(role.Trim()))
                    bFound = true;

            if ((Visible == true) && (bFound == false))
                Visible = false;


Now all I have to do is to all this ASP.NET code to our pages:

<webutility:RolePanel runat="server" ID="adminRoleHyperLink" Roles="AdministrationAccess">Admin</webutility:RolePanel>

The new Roles property is a comma delimited list of "roles" that are checked against the users permissions when the page loads, if they have one role in the list they can see everything in the panel.

Note that the same code will work for most all ASP.NET controls without changing it, just modify the name of the control you are subclassing.





Popular posts from this blog

Simple WP7 Mango App for Background Tasks, Toast, and Tiles: Code Explanation

Yet once more into the breech (of altered programming logic)

How to convert SVG data to a Png Image file Using InkScape