SQL simple registration - all time exception - asp.net

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

Related

Session Sign in - Session string is null

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

Not able to connect to database in ASP IIS

I was able to deloy my asp project on IIS and it shows the front page, there I have a login page , after entering the credentials it does not logs in, I used try and catch , and in catch it gave me an error, stating thread has aborted, it was on
page.redirect["master.apsx",true]
so I changed it to
page.redirect["master.aspx",false]
and it didnt gave error, but it was not able to login further, I guess it is not able to connect to database. So any help would be appreciable.
Thanks
CODE:
protected void Page_Load(object sender, EventArgs e)
{
strconn = #"Data Source=.\SQLEXPRESS;AttachDbFilename=" + Server.MapPath("~/App_Data/Securityservice.mdf") + ";Integrated Security=True;User Instance=True";
Label1.Text = " conn string";
}
protected void Button2_Click(object sender, EventArgs e)
{
}
protected void btn_popup_quick_login_Click(object sender, EventArgs e)
{
try
{
if (txt_username.Text != null)
{
if (txt_password.Text != null)
{
DataTable dt = new DataTable();
conn = new SqlConnection(strconn);
conn.Open();
cmd = new SqlCommand("Select * From UserMaster Where Username=#username and Password=#password", conn);
cmd.Parameters.AddWithValue("#username", txt_username.Text);
cmd.Parameters.AddWithValue("#password", txt_password.Text);
da = new SqlDataAdapter(cmd);
da.Fill(dt);
{
if (dt.Rows.Count > 0)
{
userloginname = txt_username.Text;
userloginpassword = txt_password.Text;
Session["username"] = txt_username.Text;
MessageBox.Show("User Login Sucessfully", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
Response.Redirect("Marketing.aspx",false);
}
else
{
Label1.Text = "else part";
MessageBox.Show("Invalid User Name and Password", "Login", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
txt_username.Focus();
}
txt_username.Text = "";
txt_password.Text = "";
}
}
}
}
catch (Exception ex) { MessageBox.Show(ex.Message,"Error",MessageBoxButtons.OK,MessageBoxIcon.Error); }
conn.Close();
Label1.Text = "login";
}
You should check the connection strings in web.config, to make sure they still point to the proper location of the database after you deployed the site.
I think the problem could be the Application_Start method.
Look if you have written some thing there.
Make a break point there and see is there any error.
Or have you written Response.End() in you code?
You need to provide more detail
You need to check weather you are able to connect to database or not.
You also need to check weather the page is called or not (which comes after login).

Execute Query from another function

I want to execute a query on a button click event.
But that query is written in another function.
Here is my code, and it's not working. What is my problem?
namespace MCE_Member_Registration
{
public partial class registration_form_view : System.Web.UI.Page
{
SqlConnection conn = new SqlConnection("ConnectionString");
SqlCommand cmd;
protected void Page_Load(object sender, EventArgs e)
{
createform();
}
protected void createform() {
NameValueCollection nvc = Request.Form;
surname.Text = nvc["txt_surname"];
cmd.CommandText = "Insert into mce_applicants_information values(N'" + nvc["txt_surname"] + "')";
}
protected void confirm_Click(object sender, EventArgs e)
{
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
}
}
I'm not sure if this solves your problem. But if you really need another method to create your command, let it return it.
protected SqlCommand GetCommand()
{
SqlCommand cmd = new SqlCommand("Insert into blahblah values(blahblah)", connection);
return cmd;
}
protected void Button1_Click() {
connection.Open();
GetCommand().ExecuteNonQuery();
connection.Close();
}
Note that this is not best-practise due to several reasons. The connection should be closed even if an exception occured so use using statement instead. But that would be a problem in this approach since the connection is a field.
So i would prefer the all-in-one method approach which also uses parameters tro prevent sql-injection attacks:
protected void Button1_Click()
{
ExecuteBlahBlahCommand("blahblah");
}
private void ExecuteBlahBlahCommand(string blaColumnVal)
{
const string sql = "Insert into blahblah values(#blaColumn)";
using (var con = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#blaColumn", blaColumnVal);
con.Open();
cmd.ExecuteNonQuery();
}
}
I suggest you to use CommandText property and not contructor, because instance of cmd is created before this code, so you adjust your property
protected void CreateQuery() {
cmd.CommandText = "Insert into blahblah values(blahblah)";
}
protected void Button1_Click() {
connection.Open();
CreateQuery();
cmd.ExecuteNonQuery();
connection.Close();
}
Answering the question itself - Any variable you declare inside a function cannot be seen outside that function. You need to declare the SqlCommand in the correct scope...
For instance:
SqlCommand cmd;
protected void CreateQuery()
{
cmd = new SqlCommand("Insert into blahblah values(blahblah),connection)";
}
protected void Button1_Click()
{
CreateQuery();
connection.Open();
cmd.ExecuteNonQuery();
connection.Close();
}
This will declare the variable in the class level, and be accessible to all other methods in that class.
I'll just mention that #Tim Schmelter's answer is a good solution that might better suit your needs.

Error in insert the value into database in asp.net ,c# of registration form

Code show as follow:
nection cnn = new SqlConnection("Data Source=USER-PC\\KHEMCHAND;Integrated Security=True");
protected void Page_Load(object sender, EventArgs e)
{
cnn.Open();
}
protected void Button1_Click(object sender, EventArgs e)
{
SqlCommand cmd = new SqlCommand("insert into tbl_ragistration values(#f_name,#l_name,#email_id,#pass_word,#[date of brth],#add_ress,#gender)", cnn);
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
cmd.ExecuteNonQuery();
cnn.Close();
}
Change cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text); to cmd.Parameters.AddWithValue("#[date of birth]", Texdbt.Text); in Insert parameters value assigning. And also dont open the connection in the page load event. Befor executing the query open the connection, Execute the query and then close the connection for a better approach
cnn.Open();
cmd.ExecuteNonQuery();
cnn.Close();
You can try with below way, I hope this is good approach (though database execution should put in Data Access Layer), thanks for your time.
public string ConnectionString
{
get
{
return "Data Source=USER-PC\\KHEMCHAND;Integrated Security=True";
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd =new SqlCommand(
"insert into tbl_ragistration values(#f_name,#l_name,#email_id,#pass_word,#[date of brth],#add_ress,#gender)"
,cnn))
{
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
}
make sure you declare also the column names on your insert statement:
protected void Button1_Click(object sender, EventArgs e)
{
using (SqlConnection cnn = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd =new SqlCommand(
"insert into tbl_ragistration (f_name,l_name,email_id,pass_word,[date of brth],add_ress,gender) values (#f_name,#l_name,#email_id,#pass_word,#dateofbrth,#add_ress,#gender)"
,cnn))
{
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#dateofbirth", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
cnn.Open();
cmd.ExecuteNonQuery();
}
}
}
Regards
Open the connection while executing the command & not on page Load & wrap your code inside a try catch block to log the error.
protected void Button1_Click(object sender, EventArgs e)
{
SQLConnection cnn = new SqlConnection(WebConfigurationManager.ConnectionStrings["yourConnectionString"].ConnectionString);
SqlCommand cmd = new SqlCommand("insert into tbl_ragistration values(#f_name,#l_name,#email_id,#pass_word,#[date of brth],#add_ress,#gender)", cnn);
cmd.Parameters.AddWithValue("#f_name", Texfname.Text);
cmd.Parameters.AddWithValue("#l_name", Texlname.Text);
cmd.Parameters.AddWithValue("#email_id", Texemail.Text);
cmd.Parameters.AddWithValue("#pass_word", Texpwd.Text);
cmd.Parameters.AddWithValue("#[date o birth]", Texdbt.Text);
cmd.Parameters.AddWithValue("#add_ress", Texadd.Text);
cmd.Parameters.AddWithValue("#gender", DropDownList1.Text);
try
{
cnn.Open();
cmd.ExecuteNonQuery();
}
catch(SQLException ex)
{ // Log your error
lblStatus.Text="An error occured"+ ex.Message;
throw ex;
}
finally
{
if(cnn!=null)
{
cnn.Close();
}
}
}

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