Wednesday, 24 September 2014

Asp.net Counting Number of hits to the Page

Suppose You have 2 pages in Web application and you want to count the number of hits to your page, how can you achieve this ? 

1: You should have different counters for each page, and store these counters in Application cache to be at the web application level;

2.In the Global.asax.cs init your used counter for each page like in the next example:


void Application_Start(object sender, EventArgs e)
{
   Application["Page1Counter"] = 0;
   Application["Page2Counter"] = 0;
   //...
}


2.The logic for incrementing the counters for each page should be in the Page_Load event handler like in the next example:

protected void Page1_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)   
    {
       int counter = (int)Application["Page1Counter"];//Get from the cache!
       counter++;
       Application["Page1Counter"] = counter; //Cache the result back!
    }
    //....
}

3.Example for your new question regarding only one page and multiple users:

protected void Page1_Load(object sender, EventArgs e)
{
    if (!Page.IsPostBack)   
    {
       string userID = User.Identity.Name; //Get the user ID!
       string key = string.Format("Page1CounterForUser{0}", userID);//Create the key for current user!
       int counter = (int)Application[key];//Get from the cache!
       counter++;
       Application[key] = counter; //Cache the result back!
    }
    //....
}



Using SQL Server Profiler

Microsoft SQL Server Profiler is a graphical user interface to SQL Trace for monitoring T-SQL Statements of Database Engine. We can save and reuse the state at a later point of time.
  • We can do the following using SQL Server Profiler
    • Create a trace
    • Watch the trace results as the trace runs
    • Store the trace results in a table
    • Start, stop, pause, and modify the trace results as necessary
    • Replay the trace results
  • Use SQL Server Profiler to monitor only the events in which you are interested.
Menu Path: Start | All Programs | Microsoft SQL Server | Performance Tools | SQL Server Profiler. 

  1. Then following screen will come

  
 2.  Then in Event Selection Tab click on Show all events and Show all column's check box Check below image 


     3. Mark TSql check boxes as below check boxes. Tsql helps to display query. Full form is Trasect Sql.



   4. For Transaction display mark below check boxes .





   5. For Store procedure display Mark below check boxes.



  6.  Audit related things generally not required. So uncheck everything in audit as below.



  7.  Session related info also not required so un-check everything in session section as well.

   8.  So once all the settings are done , just click on Run button. Start yours application you will find below screen & Sql tracing starts. 






 
 

Tuesday, 23 September 2014

ASP.net IsPostBack method.

It is not IsPostBack method. It is the property in the System.Web.UI namespace. It should be Page.IsPostBack.

IsPostback property is used to Gets a value that indicates whether the page is being rendered for the first time or is being loaded in response to a postback.

This IsPostBack property returns the boolean value either True or False.

The following example shows how to test the value of the IsPostBack property when the page is loaded in order to determine whether the page is being rendered for the first time or is responding to a postback. If the page is being rendered for the first time, the code calls the  BindDropDown() method.

private void Page_Load()
{
    if (!IsPostBack)
    {
        // Validate initially to force asterisks
        // to appear before the first roundtrip.
        BindDropDown();
    }
}

After render the web page, if you do any post back then it will be called. In the web page, we used to check whether its loaded first time or posted back. Because we do not want to bind the concrete controls to rebind again. It will increase the performance of the web application.
 public void Page_Load(Object sender, EventArgs e)
        {
            //Print the time when the page loaded initially
            Response.Write("The Page Loaded at: " + DateTime.Now.ToLongTimeString());
            //Attach the selected index change event for both the dropdown control and the list box control
            //so as to get the value and set it in the corresponding label
            dropDownList1.SelectedIndexChanged += new EventHandler(dropDownList1_SelectedIndexChanged);
            listBox1.SelectedIndexChanged += new EventHandler(listBox1_SelectedIndexChanged);
            if (!IsPostBack)
            {
                var posts = FaceBookPosts.Posts();
                this.listBox1.DataSource = posts;
                this.listBox1.DataTextField = "Post";
                this.listBox1.DataValueField = "UserName";

                this.dropDownList1.DataSource = posts;
                this.dropDownList1.DataTextField = "Post";
                this.dropDownList1.DataValueField = "UserName";

                this.DataBind();
            }
        }

PostBack is the name given to the process of submitting an ASP.NET page to the server for processing . PostBack is done if certain credentials of the page are to be checked against a database (such as verification of username and password). This is something that a client machine is not able to accomplish and thus these details have to be 'posted back' to the server.

Usage of IsPostBack in ASP.Net-

IsPostBack is a Boolean property of a page when is set (=true) when a page is first loaded. Thus, the first time that the page loads the IsPostBack flag is false and for subsequent PostBacks, it is true. An important point to be noted here is that each time a PostBack occurs, the entire page including the Page_Load is 'posted back' and executed.
Thus a very common programming practice is that whenever some part of the code is to be executed just the first time a page loads, it is checked against the IsPostBack flag.

Pls refer this url for examples,
http://dotnet.tekyt.info/?p=30

ASP.NET Page Life Cycle Events

Page Event
Typical Use
PreInit
Raised after the start stage is complete and before the initialization stage begins.
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed. The IsCallback and IsCrossPagePostBack properties have also been set at this time.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.
    NoteNote
    If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.
Init
Raised after all controls have been initialized and any skin settings have been applied. The Init event of individual controls occurs before the Init event of the page.
Use this event to read or initialize control properties.
Raised at the end of the page's initialization stage. Only one operation takes place between the Init and InitComplete events: tracking of view state changes is turned on. View state tracking enables controls to persist any values that are programmatically added to the ViewState collection. Until view state tracking is turned on, any values added to view state are lost across postbacks. Controls typically turn on view state tracking immediately after they raise their Init event.
Use this event to make changes to view state that you want to make sure are persisted after the next postback.
Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance.
The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page.
Use the OnLoad event method to set properties in controls and to establish database connections.
Control events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
NoteNote
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.
Raised at the end of the event-handling stage.
Use this event for tasks that require that all other controls on the page be loaded.
Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. (To do this, the Page object callsEnsureChildControls for each control and for the page.)
The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after thePreRender event of the page.
Use the event to make final changes to the contents of the page or its controls before the rendering stage begins.
Raised after each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
Raised after view state and control state have been saved for the page and for all controls. Any changes to the page or controls at this point affect rendering, but the changes will not be retrieved on the next postback.
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup to send to the browser.
If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.
A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.
Raised for each control and then for the page.
In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.
For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.
NoteNote
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as theResponse.Write method, the page will throw an exception.


This articles was originally at wiki.asp.net but has now been given a new home on CodeProject. Editing rights for this article has been set at Bronze or above, so please go in and edit and update this article to keep it fresh and relevant.
When a page request is sent to the Web server, the page is run through a series of events during its creation and disposal. In this article, I will discuss in detail the ASP.NET page life cycle Events
 (1) PreInit The entry point of the page life cycle is the pre-initialization phase called “PreInit”. This is the only event where programmatic access to master pages and themes is allowed. You can dynamically set the values of master pages and themes in this event. You can also dynamically create controls in this event. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
using System;
using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls; public partial class _Default : System.Web.UI.Page{    protected void Page_PreInit(object sender, EventArgs e)   {        //  Use this event for the following:          //  Check the IsPostBack property to determine whether this is the first time the page is being processed.        //  Create or re-create dynamic controls.        //  Set a master page dynamically.        //  Set the Theme property dynamically.           }
------------------------------------------------------------------------
(2)Init This event fires after each control has been initialized, each control's UniqueID is set and any skin settings have been applied. You can use this event to change initialization values for controls. The “Init” event is fired first for the most bottom control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.  
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Init(object sender, EventArgs e)
{// Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.}
 -------------------------------------------------------------------
(3)InitComplete Raised once all initializations of the page and its controls have been completed. Till now the viewstate values are not yet loaded, hence you can use this event to make changes to view state that you want to make sure are persisted after the next postback 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_InitComplete(object sender, EventArgs e)
{       // Raised by the  Page object. Use this event for processing tasks that require all initialization be complete. }
------------------------------------------------------------------------
(4)PreLoad Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance     
(1)Loads ViewState : ViewState data are loaded to controls
Note : The page viewstate is managed by ASP.NET and is used to persist information over a page roundtrip to the server. Viewstate information is saved as a string of name/value pairs and contains information such as control text or value. The viewstate is held in the value property of a hidden <input> control that is passed from page request to page request.     
(2)Loads Postback data : postback data are now handed to the page controls           
Note : During this phase of the page creation, form data that was posted to the server (termed postback data in ASP.NET) is processed against each control that requires it. Hence, the page fires the LoadPostData event and parses through the page to find each control and updates the control state with the correct postback data. ASP.NET updates the correct control by matching the control's unique ID with the name/value pair in the NameValueCollection. This is one reason that ASP.NET requires unique IDs for each control on any given page. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreLoad(EventArgs e)
{        // Use this event if you need to perform processing on your page or control before the  Load event.        // Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.}
------------------------------------------------------------------------
(5)Load The important thing to note about this event is the fact that by now, the page has been restored to its previous state in case of postbacks. Code inside the page load event typically checks for PostBack and then sets control properties appropriately. This method is typically used for most code, since this is the first place in the page lifecycle that all values are restored. Most code checks the value of IsPostBack to avoid unnecessarily resetting state. You may also wish to call Validate and check the value of IsValid in this method. You can also create dynamic controls in this method.
 EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_Load(object sender, EventArgs e)
{        // The  Page calls the  OnLoad event method on the  Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded.        // Use the OnLoad event method to set properties in controls and establish database connections.}
------------------------------------------------------------------------
(6)Control (PostBack) event(s)ASP.NET now calls any events on the page or its controls that caused the PostBack to occur. This might be a button’s click event or a dropdown's selectedindexchange event, for example.These are the events, the code for which is written in your code-behind class(.cs file). 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Button1_Click(object sender, EventArgs e)
{        // This is just an example of control event.. Here it is button click event that caused the postback}
---------------------------------------------------------------------
(7)LoadComplete This event signals the end of Load. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_LoadComplete(object sender, EventArgs e)
{        // Use this event for tasks that require that all other controls on the page be loaded.}
----------------------------------------------------------------------
(8)PreRender Allows final changes to the page or its control. This event takes place after all regular PostBack events have taken place. This event takes place before saving ViewState, so any changes made here are saved.For example : After this event, you cannot change any property of a button or change any viewstate value. Because, after this event, SaveStateComplete and Render events are called. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnPreRender(EventArgs e)
{        // Each data bound control whose DataSourceID property is set calls its DataBind method.        // The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.}
-----------------------------------------------------------------------
(9)SaveStateComplete Prior to this event the view state for the page and its controls is set. Any changes to the page’s controls at this point or beyond are ignored.
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected override void OnSaveStateComplete(EventArgs e)
{        // Before this event occurs,  ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored.        // Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.}
------------------------------------------------------------------------
(10)Render This is a method of the page object and its controls (and not an event). At this point, ASP.NET calls this method on each of the page’s controls to get its output. The Render method generates the client-side HTML, Dynamic Hypertext Markup Language (DHTML), and script that are necessary to properly display a control at the browser.
 Note: Right click on the web page displayed at client's browser and view the Page's Source. You will not find any aspx server control in the code. Because all aspx controls are converted to their respective HTML representation. Browser is capable of displaying HTML and client side scripts. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
// Render stage goes here. This is not an event
------------------------------------------------------------------------
(11)UnLoad This event is used for cleanup code. After the page's HTML is rendered, the objects are disposed of. During this event, you should destroy any objects or references you have created in building the page. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. Cleanup can be performed on- 
     (a)Instances of classes i.e. objects
     (b)Closing opened files
     (c)Closing database connections. 
EXAMPLE : Override the event as given below in your code-behind cs file of your aspx page
protected void Page_UnLoad(object sender, EventArgs e)   
{        // This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.        // During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.           //If you attempt to call a method such as the Response.Write method, the page will throw an exception.    }
------------------------------------------------------------------




Summery :

preInit : Master Page ,Theme
init : After control has been initialized , uniqu id
initComplete :
PreLoad : Raised after the page loads view state /Loads Postback data
Load : Page object call ,Each control  load is called , IsPostback unnecessary
Control events
Load Complete
Pre render
Save State :  view state for the page and its controls is set
Render complte
Unload :This event is used for cleanup code.
     (a)Instances of classes i.e. objects

     (b)Closing opened files

     (c)Closing database connections.