I'm creating a C# application with a ASP.net frontend, however I'm having a problem at the moment. I want to the user to enter some information, which once submitted, will be displayed within a listbox on the page which works fine. However, once I close the page, stop debugging the program and run it again - the information is still displayed but I want it to start off blank. Here if the ASPX page that I think if causing the issue, it's driving me mad.
public partial class CarBootSaleForm : System.Web.UI.Page, ISaleManagerUI
{
private SaleList saleList;
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && Application["SaleList"] != null)
{
LoadData();
}
else
{
saleList = (SaleList)Application["SaleList"];
}
if (saleList != null)
{
UpdateListbox();
}
}
private void UpdateListbox()
{
lstSales.Items.Clear();
if (saleList != null)
{
for (int i = 0; i < saleList.Count(); i++)
{
lstSales.Items.Add(new ListItem(saleList.getSale(i).ToString()));
}
}
}
protected void btnAdd_Click(object sender, EventArgs e)
{
Application.Lock();
Application["SaleList"] = saleList;
Application.UnLock();
Response.Redirect("AddSaleForm.aspx");
}
}
Forget the LoadData() within the page load as it's not actually loading anything at the moment :)
Any help is really appreciated!
The variables stored in Application state are not flushed unless you restart the web server, so you will need to use the iisreset commmand (on command-line) if you are using IIS, or you will need to stop the ASP.NET web server (use the tray icons) after each debugging session.
if it is not postback you can add
Session.Abandon(); in the else block in Page_load.
Kill Session:
How to Kill A Session or Session ID (ASP.NET/C#)
Related
from a webform file named pointA.aspx where a cookie will be initialized and sent to the webform pointB.aspx that will receive and consume that cookie.
The way the cookie is sent will be through the click event of a button where it will be redirected to the webform pointB.
I need to implement the corresponding logic so that once said cookie is sent to the webform pointB.aspx, it cannot return or access the webform pointA.aspx
I tried to validate the value of the cookie, but without success, this is implemented in the page load by means of an IF (it only works when the page is reloaded by means of an F5)
webform pointA.aspx
namespace Test
{
public partial class pointA : Page
{
HttpCookie hamburger = new HttpCookie("hamburger", "0");
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["hamburger"].value == "5")
{
Response.Redirect("pointB.aspx");
}
}
protected void btnLogin_Click(object sender, EventArgs e)
{
hamburger.Value = "5";
hamburger.Expires = DateTime.Now.AddMinutes(40);
Response.Cookies.Add(hamburger);
Response.Redirect("pointB.aspx");
}
}
}
webform pointB.aspx
namespace Test
{
public partial class pointB : Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (Request.Cookies["hamburger"] != null)
{
txtLabelHamburger.text = Request.Cookies["hamburger"].value.ToString();
}
}
}
}
To avoid code sniffed to change your submit form, here is one way to try.
1) On Form load pointA.aspx, create unique UUID/GUID hidden input in form
using server side and insert the record in a UniqueFormSubmit Table
2) On form redirect to pointB.aspx, validate if unique UUID/GUID record existed in a
UniqueFormSubmit Table and status NOT COMPLETED, then mark it STATUS COMPLETED PROCESSED.
If record already exist in the table
with STATUS COMPLETED PROCESSED,
then reject the re-submit form.
This question already has answers here:
How can I programmatically stop or start a website in IIS (6.0 and 7.0) using MsBuild?
(3 answers)
Closed 7 years ago.
I am using the MVC5 for an web application. The web app runs in IIS7 or greater.
In the Global.asax on application_start, the number of licenses will be set:
protected void Application_Start()
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch(Exception e)
{
// log exception
// stop web site.
}
}
If any expection will be thrown in this context, the web site should shut down as you can do that in the IIS-Manager:
How can I stop the current web site in my Application_Start ?
You can do it with the help of "Microsoft.Web.Administration.dll"
using Microsoft.Web.Administration;
After adding the reference of "Microsoft.Web.Administration.dll" write below code in Global.asax
protected void Application_Start(object sender, EventArgs e)
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch (Exception e)
{
// get the web site name
var lWebSiteName = System.Web.Hosting.HostingEnvironment.ApplicationHost.GetSiteName();
// log exception
// stop web site.
using (ServerManager smg = new ServerManager())
{
var site = smg.Sites.FirstOrDefault(s => s.Name == lWebSiteName);
if (site != null)
{
//stop the site...
site.Stop();
}
}
}
}
I will go not with stop it, but to show some message if you do not have license.
This is an example, and an idea.
You can use this code on global.asax where if you do not have licenses the moment you start, you open a flag, and after that you do not allow any page to show, and you send a page that you can keep on an html file.
private static bool fGotLicense = true;
protected void Application_Start()
{
try
{
MyApp.cNumberOfLicenses = COM.GetNumberOfLicenses();
}
catch(Exception e)
{
// log exception
// stop web site.
fGotLicense = false;
}
}
protected void Application_BeginRequest(Object sender, EventArgs e)
{
HttpApplication app = (HttpApplication)sender;
// if not have license - let show some infos
if (!fGotLicens)
{
// the file we look now is the app_offline_alt.htm
string cOffLineFile = HttpRuntime.AppDomainAppPath + "app_offline_alt.htm";
// if exist on root
if (System.IO.File.Exists(cOffLineFile))
{
using (var fp = System.IO.File.OpenText(cOffLineFile))
{
// read it and send it to the browser
app.Response.Write(fp.ReadToEnd());
fp.Close();
}
}
// and stop the rest of processing
app.Response.End();
return;
}
}
You can have a file named app_offline.htm with content say This website is offline now in web server and copy that to root directoy of website you want for any event.
It will directly show that message, but yes, App pool will be still ON, when you need to start , you just need to rename that to something else.
I have about 10 Session variable for storing the File Download Counts of each different 10 Categories wise. I dont know why? but my session variable that is set into Global.asax get RESET automatically.
Since, the Machine is not restarted. Still the Counter of File Downloads get Reset. Any Idea? Plz Suggest me any solution.
In Global.asax:
void Application_Start(object sender, EventArgs e)
{
Application.Add("MGM",0);
Application.Add("PC",0);
Application.Add("NC",0);
Application.Add("TC",0);
Application.Add("PGC",0);
}
The *shortCode* parameter is name of Global Session from Global.asax file. that i am passing to get the counter and increment accordingly.
In Download.aspx.cs Page:
private int GetCount(string shordCode)
{
int count=0;
count = Convert.ToInt32(Application[shortCode]);
lock (Application[shortCode])
{
Application[shortCode] = ++count;
}
return count;
}
Shall i store value in textfile and update accordingly after certain count say 500. if yes how to do? Our colleague says that if suppose many users downloading file and if both access the same value from textfile then cuncurency may occurs.I am Confused...!Help Appreciated.
Please refer to the MSDN page for ASP.NET Application State
Excerpt:
Because application state is stored in server memory, it
is lost whenever the application is stopped or restarted. For example,
if the Web.config file is changed, the application is restarted and
all application state is lost unless application state values have
been written to a non-volatile storage medium such as a database.
By default, ASP.NET applications running on IIS will have their application pool shut down during periods of inactivity. I believe the default value for this is 20 minutes. Also by default, applications pools are recycled every 1740 minutes (29 hours).
When this happens you will lose anything in the Application[] collection that you haven't stored in a more permanent location, such as a database.
Both of the above-mentioned values can be modified by right-clicking on the specific application pool in inetmgr and clicking on Advanced Properties to bring up the appropriate window.
ok good!,
Please try my simple app,four you problem:
protected void Application_Start(object sender, EventArgs e)
{
Application.Add("MGM", 0);
}
protected void Session_Start(object sender, EventArgs e)
{
Application.Lock();
Application["MGM"] = System.Convert.ToInt32(Application["MGM"]) + 1;
Application.UnLock();
}
protected void Session_End(object sender, EventArgs e)
{
Application.Lock();
Application["MGM"] = System.Convert.ToInt32(Application["MGM"]) - 1;
Application.UnLock();
}
protected void Application_End(object sender, EventArgs e)
{
Application.Clear();
}
and you method i changed:
private int GetCount(string shordCode)
{
return Convert.ToInt32(Application[shortCode]);
}
Ok,great i answer this Q,and try change your method:
Startup your web app:
protected void Application_Start(object sender, EventArgs e)
{
Application.Add("MGM",0);
Application.Add("PC",0);
Application.Add("NC",0);
Application.Add("TC",0);
Application.Add("PGC",0);
}
and changed your get count method logics:
private int GetCount(string shordCode)
{
//current app instance
var currentApp = HttpContext.Current.ApplicationInstance.Application;
//get item count
var count = Convert.ToInt32(currentApp[shordCode]);
//locking app for your asking count insrement
currentApp.Lock();
currentApp[shordCode] = ++count;
//unlock app
currentApp.UnLock();
return count;
}
is there an easy way, to store all needed global variables in sessions at once, before the PostBack starts? Or have I to store them in each step where I change them?
I will do something like:
// Global variable.
bool test = true;
// Store all needed information in a session.
protected void Before_globalvariable_is_set_to_default_value(...)
{
Session["Test"] = test;
...
}
protected void Page_Load(object sender, EventArgs e)
{
if(IsPostBack)
{
//if(Session["Test"] != null)
//{
test = (bool)Session["Test"];
Session.Contents.Remove("Test");
//}
}
}
Is something like that possible?
Additional Information
At the Page_Load (!IsPostBack) I check if the user gets more vision, if he gets, I set a global var to true. Later in my code I check if that var is true and add additional columns to a GridView.
Now if a PostBack occurs, I can’t check that var, because I lose the information. I knew that I need to store the information in a Session. If I set the Session at the time where I set the global var to true, I get problems with the session timeout (If the user is on the site, but doesn’t do something for a while). So I thought it will be good, if I set the Session shortly before I lose the information of the global var and delete the Session after reinitialization.
That’s my idea, but I don’t know if something like that is possible.
Edit2:
If I do following it works:
//Global variable
bool test = false;
protected void Page_PreRender(object sender, EventArgs e)
{
Session["Test"] = test;
}
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
test = (bool)Session["Test"]; // Session is true!!!
Session.Contents.Remove("Test");
}
else
{
test = true; // Set at the PageLoad the var to true.
}
}
I’m a little bit confused, I thought PreRender is after the PageLoad, why suddenly the test var is true and if I remove the PreRender it isn’t?
Greetz
If you're worried about losing a specific value between requests, because you've maintained the state of that variable in the Session object and it might have been cleared by a timeout, you could consider using another, more durable, mechanism to save the state: for example, cookies or database.
If the value only needs to live during that one Request, you can use class-level fields of the code-behind class. Set them in the Init or Load phase, then you can use those values in all other phases.
For a lifetime of just a single request:
public partial class MyPage: Page
{
private bool test = true;
public void Page_Load(...)
{
// maybe set 'test' to another value
}
public void Button_Click(...)
{
// you can still access 'test'
}
public void Page_PreRender(...)
{
// you can still access 'test'
}
}
If however you need that value to live from request to the next postback, you can use ViewState instead of Session. Advantage: no timeout as it is stored in the html and posted back from the browser along with other data. Disadvantage: it only works in postback-scanario's, not when you link to a different page.
How can I find out if the user pressed F5 to refresh my page (Something like how SO implemented. If you refresh your page, the question counter is not increased). I have tested many code snippets mentioned in a dozen of tutorials, but none worked correctly.
To be more clear, suppose that i have an empty web form and would like to detect whether the user has pressed F5 in client-side (causing a refresh not submit) or not.
I can use session variables, but if the user navigates to another page of my site, and then comes back , I'd like to consider it as a new visit, not a refresh. so this is not a session-scope variable.
Thanks.
Update: The only workaround I could find was to inherit my pages from a base page, override the load method like below:
public class PageBase : System.Web.UI.Page
{
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
this.Session["LastViewedPage"] = Request.RawUrl;
}
}
and in every page if I was interested to know if this is a refresh:
if (this.Session["LastViewedPage"].ToString() == Request.RawUrl)
{
// This is a refresh!
}
I run into this problem and use the following code. It works well for me.
bool isPageRefreshed = false;
protected void Page_Load(object sender, EventArgs args)
{
if (!IsPostBack)
{
ViewState["ViewStateId"] = System.Guid.NewGuid().ToString();
Session["SessionId"] = ViewState["ViewStateId"].ToString();
}
else
{
if (ViewState["ViewStateId"].ToString() != Session["SessionId"].ToString())
{
isPageRefreshed = true;
}
Session["SessionId"] = System.Guid.NewGuid().ToString();
ViewState["ViewStateId"] = Session["SessionId"].ToString();
}
}
The only sure solution is to make a redirect to the same page , and here is a similar question: Post-Redirect-Get with ASP.NET
But there are also some other tricks, by adding some ticket on the page and see if this is the same or have change, see the full example and code at:
http://www.codeproject.com/Articles/68371/Detecting-Refresh-or-Postback-in-ASP-NET
and one more:
http://dotnetslackers.com/community/blogs/simoneb/archive/2007/01/06/Using-an-HttpModule-to-detect-page-refresh.aspx