Error while uploading .xlsx file using ExcelDataReader - asp.net-mvc

I am working on asp.net MVC project.
I use ExcelDataReader component to read excel file records.
Now when I published my project to server and upload a .xlsx file with uploader I get below mentioned exception message. There are no errors with local deployment but server.
Access to the path '\Microsoft Corporation\Internet Information
Services\7.5.7600.16385' is denied.
and code where I am getting error is:
if (personsFile.FileExtension == ".xls")
{
Stream st = new MemoryStream(personsFile.FileArray);
reader = ExcelReaderFactory.CreateBinaryReader(st);
}
else if (personsFile.FileExtension == ".xlsx")
{
Stream st = new MemoryStream(personsFile.FileArray);
//exception occured on under line
reader = ExcelReaderFactory.CreateOpenXmlReader(st);
}
But when I upload a .xls file, I dont have any error.
How to resolve issue with .xlsx extenstion?

This is most likely due to ExcelDataReader 2.x extracting the xlsx archive to %TEMP% before processing it. The current pre-alpha of 3.0 no longer does this. See https://github.com/ExcelDataReader/ExcelDataReader/releases.

Related

Xamarin iOS open sqlite file SQLite.SQLiteException: 'file is not a database'

I am working in Xamarin Forms with an iOS app.
The code downloaded successfully an sqlite file and I moved the file to the following location:
/var/mobile/Containers/Data/Application/787D3CB8-01E1-41BB-B786-972534E7F563/Documents/Data/test-file.sqlite
but now when I try to open it with the following code I get a strange error:
SQLite.SQLiteException: 'file is not a database'
The database is also not encrypted
here is my code:
var db = new SQLiteAsyncConnection(_dbPath);
var versionlist = await db.QueryAsync<version_history>("SELECT * FROM version_history ORDER BY id DESC LIMIT 1")
after I do the QueryAsync I get the error, the file is not a database.
but the db object does have the information
Please help me, any ideas?
It turned out it wasn't a real sqlite file after all. It was a zip file but named as a sqlite file and the more crazy is, the fact that it was readable by the sql lite lib, when using SQLiteAsyncConnection.
Even when it was a zip file.
But the moment you fire a query, you will get the error saying that it is not a database.

How to zip PDF and XML files which are in memorystreams

I'm working with VS2015 and ASP.Net on a webservice application which is installed in the AWS cloud.
In one of my methods i got two files, a PDF and a XML.
These files just exist as instances of type MemoryStream.
Now i have to compress these two "files" in a ZIP file before adding the zip as attachment to an E-mail (class MailMessage).
It seems that i have to save the memorystreams to files before adding them as entries to the zip.
Is ist true or do i have another possibility to add the streams as entries to the zip?
Thanks in advance!
The answer is no.
It is not necessary to save the files before adding them to the stream for the ZIP file.
I have found a solution with the Nuget package DotNetZip.
Here is a code example how to use it.
In that example there two files which only exist in MemoryStream objects, not on a local disc.
It is important to reset the Position property of the streams to zero before adding them to the ZIP stream.
At last i save the ZIP stream as a file in my local folder to control the results.
//DotNetZip from Nuget
//http://shahvaibhav.com/create-zip-file-in-memory-using-dotnetzip/
string zipFileName = System.IO.Path.GetFileNameWithoutExtension(xmlFileName) + ".zip";
var zipMemStream = new MemoryStream();
zipMemStream.Position = 0;
using (Ionic.Zip.ZipFile zip = new Ionic.Zip.ZipFile())
{
textFileStream.Position = 0;
zip.AddEntry(System.IO.Path.GetFileNameWithoutExtension(xmlFileName) + ".txt", textFileStream);
xmlFileStream.Position = 0;
zip.AddEntry(xmlFileName, xmlFileStream);
zip.Save(zipMemStream);
// Try to save the ZIP-Stream as a ZIP file. And suddenly: It works!
var zipFs = new FileStream(zipFileName, FileMode.Create);
zipMemStream.Position = 0;
zipMemStream.CopyTo(zipFs);
zipMemStream.WriteTo(zipFs);
}

Copying file from local to SharePoint server location

Now on my PC I can use explorer to open a location on our SP server (location eg http://sp.myhost.com/site/Documents/). And from there I can copy/paste a file from eg my C:\ drive.
I need to replicate the copy process progmatically. FileCopy() doesn't do it - seems to be the http:// bit that's causing problems!
Does the server allow WebDAV access? If yes, there are WebDAV clients for Delphi available, including Indy 10.
In case if you are not using BLOB storage all SharePoint files are stored in the database as BLOB objects.
When you access your files with explorer you are using windows service which is reading files from SharePoiont and render it to you. This way you can copy and paste as soon as donwload them from an to SharePoint manually.
To be able to do this automatically you should achive this using the next SP API code:
using (SPSite site = new SPSite("http://testsite.dev"))
{
using (SPWeb web = site.OpenWeb())
{
using (FileStream fs = File.OpenRead(#"C:\Debug.txt"))
{
byte[] buffer = new byte[fs.Length];
fs.Read(buffer, 0, (int) fs.Length);
SPList list = web.GetList("Lists/Test AAD");
SPFile f = list.RootFolder.Files.Add("/Shared Documents/"+Path.GetFileName(fs.Name), buffer);
}
}
}
This will add new "Debug.txt" file to the "Shared Documents" library read from the disk C. To do this for each file just loop through each file in the folder. You can open web only once and do the loop each time when you add file...
Hope it helps,
Andrew

Struts File Upload identify correct extension instead of .tmp

I am new to Struts and working on File Upload using Struts.
Client:
It is Java Program which hits my Strut app by using apache HttpClient API and provides me
File.
Client as per need sometime gives me .wav file and sometime .zip file and sometime both.
Server:
Struts app which got the request from client app and upload the file.
Here, problem comes as I upload the file, it get uploaded using ".tmp" extension, which I want to get uploaded with the same extension what client has passed.
Or there is any other way by which we can check what is the extension of the file client has sent....?
I am stuck in this problem and not able to go ahead.
Please Find the code attached and tell me what modification I have to do:
Server Code:
MultiPartRequestWrapper multiWrapper=null;
File baseFile=null;
System.out.println("inside do post");
multiWrapper = ((MultiPartRequestWrapper)request);
Enumeration e = multiWrapper.getFileParameterNames();
while (e.hasMoreElements()) {
// get the value of this input tag
String inputValue = (String) e.nextElement();
// Get a File object for the uploaded File
File[] file = multiWrapper.getFiles(inputValue);
// If it's null the upload failed
if (file != null) {
FileInputStream fis=new FileInputStream(file[0]);
System.out.println(file[0].getAbsolutePath());
System.out.println(fis);
int ch;
while((ch=fis.read())!=-1){
System.out.print((char)ch);
}
}
}
System.out.println("III :"+multiWrapper.getParameter("method"));
Client code:
HttpClient client = new HttpClient();
MultipartPostMethod mPost = new MultipartPostMethod(url);
File zipFile = new File("D:\\a.zip");
File wavFile = new File("D:\\b.wav");
mPost.addParameter("recipientFile", zipFile);
mPost.addParameter("promptFile", wavFile);
mPost.addParameter("method", "addCampaign");
statusCode1 = client.executeMethod(mPost);
actually Client is written long back and cant be modified and I want to identify something at server side only to find the extension.
Please help, Thanks.
Struts2 File Uploader interceptor when uploading file pass the content type information to the Action class and one can easily find the file type by comparing contentType with MIME type.
If you want to can create a map with key as content type and file type as its value like
map.Add("image/bmp",".bmp", )
map.Add("image/gif",".gif", )
map.Add("image/jpeg",".jpeg", )
and can easily fetch the type based on the extension provides.Hope this will help you.

Excel doesn't want to open XLSX files downloaded through ASP output

I use ASP MVC3 framework, created an Excel file and outputted it using FileResult action with content type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".
When attempting to open it Excel just says "file is corrupt and cannot be opened."
When I open the source generated Excel file that was used to send the output it works without any problems. I also run file comparison on the bytes for both copies and the files are identical. I tried to email the corrupt file to myself and the attachment opens fine.
This leads me to believe it's a problem with headers or some sort of Excel/Windows security config.
If it is the latter, then I need a solution that won't make clients change their security settings.
EDIT - Found the setting:
I've found what setting causes this - "Enable protected view from files originated from the internet" in Excel's Trust Center / Protected View settings.
So I guess the question is - Is there a way for the file to appear trusted?
Here are the response headers:
Cache-Control:private
Content-Disposition:attachment;
filename="Report - Monday, March 19, 2012.xlsx" Content-Length:20569
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
The action method that makes the output:
[HttpPost]
public virtual FileResult Export()
{
try
{
...
string newFilePath = createNewFile(...);
string downloadedFileName = "Report - " + DateTime.Now.ToString("D") + ".xlsx";
return File(newFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", downloadedFileName);
}
catch (Exception ex)
{
...
}
}
How I create the Excel file:
I have a template XLSX file witch column names and some pivot charts in other sheets. From C# I create a copy of this template and then call SQL Server which outputs data into 1st sheet using OLEDB connector:
set #SQL='insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;Database=' + #PreparedXLSXFilePath + ';'', ''SELECT * FROM [Data$]'') ...
Thanks in advance for any help.
You would need a digital signature in your Excel file. How to do this from code is another question.
More info here:
http://www.delphifaq.com/faq/windows_user/f2751.shtml

Resources