Initialize variables before having anyone enter the web app - asp.net

How can I initialize variables before my Web Application starts? I want to have, for example an Application type, to count number of logged in users in my website (it's an example, I have more variables that need initialization). How can I perform that?
It could be very useful if there was some event that would be called at the start of the Web App. I thought that I could check in each Page_Load event if a certain Session called, e.g Session["Started"] is null, and if it, redirect to an .aspx page for initialization. Or, even better, have a class called, e.g MyPage which inherits from System.Web.UI.Page and have her constructor get a function as an argument, which will be called after the initialization of the base class Page_Load.
Maybe I'm just bothering, is there any built-in event called that I can overwrite to initialize everything I want in the beginning?

You can use the Global.asax file for this. In particular you can use the Application_Start, Session_Start, Session_End events.
public class Global : System.Web.HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
}
protected void Session_Start(object sender, EventArgs e)
{
}
protected void Session_End(object sender, EventArgs e)
{
}
}
Here for more informations.

Related

ASP.NET initialization of array

I have website with array (list) of 1000 objects, these objects are loading from json to array every website refresh. I would like to load these objects from json to array only once and keep it in RAM for others users. Because everytime read file is much slower than read it from RAM.
I am using ASP.NET Web Forms
How is it posssible?
I would recommend to define the array as an static member of a class and then initialize it with help of Global.asax, use the Application_Start event handler.
to add Global.asax to you project in Visual Studio:
File -> New -> File -> Global Application Class
Here is a sample C# code for Global.asax.cs:
public class Global : HttpApplication
{
protected void Application_Start(object sender, EventArgs e)
{
// ... Your initialization of the array done here ...
}
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)
{
}
}
Are these values static, i.e., do they stay constant while your application is running? In that case, the easiest way is to cache those values.
You can use static variables for that, but the recommended way is to use the thread-safe Cache object provided by ASP.NET. It can be accessed with the Cache property of the Page or of the HttpContext.
Example:
var myList = (MyListType)Cache["MyList"];
if (myList == null)
{
myList = ...; // Load the list
Cache["MyList"] = myList; // Store it, so we don't need to load it again next time.
}
Further reading:
Caching Application Data

How to use Load and Unload events in a user web control?

I swear to god I tried googling it.
I have a webcontrol that logs into the database the time and date of a page load, and same of page unload.
I can't set it up to save my life.
can somebody provide a solution?
Thanks!
You can use UserControl's Load and Unload events.
public partial class WebUserControl1 : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
// Log to Database
}
protected void Page_Unload(object sender, EventArgs e)
{
// Log to Database
}
}
Here is ASP.Net Page Life Cycle
The page fires the load event, which recursively goes through all of its controls, including your user control, to fire that load event on it. same action occurs for Unload. The page controls it all, which is controlled by the module that controls the ASP.NET framework.

Aspx and Ascx lifecycles : avoid multiple select on database

I use an ascx user control for manage CRUD o database entity. I reuse this userc control in my aspx page for show in readonly mode the database data of a record on database. The user control have inside a simple FormView and an objectdatasource.
Now, in a aspx page that contains that ascx i have to know, in DATABIND time of the aspx some data of the record of the database that is considerate by the user control. User control are databind after the aspx page, and for this reason i don't have the data. I have to do a select in aspx page on database and after the user control do the same select.
How can i do for optimize this process?
ASCX base events may be fired after your ASPX's base events, but in the whole lifecycle, you can fire your own events.
You could define an Event on your ASCX, make your page register to this event, and then propagate your custom event from your ASCX to your ASPX, with whatever data you need in the arguments
rough example (may not compile) : in the ASCX
public partial YourControl : System.Web.UI.UserControl {
public event EventHandler MyControlDataBound;
public void FireMyControlDataBound()
{
if (MyControlDataBound!= null)
{
MyControlDataBound(this, new EventArgs());
}
}
protected void MyDataBound(object sender, EventArgs e) {
// ......
FireMyControlDataBound();
}
}
and in the ASPX
public partial class MyPage: Page
{
protected void Page_Load(object sender, EventArgs e)
{
yourUserControlInstance.MyControlDataBound += HandleYourDataInYourPage;
}
protected void HandleYourDataInYourPage(object sender, EventArgs e) {
// .. do whatever needed in your page, with your data
// if you have defined a custom Args class that inherits EventArgs, your could collect data here...
}
}
Feel free to create a class that inherits EventArgs to pass data with your event if you need this
You can pass your arguments to your UserContol in init event of your Page
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
var control = (UserControl)this.FindControl("UserControlId");
control.Property = ...;//Pass User Control properties
}

Page_PreRender and Global.asax

I want to bind to the Page PreRender method on at the global.asax level, but for some reason the method is never getting called. My method looks like:
protected void Page_PreRender(object source, EventArgs e)
{
/* do stuff */
}
Am I able to call Page events like this in Global.asax?
The global.asax is derived from HttpApplication class and not contain the Page_PreRender event as you can see on the MSDN reference:
http://msdn.microsoft.com/en-us/library/system.web.httpapplication(VS.90).aspx
If you want to globally capture the PreRender event you can make a different base class for the System.Web.UI.Page, overwrite this event, and use this class to your pages.
For example
public abstract class BasePage : System.Web.UI.Page
{
protected override void OnPreRender(EventArgs e)
{
base.OnPreRender(e);
}
}
and use the BasePage on your pages

two UserControls, one page, need to notify each other of updates

I've got a user control thats used twice on the same page, each have the ability to be updated (a dropdown list gets a new item) and I'm not sure what might be the best way to handle this.
One concern - this is an older system (~4+ years, datasets, .net2) and it is amazingly brittle. I did manage to have it run on 3.5 with no problems, but I've had a few run-ins with the javascript validation (~300 lines per page) throwing up all over the place when I change/add/modify controls in the parent.
Add an event to your user control.
public event EventHandler MyEvent;
protected void OnMyEvent(EventArgs e)
{
if(MyEvent != null)
{
MyEvent(this, e);
}
}
protected void AddOptionAdded(object sender, EventArgs e)
{
OnMyEvent(EventArgs.Empty);
}
Then in your page you can subscribe to both controls event.
protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1.MyEvent += OnMyEventHander;
WebUserControl2.MyEvent += OnMyEventHander;
}
protected void OnMyEventHandler(object sender, EventArgs e)
{
// Notify the other controls that something changed.
}
Then in your page's event handler you can do whatever you need to do to update the other control. Calling a method, etc.
You can also go as far as creating your own delegate and EventArgs classes to pass additional custom data that may be needed.
Didn't even need most of it, I forgot to mention it was vb, so I put this in the user control...
Public Event UpdateListings As EventHandler
Public Function SomethingToDo
'doing some cool stuff ...not really
RaiseEvent UpdateListings(Me, EventArgs.Empty)
Return result
End Function
then on the code behind on the parent page
Protected Sub UpdateStuff(ByVal sender As Object, ByVal e As EventArgs) Handles userControl1.UpdateListings, userControl2.UpdateListings
userControl1.BindStuff()
userControl2.BindStuff()
End Sub

Resources