how to auto login after registration in asp.net - 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
}

Related

Using stored procedure to login Asp.net

I'm using asp.net to create a login page; in debugging I see the correct inputted data but I keep gettting the error message Invalid Username or Password even when it is valid. I have also executed the stored procedure with values and shows the correct result. I'm not sure what is happening.
protected void login_Click(object sender, EventArgs e)
{
String username = txtUserName.Text.ToString();
String password = txtPassword.Text;
string con = ConfigurationManager.ConnectionStrings["LoginConnectionString"].ToString();
SqlConnection connection = new SqlConnection(con);
connection.Open();
string passwords = encryption(password);
SqlCommand cmd1 = new SqlCommand("spLogin", connection);
cmd1.CommandType = CommandType.StoredProcedure;
cmd1.Parameters.AddWithValue("#UserName", username);
cmd1.Parameters.AddWithValue("#password", passwords);
SqlDataReader sqldr = cmd1.ExecuteReader();
if (sqldr.Read())
{
Session["UserName"] = username.ToUpper();
Response.Redirect("~/Home/Welcome.aspx");
}
else
{
lblError.Text = "Invalid Username or Password";
}
connection.Close();
sqldr.Close();
}
StoredProcedure
select * from Users u where UserName=#UserName and password=#password

Value cannot be null in querystring

I have 2 link buttons on my page for each product.1 of them is delete that product and the other is redirect it by query string to the other page to Edit that product.
hereprotected void dlMusic_ItemCommand(object source, DataListCommandEventArgs e)
{
int id = Convert.ToInt32(e.CommandArgument);
if (e.CommandName == "EditItem")
{
Response.Redirect("~/Admin/EditMusic.aspx?id=" + id);
}
else if (e.CommandName == "DeleteItem")
{
SqlCommand cmd = new SqlCommand("", Connection);
cmd.CommandText = "DELETE FROM MusicTable WHERE MusicId=#id";
cmd.Parameters.AddWithValue("#id", id);
Connection.Open();
cmd.ExecuteNonQuery();
Connection.Close();
LoadData();
}
}
Delete button worked correctly but on edit I have problem.
protected void Page_Load(object sender, EventArgs e)
{
int id = int.Parse(Request.QueryString["id"]);
SqlDataAdapter da = new SqlDataAdapter("", Connection);
DataTable dt = new DataTable();
da.SelectCommand.CommandText = "SELECT * FROM MusicTable WHERE MusicId=#id";
da.SelectCommand.Parameters.AddWithValue("#id", id);
da.Fill(dt);
string name = dt.Rows[0]["MusicName"].ToString();
string signame = dt.Rows[0]["SingerName"].ToString();
string prodname = dt.Rows[0]["ProducerName"].ToString();
string albname = dt.Rows[0]["AlbumeName"].ToString();
string des = dt.Rows[0]["Description"].ToString();
string cover = dt.Rows[0]["Cover"].ToString();
txtMusicName.Text = name;
txtSingerName.Text = signame;
txtProducerName.Text = prodname;
txtAlbumeName.Text = albname;
coverImg.ImageUrl = "~/images/" + cover;
txtDes.InnerText = des;
}
It works correctly until requested by query string and the error come is
Additional information: Value cannot be null.
Thanks in advance
From your comment, it is apparent that field "id" is not part of your QueryString.
Please check your URL when the Edit Page is loaded by the browser (you can see it if you put a breakpoint and switch to the browser window).
If you think your URL is correct, please post a screenshot of your loading browser.
Another idea (quite desperate, though), change "id" in whatever else (i.e. "myid")
Response.Redirect("~/Admin/EditMusic.aspx?myid=" + id);
and
int id = int.Parse(Request.QueryString["myid"]);

Data Reader and Invalid attempt to read when no data is present

This is my code:
protected void logujButton_Click(object sender, EventArgs e)
{
string user = "data source=myHostServer; database = myDataBase; user id=myLogin; password=myPassword";
SqlConnection con2 = new SqlConnection(user);
con2.Open();
string loguj = "select count(*) from uzytkownik where Login = '"+ logujTextBox.Text +"'";
SqlCommand command = new SqlCommand(loguj, con2);
int wartosc = Convert.ToInt32(command.ExecuteScalar().ToString());
con2.Close();
if (wartosc == 1)
{
con2.Open();
SqlCommand pobierzHaslo = new SqlCommand("select Haslo from uzytkownik where Login = '" + logujTextBox.Text + "'", con2);
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
string haslo = rdr["Haslo"].ToString();
if (haslo == hasloTextBox.Text)
{
errorLabel.Text = "Prawidlowe Haslo !";
}
else
{
errorLabel.Text = "Zle haslo !";
}
}
else
{
errorLabel.Text = "Taki uzytkownik nie istnieje !";
}
}
When I press button, this error is appearing: "Invalid attempt to read when no data is present". Could You tell me, where i made mistake ?. Thanks for advise !
You haven't read anything from the reader yet. You have to call the Read() method:
SqlDataReader rdr = pobierzHaslo.ExecuteReader();
if (rdr.Read())
{
string haslo = rdr["Haslo"].ToString();
....
}
If you have access to SSMS, run the query directly in a query window and make sure that you get data back. Your query may be bad. It is most likely an error from the ExecuteReader method of your SqlDataReader, based on the text of the error message.

Trouble with "Last Login" Stored Procedure

Added a column "LastLogin" to a User table, however, it only stores the last login date the first time a user logs in to a password-protected page.
When the same user logs in a second time, the cell does not reflect his last login. Here is my stored procedure:
Here is my stored procedure:
ALTER PROCEDURE [dbo].[UpdateLastLogin] (
#intUserID int
)
-- Add the parameters for the stored procedure here
AS
SET NOCOUNT ON
UPDATE Users SET LastLogin = GETDATE() WHERE UserID = #intUserID
Here is my code:
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//SqlConnection oConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["XXXConnectionString"].ConnectionString);
//SqlCommand oCommand = new SqlCommand();
//oCommand.Connection = oConnection;
//oCommand.CommandText = "UpdateLastLogin";
//oCommand.CommandType = CommandType.StoredProcedure;
//oCommand.Parameters.Add(new SqlParameter("#intUserID", SqlDbType.NVarChar, 10)).Value = Int32.MaxValue;
//SqlDataAdapter adpt = new SqlDataAdapter(oCommand);
//DataSet ds = new DataSet();
//adpt.Fill(ds);
}
protected void loginButton_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["3GPSConnectionString"].ConnectionString);
con.Open();
string cmdStr = "Select count(*) from Users where UserName='" + userTextBox.Text + "'";
SqlCommand Checkuser = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(Checkuser.ExecuteScalar().ToString());
if (temp == 1)
{
string cmdStr2 = "Select Password from Users where UserName='" + userTextBox.Text + "'";
SqlCommand pass = new SqlCommand(cmdStr2, con);
string password = pass.ExecuteScalar().ToString();
con.Close();
if (password == pwdTextBox.Text)
{
Session["New"] = userTextBox.Text;
Response.Redirect("/Protected/Default.aspx");
}
else
{
userCompareLbl.Visible = true;
userCompareLbl.Text = "Invalid Password!";
}
}
else
{
userCompareLbl.Visible = true;
userCompareLbl.Text = "Invalid Username!";
}
}
}

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