Getting unspecified error while Reading CSV file using OleDbDataAdapter - asp.net

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\";";

Related

Incorrect Syntax near ' '. Exception while inserting encrypted password (md5) in sql server?

I am encrypting password using md5 security and storing it into the database in asp.net but it gives me the exception of Incorrect Syntax near ' '. I used binary(16) data type for storing encrypted password.
query = "insert into accounts(email, password, user_type) output inserted.id values('" + clientBLL.email + "', " + clientBLL.password + ", 0);";
string accountId = DBManager.ExecuteScaler(query);
When I put single quotes around password " ' " + signIn.password + " ' " it gives me Implicit conversion from data type varchar to binary is not allowed. Use the CONVERT function to run this query error. What should I do for storing md5 encrypted password into database.
Encrypted password code.
public static string encryptMd5(string textToEncrypt)
{
using (MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider())
{
md5.ComputeHash(Encoding.ASCII.GetBytes(textToEncrypt));
byte[] result = md5.Hash;
StringBuilder str = new StringBuilder();
for (int i = 1; i < result.Length; i++)
{
str.Append(result[i].ToString("x2"));
}
return str.ToString();
}
}
Please note comments re the extremely bad practice of generating SQL this way. Your current implementation is wide open to a SQL injection attack. Rather follow the pattern in the code below.
That being said, the exception tells you to use convert
i.e.
using (SqlCommand dbCommand = new SqlCommand(#"insert into accounts(email,
password, user_type) output inserted.id
values(#username, convert(varbinary, #password),
#userType)", dbConn))
{
dbCommand.Parameters.Add("username", SqlType.VarChar).Value = clientBLL.email;
dbCommand.Parameters.Add("password", SqlType.VarBinary).Value = clientBLL.password;
dbCommand.Parameters.Add("userType", SqlType.Int).Value = 0;
dbCommand.ExecuteNonQuery();
}

Opening Excel file Using ClosedXML Error

I am trying to open a 6MB Excel file in ASP.NET using ClosedXML but I am getting an error saying "Error in implicit conversion. Cannot convert null object."
Here's my code:
Dim temppath = Path.GetTempPath()
Dim filenamestr As String = Path.GetFileNameWithoutExtension(Path.GetRandomFileName())
Dim tempfilename As String = Path.Combine(temppath, filenamestr + ".xlsx")
Using fs = New FileStream(tempfilename, FileMode.Create, FileAccess.Write)
xlStream.WriteTo(fs)
End Using
Dim xlwb = New XLWorkbook(tempfilename) 'The part having the error
Source: "DocumentFormat.OpenXml"
I also tried opening an existing Excel file, it still results to this error. Also tried putting the file in different directories thinking it's just because of the permission of my drives, no luck at all. Thanks in advance.
Below is the real time working code used to get excel file in closed xml
private void workbookProcessing(string workbookname)
{
SqlDatabase objdb = new SqlDatabase ( OSMC.constring_Property );
//Below the boqserverfilepath refers the folder where excel files stored EX: "~/Uploaded_Boq/";
string fullfilename = System.Web.HttpContext.Current.Server.MapPath ( OneStopMethods_Common.boqserverfilepath + workbookname );
XLWorkbook theWorkBook = new XLWorkbook ( fullfilename );
int worksheetcount = theWorkBook.Worksheets.Count;
foreach(IXLWorksheet theWorkSheet in theWorkBook.Worksheets)
{
foreach(IXLRow therow in theWorkSheet.Rows())
{
foreach(IXLCell thecell in therow.Cells())
{
int tenderid = 1001;
int Activity_Section_objseq = tenderosm.generateNextTenderObjSequenceNo ( tenderid, "tender_boq_activity_section" );
string boqactivitysectionInsquery = " insert into tender_boq_activity_section(fk_tender_id,obj_seq_no,parent_obj_seq_no,activity_section_no,workbook_name,worksheet_name,row_index,cell_reference,element_type,element_description) values(" + tenderid + "," + Activity_Section_objseq + ",' 10 ','20','" + workbookname + "','" + theWorkSheet.Name + "'," + therow.RowNumber ( ) + ",'"+thecell.Address+"','activity','" + thecell.Value + "');";
objdb.ExecuteNonQuery ( CommandType.Text, boqactivitysectionInsquery );
}
}
}
}
You take the values as per your requirement and insert the values in the database.
Hope the above information will be useful. Kindly let me know your thoughts.
thanks
karthik

COM Interop Exception when trying to read Excel file ASP.net

I have a very simple ASP.net 4.0 application that lets users read data from a common Excel file. The Excel file is situated within the application itself i.e. it rests on the server side in a folder right below the root.
I'm populating a Dataset with the Excel data using this code:
public DataTable GetExcelData(string ExcelFilePath)
{
DataTable dt = new DataTable();
string OledbConnectionString = string.Empty;
OleDbConnection objConn = null;
OledbConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + ExcelFilePath + ";Extended Properties=Excel 8.0;";
objConn = new OleDbConnection(OledbConnectionString);
if (objConn.State == ConnectionState.Closed)
{
objConn.Open();
}
string resName = "'";
string depName = department;
resName += userLastName + ", " + userFirstName + "'";
OleDbCommand objCmdSelect = new OleDbCommand("Select * from [" + depName + "$A3:Q10000] where Resource=" + resName, objConn);
OleDbDataAdapter objAdapter = new OleDbDataAdapter();
objAdapter.SelectCommand = objCmdSelect;
DataSet objDataset = new DataSet();
objAdapter.Fill(objDataset, "ExcelDataTable");
dt = objDataset.Tables[0];
addSumRow(dt);
objConn.Close();
return objDataset.Tables[0];
}
and after this I attache the Dataset to a Gridview and that's about it.
Now when I run the app on my local host there's no problem showing the Excel data, however, after deployment to our web server the application fails with this error:
The specified domain either does not exist or could not be contacted.
Description: An unhandled exception occurred during the execution of the current web >request. Please review the stack trace for more information about the error and where it >originated in the code.
Exception Details: System.Runtime.InteropServices.COMException: The specified domain >either does not exist or could not be contacted.
Source Error:
An unhandled exception was generated during the execution of the current web request. >Information regarding the origin and location of the exception can be identified using >the exception stack trace below.
Any help is very much appreciated!
Thanks!
few thing you may try
1>Disable anonymous access and enable identity impersonation
2>Ensure Excel file path is correct

updating a row gives error Operation must use an updateable query

I'm getting this error when I'm trying to update a record:
ERROR [HY000] [Microsoft][ODBC Microsoft Access Driver]
Operation must use an updateable query
However when I add a new record, it would add just fine.
I did some searching and found out that the problem is because The ASP.NET worker process does not have permission to update the database. But how am I being able to insert a new record (Isn't inserting updating the database!) but not update (set a record to a different value).
OdbcConnection DbConnection = new OdbcConnection("DSN=inv");
DbConnection.Open();
try
{
string newPassword = password1.Text;
OdbcCommand DbCommand = new OdbcCommand("UPDATE Users" + " SET [Password] = '" + newPassword + "'" + " Where Name = '" + Session["LoginId"] + "'" + ";", DbConnection);
DbCommand.ExecuteNonQuery();
Server.Transfer("Default.aspx", true);
}
You will often get that error if you don't have a primary key declared on that table.
Your code is also pretty ugly, at the very least you should be using a parameterized query:
OdbcCommand DbCommand = new OdbcCommand("UPDATE Users SET [Password] = #Password Where Name = #Name", DbConnection);
var param = DbCommand.Parameters.Add("#Password", OdbcType.Text);
param.Value = passWord;
param = DbCommand.Parameters.Add("#Name", OdbcType.Text);
param.Value = Session["LoginId"];
And I hope this isn't anything more than a toy/demo app -- storing passwords in the clear is bad. Storing passwords in access in the clear is a double bad.

why is my global.asax error handler not working?

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.

Resources