I'm using a third party library that converts excel files to PNG for preview purposes.
Sometimes the excel it's too complex, and the library fails with a StackoverflowException
.
That's ok, because I don't except all files to be converted, but I can't catch the exception and give the user other option to download the file (Stackoverflow exceptions aren't catcheables)
I try to run in other thread using Task.Run()
and even with a new request, but the original request stalls and I'm not able to control the fail.
Attempt 1 using Task.Run()
public string ExcelAsPNGUrl() {
try {
var TempFolder = @"/Content/Temp/";
var UniquePreviewFileName = ArchivoURL.Replace("/", "_") + ".png";
if (!System.IO.File.Exists( HttpContext.Current.Server.MapPath(TempFolder + UniquePreviewFileName))) {
var asyncTask = Task.Run(() => {
var UniquePreviewFileName = ArchivoURL.Replace("/", "_") + ".png";
var workbook = new Spire.Xls.Workbook();
workbook.LoadFromFile(HttpContext.Current.Server.MapPath(ArchivoURL));
var sheet = workbook.Worksheets[0];
sheet.SaveToImage(HttpContext.Current.Server.MapPath(TempFolder + UniquePreviewFileName));
return TempFolder + UniquePreviewFileName;
});
return asyncTask.Result;
}
return TempFolder + UniquePreviewFileName;
}
catch (Exception) {
return "";
}
}
Attempt 2 using WebClient
public string ExcelAsPNGUrl() {
try {
var TempFolder = @"/Content/Temp/";
var UniquePreviewFileName = ArchivoURL.Replace("/", "_") + ".png";
if (!System.IO.File.Exists( HttpContext.Current.Server.MapPath(TempFolder + UniquePreviewFileName))) {
var client = new System.Net.WebClient();
var retval = client.DownloadString(Sitio.URI + $"/system/GenerateExcelPreview?ArchivoURL={ArchivoURL}");
}
return TempFolder + UniquePreviewFileName;
}
catch (Exception) {
return "";
}
}
How can I call the library safely from my web app?