Session Sign in - Session string is null - asp.net

This is not working at all. I have done it many times but I don't know what's going wrong. the textbox always shows "not found" whereas it should be showing username.
Note: Textbox is just an example.
Login Page:
protected void login_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session.Abandon();
Session.Clear();
string username = email.Text.ToLower().Trim();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
con.Open();
string sql = "SELECT USERNAME, PASSWORD FROM MANAGER WHERE USERNAME = #USERNAME AND PASSWORD=#PASSWORD";
SqlCommand command = new SqlCommand(sql, con);
command.Parameters.AddWithValue("#USERNAME", username);
command.Parameters.AddWithValue("#PASSWORD", password.Text.Trim());
SqlDataAdapter da = new SqlDataAdapter(command);
DataTable dt = new DataTable();
da.Fill(dt);
command.ExecuteNonQuery();
command.Dispose();
con.Close();
if (dt.Rows.Count > 0)
{
Session["manager"] = username;
Response.Redirect("ManagerHomePage.aspx");
Session.RemoveAll();
}
else
{
Label1.Text = "Invalid Email or Password!";
}
}
ManagerHomePage.aspx :
protected void Page_Load(object sender, EventArgs e)
{
if(Session["manager"]!=null)
{
TextBox1.Text = Session["manager"].ToString();
}
else
{
TextBox1.Text = "not found";
}
}

Do not use ExecuteNonQuery for Select command. ExecuteNonQuery is used for Insert, Update, Delete command. Try using ExecuteReader
Bellow is the code
protected void login_Click(object sender, EventArgs e)
{
Session.RemoveAll();
Session.Abandon();
Session.Clear();
string username = email.Text.ToLower().Trim();
SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["myConnectionString"].ToString());
con.Open();
string sql = "SELECT USERNAME, PASSWORD FROM MANAGER WHERE USERNAME = #USERNAME AND PASSWORD=#PASSWORD";
SqlCommand command = new SqlCommand(sql, con);
command.Parameters.AddWithValue("#USERNAME", username);
command.Parameters.AddWithValue("#PASSWORD", password.Text.Trim());
SqlDataReader rdr=command.ExecuteReader();
if(rdr.HasRows())
{
Session["manager"] = username;
Response.Redirect("ManagerHomePage.aspx");
}
else
{
Label1.Text = "Invalid Email or Password!";
}
}

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"]);
}

register button has no function

Suddenly my register button is not performing any action other that validations. any idea?
here is my registration.aspx.cs:
protected void Page_Load(object sender, EventArgs e)
{
}
SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True");
SqlCommand cmd = new SqlCommand();
protected void btnSubmit_Click(object sender, EventArgs e)
{
if(Page.IsValid)
{
cmd.Connection = con; //assigning connection to command
cmd.CommandType = CommandType.Text; //representing type of command
cmd.CommandText = "INSERT INTO UserData values(#Username,#Firstname,#Lastname,#Email,#Password,#CustomerType,#DeliveryAddress,#Zip,#ContactNumber)";
//adding parameters with value
cmd.Parameters.AddWithValue("#Username", txtUser.Text);
cmd.Parameters.AddWithValue("#Firstname", txtFN.Text);
cmd.Parameters.AddWithValue("#Lastname", txtLN.Text);
cmd.Parameters.AddWithValue("#Email", txtEmail.Text);
cmd.Parameters.AddWithValue("#Password", (txtPW.Text));
cmd.Parameters.AddWithValue("#CustomerType", RadioButtonList1.SelectedItem.ToString());
cmd.Parameters.AddWithValue("#DeliveryAddress", txtAddress.Text);
cmd.Parameters.AddWithValue("#Zip", txtZip.Text);
cmd.Parameters.AddWithValue("#ContactNumber", txtContact.Text);
con.Open(); //opening connection
cmd.ExecuteNonQuery(); //executing query
con.Close(); //closing connection
label_register_success.Text = "Registered Successfully..";
}
else
{
label_register_success.Text = "Please check the registration errors";
}
}
protected void ValidateUserName(object source, ServerValidateEventArgs arguments)
{
string UserName = arguments.Value;
using (SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserData WHERE Username=#Username", con);
cmd.Parameters.AddWithValue("#Username", UserName);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
}
}
protected void ValidateEmail(object source, ServerValidateEventArgs arguments)
{
string Email = arguments.Value;
using (SqlConnection con = new SqlConnection("Data Source = 'PAULO'; Initial Catalog=ShoppingCartDB;Integrated Security =True"))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM UserData WHERE Email=#Email", con);
cmd.Parameters.AddWithValue("#Email", Email);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
if (reader.HasRows)
{
arguments.IsValid = false;
}
else
{
arguments.IsValid = true;
}
Its not performing the successful registration and the validations for the repeated username and email. please help me out, thanks!
Try triggering the validation via:
Page.Validate();
And pass in any validation groups you use as the parameter (if applicable) before checking IsValid, and see if that detects the errors. I assume your Validate methods are called from CustomValidator controls?

SQL simple registration - all time exception

i have problem with registration in ASP.NET.
When i try to add new user to table in sql i catch exception. No idea what is wrong, in my opinion code is correct.
Look at this:
public partial class Registeration : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RejConnectionString"].ConnectionString);
con.Open();
string cmdStr="Select count(*) from Registration where UserName='" + TextBoxUN.Text + "'";
SqlCommand userExist = new SqlCommand(cmdStr, con);
int temp = Convert.ToInt32(userExist.ExecuteScalar().ToString());
con.Close();
if (temp == 1)
{
Response.Write("Already exist.<br /> Change another nickname.");
}
}
}
protected void Wyślij_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["RejConnectionString"].ConnectionString);//połączenie z bazą
con.Open();
string insCmd = "Insert into Registration (UserName, Password, EmailAddress, FullName, Country) values (#UserName, #Password, #EmailAddress, #FullName, #Country)";
SqlCommand insertUser = new SqlCommand(insCmd, con);
insertUser.Parameters.AddWithValue("#UserName,", TextBoxUN.Text);
insertUser.Parameters.AddWithValue("#Password", TextBoxPass.Text);
insertUser.Parameters.AddWithValue("#EmailAddress", TextBoxEA.Text);
insertUser.Parameters.AddWithValue("#FullName", TextBoxFN.Text);
insertUser.Parameters.AddWithValue("#Country", DropDownListCountry.SelectedItem.ToString());
try
{
insertUser.ExecuteNonQuery();
con.Close();
Response.Redirect("/Account/Login.aspx");
}
catch (Exception er)
{
Response.Write("<b>STH bad happened :( Try again</b>");
}
finally
{
}
}
}
well
1. DO NOT DO REDIRECTs inside of TRY!!!! Response.Redirect("/Account/Login.aspx"); NO NO!!
2. if you do with finally DO THE CLOSE connection there
I will redo this try Open connection to be inside as well

Why session is getting null while inserting the data and getting the data from SQL LITE

I have written a code to insert the data to SQL LITE database as follows
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
count = 0;
Session["x"] = "session value";
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
string txt="insert into stu values("+TextBox1.Text +",'"+TextBox2.Text+"')";
cmd.CommandType = CommandType.Text;
cmd.CommandText = txt;
cmd.ExecuteNonQuery();
conn.Close();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
}
After inserting while retrieving data Session is getting null I don't know why
protected void Button2_Click(object sender, EventArgs e)
{
if (Session["x"] != null) // Getting Null here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
DataSet m_oDataSet = new DataSet();
string path = Server.MapPath("bin/sampldb.db");
SQLiteConnection conn = new SQLiteConnection("Data Source=" + path + "");
try
{
conn.Open();
SQLiteCommand cmd = new SQLiteCommand();
cmd.Connection = conn;
cmd.CommandType = CommandType.Text;
string txt = "select * from stu";
cmd.CommandText = txt;
SQLiteDataAdapter adp = new SQLiteDataAdapter();
adp.SelectCommand = cmd;
adp.Fill(m_oDataSet);
GridView1.DataSource = m_oDataSet.Tables[0];
GridView1.DataBind();
}
catch (Exception ex)
{
Label1.Visible = true;
Label1.Text = "Error:" + ex.Message;
}
finally
{
conn.Close();
}
}
}
The same code when tested in Sql server 2008 works fine
protected void BtnSqlInsert_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(cnstr);
con.Open();
SqlCommand cmd = new SqlCommand("Insert into [User] values ('" + TextBox1.Text + "','" + TextBox2.Text + "')", con);
cmd.ExecuteNonQuery();
con.Close();
}
protected void BtnSqlGet_Click(object sender, EventArgs e)
{
if (Session["x"] != null) //Able to get session here
{
Label1.Visible = true;
Label1.Text = Session["x"].ToString();
}
}
My sql lite path is from Bin folder as shown in image
your app writes to DB (which is in BIN folder). That causes app restart => in-proc session gets lost. You should NOT solve the consequence (by using StateServer mode), you should fix the original reason - move db file into another folder, away from BIN folder.

The ConnectionString property has not been initialized

My connection string is placed in web.config as follows.
<connectionStrings>
<add name="empcon" connectionString="Persist Security Info=False;User ID=sa;Password=abc;Initial Catalog=db5pmto8pm;Data Source=SOWMYA-3BBF60D0\SOWMYA" />
</connectionStrings>
and the code of program is...
public partial class empoperations : System.Web.UI.Page
{
string constr = null;
protected void Page_Load(object sender, EventArgs e)
{
ConfigurationManager.ConnectionStrings["empcon"].ToString();
if (!this.IsPostBack)
{
fillemps();
}
}
public void fillemps()
{
dlstemps.Items.Clear();
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["empcon"].ConnectionString);
con.ConnectionString = constr;
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "select * from emp";
cmd.Connection = con;
SqlDataReader reader;
try
{
con.Open();
reader = cmd.ExecuteReader();
while (reader.Read())
{
ListItem lt = new ListItem();
lt.Text = reader["ename"].ToString();
lt.Value = reader["empno"].ToString();
dlstemps.Items.Add(lt);
}
reader.Close();
}
catch (Exception er)
{
lblerror.Text = er.Message;
}
finally
{
con.Close();
}
i am totally new to programing....
i am able to run this application with er.message in label control as "the connection string property has not been initialized"
i need to retrieve the list of names of employees from the emp table in database into the dropdownlist and show them to the user...
can any one please fix it...
Where are you initializing your constr variable? It looks like you can leave that line out.
Also: just use using
using(SqlConnection con = new SqlConnection(
ConfigurationManager.ConnectionStrings["empcon"].ConnectionString)
{
using(SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
//Rest of your code here
}
}
Side note: Don't use Select * From. Call out your columns: Select empname, empno From...
You are not assigning ConfigurationManager.ConnectionStrings["empcon"].ToString(); to string constr
protected void Page_Load(object sender, EventArgs e)
{
constr = ConfigurationManager.ConnectionStrings["empcon"].ToString();
...
will probably solve your problem for the time being.

Resources