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

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.

Related

Unable to perform Session State in 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;
}

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.

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 does Global.asax PostAuthenticateRequest event binding happen?

How can I use the PostAuthenticateRequest event of Global.asax? I'm following this tutorial and it mentions that I have to use the PostAuthenticateRequest event. When I added the Global.asax event it created two files, the markup and the code-behind file. Here is the content of the code-behind file
using System;
using System.Web;
using System.Web.Security;
using System.Web.SessionState;
namespace authentication
{
public class Global : System.Web.HttpApplication
{
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)
{
}
}
}
Now when I type the
protected void Application_OnPostAuthenticateRequest(object sender, EventArgs e)
It is successfully called. Now I want to know how is the PostAuthenticateRequest bound to this Application_OnPostAuthenticateRequest method? How can I change the method to some other?
Magic..., a mechanism called Auto Event Wireup, the same reason you can write
Page_Load(object sender, EventArgs e)
{
}
in your code-behind and the method will automatically be called when the page loads.
MSDN description for System.Web.Configuration.PagesSection.AutoEventWireup property:
Gets or sets a value indicating whether events for ASP.NET pages are automatically connected to event-handling functions.
When AutoEventWireup is true, handlers are automatically bound to events at run time based on their name and signature. For each event, ASP.NET searches for a method that is named according to the pattern Page_eventname(), such as Page_Load() or Page_Init(). ASP.NET first looks for an overload that has the typical event-handler signature (that is, it specifies Object and EventArgs parameters). If an event handler with this signature is not found, ASP.NET looks for an overload that has no parameters. More details in this answer.
If you wanted to do it explicitly you would write the following instead
public override void Init()
{
this.PostAuthenticateRequest +=
new EventHandler(MyOnPostAuthenticateRequestHandler);
base.Init();
}
private void MyOnPostAuthenticateRequestHandler(object sender, EventArgs e)
{
}

Resources