Unable to perform Session State in ASP.NET - asp.net

I was trying to perform Session State in ASP.NET, but it always start from 1 in different pages.
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Session["count"] = 0;
}
int count = (int)Session["count"];
count++;
Label1.Text = count.ToString();
Session["count"] = count;
}
// In Global.asax
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
void Session_Start(object sender, EventArgs e)
{ // start of Session
Session["count"] = 0;
}
void Session_End(object sender, EventArgs e)
{
}
}
I expect the count continues but not starts from 1 after re-visit the webform. Thanks!

if you want to display the total active user on your site, use application object instead of session object and on session_start you increase count and on session_end, decrease count.
protected void Application_Start(object sender, EventArgs e)
{
Application["count"] = 0;
}
void Session_Start()
{ // start of Session
Application["count"] += 1;
}
void Session_End()
{
Application["count"] -= 1;
}

Related

ASP.Net OnLoad Stop event handling

I have some validation code in my WebForm page. When a user clicks on a button and does a postback.
Page_Load event gets processed then the Button1_Click event gets processed.
I can't figure out a way to stop the Button1_Click event from processing if the validation fails on Page_Load.
Is a trick to do this?
Thanks
4 variations shown below.
public partial class _Default : System.Web.UI.Page
{
private bool MyPageIsValid { get; set; }
protected void Page_Load(object sender, EventArgs e)
{
if (Page.IsPostBack)
{
bool valid = false; /* some routine here */
MyPageIsValid = valid;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
if (this.MyPageIsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button2_Click(object sender, EventArgs e)
{
if (!this.MyPageIsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
protected void Button3_Click(object sender, EventArgs e)
{
if (this.Page.IsValid)
{
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
protected void Button4_Click(object sender, EventArgs e)
{
if (!this.Page.IsValid) {return;}
this.TextBox1.Text = DateTime.Now.ToLongTimeString();
}
}
I think it should be better to check validation conditions exactly in the Button1_Click method like this:
if (!this.IsValid()) { return; }
Also if you still want to check that conditions in Page_Load method just add simple 'bool isValid' flag to your page's class and then check it in Button1_Click:
if (!this.isValid) { return; }

how to call custom method automatically in global.asax

Here is my code and i want to call the my custom method (Application_My()) automatically when application is loaded/refresh every time like Application_OnEndRequest().
Thanks in advance.
<%# Application Language="C#" %>
<script runat="server">
// THis code will be executed automatically when page is reloaded everytime
/*protected void Application_OnEndRequest()
{
Response.Write("Thsi page is executed on=" + DateTime.Now.ToString());
}*/
// how to call below method automatically when page is reloaded everytime
//such as above
protected void Application_My()
{
Response.Write("Hi welcome");
}
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
protected void Application_End(object sender, EventArgs e)
{
}
protected void Application_EndRequest(object sender, EventArgs e)
{
Application_My();
}
However, note that this is called for everything that is managed by your aspnet pipeline, so you might get called on css and image requests.
You could add Debug.WriteLine(Request.Url); to the code above to see what happens when you enter your site.

How to count days using global.asax file in asp.net 4.0

Clickhere Global.asax.cs
namespace WebApplication7
{
public class Global : System.Web.HttpApplication
{
private static int countdays=0;
protected void Application_Start(object sender, EventArgs e)
{
countdays = 0;
}
protected void Session_Start(object sender, EventArgs e)
{
countdays += 1;
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
countdays -= 1;
}
protected void Application_End(object sender, EventArgs e)
{
}
public static int CountNo { get { return countdays; } }
}
}
Global.apsx
<body>
<form id="fromHitCounter" method="post" runat="server">
Total number of days since the Web server started:
<asp:label id="lblCount" runat="server"></asp:label><br />
</form>
</body>
Global.aspx.cs
private void Page_Load(object sender, System.EventArgs e)
{
int Countdays = HitCounters.Global.Countdays;//Hit counter does not exist
lblCount.Text = Countdays.ToString();
}
How to calculate days counter in asp.net using global.asax file,In Global.aspx.cs iam getting the error hit counter does not exist in the current context
I'm not going to ask why, I probably won't like the reason you give me. However you're not counting days here. You are counting session starts.
What you really want to do is something like this:
public class Global : System.Web.HttpApplication
{
private static DateTime started;
private static int days;
protected void Application_Start(object sender, EventArgs e)
{
started = DateTime.UtcNow;
days = 0;
}
protected void Session_Start(object sender, EventArgs e)
{
TimeSpan ts = DateTime.UtcNow - started;
days = (int)ts.TotalDays;
}
...
}
}
However, that's assuming the session events fire and you're also overlooking the fact the applications can and do get unloaded, your application may not stay loaded even a single day.
Your link points to counting the number of website visits which isn't the same as counting days or getting how long the web server has been running. It is also a very poor attempt because it does not take into account repeat visits from the same user etc and is not really persistent across app domain unloads.

Session Timeout manually

I have 2 pages on my dummy site in asp.net, (default.aspx and default2.aspx), On default.aspx, i created session like below
protected void Page_Load(object sender, EventArgs e)
{
Session["MySession"] = "WELCOME";
Session.Timeout = 1;
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("default2.aspx");
}
and on default2.aspx
if (Session["MySession"] != null)
Response.Write(Session["MySession"]);
else
Response.Write("Session Timed Out");
i was wondering that after 1 min the session will get erase, as i have timeout, but after one minute when i click on the button it redirected me to default2.aspx, and displayed a session value "WELCOME". can anyone tell me how to erase session value after particular duration
In your Default.aspx you have to check if it is not a post back otherwise the session will be initialized again for each button click
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.isPostBack())
{
Session["MySession"] = "WELCOME";
Session.Timeout = 1;
}
}
protected void Button1_Click(object sender, EventArgs e)
{
Response.Redirect("default2.aspx");
}

How to do that fields not initialization?

how to do that every time s_Sort not update SortDirection.Desc
private SortDirection s_Sort = SortDirection.Desc;
protected void Page_Load(object sender, EventArgs e)
{
lblSort.Text = S_Sort.ToString();//every time == SortDirection.Desc - this is bad!
if (!IsPostBack)
{
ShowTree();
Validate();
}
}
Need
public void btnSortUp_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Asc;
}
public void btnSortDown_Click(object sender, EventArgs e)
{
S_Sort = SortDirection.Desc;
}
but after SortDirection.Desc is bad
The is a problem of the ASP.NET lifecycle. Every time a postback happens (for example, when btnSortUp or btnSortDown is clicked), a new instance of your page is created, i.e., S_Sort is reinitialized to Desc. If you want to persist the value between postbacks, you can store it in the viewstate, for example, by encapsulating it in a private property:
private SortDirection S_Sort {
get { return (SortDirection)(ViewState["S_Sort"] ?? SortDirection.Desc); }
set { ViewState["S_Sort"] = value; }
}

Resources