Trouble with "Last Login" Stored Procedure - asp.net

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!";
}
}
}

Related

How to use local variable of Page_OnLoad method in OnClick event in asp.net C#

I am designing a website in which I need to update a table Company in my database through CompanyDetails page with respect to the auto increment field CompanyID which is being passed through Query string from previous page named Company and only one button is there for insert and update. So my problem is I am unable to get the value of Companyid of Page_OnLoad event in SaveButtonClick event.
Note: I have already tried Session and View state, IsPostBack but in Onclick event even their value are not being maintained and are updated to 0 or null.
Here is my code......(Please ignore my coding mistakes)
using System;
using System.Web.UI;
using System.Data;
using System.Data.SqlClient;
public partial class CompanyDetails : System.Web.UI.Page
{
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
Session["something"] = Companyid;
}
if (cmdName == "Details")
{
BindTextBoxvalues();
}
}
protected void SaveButton_Click(object sender, EventArgs e)
{
string x = Session["something"].ToString();
try
{
if (SaveButton.Text == "Save")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
cmd = new SqlCommand("spInsertCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#Description", SqlDbType.VarChar).Value = Description.Value;
bool isstatus = IsActiveCheckBox.Checked;
cmd.Parameters.Add("#Status", SqlDbType.Int).Value = Convert.ToInt32(isstatus);
con.Open();
cmd.Connection = con;
cmd.ExecuteNonQuery();
Response.Write("<script language='javascript'>window.alert('Saved Successfully.');window.location='Company.aspx';</script>");
}
else if (SaveButton.Text == "Update")
{
SqlCommand cmd = new SqlCommand();
String mycon = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(mycon);
con.Open();
cmd = new SqlCommand("spUpdateCompany", con);
cmd.CommandType = CommandType.StoredProcedure;
int a = Convert.ToInt32(Companyid);
// I need the value here but it is being updated to zero here.
cmd.Parameters.Add("#CompanyID", SqlDbType.Int).Value = Companyid;
cmd.Parameters.Add("#CompanyName", SqlDbType.VarChar).Value = Name.Text;
cmd.Parameters.Add("#CompanyCode", SqlDbType.VarChar).Value = CompanyCode.Text;
cmd.Parameters.Add("#BusinessPhone", SqlDbType.VarChar).Value = BusinessPhone.Text;
cmd.Parameters.Add("#Extension", SqlDbType.VarChar).Value = Extension.Text;
cmd.Parameters.Add("#FaxNumber", SqlDbType.VarChar).Value = FaxNumber.Text;
cmd.Parameters.Add("#TaxID", SqlDbType.Int).Value = TaxID.Text;
cmd.Parameters.Add("#LegalName", SqlDbType.VarChar).Value = LegalName.Text;
cmd.ExecuteNonQuery();
cmd.Dispose();
con.Close();
Response.Write("<script language='javascript'>window.alert('Updated Successfully.');window.location='Company.aspx';</script>");
}
}
catch (SqlException ex)
{
ScriptManager.RegisterStartupScript(this, this.GetType(), "Message",
"alert('Oops!! following error occured : " + ex.Message.ToString() + "');", true);
}
}
protected void CancelButton_Click(object sender, EventArgs e)
{
Response.Redirect("Company.aspx");
}
private void BindTextBoxvalues()
{
SaveButton.Text = "Update";
string constr = "Data Source=.; Initial Catalog=something; Integrated Security=True";
SqlConnection con = new SqlConnection(constr);
SqlCommand cmd = new SqlCommand("select * from Company where CompanyID=" + Companyid, con);
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter(cmd);
da.Fill(dt);
Name.Text = dt.Rows[0][1].ToString();
CompanyCode.Text = dt.Rows[0][2].ToString();
LegalName.Text = dt.Rows[0][15].ToString();
TaxID.Text = dt.Rows[0][14].ToString();
BusinessPhone.Text = dt.Rows[0][3].ToString();
Extension.Text = dt.Rows[0][13].ToString();
FaxNumber.Text = dt.Rows[0][12].ToString();
Description.Value = dt.Rows[0][4].ToString();
IsActiveCheckBox.Checked = Convert.ToBoolean(dt.Rows[0][11]);
}
}
Any values stored in local variables need to be read from Request on every postback.
So do following
int Companyid = 0;
string cmdName = null;
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
cmdName = Request.QueryString["CommandType"];
if (!IsPostBack)
{
if (cmdName == "Details")// be sure about string case
{
BindTextBoxvalues();
}
}
}
Or make viewstate properties
If you want to have your property available on the PostBack, do not use !IsPostBack
protected void Page_Load(object sender, EventArgs e)
{
Companyid = Convert.ToInt32(Request.QueryString["CompanyID"]);
}

Check Email is register or not while register in Asp.net c#?

I am trying to check whilist registrating. When an enterd email exists and then try to register it untill the registration is successfull but I don't want that.
protected void btnRegister_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["conn"].ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand ("Select count(*) from tblUsers where Email = '" + txtEmail.Text + "' ", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
p.UserName = txtUsername.Text;
p.Email = txtEmail.Text;
p.DOB = Convert.ToDateTime(txtDob.Text);
p.Password = txtPass.Text;
p.InsertUser(p);
Response.Write("Registration Successfull..");
}
else {
Response.Write("This Email is Already Exist...!!");
}
}
else
{
Response.Write("Fail...");
}
}

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
}

Response.Redirect ("****.aspx");

When I enter incorrect username and password it does not go to error.aspx(form).
this is my code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection(#"Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Users\1\Documents\DB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
conn.Open();
string checkuser = "select count(*) from [Users] where Username '" + TextBoxUserName.Text + "'";
SqlCommand com = new SqlCommand(checkuser,conn);
int temp = Convert.ToInt32(com.ExecuteScalar().ToString());
conn.Close();
if (temp == 1)
{
conn.Open();
string checkpassword = "select Password from Users where Password'" + TextBoxPassword.Text + "'";
SqlCommand passComm = new SqlCommand(checkpassword, conn);
string password = passComm.ExecuteScalar().ToString();
if (password == TextBoxPassword.Text)
{
//Session["NEW"] = TextBoxUserName.Text;
Response.Redirect("Welcome.aspx");
}
**else
if (password != TextBoxPassword.Text)
{
Response.Redirect("Error.aspx");
}**
}
It gives me an error saying "Object reference not set to an instance of an object" in this line of code: string password = passComm.ExecuteScalar().ToString();

ASP.Net insert data from form to a database Exception

I'm trying to insert data from a form to my database and it is throwing this error:
No mapping exists from object type System.Web.UI.WebControls.TextBox to a known managed provider native type.
Maybe it has to do with the fact that I try to get a data from a dropdownlist and I'm not really sure the syntax is great.
Here is the code:
protected void Button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=MICROSOF-58B8A5\\SQL_SERVER_R2;Initial Catalog=Movie;Integrated Security=True");
conn.Open();
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", Title);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", GenreDropDown);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", Descreption);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
You -weren't using any of the vars where you had the values
string titleName = Title.Text;
string sqlQuery = ("INSERT INTO Movies(Ganere, Title, Descreption) VALUES (#Ganere, #Title , #Descreption) ");
SqlCommand cmd = new SqlCommand(sqlQuery, conn);
cmd.Parameters.AddWithValue("Title", titlename);
string genre = GenreDropDown.SelectedIndex.ToString();
cmd.Parameters.AddWithValue("Ganere", genre);
string descp = Descreption.Text;
cmd.Parameters.AddWithValue("Descreption", descp);
if (titleName == null || genre == null)
{
ErrorMessege.Text = "Please fill all of the fields.";
}
else
{
ErrorMessege.Text = "You have successfully add a movie!";
cmd.ExecuteNonQuery();
}
conn.Close();
}
The problem is that you are trying to use the entire textbox as the value to the parameter.
Change:
cmd.Parameters.AddWithValue("Title", Title);
to
cmd.Parameters.AddWithValue("Title", Title.Text);

Resources