Showing posts with label ASP. Show all posts
Showing posts with label ASP. Show all posts

Monday, 7 September 2015

Web Farm and Web Garden

Web Farm

This is the case where you have only one web server and multiple clients requesting for resources from the same server. But when are is huge amount of incoming traffic for your web sites, one standalone server is not sufficient to process the request. You may need to use multiple servers to host the application and divide the traffic among them. This is called “Web Farm”. So when you are hosting your single web site on multiple web servers over load balancer is called “Web Farm”. The below diagram shows the overall representation of Web Farms.
Web Farms
In general web farm architecture, a single application is hosted on multiple IIS Server and those are connected with the VIP (Virtual IP) with Load Balancer. Load Balancer IPs are exposed to external world to access. So whenever some request will come to server from clients, it will first hit the Load Balancer, then based on the traffic on each server, LB distributes the request to the corresponding web server. These web servers may share the same DB server or may be they can use a replicated server in the back end.
So, in a single statement, when we host a web application over multiple web servers to distribute the load among them, it is called Web Farm.

Web Garden

Now, let’s have a look at what is Web Garden? Both the terms sound the same, but they are totally different from each other. Before starting with Web Garden, I hope you have a fundamental idea of what an Application Pool is and what a Worker Process is. If you have already read the article, “How IIS Processes ASP.NET Request ?”, then I can expect that you now have a good idea about both of them.
Just to recall, when we are talking about requesting processing within IIS, Worker Process (w3wp.exe) takes care of all of these. Worker Process runs the ASP.NET application in IIS. All the ASP.NET functionality inside IIS runs under the scope of worker process. Worker Process is responsible for handling all kinds of request, response, session data, cache data. Application Pool is the container of worker process. Application pool is used to separate sets of IIS worker processes and enables a better security, reliability, and availability for any web application.
apppools
Now, by default, each and every Application pool contains a single worker process. Application which contains the multiple worker process is called “Web Garden”. Below is the typical diagram for a web garden application.
WebGarden Basic
In the above diagram, you can see one of the applications containing the multiple worker processes, which is now a web garden.
So, a Web application hosted on multiple servers and access based on the load on servers is called Web Farms and when a single application pool contains multiple Worker processes, it is called a web garden.


Advantages of Web Farm and Web Garden

Now, let’s have a look into the advantages of both the Web Farms and Web Gardens.

Advantages of Web Farm

  • It provides high availability. If any of the servers in the farm goes down, Load balancer can redirect the requests to other servers.
  • Provides high performance response for client requests.
  • Provides better scalability of the web application and reduces the failure of the application.
  • Session and other resources can be stored in a centralized location to access by all the servers.

Advantages of Web Garden

  • Provides better application availability by sharing requests between multiple worker process.
  • Web garden uses processor affinity where application can be swapped out based on preference and tag setting.
  • Less consumption of physical space for web garden configuration.



Friday, 28 August 2015

Calling Method in Parent Page from User Control


Use delegate by below way.

n ASP.Net, we develop custom user control as a reusable server control independent of any containing parent aspx page. User control has its own public properties, methods, delegates, etc that can be used by parent aspx page. When a user control is embedded or loaded into a page, the page can access
In ASP.Net, we develop custom user control as a reusable server control independent of any containing parent aspx page. User control has its own public properties, methods, delegates, etc that can be used by parent aspx page. When a user control is embedded or loaded into a page, the page can access public properties, methods, delegates, etc that are in user control. After loading the user control, there a situation may arise like calling methods in page itself. But when a user control is developed, it has no knowledge of containing page. So it becomes a trick to call the page method.
In .Net, Delegate class has one method DynamicInvoke. DynamicInvoke method is used to invoke (late-bound) method referenced by delegate. We can use this method to call a method in parent page from user control. Let’s try with this example.
First create a user control called CustomUserCtrl. Its code will look some thing like this:
public partial class CustomUserCtrl : System.Web.UI.UserControl
{
private System.Delegate _delWithParam;
public Delegate PageMethodWithParamRef
{
set { _delWithParam = value; }
}

private System.Delegate _delNoParam;
public Delegate PageMethodWithNoParamRef
{
set { _delNoParam = value; }
}

protected void Page_Load(object sender, EventArgs e)
{
}

protected void BtnMethodWithParam_Click(object sender, System.EventArgs e)
{
//Parameter to a method is being made ready
object[] obj = new object[1];
obj[0] = “Parameter Value” as object;
_delWithParam.DynamicInvoke(obj);
}

protected void BtnMethowWithoutParam_Click(object sender, System.EventArgs e)
{
//Invoke a method with no parameter
_delNoParam.DynamicInvoke();
}
}
Then add this user control into an aspx page. The code behind of this page is as:
public partial class _Default : System.Web.UI.Page
{
delegate void DelMethodWithParam(string strParam);
delegate void DelMethodWithoutParam();
protected void Page_Load(object sender, EventArgs e)
{
DelMethodWithParam delParam = new DelMethodWithParam(MethodWithParam);
//Set method reference to a user control delegate
this.UserCtrl.PageMethodWithParamRef = delParam;
DelMethodWithoutParam delNoParam = new DelMethodWithoutParam(MethodWithNoParam);
//Set method reference to a user control delegate
this.UserCtrl.PageMethodWithNoParamRef = delNoParam;
}

private void MethodWithParam(string strParam)
{
Response.Write(“<br/>It has parameter: ” + strParam);
}

private void MethodWithNoParam()
{
Response.Write(“<br/>It has no parameter.”);
}
}
BtnMethodWithParam and BtnMethowWithoutParam are two different buttons on the user control that are invoking the methods in the parent page. On Page_Load of the page, we are setting the references of page class methods to delegate type properties in the user control. Click different buttons of user control, you will see MethodWithParam(string strParam) and MethodWithNoParam() methods called.
This is all we have to do to call page class methods from user control in ASP.Net.


Tuesday, 25 August 2015

What is difference between Response.Write() and Response.Output.Write()

The difference between Response.Write() and Response.Output.Write() in ASP.NET. The short answer is that the latter gives you String.Format-style output and the former doesn't. The long answer follows.
In ASP.NET the Response object is of type HttpResponse and when you say Response.Writeyou're really saying (basically) HttpContext.Current.Response.Write and calling one of the many overloaded Write methods of HttpResponse.
Response.Write then calls .Write() on it's internal TextWriter object:
public void Write(object obj){ this._writer.Write(obj);}
HttpResponse also has a Property called Output that is of type, yes, TextWriter, so:
public TextWriter get_Output(){ return this._writer; }
Which means you can to the Response whatever a TextWriter will let you. Now, TextWriters support a Write() method ala String.Format, so you can do this:
Response.Output.Write("Scott is {0} at {1:d}", "cool",DateTime.Now);
But internally, of course, this this is happening:
public virtual void Write(string format, params object[] arg)
{ 
this.Write(string.Format(format, arg)); 
}

Monday, 3 August 2015

ASP.net Page Life Cycle in More depth

When an ASP.NET page runs, the page goes through a life cycle in which it performs a series of processing steps. These include initialization, instantiating controls, restoring and maintaining state, running event handler code, and rendering. The following are the various stages or events of ASP.Net page life cycle.

PreInit
  1. Check the IsPostBack property to determine whether this is the first time the page is being processed.
  2. Create or re-create dynamic controls.
  3. Set a master page dynamically.
  4. Set the Theme property dynamically.

    ASP.NET1.jpg
Note: If the request is a postback then the values of the controls have not yet been restored from the view state. If you set a control property at this stage, its value might be overwritten in the next event.

Init
  1. This event fires after each control has been initialized.
  2. Each control's UniqueID is set and any skin settings have been applied.
  3. Use this event to read or initialize control properties.
  4. The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself.

    ASP.NET2.jpg
InitComplete
  1. Until now the viewstate values are not yet loaded, hence you can use this event to make changes to the view state that you want to ensure are persisted after the next postback.
  2. Raised by the Page object.
  3. Use this event for processing tasks that require all initialization to be complete.

    ASP.NET3.jpg
OnPreLoad
  1. 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.
  2. 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.
  3. Loads ViewState: ViewState data are loaded to controls.
  4. Loads Postback data: Postback data are now handed to the page controls.

    ASP.NET4.jpg
Load
  1. 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.
  2. This is the first place in the page lifecycle that all values are restored.
  3. Most code checks the value of IsPostBack to avoid unnecessarily resetting state.
  4. You may also call Validate and check the value of IsValid in this method.
  5. You can also create dynamic controls in this method.
  6. Use the OnLoad event method to set properties in controls and establish database connections.

    ASP.NET5.jpg
Control PostBack Event(s)
  1. ASP.NET now calls any events on the page or its controls that caused the PostBack to occur.
  2. Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
  3. 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.
  4. This is just an example of a control event. Here it is the button click event that caused the postback.

    ASP.NET6.jpg
LoadComplete
  1. Raised at the end of the event-handling stage.
  2. Use this event for tasks that require that all other controls on the page be loaded.

    ASP.NET7.jpg
OnPreRender
  1. Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls.
  2. 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 the PreRender event of the page.
  3. The PreRender event of individual controls occurs after the PreRender event of the page.
  4. Allows final changes to the page or its control.
  5. This event takes place before saving ViewState, so any changes made here are saved.
  6. For example: After this event, you cannot change any property of a button or change any viewstate value.
  7. Each data bound control whose DataSourceID property is set calls its DataBind method.
  8. Use the event to make final changes to the contents of the page or its controls.

    ASP.NET7.5.jpg
OnSaveStateComplete
  1. Raised after view state and control state have been saved for the page and for all controls.
  2. Before this event occurs, ViewState has been saved for the page and for all controls.
  3. Any changes to the page or controls at this point will be ignored.
  4. Use this event perform tasks that require the view state to be saved, but that do not make any changes to controls.

    ASP.NET8.jpg
Render Method
  1. This is a method of the page object and its controls (and not an event).
  2. 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.
UnLoad
  1. This event is used for cleanup code.
  2. At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object.
  3. Cleanup can be performed on:
    • Instances of classes, in other words objects
    • Closing opened files
    • Closing database connections.
  4. This event occurs for each control and then for the page.
  5. During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream.
  6. If you attempt to call a method such as the Response.Write method then the page will throw an exception.

    ASP.NET9.jpg
     
EXAMPLES

Example 1: Control Values

In the following code, I have assigned the values to the label control on each event. When you run the code, you will see that in the "Page_UnLoad", the values are not assigned to the label. WHY? Because, during the unload stage, the page and its controls have been rendered, so you cannot change the values.

Please observe the code comments and output. It will help you to clearly understand the concepts.
public partial class PageLiftCycle : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "PreInit";
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "Init";
    }

    protected void Page_InitComplete(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "InitComplete";
    }

    protected override void OnPreLoad(EventArgs e)
    {
        //Work and It will assign the values to label.
        //If the page is post back, then label contrl values will be loaded from view state.
        //E.g: If you string str = lblName.Text, then str will contain viewstate values.
        lblName.Text = lblName.Text + "<br/>" + "PreLoad";
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "Load";
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "btnSubmit_Click";
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "LoadComplete";
    }

    protected override void OnPreRender(EventArgs e)
    {
        //Work and It will assign the values to label.
        lblName.Text = lblName.Text + "<br/>" + "PreRender";
    }

    protected override void OnSaveStateComplete(EventArgs e)
    {
        //Work and It will assign the values to label.
        //But "SaveStateComplete" values will not be available during post back. i.e. View state.
        lblName.Text = lblName.Text + "<br/>" + "SaveStateComplete";
    }

    protected void Page_UnLoad(object sender, EventArgs e)
    {
        //Work and it will not effect label contrl, view stae and post back data.
        lblName.Text = lblName.Text + "<br/>" + "UnLoad";
    }
}
Output

The first time the Page Load is output:

ASP.NET10.jpg

When you click on the Submit Button output:

ASP.NET11.jpg

During the first time of the page load with EnableViewState="false":

ASP.NET12.jpg
When you click on the Submit Button output with EnableViewState="false":

ASP.NET13.jpg
Example 2: ViewState Values

Please observe the code comments and output. It will help you to clearly understand the concepts.
public partial class PageLiftCycle : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        //Note : If page is post back or first time call and you have not set any values to ViewState["value"], then
        //Convert.ToString(ViewState["value"]) is always empty.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreInit";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        //Note : If page is post back or first time call and you have not set any values to ViewState["value"] in privious events, then
        //Convert.ToString(ViewState["value"]) is always empty.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "Init";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected void Page_InitComplete(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        //Note : If page is post back or first time call and you have not set any values to ViewState["value"] in privious events, then
        //Convert.ToString(ViewState["value"]) is always empty.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "InitComplete";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected override void OnPreLoad(EventArgs e)
    {
        //Work and It will assign the values to label.
        //Note : If page is post back and you have set or not set any values to ViewState["value"] in privious events, then
        //Convert.ToString(ViewState["value"]) will always have post back data.
        //E.g: If you string str = Convert.ToString(ViewState["value"]), then str will contain post back values.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreLoad";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "Load";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "btnSubmit_Click";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        //Work and It will assign the values to label.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "LoadComplete";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected override void OnPreRender(EventArgs e)
    {
        //Work and It will assign the values to label.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "PreRender";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected override void OnSaveStateComplete(EventArgs e)
    {
        //Work and It will assign the values to label.
        //But "SaveStateComplete" values will not be available during post back. i.e. View state.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "SaveStateComplete";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }

    protected void Page_UnLoad(object sender, EventArgs e)
    {
        //Work and it will not effect label contrl values, view state and post back data.
        ViewState["value"] = Convert.ToString(ViewState["value"]) + "<br/>" + "UnLoad";
        lblName.Text = Convert.ToString(ViewState["value"]);
    }
}

Output

During the first the Time Page Load is output:

ASP.NET14.jpg

When you click on the Submit Button output:

ASP.NET15.jpg

During the first time the page loads with EnableViewState="false":

ASP.NET16.jpg

When you click on the Submit Button the output with EnableViewState="false":

ASP.NET17.jpg

Example 3: ViewState Values

Please observe the code comments and output. It will help you to clearly understating the concepts.
 
public partial class PageLiftCycle : System.Web.UI.Page
{
    protected void Page_PreInit(object sender, EventArgs e)
    {
        Response.Write("<br/>" + "PreInit");
    }

    protected void Page_Init(object sender, EventArgs e)
    {
        Response.Write("<br/>" + "Init");
    }

    protected void Page_InitComplete(object sender, EventArgs e)
    {
        Response.Write("<br/>" + "InitComplete");
    }

    protected override void OnPreLoad(EventArgs e)
    {
        Response.Write("<br/>" + "PreLoad");
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("<br/>" + "Load");
    }

    protected void Page_LoadComplete(object sender, EventArgs e)
    {
        Response.Write("<br/>" + "LoadComplete");
    }

    protected override void OnPreRender(EventArgs e)
    {
        Response.Write("<br/>" + "PreRender");
    }

    protected override void OnSaveStateComplete(EventArgs e)
    {
        Response.Write("<br/>" + "SaveStateComplete");
    }

    protected void Page_UnLoad(object sender, EventArgs e)
    {
        //Runtime Error : Response is not available in this context.
        //Response.Write("<br/>" + "UnLoad"); //Error
    }
}

Output

ASP.NET18.jpg

Note: If you write Response.Write("<br/>" + "UnLoad"); in the Page_UnLoad event, then it will genenrate the Runtime Error "Response is not available in this context".
ASP.NET19.jpg