asp losing session after FileUpload - c#

When I upload file to my website I loss the session, and the user should login again?
This my code
if (FileUploadControl.HasFile) {
string filename = Path.GetFileName(FileUploadControl.FileName);
string newFileName = Path.Combine(Path.GetDirectoryName(filename),
string.Concat(words[0], DateTime.Now.ToString("_yyyy_MM_dd_HH_mm_ss"),
Path.GetExtension(filename)));
Session["login"] = us.Email;
Session["Id"] = us.Id;
string location = usDetail.FolderLink.Trim();
FileUploadControl.SaveAs(Server.MapPath(location) + newFileName);
lblResult.Text = "the file" + newFileName + " has uploaded";
var dateAndTime = DateTime.UtcNow;
var date = dateAndTime.Date;
var fp = new FileUpoads(usDetail.Id, DropDownList2.SelectedValue.ToString().Trim(),
location + newFileName, date);
string f = ConnectionClass.FileUplud(fp);
lblResult.Text = f;
}

Related

how to show pdf in new windows from local path

I have converted a rpt file to pdf and saved it in a local system path via web.config and trying to open the pdf file after saving it , from the saved location. I am able to save it in the required folder and able to redirect the folder path to the new windows , but the folder path is appearing with out the '\' and with drive letter as small case
this is my code
var clsPrepareFile = new clsPrepareFile(General.ConnString());
dsUserMatrixReport = clsPrepareFile.UserGroupReport(sValue);
if (dsUserMatrixReport != null && dsUserMatrixReport.Tables.Count > 1 && dsUserMatrixReport.Tables[0].Rows.Count > 0 && dsUserMatrixReport.Tables[1].Rows.Count > 0)
// if (dsUserMatrixReport != null )
{
dsUserMatrixReport.Tables[0].TableName = "Inward_Report1";
dsUserMatrixReport.Tables[1].TableName = "UserStatus";
var rptDocument = new ReportDocument();
//rptDocument.SummaryInfo.ReportTitle = "Inward_Report_" + txtFromDate.Text.Replace("/", "") + "_" + txtToDate.Text.Replace("/", "");
CrystalReportViewer1.Visible = true;
//CrystalReportViewer1.ID = "Inward_Report_" + txtFromDate.Text.Replace("/", "") + "_" + txtToDate.Text.Replace("/", "");
rptDocument.Load(Server.MapPath("~\\Report\\UserGroupReport.rpt"));
rptDocument.SetDataSource(dsUserMatrixReport);
Session.Add("CR_Session", rptDocument);
CrystalReportViewer1.ReportSource = rptDocument;
string filePath = ConfigurationManager.AppSettings["ReportPdfPath"].ToString();
string filename = "UserGroupReport" + DateTime.Now.ToString("yyyyMMdd") + ".pdf";
string pdfname = filePath + filename;
rptDocument.ExportToDisk(ExportFormatType.PortableDocFormat, pdfname);
ScriptManager.RegisterClientScriptBlock(this.Page, typeof(string), "newwindow", "window.open('" + pdfname + "', '_blank')", true);
the script manager is redirecting to anew page and the url appears like this
"c:GeneratedPDFUserGroupReport20200415.pdf"

Access to the path 'Enrollments.zip' is denied, After running Background service running

After I restart my PC, my background service works fine. If I reinstalled or made any changes to the DB, my PC access path ".zip" denied. one more thing same background is running in another PC.
Two background services running in two different PCs to exchange the data.
Here's the code:
public void GetFilesFromWebAPIAndCountTemplates(DateTime startTime,DateTime endTime,string webAPIURL,string code,string localPath)
{
ZipLocationsCount zipLocation = null;
count = 0;
if (startTime < endTime)
{
WebApiCall apiCall = new WebApiCall();
Thread.Sleep(10000);
var zipByteResponse = apiCall.CallZipWebApi(webAPIURL, "api/ZIPEnrollmentsDownload/ZIPResponse?startTime=" + startTime + "&endTime=" + endTime+ "&locationCode="+code, null, Constants.Get);
lgmr.Log(string.Concat(serviceName, " ", code, ": Get Response From WebAPI successfully"), LoggingManager.LogType.Info);
if (zipByteResponse.Result != null && zipByteResponse.Result.Length > 0)
{
string fileName = code + "_Enrollments.zip";
try
{
ConvertIntoZipAndMoveToBackUp(localPath, fileName, zipByteResponse.Result, code);
}
catch(Exception ex)
{
//GetFilesFromWebAPIAndCountTemplates(startTime, endTime, webAPIURL, code, localPath);
ecount = 0;
strECount = "Fail to Zip";
lgmr.Log(string.Concat(serviceName, " ", code, " count:", ecount, ": Failed to Converted to ZIP", ex.StackTrace, ex.InnerException, ex.Message), LoggingManager.LogType.Error);
goto label1;
}
}
else
{
ecount = 0;
if(ecount == 0)
{
strECount = "No Enrolments";
}
lgmr.Log(string.Concat(serviceName, " ", code, ": No Enrollments"), LoggingManager.LogType.Info);
}
}
else
{
lgmr.Log(string.Concat(serviceName, " ",code, ": Start Date Should be lass than End Date"), LoggingManager.LogType.Info);
}
FPSyncHistory fpSync = new FPSyncHistory();
fpSync.LocationCode = code;
fpSync.FromDate = startTime;
fpSync.ToDate = endTime;
fpSync.FPExported = ecount;
fpSync.Status = true;
fpSync.CreatedBy = 1;
fpSync.CreatedOn = DateTime.Now;
fPSyncHistories.Add(fpSync);
label1:
zipLocation = new ZipLocationsCount() { LocationCode = code, FromDate = startTime, ToDate = endTime, EnrollmentsCount = strECount };
if (zipLocation.FromDate < zipLocation.ToDate)
{
zipLocationsCounts.Add(zipLocation);
}
}
the Above Method i am calling into another method
public void GetZipResponseFromWebAPI()
{
try
{
zipLocationsCounts = new List<ZipLocationsCount>();
fPSyncHistories = new List<FPSyncHistory>();
DateTime sTime = new DateTime();
DateTime startTime = new DateTime();
DateTime eTime = new DateTime();
DateTime endTime = new DateTime();
foreach (FPSyncLocationDetail fpLocation in tmlEntity.FPSyncLocationDetails)
{
var findHistory = tmlEntity.FPSyncHistories.FirstOrDefault(x => x.LocationCode == fpLocation.Code);
if (findHistory == null)
{
if(fpLocation.Status == true)
{
sTime = DateTime.Now.AddDays(-1);
startTime = new DateTime(sTime.Year, sTime.Month, sTime.Day, 00, 00, 00);
eTime = DateTime.Now.AddDays(-1);
endTime = new DateTime(eTime.Year, eTime.Month, eTime.Day, 23, 59, 59);
GetFilesFromWebAPIAndCountTemplates(startTime,endTime,fpLocation.WebAPIURL,fpLocation.Code,fpLocation.LocalFPFolderPath);
}
}
else if (findHistory != null)
{
var locationLastDates = from n in tmlEntity.FPSyncHistories
group n by n.LocationCode into g
select new { LocationCode = g.Key, ToDate = g.Max(t => t.ToDate) };
foreach (var loc in locationLastDates)
{
if (fpLocation.Code == loc.LocationCode)
{
if (fpLocation.Status == true)
{
sTime = loc.ToDate.AddDays(1);
startTime = new DateTime(sTime.Year, sTime.Month, sTime.Day, 00, 00, 00);
eTime = DateTime.Now.AddDays(-1);
endTime = new DateTime(eTime.Year, eTime.Month, eTime.Day, 23, 59, 59);
GetFilesFromWebAPIAndCountTemplates(startTime, endTime, fpLocation.WebAPIURL, fpLocation.Code, fpLocation.LocalFPFolderPath);
}
}
}
}
}
}
catch (Exception ex)
{
string InnerException = ex.InnerException != null ? ex.InnerException.ToString() : "";
lgmr.Log(string.Concat("Error at GetZipResponseFromWebAPI", ex.StackTrace, ex.InnerException, ex.Message), LoggingManager.LogType.Error);
return;
}
}
finally CallWebAPI method logic below
public async Task<byte[]> CallZipWebApi(String WebApiUri, String uri, StringContent obj, string type)
{
try
{
count++;
HttpResponseMessage resMeg;
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
client.BaseAddress = new Uri(WebApiUri);
lgmr.Log(string.Concat(uri,": Sending Request to WebAPI"), LoggingManager.LogType.Info);
if (type == Constants.Get)
{
resMeg =await client.GetAsync(uri);
}
else
{
resMeg =await client.PostAsync(uri, obj);
}
lgmr.Log(string.Concat(uri,": Receive Response From WebAPI"), LoggingManager.LogType.Info);
var Bytes =await resMeg.Content.ReadAsByteArrayAsync();
//byte[] mybyteArray = null;
//Task<byte[]> Bytes = ProcessURLAsync(uri,client);
lgmr.Log(string.Concat(": Read the Data from WebAPI Response"), LoggingManager.LogType.Info);
return Bytes;
}
}
}
public void ConvertIntoZipAndMoveToBackUp(string localPath, string fileName, byte[] zipByteResponse, string code)
{
string Destinationpath = ConfigurationManager.AppSettings["OtherEnrollmentsBackUpPath"] + "\\" + code;
try
{
ZipArchive archive = null;
if (File.Exists(localPath + "\\" + fileName))
{
File.Delete(localPath + "\\" + fileName);
}
archive = ZipFile.Open(localPath + "\\" + fileName, ZipArchiveMode.Create);
archive.Dispose();
lgmr.Log(string.Concat(serviceName, " ", code, ": Zip File Created", localPath + "\\" + fileName), LoggingManager.LogType.Info);
File.WriteAllBytes(localPath + "\\" + fileName, zipByteResponse);
lgmr.Log(string.Concat(serviceName, " ", code, ": Download Zipfile from the WebAPI Response"), LoggingManager.LogType.Info);
archive = ZipFile.OpenRead(localPath + "\\" + fileName);
ecount = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
strECount = ecount.ToString();
lgmr.Log(string.Concat(serviceName, " ", code, ": Files Count: ",ecount, localPath + "\\" + fileName), LoggingManager.LogType.Info);
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (File.Exists(localPath + "\\" + entry.Name))
{
File.Delete(localPath + "\\" + entry.Name);
}
entry.ExtractToFile(localPath + "\\" + entry.Name);
}
archive.Dispose();
File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("Enrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now));
}
catch (Exception ex)
{
//File.Delete(localPath + "\\" + fileName);
//File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("ZipErrorEnrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now));
ecount = 0;
lgmr.Log(string.Concat(serviceName, " ", code, " ECount:", ecount, ": Failed to ZIP", localPath + "\\" + fileName, "Resend the Request to WebAPI ", ex.Message), LoggingManager.LogType.Info);
throw ex;
}
}
A few things that you can look at.
First, use the using statement to create the archive, that will make sure that it gets disposed.
Second, why do you check if the file exists, delete it, then create it with ZipFile just to Write it with File? Look at this
Third, use Path class. It will make sure that all your backslashed is correct, and it looks neater.
Fourth, check if a file can be created in the folder
Check if this code gives you the same result.
public void ConvertIntoZipAndMoveToBackUp(string localPath, string fileName, byte[] zipByteResponse, string code)
{
string Destinationpath = Path.Combine(ConfigurationManager.AppSettings["OtherEnrollmentsBackUpPath"], code);
try
{
fileName = Path.GetFileNameWithoutExtension(fileName) + DateTime.Now.ToString("yyyy-MM-dd_hh-mm-ss.fff") + ".zip"; //This will ensure that you have a unique filename to create
File.WriteAllBytes(Path.Combine(localPath, fileName), zipByteResponse);
lgmr.Log(string.Concat(serviceName, " ", code, ": Zip File Created and Downloaded from the WebAPI Response", Path.Combine(localPath, fileName)), LoggingManager.LogType.Info);
using (var archive = ZipFile.OpenRead(Path.Combine(localPath, fileName)))
{
ecount = archive.Entries.Count(x => !string.IsNullOrWhiteSpace(x.Name));
strECount = ecount.ToString();
lgmr.Log(string.Concat(serviceName, " ", code, ": Files Count: ",ecount, localPath + "\\" + fileName), LoggingManager.LogType.Info);
foreach (ZipArchiveEntry entry in archive.Entries)
{
if (File.Exists(Path.Combine(localPath, entry.Name)))
{
File.Delete(Path.Combine(localPath, entry.Name));
}
entry.ExtractToFile(Path.Combine(localPath, entry.Name));
}
}
File.Move(Path.Combine(localPath, fileName), Path.Combine(Destinationpath, code + string.Format("Enrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now)));
}
catch (Exception ex)
{
//File.Delete(localPath + "\\" + fileName);
//File.Move(localPath + "\\" + fileName, Destinationpath + "\\" + code + string.Format("ZipErrorEnrollments-{0:yyyy-MM-dd_hh-mm-ss.fff}.zip", DateTime.Now));
ecount = 0;
lgmr.Log(string.Concat(serviceName, " ", code, " ECount:", ecount, ": Failed to ZIP", localPath + "\\" + fileName, "Resend the Request to WebAPI ", ex.Message), LoggingManager.LogType.Info);
throw ex;
}
}

how to create .txt file and write it c# asp.net

I am trying create and write to a text file in a C# application using the following code
System.IO.Directory.CreateDirectory(Server.MapPath("~\\count"));
using (System.IO.FileStream fs = new System.IO.FileStream("~/count/count.txt", System.IO.FileMode.Create))
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("~/count/count.txt"))
{
sw.Write("101");
}
string _count = System.IO.File.ReadAllText("~/count/count.txt");
Application["NoOfVisitors"] = _count;
but I get an error:
The process cannot access the file 'path' because it is being used by another process.
What is my error?
You're trying to open the file twice; your first using statements creates a FileStream that is not used, but locks the file, so the second using fails.
Just delete your first using line, and it should all work fine.
However, I'd recommend replacing all of that with File.WriteAllText, then there would be no using in your code, it'd be much simpler.
var dir = Server.MapPath("~\\count");
var file = Path.Combine(dir, "count.txt");
Directory.CreateDirectory(dir);
File.WriteAllText(file, "101");
var _count = File.ReadAllText(file);
Application["NoOfVisitors"] = _count;
private void ExportTextFile()
{
#region This region Used For Private variable.
string lblName = null;
string lblACN = null;
string lblIFSC = null;
string lblBCode = null;
string lblAdd1 = null;
string lblAdd2 = null;
string lblAdd3 = null;
string lblMobileNo = null;
string lblEmai = null;
#endregion
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/text";
StringBuilder Rowbind = new StringBuilder();
for (int i = 0; i < GrdAcc.Rows.Count; i++)
{
CheckBox Chk_Status = (CheckBox)GrdAcc.Rows[i].FindControl
("ChkStatus");
Label lbl_Status = (Label)GrdAcc.Rows[i].FindControl
("lblStatus");
Label lbl_Code = (Label)GrdAcc.Rows[i].FindControl
("lblEmpCode");
if (Chk_Status.Checked == true)
{
#region Fetching ACC Details From Database.
AccPL.Status = lbl_Status.Text;
AccPL.EmpCode = lbl_Code.Text;
DataTable dt = AccBL.ExportFileAcc(AccPL);
if (dt.Rows.Count > 0)
{
lblName = dt.Rows[0]["Name"].ToString().Trim();
lblACNo = dt.Rows[0]["ACNo"].ToString().Trim();
lblBCode = dt.Rows[0]["BCode"].ToString().Trim();
lblIFSC = dt.Rows[0]["IFSC"].ToString().Trim();
lblAdd1 = dt.Rows[0]["ADd1"].ToString() + dt.Rows[0]
["PPostTehsil"].ToString();
lblAdd2 = dt.Rows[0]["Add2"].ToString().Trim() +
dt.Rows[0]["PPIN"].ToString().Trim();
lblAdd3 = dt.Rows[0]["Add3"].ToString() + dt.Rows[0]
["State"].ToString().Trim();
lblMobileNo = dt.Rows[0]["MobileNo"].ToString().Trim();
lblEmai = dt.Rows[0]["Email"].ToString().Trim();
}
#endregion
#region Generating Text File .
if (ddlExportType.SelectedValue == "2")
{
Response.AddHeader("content-disposition", "
attachment;filename=" + DateTime.Now.ToString("ddMMyyhhmmss") + ".txt");
Rowbind.Append(lblName + "#" + lblAccNo + "#" + lblIFSC
+ "#" + "#" + "#" + "#" + "#" + "#" + lbl_Code.Text);
Rowbind.Append("\r\n");
}
#endregion
Response.Output.Write(Rowbind.ToString());
Response.Flush();
Response.End();
}

Change filename on file upload in .net (asp)

How to change file name on upload ?
I have such code :
<%# WebHandler Language="C#" Class="Upload" %>
using System;
using System.Web;
using System.IO;
public class Upload : IHttpHandler {
public void ProcessRequest(HttpContext context) {
HttpPostedFile oFile = context.Request.Files["Filedata"];
string newFileName1 = HttpContext.Current.Server.MapPath(#context.Request["orderID"]);
string newFileName2 = HttpContext.Current.Server.MapPath(#context.Request["productCombinationString"]);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + oFile.ContentType;
} else {
newName = newFileName1 + oFile.ContentType;
}
string sDirectory = HttpContext.Current.Server.MapPath(#context.Request["folder"]);
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
context.Response.Write("1");
}
public bool IsReusable {
get { return false; }
}
}
And if i change oFile.Filename to newName it does not work ... what is the problem ? :)
Thank you
You can pass your Custom File Name along with Directory to SaveAs Method
oFile.SaveAs(sDirectory + "/" + "abc");
try:
// Get the extension of the uploaded file.
string fileName = Server.HtmlEncode(FileUpload1.FileName);
string extension = System.IO.Path.GetExtension(fileName);
string newName;
if(newFileName2 != "" && newFileName2 != null && newFileName2 != "<!--#Ecom:productCombinationString-->") {
newName = newFileName1 + newFileName2 + extension ;
} else {
newName = newFileName1 + extension ;
}
oFile.SaveAs(sDirectory + "/" + newName );
I haven't tried this code but I do want to point out two things of from the original code:
The first is this order of operations:
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
if (!Directory.Exists(sDirectory)) Directory.CreateDirectory(sDirectory);
I believe it should be this instead. In the above sequence, there is a potential edge case of saving into a non-existing folder. This ensures that the folder is created:
if (!Directory.Exists(sDirectory))
{
Directory.CreateDirectory(sDirectory);
}
oFile.SaveAs(sDirectory + "/" + oFile.FileName);
The other thing is that you might be running into issues with / as the path separator. I think it should be much safer to do something like:
var saveLocation = Path.Combine(sDirectory, oFile.FileName);
oFile.SaveAs(saveLocation);
I hope this helps!
Here is an example i used when saving an image look at the save as section
////saving file in the physical folder;
FileUpload FileUpload1 = file_Image;
string virtualFolder = "~/Resourceimages/";
string physicalFolder = HostingEnvironment.MapPath(virtualFolder);
string PhotoName = ((string)Session["UserName"] + (string)Session["UserSurname"]);
FileUpload1.SaveAs(physicalFolder + PhotoName + FileUpload1.FileName);
string location = virtualFolder + PhotoName + FileUpload1.FileName;
webservice.UpdateResourceImage((int)Session["UserID"], location);
lbl_Result.Text = "Your file " + FileUpload1.FileName + " has been uploaded.";
Image1.Visible = true;
Image1.ImageUrl = location;
string uploadFolder = Request.PhysicalApplicationPath + "UploadFile\\";
if (FileUpload1.HasFile)
{
string extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
FileUpload1.SaveAs(uploadFolder + "Test"+ extension);
Label1.Text = "File uploaded successfully as: " + "Test"+ extension;
}
else
{
Label1.Text = "First select a file.";
}
private string UpdateFilename(string filename)
{
try
{
filename = Server.HtmlEncode(FUJD.FileName);
string extension = System.IO.Path.GetExtension(filename);
filename = filename.Replace(extension, "");
return filename + '-' + DateTime.Now.ToString("yyyyMMddHHmmss") + extension;
}
catch (Exception ex)
{
throw ex;
}
}

retrieve username and nickname from active directory on local network

I want to read the username and NickName of any users on my local network from server's active directory. How can I do it? Thanks alot.
public void getUser()
{
DirectoryServices.SearchResult myResult;
string filterString = string.Empty;
string EntryString = "LDAP:// <Your AD Domain here>";
DirectoryServices.DirectorySearcher myDirectorySearcher = new DirectoryServices.DirectorySearcher(new DirectoryServices.DirectoryEntry(EntryString, "Username", "Password"));
string tempStr;
string[] splStr = new string[3];
filterString = "(sAMAccountName=" + Username + ")";
myDirectorySearcher.Filter = filterString;
myDirectorySearcher.PropertiesToLoad.Add("cn");
myResult = myDirectorySearcher.FindOne();
splStr = Regex.Split(myResult.Properties("cn").Item(0).ToString, " ");
tempStr = splStr(1).ToString + " " + splStr(0).ToString;
Label1.Text = "Hello " + tempStr;
}

Categories

Resources