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);
}
}
Related
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)
//{
//}
}
My application is hosted on IIS running on windows 2008R2.Code to send mail is mentioned below.
public bool SendMail(string to, string cc, string subject, string body)
{
bool abc = false;
System.Net.Mail.SmtpClient smtpClient = null;
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
bool IsSSLfailed = false;
bool allPortsFailed = false;
bool SSLEnabled = false;
bool CertificateByPassed = false;
smtpClient = new System.Net.Mail.SmtpClient();
again: try
{
// SmtpClient smtpserver = new SmtpClient("smtp.gmail.com", 25);
string from = ConfigurationSettings.AppSettings.Get("UserName");
string Password = ConfigurationSettings.AppSettings.Get("Password");
message.From = new MailAddress(from);
message.To.Add(to);
message.Subject = subject;
message.IsBodyHtml = true;
message.Body = body;
message.Subject = WebUtility.HtmlEncode(subject);
message.SubjectEncoding = Encoding.UTF8;
message.IsBodyHtml = true;
message.Body = WebUtility.HtmlDecode(body);
message.BodyEncoding = Encoding.UTF8;
smtpClient.Timeout = 10000;
message.SubjectEncoding = Encoding.UTF8;
if (IsSSLfailed)
{
if (smtpClient.Port == 587)
{
smtpClient.Port = 465;
}
else if (smtpClient.Port == 465)
{
smtpClient.Port = 25;
}
else if (smtpClient.Port == 25)
{
smtpClient.Port = 2525;
allPortsFailed = true;
}
}
else
{
smtpClient.Port = 587;
}
smtpClient.EnableSsl = SSLEnabled;
if (!CertificateByPassed)
{
BypassCertificateError();
}
System.Net.NetworkCredential nc = new System.Net.NetworkCredential(from, Password);
smtpClient.Credentials = nc;
smtpClient.Send(message);
abc = true;
}
catch (System.Net.Mail.SmtpFailedRecipientException ex)
{
IsSSLfailed = true;
logger.ErrorFormat("Error occured in SendMail() method,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString()+ " smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " Detailed error:{0}{1}", Environment.NewLine, ex.Message.ToString());
logger.ErrorFormat("Inner Exception", Environment.NewLine, ex.InnerException != null ? ex.InnerException.Message.ToString() : string.Empty);
if (!allPortsFailed)
{
goto again;
}
else if (!SSLEnabled)
{
SSLEnabled = true;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
else if (!CertificateByPassed)
{
CertificateByPassed = true;
SSLEnabled = false;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
this.upForm.Update();
throw ex;
}
catch (System.Net.Mail.SmtpException ex)
{
IsSSLfailed = true;
logger.ErrorFormat("SendMail SmtpException,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString() + " smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " StatusCode:" + ex.StatusCode.ToString() + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.Message.ToString());
logger.ErrorFormat("SendMail Inner ExceptionSmtpException StatusCode:" + ex.StatusCode.ToString() + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.InnerException != null ? ex.InnerException.Message.ToString() : string.Empty);
if (!allPortsFailed)
{
goto again;
}
else if (!SSLEnabled)
{
SSLEnabled = true;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
else if (!CertificateByPassed)
{
CertificateByPassed = true;
SSLEnabled = false;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
this.upForm.Update();
throw ex;
}
catch (Exception ex)
{
IsSSLfailed = true;
logger.ErrorFormat("SendMail error sending mail,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString() +" smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " " + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.Message.ToString());
logger.ErrorFormat("SendMail error sending mail,CertificateBypassed:" + CertificateByPassed.ToString() + " SSLEnabled: " + SSLEnabled.ToString() + " smtp User:" + ((NetworkCredential)smtpClient.Credentials).UserName + " pwd:" + ((NetworkCredential)smtpClient.Credentials).Password + " smtpClient.DeliveryMethod:" + smtpClient.DeliveryMethod.ToString() + " smtpClient.EnableSsl:" + smtpClient.EnableSsl.ToString() + " smtpClient.Host:" + smtpClient.Host.ToString() + " smtpClient.Port:" + smtpClient.Port.ToString() + " smtpClient.UseDefaultCredentials:" + smtpClient.UseDefaultCredentials.ToString() + " " + " " + smtpClient.Port.ToString(), Environment.NewLine, ex.InnerException != null ? ex.InnerException.Message.ToString() : string.Empty);
if (!allPortsFailed)
{
goto again;
}
else if (!SSLEnabled)
{
SSLEnabled = true;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
else if (!CertificateByPassed)
{
CertificateByPassed = true;
SSLEnabled = false;
IsSSLfailed = false;
allPortsFailed = false;
goto again;
}
this.upForm.Update();
throw ex;
}
return abc;
}
public static void BypassCertificateError()
{
try
{
ServicePointManager.ServerCertificateValidationCallback +=
delegate(
Object sender1,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors)
{
return true;
};
}
catch (Exception ex)
{
throw ex;
}
}
As you can see from the code,i've checked all ports that are used to send mail.
This same code works on application hosted on windows 7/8 but doesn't work on windows 2008R2.
Below is the error message i get
SendMail SmtpException,CertificateBypassed:False SSLEnabled: False
smtpClient.DeliveryMethod:Network smtpClient.EnableSsl:False
smtpClient.Host:SMTP.GMAIL.COM smtpClient.Port:587
smtpClient.UseDefaultCredentials:False StatusCode:GeneralFailure
Nothing in innerexception.This same message is repeated for all ports.I am sending this mail via gmail.I've tested with MS Outlook on the server with same gmail account,and it was working properly so i guess firewall ristriction are not applicable in my case.I've also enabled "Access for less secure app" in gmail settings.
McAfee was blocking mail attemps.Never doubted it as i could send the mail from outlook but couldn't do it from my code.Just included w3wp.exe to exclusion in mass mailing
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.
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()
The path of video(extension.wmv,.avi) is stored in SQL Server. And I have to create thumbnail and dispaly it on ASPX page.
Please share its code, if any body know this.
Thanks in Advance
For AVI you can use the below codeproject
http://www.codeproject.com/Articles/7388/A-Simple-C-Wrapper-for-the-AviFile-Library
For others try
http://sourceforge.net/projects/directshownet/
http://code.google.com/p/slimdx/
I have some bit of code for generating thumbnail video.
for that you need to have third party exe named "ffmpeg.exe" which is available for free. you can download from here
Now i have create function below which generate thumbnail video from original video.
you can change variable according to your requirement.
private bool SaveVideo(FileUpload fupload)
{
string VideoResolutionWidth = "400" ; //define video res. width
string VideoResolutionHeight = "280"; //define video res. height
string VideoThumbWidth = "100";//define jpg res. width
string VideoThumbHeight = "100"; //define jpg res. height
string VideoLocation = HttpContext.Current.Server.MapPath("~/ConverterFolder/Video/");
string ConverterPath = HttpContext.Current.Server.MapPath("~/ConverterFolder/");
String LargeFileName = "TestVideo.wmv"; // Thumb Video file name
string ThumbFileName= "Testvideo.jpg";
// Save Original video file first
if (fupload.PostedFile.FileName != "")
{
fupload.PostedFile.SaveAs(ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_")));
}
if (System.IO.File.Exists(ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_"))))
{
string inipath = ConverterPath;
string flvCMD, flvArg;
string a_res_width, a_res_height, a_audioRate, a_frameRate, i_res_width, i_res_height;
a_res_width = VideoResolutionWidth;
a_res_height = VideoResolutionHeight;
i_res_width = VideoThumbWidth;
i_res_height = VideoThumbHeight;
a_audioRate = "22050";
a_frameRate = "15";
string VideoThumbResolution = i_res_width + "x" + i_res_height;
string VideoResolution = a_res_width + "x" + a_res_height;
String videoPATH = VideoLocation + "\\" + LargeFileName.Replace(" ", "_");
flvCMD = ConverterPath + "ffmpeg.exe";
flvArg = "-i " + ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_")) + " -s " + VideoResolution + " -r " + a_frameRate + " -b 7500000 -ar " + a_audioRate + " -ab 48 " + videoPATH;
try
{
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.FileName = flvCMD;
process.StartInfo.Arguments = flvArg;
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
process.Start();
string output = process.StandardOutput.ReadToEnd();
process.Close();
process.Dispose();
if (System.IO.File.Exists(videoPATH))
{
Process process1 = new Process();
process1.StartInfo.UseShellExecute = false;
process1.StartInfo.RedirectStandardOutput = true;
process1.StartInfo.RedirectStandardError = true;
process1.StartInfo.CreateNoWindow = true;
process1.StartInfo.FileName = flvCMD;
process1.StartInfo.Arguments = "-i " + ConverterPath + "\\" + System.IO.Path.GetFileName(fupload.PostedFile.FileName.Replace(" ", "_")) + " -an -ss 00:00:01 -r 1 -vframes 1 -s " + VideoThumbResolution + " -f mjpeg -y " + VideoLocation "\\" + ThumbFileName;
process1.Start();
string outputMeta1 = process1.StandardOutput.ReadToEnd();
process1.Close();
process1.Dispose();
}
else
{
return false;
}
}
catch (Exception)
{
}
}
return true;
}
Hope this will help you. happy coding....