ProgTalk - Your archive for all source code

How To Use Tree Menu Based On User Credentials ( Logged In User / Not Logged In User).

ProgTalk » Articles » .NET » How To Use Tree Menu Based On User Credentials ( Logged In User / Not Logged In User).
 
Author: Rockin J
Page Views: 11617
Average Article Rating: rating starrating starrating starrating starrating star
 

What is this article about?
This article will demonstrate how to use a Tree Menu Control.  If you need to allow sub menu's, or a tree like structure, this is your best bet.
You can view this control on your ToolBox in Visual Studio 2005.  It is branched under [Navigation].  You will see some other menu controls such as SiteMapPath, and Menu.

Lets Get Started
This first thing we need to go is to create a master page.  If you are not going to be using master pages, then create a user control called MyMenu which will have the Tree Menu control within it.  For this example we will use the master page, which will give you an idea of how the Tree Menu control works.  The reason you would want it in a user control, or in a master page, is that the Menu dynamically generates based on the user.  You don't want to go to all you pages, and copy and paste the menu and it's code.  This way you just do it once, and do not need to look back (Except for testing).

Once you created the master page, create the structure you would like to have.  This is how I designed my master page:



The top part is just a label which is my logo.
The left side contains a Tree Menu Control.  Just drag the control there from your toolbox under [Navigation -> TreeView].  You do not need to add any items, but you can right click, and click on AutoFormat to choose a different style.  Below I used the MSDN style.





Great!  Now that we have the menu format is setup, we will go to code behind page, and add some logic for the TreeMenu.

The Code:
/* The following code will generate the menu based on if the user is logged into the system.  We will mark a session variable to show the user is logged in from our Login.aspx page(Later on in this article).  This way the menu will dynamically generate. */

using System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            //Check if user is Logged in or not.
         
  //We know this by checking for the Session["LoggedIn"] variable
           
if (Session["LoggedIn"] == null)
            {
                //================USER NOT LOGGED IN======================= 
                //Looks like we need to generate menu information
               
//Lets clear all the nodes.
               
//Why?, you may ask
               
//We clear it because it may have the Logged In Menu Stuff
               
TreeView1.Nodes.Clear();

                //if the user is not logged in, we should have 3 nodes
               
//Home, Search, Login
               
TreeNode ndHome = new TreeNode("Home", "Home", "", "~/Home.aspx", "");
                TreeNode ndSearch = new TreeNode("Search", "Search", "", "~/Search.aspx", "");
                TreeNode ndLogin = new TreeNode("Login", "Login", "", "~/Login.aspx", ""); 

                //Add the 3 nodes to the TreeView
               
TreeView1.Nodes.Add(ndHome);
                TreeView1.Nodes.Add(ndSearch);
                TreeView1.Nodes.Add(ndLogin); 
            }
            else
           
{
                //================USER LOGGED IN======================= 
                //Looks like we need to generate menu information
               
//Lets clear all the nodes.
               
//Why?, you may ask
               
//We clear it because it may have the Not Logged In Menu Stuff
               
TreeView1.Nodes.Clear();

                //if the user is not logged in, we should have 3 nodes
        
      
//Home, Search, Advanced Search, and Logout
               
TreeNode ndHome = new TreeNode("Home", "Home", "", "~/Home.aspx", "");
                TreeNode ndSearch = new TreeNode("Search", "Search", "", "~/Search.aspx", "");
                TreeNode ndAdvancedSearch = new TreeNode("Advanced Search",
                            "Advanced Search",
                            ""
,
                            "~/AdvancedSearch.aspx", "");

                TreeNode ndLogout = new TreeNode("Logout", "Logout", "", "~/Logout.aspx", ""); 

                //Add nodes to the TreeView Control
               
TreeView1.Nodes.Add(ndHome);
                TreeView1.Nodes.Add(ndSearch);
                TreeView1.Nodes[1].ChildNodes.Add(ndAdvancedSearch);
                TreeView1.Nodes.Add(ndLogout); 
            }
        }
    }
}

//=============================================================
Now we will generate our pages.  Create the following webpages:
**************   Make sure you select the option "Select Master Page" when creating the pages.  ************
**************   This will allow you to choose the master page we have just created.    ********************

Pages:
Home.aspx
Login.aspx
Logout.aspx
Search.aspx
AdvancedSearch.aspx

Home.aspx
The home page can have some sample text.  For this example, it will not have have any code behind, but be more descriptive.


Login.aspx
Here we will allow the user to login.  Create 2 textbox's for the username and password, and a button to login.  Put them inside a Table, with id Table1.  Make sure it is a server control.  You can do this by selecting the Table, Right clicking, and choosing: "Run as Server Control". 

Once the user logs in, we will validate the user, and create a session variable to mark him/her as logged in.  This will be used in our master page automatically to load the proper menu items.  Here is a sample of the Login page I created:

I created a table which was a server control, with the username, password labels, and textboxs, and a button to log in within it. 

If the user is validated, I hide this table by using Table1.Visible = false; 
See source code below the image.

The source code for the login page:

using System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls; 

public partial class Login : System.Web.UI.Page
{

    protected void Page_Load(object sender, EventArgs e)
    {

        //when the page loads, if need to check if the user is logged in or not.
       
if (IsPostBack == false)
        {

            if (Session["LoggedIn"] == null)
            {
                TABLE1.Visible = true;
            }
            else
            {
                TABLE1.Visible = false;
                this.LblMessage.Text = "Welcome, User";
            }
        }
    }

    protected void BtnLogin_Click(object sender, EventArgs e)
    {
        if (TBUserName.Text.Trim().Length > 0 && TBPassword.Text.Trim().Length > 0)
        {
            //you can check your database here, but for this example, we will just
           
//check against username: user, and password: pass
 
          
if (TBUserName.Text == "user" && TBPassword.Text == "pass")
            {
                //successfull logged in.
               
//redirect back to this page.
               
Session["LoggedIn"] = "LoggedIn";
                Response.Redirect("~/Login.aspx");
            }

            else
           
{
                this.LblMessage.Text = "* Invalid login information *";
                return;
            }
        }
        else
       
{
            this.LblMessage.Text = "* Missing login information *";
        }
    }
}

Logout.aspx
Here we will clear the session so the user cannot see the logged in options from the main tree view menu. 
The content for this page in this example is descriptive.  It only lets the user know that they successfully logged out:


The source code for the logout page:

using System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;

public partial class Logout : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

       //Clear user sessions
        Session["LoggedIn"] = null;
        Session.Abandon();
    }
}



Search.aspx
Here you would do your search features.  For this example, it is more descriptive.



AdvancedSearch.aspx
Here you would do your advanced search features.  For this example, it is more descriptive, except that we will check if the user is logged in.

Note:  If a user who is not logged in, directly goes to the advanced search page, they will be automatically redirected to the regular search page.

Source Code for AdvancedSearch.aspx

using System;
using
System.Data;
using
System.Configuration;
using
System.Collections;
using
System.Web;
using
System.Web.Security;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Web.UI.WebControls.WebParts;
using
System.Web.UI.HtmlControls;
 

public
partial class AdvancedSearch : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

       //User not logged in, they can only see regular search.
        if (Session["LoggedIn"] == null)
        {
            Response.Redirect("~/Search.aspx");
        }
    }
}

 

//=======================================================================================

Thats it, now are you all set. 
Run the application, and see how the Tree Menu changes based on when a user logs in.  

If you have have roles, or want to incorporate roles into this solution, this is what you would do:
1.  When a user logs in, create a session variable for this role, such as:  
      Session["UserRole"] = "member";
                     or
      Session["UserRole"] = "admin";
                     or any other role you have
      Session["UserRole"] = "Your Role";

2.  In the master page, code behind, check what user role is in the logged in section:
      if ( Session["UserRole"] != null && Session["UserRole"].ToString() == "admin")
      {
            //here add all the items the user has access to
            //make sure the pages also check for the user role so users can't directly go to the pages.
      }
3.  Why do I need Roles?
      It helps to maintain the site, and give some architecture to the site.

Here is a snap shot of the how menu looks when a user is not logged in (Check Tree Menu on left side below):




Here is a snap shot of the how menu looks when a user is logged in (Check Tree Menu on left side below):




  I hope this tutorial helped you.  Leave some feedback if you liked it, or had any questions.

 

Notes

This example was done in Visual Studio 2005 using Framework 2.0. I hope it shows you how to use a dynamic tree menu control with master pages. Good luck.
 

Tags

 

Ratings

Was this article helpful? Don't forget to rate it. Ratings helps community members identify top & useful articles.
Current Rating: rating starrating starrating starrating starrating star
Rate this article:
(1-Poor, 2-Needs Improvement, 3-Average, 4-Good, 5-Excellent)
 

Feedback

Have a question, suggestion or feedback for this article? Leave your comments below.
Share your feedback:
Need to upload images with your comment. Upload your images here: Image Shack. Remember to copy the url of your uploaded image and insert it into the comment.
You can insert images by clicking on the following icon: insert comment image
(Members Only)
 

Latest Comments

Below are the latest comments from other ProgTalk members.
Posted on:
4/29/2008 12:00:00 AM
Posted by:
hi
i have lil Q
let''s say we have 3 different roles
each one of them have different links and application

who can i direct em from the login page?
Posted on:
4/29/2008 12:00:00 AM
Posted by:

On the page load method just check for the roles, and rebind the tree control.  for example

if ( Session["LogginedIn"] != null)
{
    //user is logged in
    if ( Session["UserRole"] == "Admin")
    {
         //build Admin Menu here
    }
    else if ( Session["UserRole"] == "User")
    {
         //build User Menu here
    }
    else if ( Session["UserRole"] == "Guest")
    {
         //build Guest Menu here
    }
}

I may have misinterpreted your question.  Does this help?

Posted on:
4/29/2008 12:00:00 AM
Posted by:

ok maybe my question will sound lil bit  stupid but

should i write this code in side a script in the login page ?and the action will be redirect the users to the wanted pages?

10x :)

Posted on:
4/29/2008 12:00:00 AM
Posted by:
If you are using master pages, you should put this in the code behind of the master page, in the page load method.  If you are not using the master pages, you would have to implement this code where ever the menu control exists.  By the way, there is no question that is stupid.  It never hurts to make sure of something.
Posted on:
4/29/2008 12:00:00 AM
Posted by:

i'll work on it

thank you :)

Posted on:
4/6/2008 12:00:00 AM
Posted by:
Hi, I''m using a master page with a tree view control. Each node points to a content web form. My problem is that when I select one node the master page load event fires and the tree view is rebuilded collapsing the whole structure. I don''t want to collapse the tree view, just let it expanded as the user select the option.

Any suggestion to work with this?

Regards
Posted on:
4/7/2008 12:00:00 AM
Posted by:
If your parent node does not need to go to a page, add it such as the following:
TreeNode a = new TreeNode("A", "A");
TreeNode b = new TreeNode("B", "B");
TreeView1.Nodes.Add(a);
a.ChildNodes.Add(b);
Posted on:
2/24/2008 12:00:00 AM
Posted by:
Made some updates to the article,  saw a bunch of typo''s and added some more comments.
Posted on:
2/24/2008 12:00:00 AM
Posted by:
1. For this tutorial, is there anyway I can disable the root menu? For example, I need to create a menu that has:
-----------------------
File
    -New Window
    -New Tab
------------------------

The menu item ''File'' will not do anything.

2. How would I implement the roles for this tutorial other than valid the if (Session["LoggedIn"] == null)? I will probably have to check with the membership roles on the MSDN?

3. For the users password, is it a good idea to encrypt their password?

I will use the recommendation of creating an admin UserAccounts.aspx to add or modify users account.

Thanks I am learning alot.
Posted on:
2/25/2008 12:00:00 AM
Posted by:
Instead of using-
        TreeNode ndHome = new TreeNode("Home", "Home", "", "~/Home.aspx", "");
use-
     TreeNode ndHome = new TreeNode("Home", "Home");

I guess for your it would be Root, instead of Home.
Posted on:
3/4/2008 12:00:00 AM
Posted by:
The direction works somewhat, but how can I remove the underline from the root.

For example,
When the User clicks on the Root, it still shows an underline for the word Root like if its linking to something.


Also,

For the tutorial, how can I disable the auto expand for Advance Search. I just want the Advance Search menu item to expand if the User actually clicks on the Search menu item.

Thanks
Posted on:
2/25/2008 12:00:00 AM
Posted by:
I think you have the asnwer for question 1. 
As far as question 2, you need to keep the roles in your database(my recommendation). 
You should define roles in a roles table which you will be using. 
Once a user, registers, automatically assign them a role (Such as Member).  This way when the user logs in, you can check against the database, and get their role and store it in the session.

Then your menu will automatically populate and show them the proper menu.

I don''t think you have to encrypt the password.  If you are worried about security, you can make sure your site is a secure site, and it should encrypt the information passed using 128bit encryption.  That would be the simplest way.
Posted on:
2/23/2008 12:00:00 AM
Posted by:
Thanks for this menu tutorial.

Please tell me if I am doing this correctly. I plan to do the following.

I will need to make a register.aspx. When user enters all the necessary fields(username,password(need to encrypt this),email), I will put it in the mysql database, and then somehow I need the page to email me that a user wants to registrer(I think I saw a tutorial on how to email in this forum).

What is the best way to register a user.
1. Send the above data via email and if approve I manually add the user into the database?
2. Should I put the above data into a tempTable and then transfer the information into the acutal userTable after I approve the user or not.

Should I add him or her into a newly create Account database or in the MYSQL user account?

Thanks.
Posted on:
2/23/2008 12:00:00 AM
Posted by:
I think the question you are asking, may have different opinions.  The best approach I can think of is the following:
Lets us assume you User Table has the following columns:

UserID      -   int   - primary key
Email         -   varchar
Password   -  varchar
FirstName   - varchar
LastName   - varchar
Validated    - varchar
ValidationKey - varchar
Enable            -  char
CreatedDate   - datetime
ExpirationDate - datetime

Now when a user registers for an account, insert a record to the database. 
Make sure the Enable is "N", Validated = "N", ValidationKey = "2993SwesvhDasdfio349x3D" (This you should randomly generate), and CreatedDate = "Todays Date", ExpirationDate = "Todays Date plus 10 days"

Next generate an email that tells the user to click on a link to validate their account.  Let that link be the following:
http://www.yoursite.com/ValidateAccount.aspx?email=JohnDoe@abc.com&code=2993SwesvhDasdfio349x3D

Now on your ValidateAccount.aspx code, look for the email and code:
if ( Request.QueryString["email"] != null && Request.QueryString["code"] != null)
{
       string email = Request.QueryString["email"].ToString();
       string code = Request.QueryString["code"].ToString();

       //Now check your database table, for a user with that email and verification code.  If they exist, change the Validated = "Y",
        and enable = "Y".
}

Now
Posted on:
2/23/2008 12:00:00 AM
Posted by:
Also, can you go over a little detail on the users role. Regular, Admin. Thanks.
Posted on:
2/23/2008 12:00:00 AM
Posted by:
Now you also have to make sure you run a query against your database for not validated accounts that have a expirationdate before todays date.  If you wish you can delete those records, and even send them another email as a last approach before deleting.

The roles is more important based on what you want for the users.  Are different users going to see different menus.  Who will maintain the site, and make updates.  Who has the ability to see other users private information.

The simplest forms, could be having two users:
Members
Administrator

So what does the Members have access to?
    They can use all the functionalities of your site, but can only view public information of all users.  No private information will be shared.
So what does the Administrator do?
    He can see pages, that will allow him to delete users.
    He can see user accounts, and remove curses.
    If your site is a blog, or has forums, he can edit members profiles or comments.
    He can delete invalid accounts from your database through some front end page
    etc... you get the idea.

Remember, no one likes to open the db browser, and select a record, and manually update, delete, or edit.  These things should be a part of the site, which will make it easier for you and the future admins to use.