ASP.NET MVC session gets null after IO operation - asp.net

Here is the code I wrote.
if (propertyModel.PropertyName.Replace(" ", "") != model.PropertyName.Replace(" ", "") && propertyModel.PropertyRegistrationCompletedPercentage >= 71)
{
var originalDirectory = new DirectoryInfo(string.Format("{0}Images\\ProprtyImages", Server.MapPath(#"\")));
string pathString = System.IO.Path.Combine(originalDirectory.ToString(), propertyModel.PropertyName.Replace(" ", "") + "__" + User.Identity.GetUserId().Replace("-", "") + "__" + "propertyid" + "__" + propertyModel.PropertyId.ToString());
string newpathstring = System.IO.Path.Combine(originalDirectory.ToString(), model.PropertyName.Replace(" ", "") + "__" + User.Identity.GetUserId().Replace("-", "") + "__" + "propertyid" + "__" + propertyModel.PropertyId.ToString());
bool isExists = System.IO.Directory.Exists(pathString);
if (isExists)
{
Directory.Move(pathString, newpathstring);
}
else
{
ViewBag.Message = "Unexpected IO error occurred.";
return View("ErrorPageWithCustomMessage");
}
}
Session["PropertyRegistrationCompletedPercentage"] = propertyModel.PropertyRegistrationCompletedPercentage;
Session["IsPropertyBeingStartedToAdd"] = propertyModel.IsPropertyBeingStartedToAdd;
Session["IsPropertyAddingCompleted"] = propertyModel.IsPropertyAddingCompleted;
Session["IsThePropertyVerified"] = propertyModel.IsThePropertyVerified;
When I try to retrieve session variable after redirecting in to an another action those values are gone how to fix this?

Related

Unable to convert string to date (dd/MMM,YYYY) format ASP.NET

var LR_No_Of_Days = "";
$("#DateRange").jqxDateTimeInput({ width: 250, height: 25, selectionMode: 'range' }); $("#DateRange").on('change', function (event) {
var selection = $("#DateRange").jqxDateTimeInput('getRange');
if (selection.from != null) {
$("#selection").html("<div>From: " + selection.from.toLocaleDateString() + " <br/>To: " + selection.to.toLocaleDateString() + "</div>");
}
var LR_Request_Date_From = selection.from.toLocaleDateString();
var LR_Request_Date_To = selection.to.toLocaleDateString();
$('#LR_Request_Date_From').val(LR_Request_Date_From);
$('#LR_Request_Date_To').val(LR_Request_Date_To);
NoOfdays();
function NoOfdays() {
var LR_No_Of_Days = Math.floor((Date.parse(LR_Request_Date_To) - Date.parse(LR_Request_Date_From)) / 86400000); if (LR_No_Of_Days == '0') {LR_No_Of_Days = 1;} else { LR_No_Of_Days-1; }; alert(LR_Request_Date_From + " &&& " + LR_Request_Date_To + " No of days:" + LR_No_Of_Days);
$("#LR_No_Of_Days").val(LR_No_Of_Days);}});
I'm unable to convert the string variable(LR_Request_Date_From and LR_Request_Date_To) to date format. I receive error converting string to date.
You have to use MM instead of mm and CultureInfo.InvariantCulture as second parameter
string dt = DateTime.Parse(txtVADate.Text.Trim()).ToString("MM/dd/yyyy", CultureInfo.InvariantCulture);

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);
}
}

how we get Uncheckitems CheckBoxList control in asp.net 3.5?

when user uncheckitems items.how we get that uncheckitems
for (int i = 0; i < ChkLstUserRoles.Items.Count; i++)
{
if (ChkLstUserRoles.Items[i].Selected == true)
{
URoles = URoles + "|" + ChkLstUserRoles.Items[i].Value;
ActivityLog = ActivityLog + "Grant the " + ChkLstUserRoles.Items[i].Text + " to user [" + CboUserName.Text + "]çGrantRole|";
}
}
Use this condition,
ChkLstUserRoles.Items[i].Selected == false

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()

How to create thumbnail of video (extension.wmv,.avi)

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....

Resources