i have the following code in my global.ascx and when i click a generate error button the code gets run but seems to fail on the insert error into the DB.
I want the error to be saved to the DB and redirect to default.aspx.
pretty standard stuff.
the error i get is: exe.Message = "Incorrect syntax near 'System'."
(looks like somethign with the SQL objects used in global.asx)
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
Exception ex = Server.GetLastError();
StringBuilder theBody = new StringBuilder();
theBody.Append("Error Message: " + ex.ToString() + "\n");
Server.ClearError();
try
{
string sSQL = "INSERT INTO PMISwebErr VALUES ('" + theBody.ToString() + "', GETDATE())";
using (System.Data.SqlClient.SqlConnection con = STAR.Global.GetConnection())
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(sSQL, con);
cmd.CommandType = System.Data.CommandType.Text;
cmd.ExecuteScalar();
}
Response.Redirect("~/default.aspx?Err=sysError");
}
catch (Exception exe) {
Response.Redirect("~/default.aspx?Err="+ exe.Message.ToString() );
}
}
the problem is in the addition of the error message. it has a single quote that breaks the SQL. The code gets this value as a result at this line:
theBody.Append("Error Message: " + ex.ToString() + "\n");
sSQL = "INSERT INTO PMISwebErr VALUES
('URL:
http://localhost:14854/PMIS/Default.aspx\nReferer:
http://localhost:14854/PMIS/Default.aspx\nIP:
127.0.0.1\nError Message: System.Web.HttpUnhandledException:
Exception of type
'System.Web.HttpUnhandledException'
was thr...
that's the actual value from my quick watch, strange to see the ... at the end.
You really should use a parameterized insert. I'm sure there are quote issues with the string you're trying to insert, and it's causing the exception.
Here is an example:
https://web.archive.org/web/20210512233418/http://www.4guysfromrolla.com/webtech/092601-1.shtml
This should really be an ExecuteNonQuery() call. ExecuteScalar() is intended more for selecting atomic values from aggregates.
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx
As #ScottE already expected, you have a problem with quotes. The string is surronded by single quotes, but inside is the text Exception of type 'System.Web.. which adds a quote in a place where you don't want it.
The solution? Use parameters and let the driver handle those quotes.
Related
Update 1 : I think schema.ini is incorrect. Please refer to below question.
The file (dsTextFile) has just one row of data but record count is zero. So it means it is not reading at all. This is with removing FMT altogether or with Delimi. I still get error if FMT is fixed though. So, how do I create SCHEMA.ini or make sure schema.ini is correct?
private bool LoadTextFile(string textFilePath, out string errorInfo) {
errorInfo = String.Empty;
try {
string textFileFolder = (new System.IO.FileInfo(textFilePath)).DirectoryName;
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Fixed\";";
OleDbConnection textConnection = new OleDbConnection(textConnectionString);
textConnection.Open();
textFilePath = (new System.IO.FileInfo(textFilePath)).Name;
string selectCommand = "select * from " + textFilePath;
OleDbCommand textOpenCommand = new OleDbCommand(selectCommand);
textOpenCommand.Connection = textConnection;
OleDbDataAdapter textDataAdapter = new OleDbDataAdapter(textOpenCommand);
Console.WriteLine("Trying to set textDataAdapter");
int rows = textDataAdapter.Fill(dsTextFile); //This is where error is coming.
Console.WriteLine("detail rows being filled");
textConnection.Close();
textConnection.Dispose();
return true;
}
catch (Exception ex_load_text_file) {
Console.WriteLine("error in loadTextFile is " + ex_load_text_file.Message.ToString());
return false;
}
}
Please find the above source where I am getting error 'UnSpecified" for below line.
UnSpecified Error is coming at below line
int rows = textDataAdapter.Fill(dsTextFile)
What could be the issue? I have checked user permissions on c:\windows\temp but no success.
This is a console application and I have even tried to add below code in app.config but no success yet.
<system.web>
<identity imperonate = "false"/> </system.web>
This is a legacy application but needs to run on windows server 2012 setup.
You are using FMT=Fixed on the connection string, if you are not using a schema.ini, change it to FMT=Delimited and it will work.
i.e.:
string textConnectionString = #"Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source=" + textFileFolder + ";" +
"Extended Properties=\"text;HDR=No;FMT=Delimited\";";
str = "INSERT INTO reg (Name,ContentType,Data) values (?,?,?)"
Try
cmd = New OleDbCommand(str, dbcon)
cmd.Parameters.AddWithValue("Name", "chillax")
cmd.Parameters.AddWithValue("ContentType", "audio")
cmd.Parameters.AddWithValue("Data", System.IO.File.ReadAllBytes("E:\chillax.wav"))
cmd.ExecuteNonQuery()
MsgBox("inserted")
Catch ex As Exception
MsgBox("notWorking")
End Try
well, above code is not working(Data - binary datatype)
can anyone know wats wrong in tat code
I have the following code snippet.
SqlCommand cmd = new SqlCommand("SELECT FName,LName FROM EMPLOYEE_TABLE WHERE EmployeeID = '" +TextBox1.Text + "' AND Password = '"+ TextBox2.Text +"'", con);
SqlDataReader x = cmd.ExecuteReader();
try
{
if (x.Read())
{
name = (string)x["FName"] +' '+ (string)x["LName"];
Session["NAME"] = name;
Session["ID"] = TextBox1.Text;
Response.Redirect("sample.aspx?action=On_Click");
}
else
{
errormsg.Text = "login failed.Please enter Valid UserID and Password";
errormsg.ForeColor = System.Drawing.Color.Red;
}
}
catch (Exception exp)
{
errormsg.Text = "Sorry,You dont have access to this portal.";
}
finally
{
x.Close();
con.Close();
}
Now, when i use a valid id (that exists) and password as abc' or 'x'='x then it logs in into the first account of the table in the database. Till this it's fine.
However when I try to debug the code, it throws an error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack..
Also if it is throwing an error then why is it logging into this 1st account of the database. Note: the first account of the database has a different userid than that which i m providing.
Note: I am the developed of this application. So I'm not doing anything illegal. :)
Look at this part of your SQL:
"' AND Password = '"+ TextBox2.Text +"'"
With your password, it's
"' AND Password = ''x'='x'"
which is not the SQL you want.
Even if you are trying to do SQL injection, you have to result in valid SQL. Usually, it's by ending the statement with a semi-colon after closing the quote. See this:
http://xkcd.com/327/
OK, to provide an answer based on the primary issue you've got (as you've stated, you're new to the SQL Injection issue).
SQL Injection is caused by dynamically building a SQL query using user input as part of the construction. The simplest solution to this in .Net is to create a parameterized query.
I think Jeff Atwood has the most complete yet concise article providing an explanation and complete example here
Quoted from above link:
SqlConnection conn = new SqlConnection(_connectionString);
conn.Open();
string s = "SELECT email, passwd, login_id, full_name " +
"FROM members WHERE email = #email";
SqlCommand cmd = new SqlCommand(s);
cmd.Parameters.Add("#email", email);
SqlDataReader reader = cmd.ExecuteReader();
The issue at hand:
The reason it's still logging into the account is because the query is still "valid".
The statement will still be executed, and the relevant record will still be returned from the database, no exception will be thrown.
The only way you will stop the login process when invalid data is provided is to validate the input before executing the query. You should always validate user input before sending it off to the database. If the user were to provide:
username'; drop table users;--
as the username, you would be in a LOT of trouble.
The error you're encountering is a debugging error, not an actual program exception. That's why it works when you run it normally.
To remedy the error, I'd first make sure that everything is running with a Debug build. Also, make sure you're currently debugging in the function of the variable you want to inspect. Try stepping (F10) a few times past your breakpoint to refresh the context. There are a slew of other suggestions on the internet for that particular error, so if you're still having problems you might have to do some googling.
Although I have been able to see the last ran query which is a Stored Procedure executed but I didn't get the parameters values with which the SP was invoked. Rather I got the following:
StoredProcedureName;1
from the following command:
DBCC INPUTBUFFER(SPID)
Where I got the SPID by viewing it in the ObjectExplorer->Management->ActivityMonitor
Is there any way I can get the complete text including the parameters with which the SP was executed ?
I know this answer may not be what you are looking for, as it doesn't really answer your question, I took a leap of thought and ended up thinking this might help.
I don't know how many queries you have and how big your program is... but for debugging purposes I wanted to do something similar for all of my queries, both plain text and stored procedures. So I wrote a simple wrapper class that lets me execute plain text queries/stored procs with and without parameters. Then, if an execption occurs, I trap it, build a new custom exception with the original exception plus the query that was executed and all parameters, and return it all in a custom message. I'm using Oracle in my wrapper but it's almost exactly the same:
Public Function ExecuteCommandQuery(ByRef oCMD As OracleClient.OracleCommand) As DataTable
oCMD.Connection = _oConn
Dim dt As New DataTable
'exception if one occured'
Dim DBException As Exception = Nothing
Try
'get an adapter'
Dim cmd As New OracleDataAdapter(oCMD)
'Fill the data table and ket a count of records returned'
cmd.Fill(dt)
Catch ex As Exception
'capture exception, and rethrow after properly closing the Oracle Connection'
DBException = ex
Finally
_oConn.Close()
End Try
'if exception occured, rethrow'
If DBException IsNot Nothing Then
Throw New Exception( _
String.Format("A database error occured: {0} " + _
Environment.NewLine + Environment.NewLine + " --- " + _
Environment.NewLine + Environment.NewLine + _
" Your query: {1}" + _
Environment.NewLine + Environment.NewLine + " --- " + _
Environment.NewLine + Environment.NewLine + _
" Your Parameters: " + Environment.NewLine + "{2}" _
, DBException.ToString(), oCMD.CommandText, GenerateParameterErrorInfo(oCMD)))
End If
Return dt
End Function
I have used the following code to add the feedback entered to the web form into a database.
The code works fine. But when I try to deleted thi statement
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
I am getting an error I mean it is executing the else part.
Can any one tell me what is the use of SqlCommandBuilder?
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (txtName.Text.Trim() == "")
{
Response.Write("<script>alert ('Name Field cannot be left blank')</script>");
return;
}
if (txtFeedBack.Text.Trim() == "")
{
Response.Write("<script>alert('FeedBack Field cannot be left blank')</script>");
return;
}
objSqlConnection.ConnectionString = connectionStringSetting;
objSqlConnection.Open();
try
{
SqlDataAdapter objDa = new SqlDataAdapter("select * from FeedBack", objSqlConnection);
SqlCommandBuilder objcb = new SqlCommandBuilder(objDa);
DataSet objDs = new DataSet("FeedBack");
objDa.Fill(objDs, "FeedBack");
DataRow dr = objDs.Tables["FeedBack"].NewRow();
dr[1] = txtName.Text;
dr[2] = txtAddress.Text;
dr[3] = txtCity.Text;
dr[4] = txtCountry.Text;
dr[5] = txtEmail.Text;
dr[6] = Convert.ToInt32(txtContactNo.Text);
dr[7] = txtFeedBack.Text;
objDs.Tables["FeedBack"].Rows.Add(dr);
objDa.Update(objDs, "FeedBack");
Response.Write("<script>alert('Your FeedBack has been submitted')</script>");
objSqlConnection.Close();
}
catch (Exception)
{
Response.Write("<script> alert('Error on Page. Please try after sometime')</script>");
objSqlConnection.Close();
}
And is there any way to display the specific error messages like if an user enters a string value instead of Integer value it should display the message as 'Input String not entered in correct format?
Never use catch (Exception). It hides the problem. If an exception is being thrown, then there's something serious wrong. You need to learn about it.
Remove the entire try/catch block (keep the code inside it!). Then run your code again. If there's an exception, then you'll see it on the error page. If not, then use the Event Viewer to look in the Windows Event Log for a warning message from the "ASP.NET" source. It should contain the complete exception.
Final answer is that the line you are talking out is doing a bunch of stuff in the background.
It is adding the insert, update and delete commands to the DataAdapter. So without it, you will crash and burn, unless you add those commands yourself to the DataAdapter.