Role Bases Access using C# and XML


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.


Similar Articles