Code doesn't work when deploying on Server - asp.net

I have written the following code to export data to excel.
This code works fine on local,but when we deploy this code on Server (UAT),it doesn't work.
If we restart server, it works for a while but again after a while it fails.
Code:
public void ExportToExcelFunction(string FlName, DataTable mydt, string DispColName, string BindCols)
{
Excel.Application xlObj = new Excel.Application();
object oMissing = System.Reflection.Missing.Value;
xlObj.Visible = false;
//vinod
string filepath = Server.MapPath("Export");
string strFlName = filepath + "\\Master.xlsx";
Excel.Workbook xlWB = xlObj.Workbooks.Open(strFlName, 0, true, 5, "", "", false, Excel.XlPlatform.xlWindows, "", true, true, 0, true);
Excel.Worksheet xlSheet = (Excel.Worksheet)xlWB.ActiveSheet;
int cols = mydt.Columns.Count;
int rows = mydt.Rows.Count;
//Added for export to excel
try
{
//For Column
string[] strCols = DispColName.Split(',');
for (int i = 1; i <= strCols.Length; i++)
{
if (strCols[i - 1].Length > 0 && strCols[i - 1] != null)
xlSheet.Cells[1, i] = Convert.ToString(strCols[i - 1]);
}
// for Row
string[] strColBind = BindCols.Split(',');
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < strColBind.Length; c++)
{
xlSheet.Cells[r + 2, c + 1] = mydt.Rows[r][strColBind[c]];
}
}
}
catch (Exception ex)
{
}
String newFlName = "\\" + DateTime.Now.Ticks.ToString() + "_" + FlName + ".xls";
xlWB.SaveAs(filepath + newFlName, Excel.XlFileFormat.xlWorkbookNormal, "", "", false, false, Excel.XlSaveAsAccessMode.xlExclusive, true, false, "", true);
xlWB.Close(true, oMissing, oMissing);
xlObj.Quit();
System.IO.FileInfo file = new System.IO.FileInfo(#"" + filepath + newFlName + "");
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AppendHeader("Content-Disposition", "attachment; filename = " + FlName + ".xls");
Response.AppendHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/download";
Response.WriteFile(file.FullName);
Response.Flush();
Response.Close();
Response.End();
}

Two things you should know.
The first, is that your code appears to be using Excel Interop Services, thus it requires Excel to be installed on the server.
The second thing is that using Excel Interop Services on the server side is not supported by Microsoft, for a number of good reasons.
Instead, I suggest using an alternative library such as EPPlus or Open Office XML SDK, both of which run on the server side just fine.

Related

How to insert a picture into a word processing document using DocumentFormat.OpenXML Library and AltChunk Class c#

I am using Telerik:RadEditor component for Asp.Net to save openXML and html report, I need to download word file format from this html report using DocumentFormat.OpenXML library from Microsoft, the code i used working successfully but can't see image after download word file.
I tried the below references but image not showing also.
https://learn.microsoft.com/en-us/office/open-xml/how-to-insert-a-picture-into-a-word-processing-document
https://learn.microsoft.com/en-us/dotnet/api/documentformat.openxml.wordprocessing.altchunk?view=openxml-2.8.1
Add HTML String to OpenXML (*.docx) Document
How to insert a non-inline picture into a word document using VB6?
Adding image in word document
My Code is as follows:
protected void btnsavetoword_Click(object sender, EventArgs e)
{
try
{
clsReportTemplateBO objexist = new clsReportTemplateBO();
objexist.RefNo = hdnRefNo.Value;
objexist.CreatedBy = clsUser.UserName;
List<clsReportTemplateBO> objReport = clsReportTemplateBL.GetSavedReports(objexist);
if (objReport.Count > 0)
{
string ReportText = edrReport.Content;
ReportText = ReportText.Replace(objReport[0].HeaderHTML, "");
ReportText = ReportText.Replace(objReport[0].FooterHTML, "");
objexist.ReportCode = objReport[0].ReportCode;
foreach (clsReportTemplateBO datarow in objReport)
{
if (datarow.ReportFormat == "Word")
{
objexist.PatientReportId = datarow.PatientReportId;
}
}
if (objReport.Count == 2)
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
else if (objReport.Count == 1 && objReport[0].ReportFormat == "HTML")
{
objexist.ReportName = objReport[0].ReportName;
objexist.HID = objReport[0].HID;
objexist.CreatedBy = clsUser.UserName;
objexist.ReportFormat = "Word";
objexist.RefNo = hdnRefNo.Value;
if (clsReportTemplateBL.SavePatientReport(objexist))
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
else if (objReport.Count == 1 && objReport[0].ReportFormat == "Word")
{
string PatientReportId = objexist.PatientReportId;
ConverttoWord(objexist.ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
else
{
clsReportTemplateBO obj = new clsReportTemplateBO();
string ReportCode = HttpContext.Current.Session["ReportCode"].ToString();
obj = clsReportTemplateBL.GetReportTemplate(ReportCode);
obj.ReportName = ReportName;
obj.ReportCode = ReportCode;
obj.HID = HID;
obj.CreatedBy = clsUser.UserName;
obj.ReportFormat = "Word";
obj.RefNo = hdnRefNo.Value;
string ReportText = edrReport.Content;
ReportText = ReportText.Replace(obj.HeaderHTML, "");
ReportText = ReportText.Replace(obj.FooterHTML, "");
if (clsReportTemplateBL.SavePatientReport(obj))
{
string PatientReportId = obj.PatientReportId;
ConverttoWord(ReportCode, PatientReportId, ReportText);
rdWMngr.RadAlert("Report saved successfully", 400, 150, "Report", null, clsConstants.SucccessMessage);
}
}
}
catch
{
rdWMngr.RadAlert("Report saved failed", 400, 150, "Report", null, clsConstants.ErrorMessage);
}
}
ConvertToWord method as follows:
protected void ConverttoWord(string ReportCode, string PatientReportId, string ReportText)
{
string domain = HttpContext.Current.Request.Url.Authority;
string RefNo = hdnRefNo.Value;
int PatientReportDetailId = clsReportTemplateBL.SavePatientReportDetail(PatientReportId, RefNo, domain, clsUser.UserName);
string sourceFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ReportFormatPath"].ToString() + ReportCode + ".docx");
string destFile = HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["SavedReportPath"].ToString() + RefNo + PatientReportDetailId.ToString() + ".docx");
System.IO.FileInfo file = new System.IO.FileInfo(sourceFile);
System.IO.FileInfo dest = new System.IO.FileInfo(destFile);
if (file.Exists)
{
if (dest.Exists)
{
rdWMngr.RadAlert("File already converted. Try to download from Saved Report", 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
else
{
File.Copy(sourceFile, destFile);
}
exporttoword(destFile, ReportText);
}
else
{
rdWMngr.RadAlert("File not exist on " + sourceFile, 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
}
ExportToWord method as follows:
private void exporttoword(string FilePath, string ReportText)
{
using (WordprocessingDocument myDoc = WordprocessingDocument.Open(FilePath, true))
{
string altChunkId = "AltChunkId1";
MainDocumentPart mainPart = myDoc.MainDocumentPart;
AlternativeFormatImportPart chunk = mainPart.AddAlternativeFormatImportPart("application/xhtml+xml"/*AlternativeFormatImportPartType.Html*/, altChunkId);
//string stamp = "~/images/Menu/EStamp.png"; //Location of image that I need to insert into word when i save
using (Stream chunkStream = chunk.GetStream(FileMode.Create, FileAccess.Write))
{
using (StreamWriter streamWriter = new StreamWriter(chunkStream))
{
streamWriter.Write(ReportText);
}
}
AltChunk altChunk = new AltChunk();
altChunk.Id = altChunkId;
// this inserts altChunk after the last Paragraph
mainPart.Document.Body
.InsertAfter(altChunk, mainPart.Document.Body.Elements<Paragraph>().Last());
mainPart.Document.Save();
}
//Download
System.IO.FileInfo file = new System.IO.FileInfo(FilePath);
if (file.Exists)
{
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + file.Name);
Response.AddHeader("Content-Length", file.Length.ToString());
Response.ContentType = "application/octet-stream";
Response.WriteFile(file.FullName);
Response.End();
}
else
{
rdWMngr.RadAlert("Error", 400, 150, "Saved Report", null, clsConstants.WarningMessage);
}
}
How can I insert image to the word file when I need to download it using DocumentFormat.OpenXML library in Asp.Net?

Cutting and saving video in folder using ffmpeg

private bool ReturnVideo(string fileName)
{
string html = string.Empty;
//rename if file already exists
int j = 0;
string AppPath;
string inputPath;
string outputPath;
// string imgpath;
AppPath = Request.PhysicalApplicationPath;
//Get the application path
inputPath = AppPath + "OriginalVideo";
//Path of the original file
outputPath = AppPath + "ConvertVideo";
//Path of the converted file
// imgpath = AppPath + "Thumbs";
//Path of the preview file
string filepath = Server.MapPath("~/OriginalVideo/" + fileName);
while (File.Exists(filepath))
{
j = j + 1;
int dotPos = fileName.LastIndexOf(".");
string namewithoutext = fileName.Substring(0, dotPos);
string ext = fileName.Substring(dotPos + 1);
fileName = namewithoutext + j + "." + ext;
filepath = Server.MapPath("~/OriginalVideo/" + fileName);
}
try
{
this.fileuploadImageVideo.SaveAs(filepath);
}
catch
{
// return false;
}
string outPutFile;
outPutFile = "~/OriginalVideo/" + fileName;
int i = this.fileuploadImageVideo.PostedFile.ContentLength;
System.IO.FileInfo a = new System.IO.FileInfo(Server.MapPath(outPutFile));
string cmd = "-y -ss 00:00:00 -to 00:00:10 -i " + inputPath + "\\" + fileName + " -vcodec copy -acodec copy " + outputPath + "\\" + fileName.Remove(fileName.IndexOf(".")) + ".mp4";
ConvertNow(cmd);
return true;
}
private void ConvertNow(string cmd)
{
string exepath;
string AppPath = Request.PhysicalApplicationPath;
//Get the application path
exepath = AppPath + "ffmpeg\\ffmpeg.exe";
Process proc = new Process();
proc.StartInfo.FileName = exepath;
//Path of exe that will be executed, only for "filebuffer" it will be "flvtool2.exe"
proc.StartInfo.Arguments = cmd;
//The command which will be executed
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.CreateNoWindow = true;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
//while (proc.HasExited == false)
//{
//}
}

How to use and improve wakhtmltopdf performance?

I have my aspx pages , and some logic is written in code behind to bind the data of aspx pages.Now using wkhtmltopdf i am sending these files to convert into pdf files.Its work very well when the data is smaller in size however when the data comes in larger side for that page the wkhtmltopdf stops working and doesnt create any pdf file.
Can you suggest any way to overcome this problem. What i tried was limiting the data.. for example i have repeater control on my page if that controls binds 350 record i am only taking 20 records , but also if size of those 20 records are large it happens the same
the also next option i tried is my giving the parameter inside
Process myProcess = Process.Start(startInfo);
myProcess.WaitForExit(few seconds);
but it still doesnt work
Please suggest
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
This is the answer => what happen is when u start process , and wait for exit () both creates a deadlock somtimes which hammers the performance .. by adding readtoend() method before waitforexit() clears the deadlock and then continues further processing ...
this solves my problem.
The reason i am showing complete solution is that , wkhtmltopdf is very good for creating dynamic pdf files , but this is free tool as well and hence very limited documentation for this ..
private void ProcessHtmlToPdf(List<ExportToPdfCategories> lstExportToPdfCategories)
{
try
{
string pdfExportPath = string.Empty;
string PDFdeletePath = string.Empty;
string deletePath = string.Empty;
string PdfSavePath = string.Empty;
if (lstExportToPdfCategories != null)
{
foreach (var item in lstExportToPdfCategories)
{
path = "";
pdfExportPath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
PDFdeletePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString();
PdfSavePath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
htmlpath = profile + ApConfig.CurrentCompany.CompId + "/" + objExpDetails.AddedForId.ToString() + "/" + item.HeaderCategory;
deletePath = Server.MapPath(PDFdeletePath);
string ClearDirectory = Server.MapPath(PdfSavePath);
if (Directory.Exists(deletePath))
{
//Directory.Delete(ClearDirectory, true);
//Directory.Delete(deletePath, true);
}
if (!Directory.Exists(Server.MapPath(pdfExportPath)))
{
Directory.CreateDirectory(Server.MapPath(pdfExportPath));
}
string name =
pdfExportPath = pdfExportPath + "/" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-" + item.HeaderCategory + "_" + (drpYear.SelectedValue != "0" ? Convert.ToString(drpYear.SelectedValue) : System.DateTime.Now.Year.ToString()) + ".pdf";
objpath = Server.MapPath(pdfExportPath);
//this will create html mockup
//item.WebsiteUrl = CreateTemportHtmlFile(item.HeaderCategory, PdfSavePath, item.WebsiteUrl);
if (path == "")
{
path = CreateTemportHtmlFile(PdfSavePath, item.HeaderCategory);
}
HtmlToPdf(item.WebsiteUrl, objpath, path);
}
Response.Clear();
Response.AddHeader("Content-Disposition", "attachment; filename=" + objExpDetails.FirstName + "." + objExpDetails.LastName + "-actusdocs.zip");
Response.ContentType = "application/zip";
objZip.Save(Response.OutputStream);
Response.End();
}
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("ProcessHtmlToPdf method : ", ex.Message + ex.StackTrace, objExpDetails);
}
}
//Method overloading
//this is for testing html pages(not in used during main running)
private string CreateTemportHtmlFile(string categoryName, string htmlMockupSavingPath, string websiteURL)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
htmlMockupSavingPath = Server.MapPath(htmlMockupSavingPath) + "\\" + categoryName + ".html";
StreamWriter sw;
HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(websiteURL);
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(htmlMockupSavingPath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(htmlMockupSavingPath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlMockupSavingPath;
}
private string CreateTemportHtmlFile(string PdfSavePath, string categoryName)
{
try
{
string sessionId = Session.SessionID;
int employeeId = Convert.ToInt32(hdnEmployeeId.Value);
PdfSavePath = Server.MapPath(PdfSavePath) + "\\BindHeader.html";
htmlpath = htmlpath.Substring(1);
htmlpath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + htmlpath + "/BindHeader.html";
string exportedYear = (drpYear.SelectedValue == "0" ? System.DateTime.Now.Year.ToString() : drpYear.SelectedValue);
StreamWriter sw;
if (categoryName == "MidYearAppraisal" || categoryName == "EndYearAppraisal")
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeaderforAppraisal.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
else
{
myRequest = (HttpWebRequest)WebRequest.Create(ConfigurationManager.AppSettings["pdfUrlPath"] + "/User/UserPdfReports/UserPdfHeader.aspx?session=" + sessionId + "&empId=" + employeeId + "&catName=" + categoryName + "&expYear=" + exportedYear);
}
myRequest.Method = "GET";
WebResponse myResponse = myRequest.GetResponse();
StreamReader sr = new StreamReader(myResponse.GetResponseStream(), System.Text.Encoding.UTF8);
string result = sr.ReadToEnd();
sw = File.CreateText(PdfSavePath);
sw.WriteLine(result);
sw.Close();
Response.WriteFile(PdfSavePath);
}
catch (Exception ex)
{
SendEmail.SendErrorMail("CreateTemportHtmlFile method : ", ex.Message + ex.StackTrace, objExpDetails);
}
return htmlpath;
}
private void HtmlToPdf(string website, string destinationFile, string path)
{
try
{
string hrmlPath = ConfigurationManager.AppSettings["pdfUrlPath"].ToString() + "/user/UserPdfReports/FooterPdfReports.html";
ProcessStartInfo startInfo = new ProcessStartInfo();
string switches = "";
switches += "--header-html " + path + " --footer-html " + hrmlPath;
startInfo.UseShellExecute = false;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardError = true;
startInfo.CreateNoWindow = true;
startInfo.FileName = "C:\\Program Files\\wkhtmltopdf\\bin\\wkhtmltopdf.exe";
startInfo.Arguments = switches + " " + website + " " + destinationFile;
Process myProcess = Process.Start(startInfo);
string error = myProcess.StandardError.ReadToEnd();
myProcess.WaitForExit();
myProcess.Close();
objZip.AddFile(destinationFile, "Files");
myProcess.Dispose();
myProcess = null;
}
catch (Exception ex)
{
//SendEmail.SendErrorMail("HtmlToPdf : ", ex.Message + ex.StackTrace, objExpDetails);
}
}

Exception Occurs While Opening a Downloaded Excel Sheet(.xls) In Asp.Net

I download an Excel Sheet by using the following code.
The above code is starting code of my logic.After downloaded, I open the Excel Sheet.It shows an Warning like this
Because of this warning,when Im trying to upload the same page to Mysql DataBase using Asp.Net.It shows an Exception like "Page is not in correct Format".
This Is My Entire Logic For Downloading an Excel Sheet
protected void download_Click(object sender, EventArgs e)
{
ExportToExcel(SqlDataSource1, "StudentMarks");
}
public void ExportToExcel(SqlDataSource dataSrc, string fileName)
{
//Add Response header
Response.Clear();
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/ms-excel";
//GET Data From Database
MySqlConnection cn = new MySqlConnection(dataSrc.ConnectionString);
// string query = dataSrc.SelectCommand.Replace("\r\n", " ").Replace("\t", " ");
MySqlCommand cmd9 = new MySqlCommand("select subject from class_subject where standard='" + DropDownList1.SelectedItem.Value + "';", cn);
// cn.Open();
//DataSet ds9=new DataSet();
MySqlDataAdapter da9 = new MySqlDataAdapter(cmd9);
// da9.Fill(ds9);
DataTable dt = new DataTable();
da9.Fill(dt);
StringBuilder sb9 = new StringBuilder();
for (int count = 0; count < dt.Rows.Count; count++)
{
// string headerRowText = GridView4.HeaderRow.Cells[i].Text;
sb9.Append("'");
sb9.Append(dt.Rows[count][0].ToString());
sb9.Append("'");
if (count < dt.Rows.Count - 1)
//if (count < count3 - 1)
{
sb9.Append(",");
}
}
Label2.Text = sb9.ToString();
//MySqlCommand fyearcmd = new MySqlCommand("select fyear from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and completed_status='running';", cn);
//MySqlDataReader fyeardr = fyearcmd.ExecuteReader();
string query = "select Admission_Num,Name,'Standard','Fyear','Type_of_exam'," + sb9.ToString() + " from student_data where standard='" + DropDownList1.SelectedItem.Value + "' and fyear='" + DropDownList4.SelectedItem.Value + "';";
MySqlCommand cmd = new MySqlCommand(query, cn);
cmd.CommandTimeout = 999999;
cmd.CommandType = CommandType.Text;
try
{
cn.Open();
MySqlDataReader dr = cmd.ExecuteReader();
StringBuilder sb = new StringBuilder();
//Session["fieldcount"] = dr.FieldCount.ToString();
//Label1.Text = dr.FieldCount.ToString();
//Add Header
int count3 = 4;
for (int count = 0; count < dr.FieldCount; count++)
//for (int count = 0; count < count3; count++)
{
if (dr.GetName(count) != null)
sb.Append(dr.GetName(count));
if (count < dr.FieldCount - 1)
//if (count < count3 - 1)
{
sb.Append("\t");
}
}
Response.Write(sb.ToString() + "\n");
Response.Flush();
//Append Data
while (dr.Read())
{
sb = new StringBuilder();
//for (int col = 0; col < dr.FieldCount - 1; col++)
for (int col = 0; col <= count3; col++)
{
if (col < (count3 - 2))
{
if (!dr.IsDBNull(col))
sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append("\t");
}
if (col == (count3 - 2))
{
if (!dr.IsDBNull(col))
sb.Append(DropDownList1.SelectedItem.Text);
sb.Append("\t");
}
if (col == (count3 - 1))
{
if (!dr.IsDBNull(col))
{
//sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(DropDownList4.SelectedItem.Text);
}
sb.Append("\t");
}
if (col == count3)
{
if (!dr.IsDBNull(col))
{
//sb.Append(dr.GetValue(col).ToString().Replace(",", " "));
sb.Append(DropDownList3.SelectedItem.Text);
}
sb.Append("\t");
}
}
//if (!dr.IsDBNull(dr.FieldCount - 1))
// sb.Append(dr.GetValue(dr.FieldCount - 1).ToString().Replace(",", " "));
Response.Write(sb.ToString() + "\n");
Response.Flush();
}
dr.Dispose();
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
cmd.Connection.Close();
cn.Close();
}
Response.End();
}
So Please give me the suggestion how to download the Excel Sheet with out showing errors while opening.
You you are generating a csv file, not a excel file. Try to change you header:
Response.ContentType = "text/csv";
Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");
Normally excel is default for opening csv files.

Saving Multiple Image Path url in Database at once

My multiple image upload code works fine. But while inserting the image path url in the database only one image path is saved. How can i save all the image path url's at once.
Here is my GetPictureData()
public string GetPictureData()
{
string retFileName = "";
try
{
if (((FileUpload1.PostedFile != null)))
{
if ((FileUpload1.PostedFile.ContentType.ToUpper().Contains("IMAGE")))
{
HttpFileCollection hfc = Request.Files;
for (int i = 0; i < hfc.Count; i++)
{
HttpPostedFile hpf = hfc[i];
if (hpf.ContentLength > 0)
{
//Stream inStream = hpf.InputStream;
//byte[] fileData = new byte[hpf.ContentLength];
//inStream.Read(fileData, 0, hpf.ContentLength);
String sTimeStamp = GetTimeStamp();
string iFileName = System.IO.Path.GetFileName(hpf.FileName);
string newFileName = iFileName.Replace(" ", "_");
string OutFile = Server.MapPath(ConfigurationManager.AppSettings["LocalImageDirectory"]) + "\\" + sTimeStamp + "_" + newFileName;
hpf.SaveAs(OutFile);
OutFile = ConfigurationManager.AppSettings["LocalImageDirectory"] + "\\" + sTimeStamp + "_" + newFileName;
retFileName = OutFile;
}
}
}
}
}
catch(Exception ex)
{
string msg = ex.Message;
Response.Write(msg);
}
return retFileName;
}
and here is my UploadButton code
protected void btnUpload_Click(object sender, EventArgs e)
{
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
}
}
Thanks
You error lies in the fact that the GetPictureData loops over a collection of files, but only the last file is returned to the button event where you call the save to database code. Of course, only the last file will be saved in the database.
The workaround is to create a standalone method to save in the database where you pass the filename and the localAuctionID. You call this method inside the GetPictureData (renamed more correctly to SavePictureData) internal loop for each file to be saved
As a pseudocode (not tested)
private void SaveToDb(int localAutID, string filepath)
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) " +
"values(#auID, #file, 0); " +
" update auctionstep1 set ListingStatus = 'Photographed' " +
"where auctionid = #auID and (listingstatus <> 'Created' " +
"AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
DbParameter p1 = cmd.CreateParameter()
{ParameterName="#auID", DbType=DbType.Int32, Value=localAutID};
DbParameter p2 = cmd.CreateParameter()
{ParameterName="#file", DbType=DbType.AnsiString, Value=filepath};
db.ExecuteNonQuery(cmd);
}
And if SavePictureData call it inside the for loop
for (int i = 0; i < hfc.Count; i++)
{
.....
retFileName = OutFile;
SaveToDb(Convert.ToInt32(Session["localauctionid"]), retFileName);
}
if (Session["localauctionid"] != null && Session["localauctionid"].ToString() != "")
{
string filepath = GetPictureData();
if (filepath != "")
{
string sqlcommand = " insert into auctionimages (auctionid, ImagePath, GalleryPic) values(" + Session["localauctionid"].ToString() + ",'" + filepath + "', 0);" +
" update auctionstep1 set ListingStatus = 'Photographed' where auctionid = " + Session["localauctionid"].ToString() + " and (listingstatus <> 'Created' AND listingstatus <> 'Saved');";
Database db = DatabaseFactory.CreateDatabase();
DbCommand cmd = db.GetSqlStringCommand(sqlcommand);
db.ExecuteNonQuery(cmd);
LoadImages();
}
The person only clicks the upload button once - hence only one image being saved.
Personally I would evaluate the way you have coded this. I would move the code you use to save the image to the db into a stand alone method and call it when the image upload is complete in GetPictureData()

Resources