Cookies or Session and how to begin - asp.net

Heey Stackoverflow,
I have an question im started to learn asp.net language csharp and i have the following login code my question is how to begin or where can i learn to write down the session cookie and than i can get back to the other page to read this cookie out again for the username and password that did match ty very much
public partial class Administratie : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
try
{
string cnnString = ConfigurationManager.ConnectionStrings["Stefan"].ConnectionString;
using (SqlConnection con = new SqlConnection(cnnString))
using (SqlCommand cmd = new SqlCommand("select [Username],[Password] from Admin where [Username] = #Username and [Password] = #Password", con))
{
string Username = (textUsername.Text.Length > 0) ? textUsername.Text : null;
string Password = (TextPassword.Text.Length > 0) ? TextPassword.Text : null;
cmd.Parameters.Add("#Username", System.Data.SqlDbType.VarChar).Value = textUsername.Text;
cmd.Parameters.Add("#Password", System.Data.SqlDbType.VarChar).Value = TextPassword.Text;
con.Open();
using (SqlDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
if (Page.IsValid)
{
// Login Succeed
// Response.Redirect("Admin.aspx");
}
}
}
}
catch (Exception) { }
// Login Failed
Response.Write("Wrong Username ");
}
}

Try look here:
Create and retrieve Cookie data (C#)
Read a Cookie:
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
lblWelcome.Text = "<b>Unknown Customer</b>";
}
else
{
lblWelcome.Text = "<b>Cookie Found.</b><br><br>";
lblWelcome.Text += "Welcome, " + cookie["Name"];
}
Set a Cookie
HttpCookie cookie = Request.Cookies["Preferences"];
if (cookie == null)
{
cookie = new HttpCookie("Preferences");
}
cookie["Name"] = txtName.Text;
cookie.Expires = DateTime.Now.AddYears(1);
Response.Cookies.Add(cookie);
If you want to store data in a Session just set it:
Session["username"]=username;
and read:
string username=Session["username"];

You can use session to store username and password. If you want to use remember me option you can save the username and password in cookies.
Please check the links for using session and cookies

Related

how to auto login after registration in asp.net

I want to login automatically after registration by using a session like Session["ud"] , but I don't know where should I put it.
public partial class index : System.Web.UI.Page
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.AppSettings["dbpath"]);
protected void btnSave_Click(object sender, EventArgs e)
{
long idx;
SqlCommand cmd = new SqlCommand();
cmd.Connection = cnn;
cmd.CommandText = "Insert into tblUser (UInfo,UEmail,UName,UPass, UGender) Values (#P1,#P2,#P3,#P4,#P5) select ##Identity";
cmd.Parameters.AddWithValue("#P1", txtInfo.Text);
cmd.Parameters.AddWithValue("#P2", txtEmail.Text);
cmd.Parameters.AddWithValue("#P3", txtUserName.Text);
cmd.Parameters.AddWithValue("#P4", txtPass.Text);
cmd.Parameters.AddWithValue("#P5", rdbMale.Checked);
cnn.Open();
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
here we want to upload the image of user and it works correctly
string fn = "";
if (FileUpload1.HasFile == true)
{
fn = FileUpload1.FileName;
string des = Server.MapPath("\\UserImg\\") + idx.ToString() + ".jpg";
FileUpload1.PostedFile.SaveAs(des);
SqlCommand cmdUpdate = new SqlCommand();
cmdUpdate.Connection = cnn;
cmdUpdate.CommandText = "Update tblUser Set UImg=#P5 where UId=#P0";
cmdUpdate.Parameters.AddWithValue("#P5", idx.ToString() + ".jpg");
cmdUpdate.Parameters.AddWithValue("#P0", idx);
cnn.Open();
cmdUpdate.ExecuteNonQuery();
cnn.Close();
}
Response.Redirect("Profile.aspx");
}
}
once you have entered data into in sql database you will get id of new user here
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
Once you get the id assign it to your session
idx = Convert.ToInt64(cmd.ExecuteScalar()); // i think here we can do something
cnn.Close();
Session["ud"]=idx;
once you have assigned session ,you just have to redirect to required page and validate Session variable if it's null or not.
i hope on Profile.aspx page you are checking for same session variable.
Profile.aspx.cs--on page load
if (Session["ud"] != null)
{
//successfull login
}
else
{
//redirect to login page
}

Restricting user access in asp.net

I am working on asp.net application. I want only logged in users to access the Game page. When the users log in, the id and pass are authenticated from the SQL then they are logged in. and I want the logged in users to have an access to Games.aspx.
Here is the login code,
public partial class Login : System.Web.UI.Page
{
//"Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
protected void Page_Load(object sender, EventArgs e)
{
lbInfo.Enabled = false;
}
public bool IsAuthenticated
{
get { return Convert.ToBoolean(Session["sIsAuthenticated"] ?? false); }
set { Session["sIsAuthenticated"] = value; }
}
protected void Button1_Click(object sender, EventArgs e)
{
string strcon = "Data Source=MUNIZA\\SQLEXPRESS;Initial Catalog=LD_Server;Integrated Security=True";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("spStudentProfile", con);
com.CommandType = CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("RegNo", TextBox2.Text);
SqlParameter p2 = new SqlParameter("Password", TextBox1.Text);
com.Parameters.Add(p1);
com.Parameters.Add(p2);
con.Open();
SqlDataReader rd = com.ExecuteReader();
if (rd.HasRows)
{
IsAuthenticated = true;
rd.Read();
Response.Redirect("~/Games.aspx");
}
else
{
IsAuthenticated = false;
lbInfo.Enabled = true;
lbInfo.Text = "Invalid username or password.";
}
}
It is the login code on every page,
<%
string url = "~/Login.aspx", text = "Log in";
if (Convert.ToBoolean(Session["sIsAuthenticated"] ?? false))
{ url = "~/Home.aspx"; text = "Log out"; }
%>
<%: text %>
</div>

How to connect to SQL Server using ADO.Net

This is the first time I'm designing a web site. I'm having problem on connecting to my database. None of buttons work on pages. The most important one is Register button. I fill the form correctly but when I press Register button it doesn't register the new user into database. It even doesn't show any error message which I've considered. For example, it doesn't show that You've registered before or Your registration wasn't successful. No error message and no new record in my database. I've removed the captcha code because I thought that may cause problem.Here's my code:
using System;
using System.Data.SqlClient;
using System.Web.UI.WebControls;
public partial class SignUp : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string strname = Cache["TF"] as string;
if (strname != null)
{
(Master.FindControl("Lozv") as Label).Text = strname;
(Master.FindControl("LinkButton1") as LinkButton).Visible = true;
}
else
{
(Master.FindControl("Lozv") as Label).Text = "Guest";
(Master.FindControl("LinkButton1") as LinkButton).Visible = false;
}
}
protected void Button1_Click1(object sender, EventArgs e)
{
string username = txtboxUser.Text;
SqlConnection sqlc = new SqlConnection("Data Source=.; Database=LDatabase; Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT dbo.CheckUserName(#UN)");
cmd.Parameters.AddWithValue("#UN", txtboxUser.Text);
sqlc.Open();
Boolean User = Convert.ToBoolean(cmd.ExecuteScalar());
sqlc.Close();
if (User == false) ////////////// if user name is not in DB//////////////
{
SqlConnection sqlca = new SqlConnection();
sqlca.ConnectionString = "data source=. ; database=LDatabase ; integrated security=true";
SqlCommand cmda = new SqlCommand();
cmda.Connection = sqlca;
cmda.CommandText = "INSERT INTO User_Pass values(#UserName,#Pass,#Name,#LastName,#Email,#Date,#Sex,'0')";
cmda.Parameters.AddWithValue("#UserName", txtboxUser.Text);
cmda.Parameters.AddWithValue("#Pass", txtboxPass.Text);
cmda.Parameters.AddWithValue("#Name", txtboxName.Text);
cmda.Parameters.AddWithValue("#LastName", txtboxSurname.Text);
cmda.Parameters.AddWithValue("#Email", txtboxEmail.Text);
cmda.Parameters.AddWithValue("#Date", DateTime.Now);
cmda.Parameters.AddWithValue("#Sex", rbtnGender.SelectedValue.ToString());
cmd.Parameters.AddWithValue("#manager", "No");
sqlca.Open();
int n= cmda.ExecuteNonQuery();
if (n <= 0)
LMsg.Text = "Your registration wasn't successful";
else
{
txtboxName.Text = "";
txtboxSurname.Text = "";
txtboxUser.Text = "";
txtboxPass.Text = "";
txtboxRePass.Text = "";
txtboxEmail.Text = "";
rbtnGender.SelectedIndex = -1;
LMsg.Text = "You registered successfully.";
}
sqlca.Close();
}
else //////////////if user name is in db//////////////
{
LMsg.Text = "This username has already registered.";
}
}
}
Does Captcha have anything to do with this type of problem? Any help would be appreciated.
Put your button like this in the aspx-markup:
<asp:Button ID="btnRegister" runat="server" Click="Button1_Click1" Height="26px" Text="register" Width="88px"/>
It should trigger the method.
Edit: Or bind the event in the Page_Load method (remove the Click-attribute from the button first - from my previous example above).
protected void Page_Load(object sender, EventArgs e)
{
btnRegister.Click += new EventHandler(Button1_Click1);
string strname = Cache["TF"] as string;
[...]

Session disappears on return to home page

I have a web site running on Azure where a user can login then navigate to other pages (naturally). My problem is that when I return to the Index/Homepage the session just disappears. I thought it my have something to do with the login control and its authentication method in the code behind but I tried putting another login on another page with the same authenticate event but that is completely fine.
I haven't found anyone with a similar problem.
here is the code behind for index.aspx
string Connection = ConfigurationManager.ConnectionStrings["****"].ConnectionString;
protected void Page_Load(object sender, EventArgs e) {}
protected void Login1_Authenticate(object sender, AuthenticateEventArgs e) {
string Username = Login1.UserName;
string pwd = Login1.Password;
SqlConnection connection = new SqlConnection(Connection);
connection.Open();
//SqlCommand comm = new SqlCommand("SELECT COUNT([*****], [*****]) FROM ***** WHERE [****] = '***' AND [****] = '****'", connection);
string sqlUserName = "SELECT [****] ,[****] FROM ***** WHERE [*****] ='" + * * * * * +"' AND [*****] ='" + * * * +"'";
SqlCommand cmd = new SqlCommand(sqlUserName, connection);
string CurrentName;
CurrentName = (string) cmd.ExecuteScalar();
if(CurrentName != null) {
Login1.FailureText = "Welcome";
Session["User"] = Username;
Session["LoggedIn"] = true;
Label1.Text = Session["User"].ToString();
if((bool) Session["LoggedIn"] == true && Session["User"].ToString() == "admin1") {
HyperLink3.Visible = true;
} else if((bool) Session["LoggedIn"] == true) {
HyperLink1.Visible = true;
}
} else {
Session["User"] = "";
}
}
}
Your if statement must be bugging out somewhere, or CurrentName is null.
if (CurrentName != null)
{
Login1.FailureText = "Welcome";
Session["User"] = Username;
Session["LoggedIn"] = true ;
Label1.Text = Session["User"].ToString();
if ((bool)Session["LoggedIn"] == true && Session["User"].ToString() == "admin1")
{
HyperLink3.Visible = true;
}
else if ((bool)Session["LoggedIn"] == true)
{
HyperLink1.Visible = true;
}
}
else
{
Session["User"] = "";
}
The most likely culprit is the preceding SQL query. Double check your syntax with the SQL query. I'm not sure what the asterisk variables are you have combined in there, but they could be causing an issue. You should proceed with line-by-line debugging of that script. Catch it mid-way through and check the value of CurrentName.

How to check if email is already in use in asp.net and making sure email is available before allowing the user to register?

I need to check an SQL Server database (not asp.net membership) to see if an email is already in use before allowing the user to register.
I have tried using the information in this website but it does not seem to work.
Your help will be much appreciated
You can try
protected void txtUsername_TextChanged(object sender, EventArgs e)
{
if (!string.IsNullOrEmpty(txtUsername.Text))
{
SqlConnection con = new SqlConnection("Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB");
con.Open();
SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like " + txtUsername.Text.Trim(), con);//I changed
SqlDataReader dr = cmd.ExecuteReader();
if (dr.HasRows)
{
checkusername.Visible = true;
imgstatus.ImageUrl = "NotAvailable.jpg";
lblStatus.Text = "UserName Already Taken";
}
else
{
checkusername.Visible = true;
imgstatus.ImageUrl = "Icon_Available.gif";
lblStatus.Text = "UserName Available";
}
con.Close();//I added
}
else
{
checkusername.Visible = false;
}
}

Resources