Click here to Skip to main content
15,394,025 members
Articles / Database Development / SQL Server / SQL Server 2012
Tip/Trick
Posted 21 Feb 2015

Stats

10.7K views
2 bookmarked

Implementing UserRights in Winform App using Menustrip

Rate me:
Please Sign up or sign in to vote.
2.67/5 (3 votes)
21 Feb 2015CPOL1 min read

Introduction

This tip will demonstrate a simple way for implementing user rights within the winform Application.

Background

I was writing an application with more than 80 WinForms and  multiple departments are intended to work on the same .And each user are allowed to only access the screen they are allowed . Almost all the main Forms are accessed by the user via Menustrip control in the MainForm(MDIParent).So hidding the unwanted Items from toolstrip menuitems will solve the issue .So I  placed a form with a combobox and a treeview with checkbox enabled .The combobox consist of the  Usernames and  treeview consist of the All the menustripitems.

Using the code

The main functions used in the areas where user rights are assigned are

1.loadtreeview()

Load the treeview with menusitems. A recursive call to another form Getchild is used to get alla the child nodes

public void loadtreeview()
       {
           //creates the instance of MDI parent
           MainForm frm = new MainForm(1);
           //for each menusdtrip items
           foreach (ToolStripMenuItem tsmi in frm.menuStrip1.Items)
           {
               // create a new treenode with the menitem string as name
               TreeNode tn = new TreeNode(tsmi.Text);
               //try to get the  child nodes
               getChildNodes(tsmi, tn);
               treeView1.Nodes.Add(tn);
           }
       }

 private void getChildNodes(ToolStripDropDownItem mi, TreeNode tn)
       {
           foreach (object item in mi.DropDownItems)
           {
               // if toolstrip item is  spearator leave it
               if (item.GetType() == typeof(ToolStripSeparator))
               {
                   continue;
               }

               //else create a new node of same name
               TreeNode node = new TreeNode(((ToolStripDropDownItem)item).Text);
               //add it to node
               tn.Nodes.Add(node);
               //try to check foir more child node for the node
               getChildNodes(((ToolStripDropDownItem)item), node);
           }
       }

 

2.insertRights()

Inserts the Rights to the useron the database

public void insertRights()
{
    if (cmb_EmpCode.Text != "")
    {

        //deletes the existing rights
        GridViewmModels.ClsDatabase.Set_Data("delete from User_Rights where user_id=" + cmb_EmpCode.SelectedValue + "");

        CallNodesSelector();
    }

    ATCHRM.Controls.ATCHRMMessagebox.Show("Done");
    this.Close();

}

/// <summary>
/// function to get the child nodes of treeview
/// </summary>
private void CallNodesSelector()
{
    TreeNodeCollection nodes = this.treeView1.Nodes;
    foreach (TreeNode n in nodes)
    {
        GetNodeRecursive(n);
    }
}
private void GetNodeRecursive(TreeNode treeNode)
{
    //select only the checked nodes
    if (treeNode.Checked == true)
    {

        string checkedValue = treeNode.Text.ToString();
        //insert into the database
        GridViewmModels.ClsDatabase.Set_Data("insert into User_Rights (user_id,form_name,access_right) values "
                   + " (" + cmb_EmpCode.SelectedValue + ",'" + checkedValue + "','Y')");
    }
    foreach (TreeNode tn in treeNode.Nodes)
    {


        //get the childnode again
        GetNodeRecursive(tn);

    }

}

3.getexistingprivillege();

    This function will show the current privellege of the user from the Database 

  public void getexistingprivillege()
        {
           
            using (SqlConnection sqlConnection1 = new SqlConnection(Program.ConnStr))
            {

                sqlConnection1.Open();

                using (SqlCommand command = new SqlCommand(@" SELECT        User_Rights.Form_name
FROM            User_Rights INNER JOIN
                         UserMaster_tbl ON User_Rights.User_Id = UserMaster_tbl.empid
WHERE        (User_Rights.Access_Right = 'Y') AND (UserMaster_tbl.Empid = @Param2)", sqlConnection1))
                {

                    command.Parameters.AddWithValue("@Param2", int.Parse(cmb_EmpCode.SelectedValue .ToString()));

                    SqlDataReader reader = command.ExecuteReader();
                    DataTable DT = new DataTable();

                    DT.Load(reader);

                    if (DT != null)
                    {
                        if(DT.Rows.Count!=0)
                        {

                            for (int i = 0; i < DT.Rows.Count; i++)
                            {
                                for (int x = 0; x < treeView1 .Nodes .Count; x++)                               
                                   
                                {
                                    if (treeView1 .Nodes [x].Text .ToString () == DT.Rows[i][0].ToString())
                                    {
                                        treeView1 .Nodes[x].Checked=true;
                                    }
                                   
                                }

                            }

                        }
                    }

                }

                sqlConnection1.Close();

               

            }
        }

4. getitems();

This is the function which is written in the load event of the MDI parent which will prevent the   unwanted Toolstripitems from being displayed

private void MainForm_Load(object sender, EventArgs e)
       {

       getitems();

         }

 public   void getitems()

       {
           foreach (ToolStripMenuItem i in menuStrip1.Items)
           {
               GetMenuItems(i);
           }
   }

 public void GetMenuItems(ToolStripMenuItem item)
   {
       int id = Program.USERPK;
       GridViewmModels.ClsDatabase.Set_Data("delete from Message_Alert where user_id=" + id + "");
       foreach (ToolStripItem i in item.DropDownItems)
       {
           if (i is ToolStripMenuItem)
           {

               if (Get_Menu(id, i.Text) == true)
               {
                   i.Visible = true;
                   if ((i.Text == "level1ToolStripMenuItem") || (i.Text == "level2ToolStripMenuItem") || (i.Text == "level3ToolStripMenuItem") || (i.Text == "lHLevel1ToolStripMenuItem") || (i.Text == "lHLevel2ToolStripMenuItem") || (i.Text == "lHLevel3ToolStripMenuItem") || (i.Text == "actionApproval1ToolStripMenuItem") || (i.Text == "actionApproval2ToolStripMenuItem") || (i.Text == "actionApproval3ToolStripMenuItem"))
                   {
                       GridViewmModels.ClsDatabase.Set_Data("insert into Message_Alert (Menu_Name,User_Id) values('" + i.Text + "'," + id + ")");
                   }
               }
               else
               {
                   i.Visible = false;
               }
               GetMenuItems((ToolStripMenuItem)i);

           }
       }
   }

 

Points of Interest

More easiness in selection of the nodes may be done by  grouping the nodes asper the Departments or nature or work and making the nbodes selected when that nodes are selected

History

Keep a running update of any changes or improvements you've made here.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

SREENATH GANGA
Software Developer
United Arab Emirates United Arab Emirates
No Biography provided

Comments and Discussions

 
GeneralMy vote of 1 Pin
Jackson Savitraz21-Feb-15 15:20
professionalJackson Savitraz21-Feb-15 15:20 
GeneralRe: My vote of 1 Pin
SREENATH GANGA21-Feb-15 20:52
MemberSREENATH GANGA21-Feb-15 20:52 
GeneralMy vote of 2 Pin
manchanx21-Feb-15 10:23
professionalmanchanx21-Feb-15 10:23 
GeneralRe: My vote of 2 Pin
SREENATH GANGA21-Feb-15 21:07
MemberSREENATH GANGA21-Feb-15 21:07 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.