Blue Theme Orange Theme Green Theme Red Theme
 
Home | Forums | Videos | Photos | Downloads | Blogs | Interviews | Jobs | Beginners | Training
 | Consulting  
Submit an Article Submit a Blog 
 Login Close
User Id:
Password:
 
Forgot Password
Forgot Username
Why Register
 Jump to
Skip Navigation Links
TechnologyExpand Technology
WebsiteExpand Website
 Resources  
Close
 Our Network  
Close
Search :       Advanced Search »
Home » Visual Studio .NET » Role Bases Access using C# and XML

Role Bases Access using C# and XML

Here I am trying to give a simple and configurable solution to implement Role Bases Access to your application using C# and XML. Remember that this article intent is to provide Role Based Access and not Role Based Autorization.

Total page views :  17653
Total downloads : 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
Become a Sponsor


Role Based Access (Not Role Based Authorization)

Role-based access control attempts to allow administrators to specify access control in terms of the organizational structure of a company. You assign a user or a group of users to a role to perform a specific job function and restrict them to do certain other job functions.  

In this Role Based Access control, the administrator uses the RoleValidations.xml file to manage permissions and assignments. For example, all the fields are locked in all screens of the application for a role called Inquiry that has the read-only permissions.

While Input validation ensures a user only enters required, appropriate and correctly formatted values. The role based Access ensures that only permitted users can do certain specific job functions.

To implement the above we have used the following:

  • An XML file to store the input field control for each screens in the application.
  • A C# class in a singleton approach that stores the XML data in cached manner and certain methods to make use of this XML based validation engine in ASP.NET pages/forms. 

The XML file (RoleValidations.xml):

 <Validations>

  <Field>

    <Name>Invoice_Name</Name>

    <Enabled> FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=false</Enabled>

    <Visible>FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=true</Visible>

  </Field>

  <Field>

    <Name>Invoice_Commission</Name>

    <Enabled>FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=false</Enabled>

    <Visible>FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=true</Visible>

  </Field>

  <Field>

    <Name>Invoice_Save</Name>

    <Enabled>FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=false</Enabled>

    <Visible>FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=true</Visible>

  </Field>

  <Field>

    <Name>Invoice_Delete</Name>

    <Enabled>FULL_ACCESS=true#BRANCH_ACCESS=false#INQUIRY_ACCESS=false</Enabled>

    <Visible>FULL_ACCESS=true#BRANCH_ACCESS=true#INQUIRY_ACCESS=false</Visible>

  </Field>

</Validations>


The elements of the above XML file: 

  • <Field> defines a unique field name that defines the control name on the screen to be bind to the role access validation.
  • <Enabled> is the enabled property of the control.
  • <Visible> is the visible property of the control. 

The above XML file can be modified throughout the development process as and when the new fields are being added / removed and/or whenever any changes are requested.

Notice in the above XML file, the Save control/field is set true to FULL_ACCESS role as well as BRANCH_ACCESS role but the Delete control/field is set true to FULL_ACCESS role while set false to BRANCH_ACCESS role. This means that any user having the FULL_ACCESS can save as well as delete the Invoice record but the users having BRANCH_ACCESS role can only save the invoice record but cannot delete the same.

The Role Validation Class that loads the XML file into memory (RoleValidation.cs):

using System;

using System.Collections.Generic;

using System.Text;

using System.Data;

using System.Collections.Specialized;

using System.Collections;

using System.Web.Configuration;

 

namespace BusinessComponents

{

    /// <summary>   

    /// This class provides a way to implement the role based security to the application.

    /// The screen fields are defined in the xml and this file reads the xml and loads it into

    /// cache memory as a strongly typed class to be accessed and used inthe screens.

    /// </summary> 

    public class Role

    {

        #region Private Fields       

        private static Role RoleInstance = new Role();

        /// <summary>

        /// HybridDictionary cachedRoleFields, populated in Role's constructor,

        /// is the core of this class, as it holds the collection of RoleField objects.

        /// cachedRoleFields can only be accessed through the Field property,

        /// which retrieves a particular RoleField object from the collection

        /// based on a string key.

        /// </summary>

        private HybridDictionary cachedRoleFields = new HybridDictionary();

        private const string ROLE_SEPRATOR = "#";

        private const string ROLE_ASSIGNMENT = "="; 

        #endregion

 

        #region Properties 

        public static Role Instance

        {

            get { return RoleInstance; }

        }

 

        public static RoleField Field(string fieldName)

        {

            return ((RoleField)(RoleInstance.cachedRoleFields[fieldName]));

        } 

        #endregion

 

        /// <summary>

        /// Contains the structure for the RoleField

        /// </summary> 

        public class RoleField

        {

            /// <summary>

            ///  Name is the key used in the calling code to retrieve the appropriate values.

            /// </summary>

            public String Name = String.Empty;

 

            /// <summary>

            /// Control is the control Name in the respective screen

            /// </summary>

            public String Control = String.Empty;

 

            /// <summary>

            /// Collection to hold the property values either true/false

            /// </summary>

            public Hashtable Enabled = new Hashtable();

 

            /// <summary>

            /// Collection to hold the property values either true/false

            /// </summary>

            public Hashtable Visible = new Hashtable();

        } 

        /// <summary>

        ///The constructor is only called once, the first time this class is instantiated.

        ///Every time an instance of this object is called after the first time,

        ///the "in memory" copy contained in RoleInstance is used.

        ///The constructor performs the basics.

        ///It reads RoleValiations.xml into memory, in a DataSet.

        ///It reads through each row of the DataSet and populates a new RoleField object.

        ///Finally, it adds the RoleField object to the cachedRoleFields collection.

        ///Once the DataSet is populated it is not changed until it is reloaded from the

        ///XML when the application is restarted.

        /// </summary>

        private Role()

        {

            #region Local Variable Declaration

            RoleField Field = null;

            DataSet ds = new DataSet();

            string[] RoleEnabledList;

            string[] RoleEnabled;

            string[] RoleVisibleList;

            string[] RoleVisible;

            int Ctr = 0;

            #endregion

 

            try

            { 

                #region Reads ScreenRoles.xml into memory

                string RoleFilePath = WebConfigurationManager.AppSettings["RoleValidation"].ToString();

                ds.ReadXml(System.Web.HttpContext.Current.Server.MapPath(RoleFilePath));

                #endregion

 

                foreach (DataRow dr in ds.Tables[0].Rows)

                {

                    #region Reads through each row of the DataSet and populates a new Field object

                    Field = new RoleField();

                    Field.Name = dr["Name"].ToString();

                    Field.Control = dr["Control"].ToString();

                    RoleEnabledList = dr["Enabled"].ToString().Split(ROLE_SEPRATOR.ToCharArray());

 

                    #region Spilting Enabled properties by role

                    for (Ctr = 0; Ctr < RoleEnabledList.Length; Ctr++)

                    {

                        RoleEnabled = RoleEnabledList[Ctr].Split(ROLE_ASSIGNMENT.ToCharArray());

                        Field.Enabled.Add(RoleEnabled[0], RoleEnabled[1]);

                    }

                    #endregion

 

                    RoleVisibleList = dr["Visible"].ToString().Split(ROLE_SEPRATOR.ToCharArray());

 

                    #region Spilting Enabled properties by role

                    for (Ctr = 0; Ctr < RoleVisibleList.Length; Ctr++)

                    {

                        RoleVisible = RoleVisibleList[Ctr].Split(ROLE_ASSIGNMENT.ToCharArray());

                        Field.Visible.Add(RoleVisible[0], RoleVisible[1]);

                    }

                    #endregion

 

                    #endregion

 

                    #region Adds the Field object to the cachedRoleFields collection.

                    cachedRoleFields.Add(Field.Name, Field);

                    #endregion

                }

            }

            catch (Exception ex)

            {

                throw;

            }

        }

        /// <summary>

        /// The Reset method allows for dynamic reloading of ScreenRoles.xml during runtime.

        /// Any screen/page/class could very easily call this method in a event handler to

        /// allow administrators to reload ScreenRoles.xml on the fly without restarting

        /// the application.

        /// </summary>

        public static void Reset()

        {

            RoleInstance = new Role();

        }

    }
}


How to access/implement the Role Validation in web page(s): 

Suppose you have already designed your web page and placed the appropriate controls. A method named BindValidation(String role) that appears on every page of your application. The first time a page loads a call is made to BindValidation(String role),which retrieves the values from the singleton and assigns them to the screen controls.

protected void Page_Load(object sender, System.EventArgs e)

{

    if (!IsPostBack)

    {

        string role = session["role"];

        BindValidation(role);

    }

}

 

protected void BindValidation(String role)

{

    try

    {

        txtAccountName.Enabled = Role.Field("Invoice_Name").Enabled[role];

        txtAccountName.Visible = Role.Field("Invoice_Name").Visible[role];

 

        cmdSave.Enabled = Role.Field("Invoice_Save").Enabled[role];

        cmdSave.Visible = Role.Field("Invoice_Save").Visible[role];

 

        cmdDelete.Enabled = Role.Field("Invoice_Delete").Enabled[role];

        cmdDelete.Visible = Role.Field("Invoice_Delete").Visible[role];

    }

    catch (Exception ex)

    {

        //throw;

    }

} 

The main advantage of this approach is the maintainability provided by storing the myriad of string values in a single repository. In addition, using XML means only a text editor is required to modify these values, eliminating the need for recompilation.


Login to add your contents and source code to this article
 About the author
 
Subal Mishra
He has Masters degree in the field of Information Technology and Microsoft Certified Professional  with over ten years of experience in Project Management, System Design, Implementation and strategic consulting of web based and intranet based systems using Microsoft Technologies. He has a strong foundation in OOAD methodologies, system analysis and design.
Looking for C# Consulting?
C# Consulting is founded in 2002 by the founders of C# Corner. Unlike a traditional consulting company, our consultants are well-known experts in .NET and many of them are MVPs, authors, and trainers. We specialize in Microsoft .NET development and utilize Agile Development and Extreme Programming practices to provide fast pace quick turnaround results. Our software development model is a mix of Agile Development, traditional SDLC, and Waterfall models.
Click here to learn more about C# Consulting.
 
Introducing MaxV - one click. infinite control. Hyper-V Hosting from MaximumASP.
Finally – a virtual platform that delivers next-generation Windows Server 2008 Hyper-V virtualization technology from a managed hosting partner you can truly depend on. Visit www.maximumasp.com/max for a FREE 30 day trial. Hurry offer ends soon. Climb aboard the MaxV platform and take advantage of High Availability, Intelligent Monitoring, Recurrent Backups, and Scalability – with no hassle or hidden fees. As a managed hosting partner focused solely on Microsoft technologies since 2000, MaximumASP is uniquely qualified to provide the superior support that our business is built on. Unparalleled expertise with Microsoft technologies lead to working directly with Microsoft as first to offer IIS 7 and SQL 2008 betas in a hosted environment; partnering in the Go Live Program for Hyper-V; and product co-launches built on WS 2008 with Hyper-V technology.
Dynamic PDF
ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
Go.NET
Build custom interactive diagrams, network, workflow editors, flowcharts, or software design tools. Includes many predefined kinds of nodes, links, and basic shapes. Supports layers, scrolling, zooming, selection, drag-and-drop, clipboard, in-place editing, tooltips, grids, printing, overview window, palette. 100% implemented in C# as a managed .NET Control. Document/View/Tool architecture with many properties&events. Optional automatic layout.
Dundas Software
Dundas Chart for .NET is the most advanced .NET charting package available today.  With an extremely complete feature set, elegant architecture and easy implementation, Dundas Chart can quickly add advanced Charting functionality to enhance and transform ASP.NET and Windows Forms applications.  Whether you are implementing charting into internal projects, or building applications for clients, Dundas Chart offers advanced technology and advanced results to get the most out of data.
Clickatell's SMS Gateway
Clickatell's Developer Solutions allow you to SMS enable any website or application via a range of API's. Learn More about our API connections.
Free access to .NET Memory Management video
Everything you need to know about Garbage Collection, Temporary Objects, Fragmentation, Finalization and common causes of memory leaks in .NET. Watch the video here.
Microsoft Visual Studio 2010 Professional
Microsoft Visual Studio 2010 Professional will launch on April 12, but you can beat the rush and secure your copy today by pre-ordering at the affordable estimated retail price of $549 (US). Pre-order now.
Nevron Chart for .NET 2010.1 Now Available
The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Developer-Ready ASP.NET 2.0 Web Hosting with 3 MONTHS FREE
Now supporting .NET 3.0 Framework with Windows Workflow Foundation, Windows Communication Foundation (WCF), Windows Presentation Foundation (WPF), windows CardSpace (WCS)! Providing more flexibility for Developers with Web Services Support and a User/Permission Manger. Also supporting MS SQL 2005/2000 with Real-Time Backups, FREE Automated Attach .MDF Tool, FREE SQL Restore and Shrink SQL DB Tools, and SQL
 
   Print Read/Post comments Post a comment  Similar Articles  
   Email to a friend  Bookmark  Author's other articles  
 
 Post a Feedback, Comment, or Question about this article
Subject:  
Comment:  
Become a Sponsor
 Comments
Using System.Web.Security by William On March 30, 2007
Since I am already using System.Web.Security.Roles for my authorization in my asp.net application, could I not use the public static string[] GetRolesForUser () instead of the Session variable?
Reply | Email | Delete | Modify | 
Re: Using System.Web.Security by Subal On April 10, 2007
Yes you can, its one of the same thing.  the idea is to get the current role from a centralized location whereever you're saving it. could be your static array or session or may be some other lookup.
Reply | Email | Delete | Modify | 
Hi Sir by pk On January 1, 2008

I AM NEW TO C# AND I HAVE TO MADE A ROLE BASE PROJECT TO OPEN PAGES ACCORDING TO ROLE OF THE  USER . CAN U HAVE ANY PROJECT RELATED  TO THIS PROJECT

Reply | Email | Delete | Modify | 
NOT FOUND LINK TO DOWNLOAD by pk On January 1, 2008
CAN U SEND ME THE LINK TO DOWNLOAD THE ARTICLE
Reply | Email | Delete | Modify | 
Searching File by Abhijeet On March 6, 2009
How to search a specific file in Drive using Asp.net C#
Reply | Email | Delete | Modify | 
Blogs designing by Abhijeet On March 6, 2009
How to create a feedback section with reply, email, delete, modify as given in this forum
Reply | Email | Delete | Modify | 

 Hosted by MaximumASP  |  Found a broken link?  |  Contact Us  |  Terms & conditions  |  Privacy Policy  |  Site Map  |  Suggest an Idea  |  Media Kit
Current Version: 5.2009.6.2
 © 2010  contents copyright of their authors. Rest everything copyright Mindcracker. All rights reserved.