So i have to make a website with a registration,login and user profile where the user can change details , but i want the site to remember the user that is loged in so that they can see and change their info when they click on the my profile button.
Im currently testing if my session works but cant get it to work im useing home page and a lable to show a user name but it doesnt show anything.
Error Im getting:Is that the value isnt there but thats only when i use a breakpoint if i run the application normly the lable is just empty and doesnt work but also doesnt give any errors
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceForStuff;
using System.Collections; using System.Configuration; using System.Data; using System.Data.OleDb;
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections; using System.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//if (Request.Cookies["LoggedIn"] != null &&
// Request.Cookies["LoggedIn"].Value == "true")
//{
// Response.Redirect("Home.aspx");
// }
}
protected void Loginbtn_Click(object sender, EventArgs e)
{
// Create a new instance of the UseDatabase class.
usedatabase useDb = new usedatabase(Request.PhysicalApplicationPath +
"App_Code\\Bookwebsite.mdb");
// Construct a query string using the values from the text boxes.
string queryString = "SELECT * FROM [BookUsers] WHERE UserName = '";
queryString += UserNameText.Text + "' AND Password = '";
queryString += PassText.Text + "';";
if (dbReader != null && dbReader.HasRows)
{
// Set up the cookies.
//HttpCookie loggedInCookie = new HttpCookie("LoggedIn", "true");
//Response.Cookies.Add(loggedInCookie);
Response.Redirect("Home.aspx");
Session["StoreID"] = (int)dbReader["UserID"];
useDb.DisconnectDatabase();
dbReader.Close();
}
In your code, the problem is here, you use Response.Redirect("Home.aspx") to redirect the page, which is equivalent to
Response.Redirect("Home.aspx",true), it will interrupt the current response and directly perform page redirection.
So your code for setting the session It was not executed.
Please solve it in two ways:
Use Response("Home.aspx",false);
Set up the session before page redirection
You could also read more details about HttpResponse.Redirect Method, which contains a description of the parameters in the method.
I personally recommend that you use the first method to solve this problem.
Best regards,
Xudong Peng
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
Okay I tried what you suggested, but its still not loading the user ID that is in the database , i changed the code to if (dbReader != null && dbReader.HasRows)
{
// Set up the cookies.
//HttpCookie loggedInCookie = new HttpCookie("LoggedIn", "true");
//Response.Cookies.Add(loggedInCookie);
Session["StoreID"] = (int)dbReader["UserID"];
useDb.DisconnectDatabase();
dbReader.Close();
Response.Redirect("Home.aspx", false);
It seems to read it correctly but doesn't display it on the homepage after redirection
I used this for the label
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
.NET forums are moving to a new home on Microsoft Q&A, we encourage you to go to Microsoft Q&A for .NET for posting new questions and get involved today.
This doesnt work getting already defined error i already used it to log a user in at the start
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Configuration;
protected void Loginbtn_Click(object sender, EventArgs e)
{
// Create a new instance of the UseDatabase class.
usedatabase useDb = new usedatabase(Request.PhysicalApplicationPath +
"App_Code\\Bookwebsite.mdb");
// Construct a query string using the values from the text boxes.
string queryString = "SELECT * FROM [BookUsers] WHERE UserName = '";
queryString += UserNameText.Text + "' AND Password = '";
queryString += PassText.Text + "';";
How do u do that cuz i tried using a cookie but couldnt get it to display the current logged in users id or user name?
Using a cookie is the standard for authentication in browser applications. ASP.NET has a forms authentication library built-in and it works with all the security features in ASP.NET. This includes displaying the username.
Thx for the help btw i see what u mean but for some reason the project im working on wants me to create the login with a session variable and use web methods with that to retrieve infromation about a user and information about books in a database.
Thx for the help btw i see what u mean but for some reason the project im working on wants me to create the login with a session variable and use web methods with that to retrieve infromation about a user and information about books in a database.
Web methods are stateless and don't look for Session. You have to modify the default behavior to get a Web Method to make this work.
Clasuis
Thx for the help appreciate it a lot still not getting anything to display in the label tho.
You have to understand that displaying a username has been solved for many many years. I'm a bit confused, as the link I provided shows how to create a Forms Auth ticket. If you followed the code example, then the user name can be fetched from...
User.Identity.Name
This approach has been a standard for many years in ASP.NET Web Forms.
Huh? This exception has nothing to do with your original question. The error is telling you "command" has not been defined. It looks like you copied the code from Xudong Peng's post without understand how it works. Xudong Peng, is
demonstrating the ExecuteScalar() method which returns a single value. It is up to you to build the command object like you are doing in your other code.
This error message means that command is not declared. If trying the minimal amount of change is easier given your current experience, try to just change :
OleDbDataReader dbReader = useDb.ExecuteQuery(queryString);
if (dbReader.Read()) // Could use that instead
// if (dbReader != null && dbReader.HasRows) NOT NEEDED
{
// do whatever if a row is found
}
I'm not convinced this is your current problem. Or have you SEEN that you are not entering in the
if (dbReader != null && dbReader.HasRows) condition ?
Now it's unclear if you see on other pages that this session variable is not set or what (seems also weird to store the "UserID" in a "StoreID" session variable, is this really the name you are using on other pages ?)
Another option is that defining the first session variable (which generate a fixed coookie value to identify the browser session) and doing a redirect as part of the same response doesn't play well together (was the case with older browsers).
Also as pointed already, it could be best to take advantage of what ASP.NET offers oout of the box.
None
0 Points
11 Posts
ASP.Net With a database connection and session to remember a loged on User
Jul 31, 2020 09:53 PM|Clasuis|LINK
So i have to make a website with a registration,login and user profile where the user can change details , but i want the site to remember the user that is loged in so that they can see and change their info when they click on the my profile button.
Im currently testing if my session works but cant get it to work im useing home page and a lable to show a user name but it doesnt show anything.
Error Im getting:Is that the value isnt there but thats only when i use a breakpoint if i run the application normly the lable is just empty and doesnt work but also doesnt give any errors
HomePage.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Home.aspx.cs" Inherits="Home" %>
<%@ Register src="Header.ascx" tagname="Header" tagprefix="uc1" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.auto-style1 {
width: 100%;
height: 110px;
}
.auto-style2 {
text-align: center;
}
.auto-style3 {
color: #9999FF;
font-weight: normal;
text-decoration: underline;
}
.auto-style4 {
height: 23px;
}
.auto-style5 {
height: 23px;
text-align: center;
}
.auto-style10 {
font-style: italic;
font-weight: bold;
background-color: #FF6699;
}
.auto-style11 {
text-align: right;
}
.auto-style13 {
font-weight: bold;
font-style: italic;
background-color: #FFFF99;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<p>
</p>
<uc1:Header ID="Header1" runat="server" />
<div>
<table class="auto-style1">
<tr>
<td class="auto-style2" colspan="3">
<em>
<h2>
<em>
<strong>
<asp:Button ID="Button1" runat="server" CssClass="auto-style13" Height="49px" OnClick="Button1_Click" Text="My Profile" Width="203px" />
<asp:Button ID="submitabook" runat="server" Text="Submit New Book" OnClick="SubmitBook" Width="197px" CssClass="auto-style10" Font-Names="Arial" Height="49px" />
</strong>
<asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</em></h2>
<p class="auto-style11">
</em></p>
</td>
</tr>
<tr>
<td class="auto-style4"></td>
<td class="auto-style5">
<asp:Repeater ID="RepeaterBooks" runat="server" DataSourceID="SqlDataSource1" OnItemCommand="RepeaterBooks_ItemCommand">
<ItemTemplate>
<table align="center">
<tr>
<th colspan="2" class="auto-style1">
<%#DataBinder.Eval(Container.DataItem, "BookName") %>
</th>
</tr>
<tr>
<td class="auto-style2">Author:</td>
<td class="auto-style5">
<%#DataBinder.Eval(Container.DataItem, "Author") %>
</td>
</tr>
<tr>
<td class="auto-style2">Genre:</td>
<td class="auto-style5">
<%#DataBinder.Eval(Container.DataItem, "Genre") %>
</td>
</tr>
<tr>
<td colspan="2" style="text-align:center">
<asp:HiddenField ID="hdfBookID" runat="server" Value='<%#DataBinder.Eval(Container.DataItem, "BookID") %>'/><br />
<asp:Button ID="btnView" runat="server" Text="View" OnClick="ViewBook"/>
</td>
</tr>
</table>
<hr width="25%"/>
</ItemTemplate>
</asp:Repeater>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:BookwebsiteConnectionString4 %>" ProviderName="<%$ ConnectionStrings:BookwebsiteConnectionString4.ProviderName %>" SelectCommand="SELECT * FROM [BookInformation]"></asp:SqlDataSource>
</td>
<td class="auto-style4"></td>
</tr>
<tr>
<td> </td>
<td class="auto-style2"> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td class="auto-style2"> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td class="auto-style2">
</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td class="auto-style2">
</td>
<td> </td>
</tr>
<tr>
<td> </td>
<td class="auto-style2">
</td>
<td> </td>
</tr>
</table>
</div>
</form>
</body>
</html>
Home.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ServiceForStuff;
using System.Collections; using System.Configuration; using System.Data; using System.Data.OleDb;
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label2.Text = (string)Session["StoreID"];
}
protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
{
}
protected void RepeaterBooks_ItemCommand(object source, RepeaterCommandEventArgs e)
{
}
protected void ViewBook(object send, EventArgs e)
{
Response.Redirect("ViewBook.aspx");
}
protected void SubmitBook(object send, EventArgs e)
{
Response.Redirect("SubmitBook.aspx");
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("UserProfile.aspx");
}
}
Login Page Code:
Login.aspx.cs
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections; using System.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//if (Request.Cookies["LoggedIn"] != null &&
// Request.Cookies["LoggedIn"].Value == "true")
//{
// Response.Redirect("Home.aspx");
// }
}
protected void Loginbtn_Click(object sender, EventArgs e)
{
// Create a new instance of the UseDatabase class.
usedatabase useDb = new usedatabase(Request.PhysicalApplicationPath +
"App_Code\\Bookwebsite.mdb");
// Construct a query string using the values from the text boxes.
string queryString = "SELECT * FROM [BookUsers] WHERE UserName = '";
queryString += UserNameText.Text + "' AND Password = '";
queryString += PassText.Text + "';";
useDb.ConnectToDatabase();
// Check for matches.
OleDbDataReader dbReader = useDb.ExecuteQuery(queryString);
dbReader.Read();
if (dbReader != null && dbReader.HasRows)
{
// Set up the cookies.
//HttpCookie loggedInCookie = new HttpCookie("LoggedIn", "true");
//Response.Cookies.Add(loggedInCookie);
Response.Redirect("Home.aspx");
Session["StoreID"] = (int)dbReader["UserID"];
useDb.DisconnectDatabase();
dbReader.Close();
}
else
{
// Display the error message.
ErrorLabel.Text = "Incorrect username or password!";
}
// Disconnect.
}
}
Contributor
2110 Points
674 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 02:17 AM|XuDong Peng|LINK
Hi Clasuis,
In your code, the problem is here, you use
Response.Redirect("Home.aspx")
to redirect the page, which is equivalent toResponse.Redirect("Home.aspx",true)
, it will interrupt the current response and directly perform page redirection.So your code for setting the session It was not executed.
Please solve it in two ways:
You could also read more details about HttpResponse.Redirect Method, which contains a description of the parameters in the method.
I personally recommend that you use the first method to solve this problem.
Best regards,
Xudong Peng
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 04:15 AM|Clasuis|LINK
Okay I tried what you suggested, but its still not loading the user ID that is in the database , i changed the code to if (dbReader != null && dbReader.HasRows)
{
// Set up the cookies.
//HttpCookie loggedInCookie = new HttpCookie("LoggedIn", "true");
//Response.Cookies.Add(loggedInCookie);
Session["StoreID"] = (int)dbReader["UserID"];
useDb.DisconnectDatabase();
dbReader.Close();
Response.Redirect("Home.aspx", false);
It seems to read it correctly but doesn't display it on the homepage after redirection
I used this for the label
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
Label2.Text = (string)Session["StoreID"];
}
Contributor
2110 Points
674 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 06:47 AM|XuDong Peng|LINK
Hi Clasuis,
If you want to get row data from OleDbDataReader, you must use the read() method, like this:
Best regards,
Xudong Peng
All-Star
194511 Points
28081 Posts
Moderator
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 08:48 AM|Mikesdotnetting|LINK
Don't use session to remember a logged in user. Use a forms authentication cookie instead.
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 09:51 AM|Clasuis|LINK
How do u do that cuz i tried using a cookie but couldnt get it to display the current logged in users id or user name?
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 09:52 AM|Clasuis|LINK
This doesnt work getting already defined error i already used it to log a user in at the start
using System;
using System.Collections.Generic;
using System.Data.OleDb;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Collections;
using System.Configuration;
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//if (Request.Cookies["LoggedIn"] != null &&
// Request.Cookies["LoggedIn"].Value == "true")
//{
// Response.Redirect("Home.aspx");
// }
}
protected void Loginbtn_Click(object sender, EventArgs e)
{
// Create a new instance of the UseDatabase class.
usedatabase useDb = new usedatabase(Request.PhysicalApplicationPath +
"App_Code\\Bookwebsite.mdb");
// Construct a query string using the values from the text boxes.
string queryString = "SELECT * FROM [BookUsers] WHERE UserName = '";
queryString += UserNameText.Text + "' AND Password = '";
queryString += PassText.Text + "';";
useDb.ConnectToDatabase();
// Check for matches.
OleDbDataReader dbReader = useDb.ExecuteQuery(queryString);
dbReader.Read();
if (dbReader != null && dbReader.HasRows)
{
// Set up the cookies.
//HttpCookie loggedInCookie = new HttpCookie("LoggedIn", "true");
//Response.Cookies.Add(loggedInCookie);
Session["StoreID"] = (int)dbReader["UserID"];
useDb.DisconnectDatabase();
dbReader.Close();
Response.Redirect("Home.aspx", false);
}
else
{
// Display the error message.
ErrorLabel.Text = "Incorrect username or password!";
}
// Disconnect.
}
All-Star
53081 Points
23655 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 11:07 AM|mgebhard|LINK
Using a cookie is the standard for authentication in browser applications. ASP.NET has a forms authentication library built-in and it works with all the security features in ASP.NET. This includes displaying the username.
https://docs.microsoft.com/en-us/dotnet/api/system.web.security.formsauthenticationticket?view=netframework-4.8
There is also OWIN cookie authentication. This is a newer approach that uses an external library to an ASP.NET application.
https://docs.microsoft.com/en-us/previous-versions/aspnet/dn385599(v=vs.113)
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 11:54 AM|Clasuis|LINK
Thx for the help btw i see what u mean but for some reason the project im working on wants me to create the login with a session variable and use web methods with that to retrieve infromation about a user and information about books in a database.
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 11:55 AM|Clasuis|LINK
Thx for the help appreciate it a lot still not getting anything to display in the label tho.
All-Star
53081 Points
23655 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 12:10 PM|mgebhard|LINK
Web methods are stateless and don't look for Session. You have to modify the default behavior to get a Web Method to make this work.
You have to understand that displaying a username has been solved for many many years. I'm a bit confused, as the link I provided shows how to create a Forms Auth ticket. If you followed the code example, then the user name can be fetched from...
This approach has been a standard for many years in ASP.NET Web Forms.
Share your Forms Authentication code.
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 12:15 PM|Clasuis|LINK
https://gyazo.com/01e49fada8f8df4a1efba821d7fdd947
this is the error
All-Star
53081 Points
23655 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 12:37 PM|mgebhard|LINK
Huh? This exception has nothing to do with your original question. The error is telling you "command" has not been defined. It looks like you copied the code from Xudong Peng's post without understand how it works. Xudong Peng, is demonstrating the ExecuteScalar() method which returns a single value. It is up to you to build the command object like you are doing in your other code.
Do a Google search to find OleDb examples.
https://docs.microsoft.com/en-us/dotnet/api/system.data.oledb.oledbcommand.executescalar?view=dotnet-plat-ext-3.1
Google
https://www.google.com/search?q=ADO.NET+oledb+executescalar
All-Star
48570 Points
18081 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 12:39 PM|PatriceSc|LINK
This error message means that command is not declared. If trying the minimal amount of change is easier given your current experience, try to just change :
OleDbDataReader dbReader = useDb.ExecuteQuery(queryString);
if (dbReader.Read()) // Could use that instead
// if (dbReader != null && dbReader.HasRows) NOT NEEDED
{
// do whatever if a row is found
}
I'm not convinced this is your current problem. Or have you SEEN that you are not entering in the if (dbReader != null && dbReader.HasRows) condition ?
Now it's unclear if you see on other pages that this session variable is not set or what (seems also weird to store the "UserID" in a "StoreID" session variable, is this really the name you are using on other pages ?)
Another option is that defining the first session variable (which generate a fixed coookie value to identify the browser session) and doing a redirect as part of the same response doesn't play well together (was the case with older browsers).
Also as pointed already, it could be best to take advantage of what ASP.NET offers oout of the box.
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 03:16 PM|Clasuis|LINK
Yes the StoreID just a name that i gave so it can store a useres iD for the session, the UserID is the same as it is in the database
None
0 Points
11 Posts
Re: ASP.Net With a database connection and session to remember a loged on User
Aug 03, 2020 03:19 PM|Clasuis|LINK
Oooh sorry, i thought he meant to replace if (dbReader,Read with only that.