Opening Excel file Using ClosedXML Error - asp.net

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

Related

Sqlite insert gives syntax error

I am working on flex actionscript project. In which i am going to save/insert records in sqlite database, which i got in response.
But, form that records some records are not inserted into table. When i catch the error it gives sql error.
near '/': syntax error
In response i have got whole html markup.
I have written/execute query inside for loop like:
var insert:SQLStatement = new SQLStatement();
insert.sqlConnection = sqlConnectionSync;
insert.text = 'INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES ("' + listArray[i].MessageID + '","' + listArray[i].AccountID + '","' + listArray[i].Body + '")';
insert.execute();
I have also tried changing " in place of ' and vice versa.
But it gives other error of '
Error #3115: SQL Error.
near 'll': syntax error
And
near '_blank': syntax error
Any help would greatly appreciated.
To avoid such problem, you can use SQLStatement.parameters property like this, for example :
var insert:SQLStatement = new SQLStatement();
insert.text = 'INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES (:param1, :param2, :param3)';
insert.parameters[':param1'] = listArray[i].MessageID;
insert.parameters[':param2'] = listArray[i].AccountID;
insert.parameters[':param3'] = listArray[i].Body;
insert.execute();
Hope that can help.
Posting the full query as text would help but most likely you have " or ' characters in your data (like ...="_blank" or "You'll"). You'd need to escape your variable values before inserting them into the database. I have switched " and ' from your example:
insert.text = "INSERT OR IGNORE INTO TableName (MessageID, AccountID, Body) VALUES ('" + escapeChars(listArray[i].MessageID) + "','" + escapeChars(listArray[i].AccountID) + "','" + escapeChars(listArray[i].Body) + "')";
private function escapeChars(myString:String):String
{
// Since we are using "'" we'd need to escape all other "'" characters
return myString.replace(/'/gi, "\'");
}

VB Saving img file with path adds folder name to file name

Hi I am having some problems with saving img files using Visual Basic, the files are being named wrongly with the folder name being added to the start of the file name.
I parse a web address and then use the split address values to rename my files however the the path value seems to be added to the file as well.
The files in the photo should be named for example "DCAT040iMBE Test13.jpg"
but this file is being name "Test1DCAT040iMBE Test13.jpg"
Protected Sub GeneratedCode()
Dim path As String = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\"
LogoUpload.SaveAs(path + LogoUpload.FileName)
TextFile.SaveAs(path + TextFile.FileName)
Dim lines() As String = IO.File.ReadAllLines(path + TextFile.FileName)
For Each line As String In lines
Dim count As Integer
Dim encoder As New QRCodeEncoder()
encoder.QRCodeErrorCorrect = QRCodeEncoder.ERROR_CORRECTION.H
encoder.QRCodeScale = 10
Dim img As Bitmap = encoder.Encode(line)
Dim logo As System.Drawing.Image = System.Drawing.Image.FromFile(path + LogoUpload.FileName)
Dim left As Integer = (img.Width / 2) - (logo.Width / 2)
Dim top As Integer = (img.Height / 2) - (logo.Height / 2)
Dim g As Graphics = Graphics.FromImage(img)
Dim parseLine = line
Dim replaceDelimiter As String
If Not String.IsNullOrWhiteSpace(line) Then
replaceDelimiter = Replace(line, "&", "=")
End If
Dim fileNameSplit() As String = replaceDelimiter.Split("=")
Dim newFileName As String
Dim partTwo = fileNameSplit(1)
Dim partSix = fileNameSplit(5)
Dim objFSO
Dim newFolder As String
newFolder = "C:\Users\Grey\Documents\visual studio 2010\Projects\QRCodeGenerator\QRCodeGenerator\Output\" + partSix
objFSO = CreateObject("Scripting.FileSystemObject")
If (Not System.IO.Directory.Exists(newFolder)) Then
System.IO.Directory.CreateDirectory(newFolder)
End If
count += 1
g.DrawImage(logo, New Point(left, top))
newFileName = partTwo & " " & partSix & count & ".jpg"
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
amountCreatedLbl.Text = count & " QRCodes Created"
logo.Dispose()
Next
End Sub
Could it be that I am generating my newFolder Values wrongly?
edited to add an example of data from the parsed txt file.
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test1
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test2
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAT050&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT055iMB&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DCAT040iMBE&Logo=MyLogo&Companyloc=Test3
https://mywebsite.com/QRCode/default.aspx?materialcode=DTAB060&Logo=MyLogo&Companyloc=Test
Looks like you are missing a slash on the line:
img.Save(newFolder + newFileName, ImageFormat.Jpeg)
It should be:
img.Save(newFolder + "\" + newFileName, ImageFormat.Jpeg)
The program doesn't realize that the newDirectory variable is supposed to be a directory, it's just being concatenated to the filename directly. A better option would be to use:
img.Save(System.IO.Path.Combine(newFolder, newFileName), ImageFormat.Jpeg)
The System.IO.Path.Combine() function automatically adds the missing slash between the directory and filename, as well as some additional checks to make sure the result is valid.
As a side note, I would also recommend using & instead of + when joining strings together. Hard to debug issues can come up when you do it that way. I would also recommend turning Option Strict On, you will see a couple of other warnings that come up with your code as is. But, to resolve your issue, the above will work.

Getting unspecified error while Reading CSV file using OleDbDataAdapter

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

File already exist using system.io.file.copy

I'm using System.IO.File.Copy to copy files from serverA to serverB. This works fine accept when the file exsist I get an error "File already exist". I tried trapping it using if file.exsist and nothing.
here is my code.
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("../pdf/audits/" & FileName))
'Local Server
Dim localPath As String = "\\server01\folder1$\pdf\audits\"
'Remote Server
Dim remotePath As String = "\\server02\folder2$\pdf\audits\"
System.IO.File.Copy(localPath + FileName, remotePath + FileName)
What am I missing?
If you just modify your copy operation like this, it should work. The last parameter will overwrite the file.
System.IO.File.Copy(localPath + FileName, remotePath + FileName, True);
If you have large files, you are not going to want to overwrite them everytime. Try fixing your check to see if the file exist. Something like this (C#):
var localPath = #"C:\";
var remotePath = #"\\server\folder\";
var fileName = "test.txt";
if (!new System.IO.FileInfo(remotePath + fileName).Exists)
{
System.IO.File.Copy(localPath + fileName, remotePath + fileName);
}
There's a third parameter to overwrite if it already exists
System.IO.File.Copy(fileName, destName, overwrite);
I got it working with help from RLG.
'Save files to disk
FileUpload1.SaveAs(Server.MapPath("../pdf/audits" & FileName))
'SIGAR Public CMS
Dim localPath As String = "\\hqdadev01\sigar_cms$\pdf\audits\"
'SIGAR Dev
Dim remotePath As String = "\\hqdadev02\sigar_public$\pdf\audits\"
Added this to check.
If Not New System.IO.FileInfo(remotePath + FileName).Exists Then
File.Copy(localPath + FileName, remotePath + FileName, overwrite)
End If

why is my insert not inserting a record in database

I am trying to insert a record into the database using the below method. I am calling this method in a button click event but for some reasons no record is being inserted.
There are four fields which need to be inserted: rpttemplateid - I am getting that field from another database table and all the other feilds are just static values.
What am i doing wrong below?
public void updatereporttemplate()
{
string cnn = WebConfigurationManager.ConnectionStrings["Underwriting"].ConnectionString;
SqlConnection cnn1 = new SqlConnection(cnn);
cnn1.Open();
string getrptdesc = "select max(rptdesc) + 1 from report_description where rptdesc < 999 and rptdesc is not null";
SqlCommand cmd = new SqlCommand(getrptdesc, cnn1);
SqlDataReader sdr = cmd.ExecuteReader();
sdr.Read();
int getcount = int.Parse(sdr[0].ToString());
sdr.Close();
string commandtext1 = "INSERT INTO report_template" + "(rpttemplateid,rpttemplatedescr,minsubs,minmebers) " +
" Values( " + getcount + "," + " " + " , " + 0 + "," + 0 + ")";
SqlCommand command1 = new SqlCommand
{
CommandText = commandtext1,
Connection = cnn1
};
You are missing command1.ExecuteNonQuery();
Also, have you considered using an IDENTITY column in your table instead of trying to manually set the count? What if that page is hit by multiple people at the same time?
You need to open the connection
cnn1.Open();
And then execute the command
command1.ExecuteNonQuery();

Resources