Capture Role from database into Session

My Developer Friends

my Login table have 3 field username, userpass, userrole.

From Login Page I would like to store Session["Role"], once I capture Role (Admin/User) then I will populate Treeview based on the Role

so, pls help me how to capture Role thru session.


  private bool ValidateLogin(string strUserName, string strPassword)
    {
        bool blnValidLogin = false;
        SqlDataReader sqlDr = null;

        SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
        string strSQL = "Select username, userpass, userrole From login Where username = '" + strUserName + "' And userpass = '" + strPassword + "'";

        try
        {
            sqlConn.Open();
            SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn);
            sqlDr = sqlCmd.ExecuteReader();
           
            if (sqlDr.HasRows)
            {
               
                blnValidLogin = true;
                Session["LoggedIn"] = "LoggedIn";

  //string role = (string)sqlDr[2];
                //Session["Role"] = "role";
            }
            return blnValidLogin;
        }
        catch (SqlException ex)
        {
            ctrlLogin.FailureText = ex.Message;
            return false;
        }
        finally
        {
            sqlConn.Close();
        }
    }

 

 

0
samir1973
9/5/2008 10:38:24 AM
asp.net.state-management 8807 articles. 0 followers. Follow

5 Replies
365 Views

Similar Articles

[PageSpeed] 19

string role = (string)sqlDr[3];
Session["Role"] = role;

Does this not work to set the Session variable?

 


jameswright
www.jwright.info

"Never be so busy making a living that you forget to make a life."
0
jameswright
9/5/2008 4:22:24 PM

hi Friends

noop its not working, please help. am sending the project concept once again what i have done

I have done RoleBased authentication. Here everything is working fine only am unable to capture Role into session from runtime login

my Login table have 3 field username, userpass, userrole.

From Login Page I would like to store Session["userrole"], once I capture UserRole (Admin/User) then I will populate Treeview based on the Role

so what will be the line to capture UserRole into session, pls help my login & master page


Login Page :

private bool ValidateLogin(string strUserName, string strPassword)
{
bool blnValidLogin = false;
SqlDataReader sqlDr = null;

SqlConnection sqlConn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"]);
string strSQL = "Select username, userpass, userrole From login Where username = '" + strUserName + "' And userpass = '" + strPassword + "'";

try
{
sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn);
sqlDr = sqlCmd.ExecuteReader();

if (sqlDr.HasRows)
{

blnValidLogin = true;
Session["LoggedIn"] = "LoggedIn";

//string userrole = (string)sqlDr[3];

//Session["userrole"] = userrole;

}
return blnValidLogin;
}
catch (SqlException ex)
{
ctrlLogin.FailureText = ex.Message;
return false;
}
finally
{
sqlConn.Close();
}
}

protected void ctrlLogin_Authenticate(object sender, AuthenticateEventArgs e)

{

bool blnAuthenticate = false;

blnAuthenticate=ValidateLogin(ctrlLogin.UserName,ctrlLogin.Password);

e.Authenticated=blnAuthenticate;

if (blnAuthenticate == true)

{

 

Response.Redirect(
"Welcome.aspx?LoginName=" + ctrlLogin.UserName);

}

else

{

Response.Redirect(
"Logout.aspx");

}

}

------------------------

Master 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 MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (IsPostBack == false)
        {
            if (Session["LoggedIn"] == null)
            {
                TreeView1.Nodes.Clear();

                TreeNode ndHome = new TreeNode("Home", "Home", "", "~/HomePage.aspx", "");
                TreeNode ndLogin = new TreeNode("Login", "Login", "", "~/Login.aspx", "");

                TreeView1.Nodes.Add(ndHome);
                TreeView1.Nodes.Add(ndLogin);
            }


            else
            {
                 if (Session["LoggedIn"] != null && Session["userrole"].ToString() == "user")
                {
                    TreeView1.Nodes.Clear();

                    TreeNode ndHome = new TreeNode("Home", "Home", "", "~/HomePage.aspx", "");
                    TreeNode ndReport = new TreeNode("Report", "Report", "", "~/Report.aspx", "");
                    TreeNode ndSearch = new TreeNode("Search", "Search", "", "~/Search.aspx", "");
                    TreeNode ndLogout = new TreeNode("Logout", "Logout", "", "~/Logout.aspx", "");

                    TreeView1.Nodes.Add(ndHome);
                    TreeView1.Nodes.Add(ndReport);
                    TreeView1.Nodes[1].ChildNodes.Add(ndSearch);
                    TreeView1.Nodes.Add(ndLogout);
                }
                else if (Session["LoggedIn"] != null && Session["userrole"].ToString() == "admin")
                {
                    TreeView1.Nodes.Clear();
                    
                    TreeNode ndHome = new TreeNode("Home", "Home", "", "~/HomePage.aspx", "");
                    TreeNode ndReport = new TreeNode("Report", "Report", "", "~/Report.aspx", "");
                    TreeNode ndSearch = new TreeNode("Search", "Search", "", "~/Search.aspx", "");
                    TreeNode ndAdmin = new TreeNode("Admin", "Admin", "", "~/Admin.aspx", "");
                    TreeNode ndLogout = new TreeNode("Logout", "Logout", "", "~/Logout.aspx", "");

                    TreeView1.Nodes.Add(ndHome);
                    TreeView1.Nodes.Add(ndReport);
                    TreeView1.Nodes[1].ChildNodes.Add(ndSearch);
                    TreeView1.Nodes.Add(ndAdmin);
                    TreeView1.Nodes.Add(ndLogout);
                }
            }

        }
    }
}

 

0
samir1973
9/9/2008 4:55:34 AM

samir1973:

sqlConn.Open();
SqlCommand sqlCmd = new SqlCommand(strSQL, sqlConn);
sqlDr = sqlCmd.ExecuteReader();

if (sqlDr.HasRows)
{

blnValidLogin = true;
Session["LoggedIn"] = "LoggedIn";

//string userrole = (string)sqlDr[3];

//Session["userrole"] = userrole;

}

Hi samir1973,

By checking your posted code and testing it on my local machine, I find the problem is you forgot to invoke the “Read” method that causes the “sqlDr[3]” item invalid. Please change it to the following one.

            if (sqlDr.Read())        //if (sqlDr.HasRows)
            {
                blnValidLogin = true;
                Session["LoggedIn"] = "LoggedIn";
                string userrole = (string)sqlDr[3];
                Session["userrole"] = userrole;
            }

 


Sincerely,
Benson Yu
Microsoft Online Community Support

Please remember to mark the replies as answers if they help and unmark them if they provide no help. This can be beneficial to other community members reading the thread.
0
Benson
9/10/2008 7:35:42 AM

hi Benson Yu

sorry for delayed response as was out of town. you are just fantastic and confirming its working properly. You are just awesome

only just help me how can i removed the blank space i.e how to use trim while capturing role as I have noticed that when am capturing role its taking some blank space from database, this i have noticed in debug mode.

thanx a lot,

samir

0
samir1973
9/15/2008 7:08:15 AM

Hi Benson Yu

I have temporarily done it thru database (i.e removed the extra width) and so now its taking properly. but If database userrole field is having width 10. and value i provide User or Admin then how can i ignore space on runtime.

what will be the code i have to change as I have tried with this replace command, its not working

string strSQL = "Select uid, username, userpass, replace(userrole,'','') From login Where username = '" + strUserName + "' And userpass = '" + strPassword + "'";

hope you got my issues

samir 

0
samir1973
9/15/2008 7:19:53 AM
Reply:

Similar Artilces:

Database Roles in Session database
We have two websites developed in VS2005 beta 2 in our project.  I am creating the Session state database(for session state management) for those websites in a separate database server using the aspnet_regsql tool .  The issue is I run my websites under a account which has minimal permissions  . For our project databases we create database roles with required permissions and assign the portal user to those roles .So there is no problem accessing the databases we create .  Now how do I give the portal user rights to the Session state database .  .There are no prede...

Session State to Capture UserID & Role at login
Thank you for your time\solutions using ASP.NET 2.0\Visual Basic:  How can I capture a UserID & Role into session State Variables that can feed existing sql_datasources expecting @userName, @userRole?  Hi, Session("UserName") = Membership.GetUser.UserID.ToString Session("UserRole") = Memberhip.GetUser.Role.ToString   Hope it helps   Regards -------------------------------------------------------------------------------- Please don't forget to mark as "Answer" the correct answer. Thanks   Use <Sessio...

Membership and Role Management
Hello, I've configured SQL server 2005 as my back-end data store via aspnet_regsql.exe. I presume it was succesvol. Creating users en roles programmatically is no problem. When I start the Web Site Administration Tool I can see the created users and roles. But when I want to show them by code I get an empty result. ... ... Roles.GetAllRoles()...... membership.GetAllUsers() The roleManager is enabled in web.config.<roleManager defaultProvider="SqlProvider" enabled="true" cacheRolesInCookie="true" cookieName=".ASPROLES" cookieTimeout="30" cookiePath="/" cookieRequireSS...

Managing Session State
 Hi, Is there a way to set how long a session variable persists before it is destroyed?  I use forms based authentication on my site, but some events are based on particular session variables, and often times the session variable will be destroyed if the user leaves the session idle for a few minutes.  Can I configure my site so that session variables stick around until the forms authentication session is over?  Or, is it possible to set an event that triggers when the session state expires or when the session variables are destroyed that redirects to the login page?...

about session state management
i am new in this field and i want to know , how can i manage login state management in web application . what namespace and attribute and property should i use. please reffer me   Check these links.. http://msdn.microsoft.com/en-us/library/879kf95c.aspx http://msdn.microsoft.com/en-us/library/ms178331.aspx http://quickstarts.asp.net/QuickStartv20/aspnet/doc/security/login.aspxMy Blog"Don't be afraid to be wrong; otherwise you'll never be right." check out previous discussion http://forums.asp.net/p/1131994/1798030.aspx  Haissam Abdul MalakMCAD.NET| Bl...

Session State Management
Which is the better option? Storing Session In Process .. Same process as the Web Server Storing Session State in a Windows Service .... ASP.NET State Storing Session State in Database. I am debating the pro's and con's of the three, basically it is for providing the typical who is online and what portion of the site they are visiting at the moment. I am tempted to use the Windows Service and run in on a secondary box.    AngeloA Hi,I moved your post from the FAQ forum to here as the FAQ forum is for posting answers to commonly asked questions, not asking questions.Ryan...

Session state managment
Can anyone refer me to a session state managment book and security practices if there is anything like that out their. Pelease check these sites. You may find them helpful. http://msdn2.microsoft.com/en-us/magazine/cc163730.aspx http://www.faqs.org/rfcs/rfc2964.html http://www.dotnetjohn.com/articles.aspx?articleid=249 http://www.informit.com/articles/article.aspx?p=31842&seqNum=3 http://coldfusion.sys-con.com/read/42075.htmPlease Mark As Answer if it helps you!...

The page requires session state that is no longer available. Either the session has expired, the client did not send a valid session cookie, or the session state history size is too small. Try increas
Hi.. I am making a mobile application using .net framework 2.0. My Application has  web farm scenario so for state management  I am using Sateserver in my application. My application runs fine if I dont use web farm scenario But in case of web farm scenario it is giving me error "The page requires session state that is no longer available. Either the session has expired, the client did not send a valid session cookie, or the session state history size is too small. Try increasing the history size or session expiry limit."   &...

Manage Users For This Role / Manage Roles For This User Question
In the roles/user management pages there is a link called Manage Users For This Role and Manage Roles For This User respectively. I want non Admins to be able to see these pages, and currently I have it so that they can see the manage users and manage roles pages. However, when a non admin clicks on Manage Users For This Role or Manage Roles For This User link it does not display the control, just an empty page. I can get around this by giving edit rights to the page, but I do not want them to have edit rights for the page. Any ideas? Thanks  ...

"The page requires session state that is no longer available. Either the session has expired, the client did not send a valid session cookie, or the session state history size is too small. Try increa
Hi.. I am making a mobile application using .net framework 2.0. My Application has web farm scenario so for state management I am using Sateserver in my application. My application runs fine if I dont use web farm scenario But in case of web farm scenario it is giving me error "The page requires session state that is no longer available. Either the session has expired, the client did not send a valid session cookie, or the session state history size is too small. Try increasing the history size or session expiry limit." I am not getting why this error is coming ..Though I already h...

Out Of Process Session state management
Hi,My web application is based on ASP.NET 2.0 with C#, SQL Server 2005. We are using InProc session state management. When the user logs in I am  storing some basic user information like userid, emailaddress, customerid, account no is the session variables. This information frequently required in several pages of the application. The application is hosted in a web farm.  I have often heard and read that applications hosted in web farm should use Out of process session state management. Would using State Service be a good option? Is it reliable? If I decide change to OutofProce...

session state management help
If im storing sessions as 'session.contents("mysession") = "this is the text in my session" And i want to change the length of time before it timesout, is this a custom session? how would i set the timeout in the web.config file?i dont know what providers to use, i want it to be about an hour, so timeout="60"can anyone help?thanks Hi Friend, Here is the option to set the session time out.. 1. In Web.config like..            <sessionState mode="InProc" timeout="60" cookieless=...

State Management; .Net Profiler
Here is the situation with the customized profiler. I got a profiler class called SSOProfileProvider inheriting from ProfileProvider. I've implemented the Initilization, GetPropertyValues and SetPropertyValues. The Get... and Set.. are making a call to the database to store profile into the database. This class has been stored in the separate DLL called "Security.DLL" and there is a web site that is using this dll. The web.Config for this website is as follow:<profile enabled="true" inherits="AppProfileBase" defaultProvider="SSO" automat...

VB.NET roles and sessions
I'm building a website where there are 5 user roles. Some of the roles are shared, but not all, so what I'm doing is making 5 folders and placing the pages that that role and the superusers to that role can access, and the super user gets pages only it should access. I've done this before in C# with allowing only a certain role to access a folder. How do I do it in the VB.NET side? Also, I wish to track what pages any user is on at any given time. The problem could me, however, that a user could sign in multiple times and be on multiple pages at a time. Are there any implementation s...

Web resources about - Capture Role from database into Session - asp.net.state-management

Database - Wikipedia, the free encyclopedia
A database is an organized collection of data . The data are typically organized to model aspects of reality in a way that supports processes ...

Database - Wikipedia, the free encyclopedia
... requiring information. For example, modelling the availability of rooms in hotels in a way that supports finding a hotel with vacancies. Database ...

Dodgy database exposes details of 191 million US voters
... years, there's a high chance that your personal details are now out in the wild. Security researcher Chris Vickery found a misconfigured database ...

Huge database of 191 million U.S. voters found on the open Internet
... such bulk information online, a recent discovery seems to indicate. According to VentureBeat , a security researcher found the exposed database ...

3.3 million Hello Kitty fans' details have been exposed in a huge database leak
... week after week, the hacks, breaches and data leaks continue to roll in. The latest victim? Hello Kitty. CSO Online is reporting that a database ...

Under pressure, DNC restores Bernie Sanders campaign's access to their database - Videos - CBS News
A strange twist in the race for the democratic presidential nomination: the campaign of Vermont Senator Bernie Sanders has filed a complaint ...

Massive Voter Database Left Open For Public Consumption
Gosh, we could have avoided all the angst about the Clinton/Sanders voter database breach if only we'd known about this major database , accessible ...

Database configuration issues expose 191 million voter records
A misconfigured database has led to the disclosure of 191 million voter records. The database, discovered by researcher Chris Vickery, doesn't ...

Database error publishes data of 3 million Hello Kitty fans
Online researcher Chris Vickery uncovered a database this weekend containing the personal information of 3.3 million accounts associated with ...

191 Million US Voter Registration Records Leaked In Mystery Database
A huge database of 191 million US citizens is uncovered. But no one knows who carelessly left it open, whilst the FBI have been contacted.

Resources last updated: 1/2/2016 4:08:22 PM