Invalid postback or callback argument. why my code doesnt work? - asp.net

I am trying to update my data base from the web but it doesnt work and I dont know why. it says: "Invalid postback or callback argument. Event validation is enabled using in configuration or <%# Page EnableEventValidation="true" %> in a page. For security purposes, this feature verifies that arguments to postback or callback events originate from the server control that originally rendered them. If the data is valid and expected, use the ClientScriptManager.RegisterForEventValidation method in order to register the postback or callback data for validation."
what do I need to do?
protected void button1_Click(object sender, EventArgs e)
{
string strConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=" +
System.Web.HttpContext.Current.Server.MapPath(#"DataBase\Users.accdb");
string Query = "update Users.users set (aid,email) (id='" +
id_txt.Value.ToString() + "',email='" + email_txt.Value.ToString() + "'
where id='" + id_txt.Value.ToString() + "' ;";
System.Data.OleDb.OleDbConnection con = new
System.Data.OleDb.OleDbConnection(strConnection);
System.Data.OleDb.OleDbCommand cmd = new
System.Data.OleDb.OleDbCommand(Query, con);
System.Data.OleDb.OleDbDataReader myReader;
try
{
con.Open();
myReader = cmd.ExecuteReader();
while (myReader.Read())
{
}
}
catch (Exception ex)
{
}
}

Related

Submit button to update database, won't work if there is postback stated in page_load

I have a web form page that I am going to query the data from database via selecting different values from dropdown list, after I selected proper value, in the description I want to update the database record while I click the submit button, for example, customer name, and status, there will be only one record coming back and the description will show(I can do it in isPostback and query the database, using SQL DataReader and then call related index element to get it) but when I typed something in the description and click submit, it won't update in the database, but if I don't use if(isPostback) it is working.
P.S. if there is no if(ispostback) case block there,dataUpdate.Update() works well.
So my question is;
protected void btnSubmit_Click(object sender, EventArgs e)
{
dataUpdate.Update();
}
The page_load code:
protected void Page_Load(object sender, EventArgs e)
{
ValidationSettings.UnobtrusiveValidationMode = UnobtrusiveValidationMode.None;
if (!IsPostBack)
{
SqlConnection conn1 = new SqlConnection(cxInfo.ConnectionString);
string userInfoQuery1 = "select * from users where id=#id";
SqlCommand userInfo1 = new SqlCommand(userInfoQuery1, conn1);
userInfo1.Parameters.AddWithValue("#id", dropdlCx.SelectedValue);
conn1.Open();
SqlDataReader reader1 = userInfo1.ExecuteReader();
reader1.Read();
if (reader1.HasRows )
{
lblCxId.Text = "" + reader1[0];
SqlConnection conn = new SqlConnection(dataUpdate.ConnectionString);
string userInfoQuery = "select cx_first_name+',' + cx_last_name as 'name',cx_id ,incident_id,description,contact_method from incident where cx_id=#id and status=#status";
SqlCommand userInfo = new SqlCommand(userInfoQuery, conn);
userInfo.Parameters.AddWithValue("#id", lblCxId.Text);
userInfo.Parameters.AddWithValue("#status", dropStatus.SelectedValue);
conn.Open();
SqlDataReader reader = userInfo.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
lblCxId.Text = "" + reader1[0];
txtDesc.Text = (string)reader[3];
radioContact.SelectedValue = (string)reader[4];
desc= (string)reader[3];
}
conn.Close();
}
conn1.Close();
}
if (IsPostBack)
{
lblCxId.Text = dropdlCx.SelectedValue;
/*I want to have txtDesc.txt= database query here, but as long as I add the code here, then the update won't work*/
}
}
So I think there only thing I got stuck is how to let the system know that what I submit is not the thing that he is going to refresh, please accept my value instead of the refresh?

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).

ASP.NET catch{} section firing without any Exception

I have a little problem.
In this code, always there is catch{} section firing. Even if any exception is thrown. I checked in debugger and no exception is THROWN but somehow code from catch{} is firing and it transfers me to google.com.
If I comment the code from catch{}, Page is running fine.
Someone know why is that? It makes me mad.
Thanks
protected void Button5_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
try
{
conn = new MySqlConnection("Server=localhost;Port=3306;Database=ewidencja;Uid=webuser;Pwd=web1;");
conn.Open();
MySqlDataAdapter mda = new MySqlDataAdapter();
mda.SelectCommand = new MySqlCommand("select id from pacjenci where pesel='" + Session["pesel"].ToString() + "';", conn);
int id_pacjenta = (int)mda.SelectCommand.ExecuteScalar();
int id_lekarza=Int32.Parse(DropDownList1.SelectedValue);
mda.InsertCommand = new MySqlCommand("insert into planowane_wizyty (id_pacjenta, id_lekarza, data_wizyty) values(" + id_pacjenta + ", " + id_lekarza + ", '" + Calendar1.SelectedDate.ToString().Substring(0,10)+" "+ ListBox1.SelectedItem.Value + "');", conn);
if (mda.InsertCommand.ExecuteNonQuery() == 1)
Response.Redirect("wizyty.aspx");
else
Response.Redirect("info.aspx");
}
catch (Exception ex)
{
Response.Redirect("http://www.google.com");
}
}
}
Response.Redirect can throw a ThreadAbortException. This then hits the outer exception handler, triggering the second Response.Redirect.
See Why Response.Redirect causes System.Threading.ThreadAbortException?
More importantly, this is one reason that data access code should not be mixed so tightly with UI behavior. Debugging such code is difficult, unit testing is near impossible, and reusability is low.
It also looks like your query is being constructed via string concatenation, which is vulnerable to SQL injection. Parameterize the query instead.
The overload of Response.Redirect you are using will always try and stop the current thread. This causes the exception you are seeing. System.Threading.ThreadAbortException
There is an overload available: Response.Redirect(string url, bool endResponse) that allows you to control whether to end the current thread using the endResponse parameter.
All that being said, you can catch this specific error and ignore it. The suggestion below is just one of a few solutions you can implement. It all depends on what you are trying to do.
protected void Button5_Click(object sender, EventArgs e)
{
if (Page.IsValid == true)
{
try
{
conn = new MySqlConnection("Server=localhost;Port=3306;Database=ewidencja;Uid=webuser;Pwd=web1;");
conn.Open();
MySqlDataAdapter mda = new MySqlDataAdapter();
mda.SelectCommand = new MySqlCommand("select id from pacjenci where pesel='" + Session["pesel"].ToString() + "';", conn);
int id_pacjenta = (int)mda.SelectCommand.ExecuteScalar();
int id_lekarza=Int32.Parse(DropDownList1.SelectedValue);
mda.InsertCommand = new MySqlCommand("insert into planowane_wizyty (id_pacjenta, id_lekarza, data_wizyty) values(" + id_pacjenta + ", " + id_lekarza + ", '" + Calendar1.SelectedDate.ToString().Substring(0,10)+" "+ ListBox1.SelectedItem.Value + "');", conn);
if (mda.InsertCommand.ExecuteNonQuery() == 1)
Response.Redirect("wizyty.aspx");
else
Response.Redirect("info.aspx");
}
catch (System.Threading.ThreadAbortException)
{
//do nothing. This is an expected error stemming from Response.Redirect
}
catch (Exception ex)
{
Response.Redirect("http://www.google.com");
}
}
}

Multipart Identifier "arafa.almahmud08#gmail.com" couldnot be bound

I have built a custom validator,
I have a sql query like this:
protected void custom_serverValidate(object sender, ServerValidateEventArgs e)
{
connect();
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress=" + REmailTextBox.Text;
SqlCommand cmd = new SqlCommand(strSQL, objConnection);
if (e.Value.ToString() == cmd.ExecuteScalar().ToString())
{
e.IsValid = false;
}
else
e.IsValid = true;
disConnect();
}
when I execute my code in the browser and an email address and submit it , I get the error mentioned in the title. how to fix it ?
You are missing quotes around your email address. However - this is a SQL injection attack waiting to happen. Please switch to using a parameter.
string strSQL = "select EmailAddress from Accounts_Users where EmailAddress = #EmailAddress"
...
cmd.Parameters.AddWithValue("#EmailAddress", REmailTextBox.Text);
You forgot to use the single quotes. Use:
string commandText = "select EmailAddress from Accounts_Users where EmailAddress=#EmailAttress";
SqlCommand cmd = new SqlCommand(commandText, conn);
cmd.Parameters.Add("#EmailAddress", REmailTextBox.Text);

DetailsviewInside Linkbutton onclick it rediects and open newtab

I am working with Details view inside details view Itemtemplete i have link button when click that link button it need to redirect and open new tab for that i use this code
protected void lnkPost_Click(object sender, EventArgs e)
{
DetailsViewRow row= (DetailsViewRow)((LinkButton)sender).NamingContainer;
int postID = Convert.ToInt32((row.FindControl("lblPostID") as Label).Text);
if (postID != null)
{
string Query = "Select * from GigPost where GigPostID='" + postID + "'";
SqlCommand cmd = new SqlCommand(Query, cn);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
string Postsource = dr["PostSource"].ToString();
Response.Write("<script> window.open('"+ Postsource+"' ); </script>");
Response.End();
}
}
}
I am getting "Unable to cast object of type 'System.Web.UI.WebControls.DetailsView' to type 'System.Web.UI.WebControls.DetailsViewRow'." this error please help me how to resolve this issue
Regards,
Venkat
DetailsViewRow row = (DetailsViewRow)(((LinkButton)sender).NamingContainer);
may work - (untested)
But really - what's wrong with using the ItemCommand of the DetailsView and grab the current datakey?

Resources