Auto Complete Using AutoCompleteExtender

18 Mar

Webservice.cs

using System;using System.Collections.Generic;using System.Web.Services;using System.Data;using System.Data.SqlClient;

[WebService(Namespace = “http://tempuri.org/”)][WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)][System.Web.Script.Services.ScriptService]public class AutoComplete : WebService{
SqlDataReader dr;    DataSet Ds;    public AutoComplete()    {    }
[WebMethod]
public string[] GetCompletionList(string prefixText)    {        SqlConnection con = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings[“SiteSqlServer”].ToString());
List<string> citynm = new List<string>();        string query = “select ValName from autovalue where ValName like ‘” + prefixText + “%'”;        SqlCommand cmdDa = new SqlCommand(query, con);        //cmdDa.Fill(Ds, “autovalue”);        con.Open();        dr = cmdDa.ExecuteReader();        while (dr.Read())        {            string strtemp = Convert.ToString(dr[“ValName”]);
citynm.Add(strtemp);        }        con.Close();        return citynm.ToArray();
}
}

Default.aspx

<%@ Page Language=”C#” MasterPageFile=”~/DefaultMaster.master” AutoEventWireup=”true”    Inherits=”CommonPage” Title=”AutoComplete Sample” Theme=”SampleSiteTheme” %>
<%@ Register Assembly=”AjaxControlToolkit” Namespace=”AjaxControlToolkit” TagPrefix=”ajaxToolkit” %><asp:Content ContentPlaceHolderID=”SampleContent” runat=”Server”>    <ajaxToolkit:ToolkitScriptManager runat=”server” ID=”ScriptManager1″ />    <div >        <div >                  <br />        <br />                <asp:TextBox ID=”txtbox” runat=”server”></asp:TextBox>                <ajaxToolkit:AutoCompleteExtender id=”autoxtender” runat=”server” TargetControlID=”txtbox” MinimumPrefixLength=”1″ServicePath=”AutoComplete.asmx” ServiceMethod=”GetCompletionList” ></ajaxToolkit:AutoCompleteExtender>             <asp:Button ID=”Button1″ runat=”server” Text=”Submit” />

<script type=”text/javascript”>            // Work around browser behavior of “auto-submitting” simple forms            var frm = document.getElementById(“aspnetForm”);            if (frm) {                frm.onsubmit = function() { return false; };            }        </script>
<input type=”submit” style=”display: none;” />    </div>    <div>    </div></asp:Content>

ASP.NET Custom Repeater Control with EmptyTemplate, ShowHeaderWhenEmpty,ShowFooterWhenEmpty,ShowCount Propert

16 Mar

If you have worked with ASP.NET GridView Control you must be aware of GridView.EmptyDataTemplateProperty  which Gets or sets the user-defined content for the empty data row when a GriimagedView control  data source has no records. Similarly ShowHeaderWhenEmptyproperty allows you to show or hide the Header row when there is no records. These are the really good and very frequent required properties. Now, if you are working with the Repeater Control, it doesn’t have any direct features which enables you to set user define content when data source is empty. In this blog post I will discuss how we can create a custom ASP.NET Repeatercontrol with support of EmptyTemplate along with few more important features.

The basis of the complete implementation is stands on developing a custom ASP.NET Control. Here I will be developing a custom ASP.NET Repeater control which inherits  from Repeater as you can see in the bellow code snippet.

image

Now, once you inherits you control from default Repeater control, you have access of all methods and properties of Repeater control. The most important thing to here that you need to know about ITemplateInterface. ITemplate defines the behavior for populating a templated ASP.NET server control with child controls . These ITemplate having a method InstantiateIn which actually instantiate the template with in the control object.  As we required an Template here I created a  properties named “EmptyTemplate” of type “ITemplate”

1 [PersistenceMode(PersistenceMode.InnerProperty)]
2 public ITemplate EmptyTemplate
3 {
4 get;
5 set;
6 }

In the above code snippets you have notices I have added one attributes as

1 PersistenceMode(PersistenceMode.InnerProperty)]

These actually define the type of the property with PersistenceMode Enumeration. InnerProperty tells the control that these properties should be used a inner nested tag not as top level attributes.  I discussed about few other values in later part of this article.

Once we are done with the Property define , we just need to override the CreateChildControls() andOnDataBinding() Events.

01 /// <summary>
02 /// Creates the child controls.
03 /// </summary>
04 protected override void CreateChildControls()
05 {
06 base.CreateChildControls();
07 EnabledEmptyTemplate();
08 }
09
10 /// <summary>
11 /// Raises the DataBinding event.
12 /// </summary>
13 /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
14 protected override void OnDataBinding(EventArgs e)
15 {
16 base.OnDataBinding(e);
17 EnabledEmptyTemplate();
18
19 }
20
21 /// <summary>
22 /// Enableds the empty template.
23 /// </summary>
24 private void EnabledEmptyTemplate()
25 {
26 if (this.Items.Count <= 0 && EmptyTemplate != null)
27 {
28 this.Controls.Clear();
29
30 EmptyTemplate.InstantiateIn(this);
31
32 }
33 }

While overriding those methods, I have internally called a method EnabledEmptyTemplate() which actually checks for the Item Counts, if its &lt;=0,  it will Instantiate the EmptyTemplate.

That’s all. If you build the control, you will get an Control Icon with in ToolBox, which you can directly drag and drop.

image

Now let’s consider you have bellow Student Data Source which you want to bind with this gridview

Sample Student Data Source and binding with repeater

01 public partial class _Default : System.Web.UI.Page
02 {
03 protected void Page_Load(object sender, EventArgs e)
04 {
05 List<MyClass> names = new List<MyClass>()
06 {
07 new MyClass { Name ="Student 1", Address="Address 1"},
08 new MyClass { Name ="Student 2", Address="Address 2"},
09 new MyClass { Name ="Student 3", Address="Address 3"},
10 new MyClass { Name ="Student 4", Address="Address 4"}
11 };
12 ExRepeater1.DataSource = names;
13 ExRepeater1.DataBind();
14 }
15 }
16
17 class MyClass
18 {
19 public string Name { get; set; }
20 public string Address { get; set; }
21 }

Design View for Custom Repeater

01 <cc1:ExRepeater ID="ExRepeater1" runat="server" >
02 <HeaderTemplate>
03 <table>
04 <tr>
05 <td>
06 Name
07 </td>
08 <td>
09 Address
10 </td>
11 </tr>
12 </HeaderTemplate>
13 <ItemTemplate>
14 <tr>
15 <td>
16 <%#Eval("Name")%>
17 </td>
18
19 <td>
20 <%#Eval("Address")%>
21 </td>
22 </tr>
23 </ItemTemplate>
24 <EmptyTemplate>
25 <tr><td> No Records Exist !!!!</td></tr>
26 </EmptyTemplate>
27 <FooterTemplate>
28 </table>
29 </FooterTemplate>
30 </cc1:ExRepeater>

Output

image

Now, if there is no records in the data source, output will be look like below

image

Well, this is exactly what we were looking for. So now you have one Template called “EmptyTemplate” where you can put what ever the content you want to rendered if the data source is empty.

ShowHeaderWhenEmpty

You have noticed, the message “No Records Exists” is being displayed along with the header. Now if you want the same features like GridView, that you need control on the showing or hiding header when records is empty.

Let’s add a bool type property with name ShowHeaderWhenEmpty ,

image

This properties will accepts a Boolean value based on that Header will be shown. One more point over here is,  PersistenceMode.Attribute, which means I am going to use the properties as a top level attributes tag. So ShowHeaderWhenEmpty will be accessible as shown in below

image

Below Snippets describes how to implement the ShowHeaderWhenEmpty Properties.

01 /// <summary>
02 /// Enableds the empty template.
03 /// </summary>
04 private void EnabledEmptyTemplate()
05 {
06 if (this.Items.Count <= 0 && EmptyTemplate != null)
07 {
08 this.Controls.Clear();
09
10 // Instantiate Header Template When Item count 0
11 if (ShowHeaderWhenEmpty == true)
12 {
13 HeaderTemplate.InstantiateIn(this);
14 }
15
16 EmptyTemplate.InstantiateIn(this);
17 }
18 }

ShowFooterWhenEmpty

Like Header, you can implement the same to show or hide footer when there is no records in repeater.

image

01 /// <summary>
02 /// Enableds the empty template.
03 /// </summary>
04 private void EnabledEmptyTemplate()
05 {
06 if (this.Items.Count <= 0 && EmptyTemplate != null)
07 {
08 this.Controls.Clear();
09 EmptyTemplate.InstantiateIn(this);
10 // Instantiate Footer Template When Item count 0
11 if (ShowFooterWhenEmpty == true)
12 {
13 FooterTemplate.InstantiateIn(this);
14 }
15
16 }
17 }

ShowCount

By this properties I just wanted to show the customization or enhancement idea. Let’s say you want to display the number of total records at the end of the repeater, so by using these properties you can enable or disabled it.

image

If you make it true, you will get the number of records count at the end of repeater records.

image

Below is the implementation for the same.

01 /// <summary>
02 /// Enableds the empty template.
03 /// </summary>
04 private void EnabledEmptyTemplate()
05 {
06 if (this.Items.Count <= 0 && EmptyTemplate != null)
07 {
08 this.Controls.Clear();
09
10 // Instantiate Header Template When Item count 0
11 if (ShowHeaderWhenEmpty == true)
12 {
13 HeaderTemplate.InstantiateIn(this);
14 }
15
16 EmptyTemplate.InstantiateIn(this);
17 }
18 }

ShowFooterWhenEmpty

Like Header, you can implement the same to show or hide footer when there is no records in repeater.

image

01 /// <summary>
02 /// Raises the DataBinding event.
03 /// </summary>
04 /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
05 protected override void OnDataBinding(EventArgs e)
06 {
07 base.OnDataBinding(e);
08 EnabledEmptyTemplate();
09 if (ShowCount == true)
10 {
11
12 this.Controls.Add(new LiteralControl("<br/>Total Number of Records : " + this.Items.Count ));
13 }
14 }

Put everything Together :

001 // Custom Repeater With EmptyItemTemplate and ShowHeaderWhenEmpty Properties
002 namespace RepeaterTest
003 {
004 using System;
005 using System.Collections.Generic;
006 using System.Linq;
007 using System.Web;
008 using System.Web.UI.WebControls;
009 using System.ComponentModel;
010 using System.Web.UI;
011
012 /// <summary>
013 /// Advance ASP.NET Repeater with EmptyTemplate, ShowHeaderWhenEmpty, ShowFooterWhenEmpty
014 /// </summary>
015 [ToolboxData("<{0}:ExRepeater runat=server>")]
016 public class ExRepeater : Repeater
017 {
018 #region Repeater Properties
019
020 /// <summary>
021 /// Gets or sets a value indicating whether [show header when empty].
022 /// </summary>
023 /// <value>
024 ///     <c>true</c> if [show header when empty]; otherwise, <c>false</c>.
025 /// </value>
026 [PersistenceMode(PersistenceMode.Attribute)]
027 public bool ShowHeaderWhenEmpty
028 {
029 get;
030 set;
031 }
032
033 [PersistenceMode(PersistenceMode.Attribute)]
034 public bool ShowFooterWhenEmpty
035 {
036 get;
037 set;
038 }
039
040 /// <summary>
041 /// Gets or sets the empty template.
042 /// </summary>
043 /// <value>The empty template.</value>
044 [PersistenceMode(PersistenceMode.InnerProperty)]
045 public ITemplate EmptyTemplate
046 {
047 get;
048 set;
049 }
050
051 /// <summary>
052 /// Gets or sets the empty template.
053 /// </summary>
054 /// <value>The empty template.</value>
055 [PersistenceMode(PersistenceMode.Attribute)]
056 public bool ShowCount
057 {
058 get;
059 set;
060 }
061
062 #endregion
063
064 #region Repeater Methods
065
066 /// <summary>
067 /// Creates the child controls.
068 /// </summary>
069 protected override void CreateChildControls()
070 {
071 base.CreateChildControls();
072 EnabledEmptyTemplate();
073 }
074
075 /// <summary>
076 /// Raises the DataBinding event.
077 /// </summary>
078 /// <param name="e">An <see cref="T:System.EventArgs"/> object that contains the event data.</param>
079 protected override void OnDataBinding(EventArgs e)
080 {
081 base.OnDataBinding(e);
082 EnabledEmptyTemplate();
083 if (ShowCount == true)
084 {
085
086 this.Controls.Add(new LiteralControl("<br/>Total Number of Records : " +this.Items.Count ));
087 }
088 }
089
090 /// <summary>
091 /// Enableds the empty template.
092 /// </summary>
093 private void EnabledEmptyTemplate()
094 {
095 if (this.Items.Count <= 0 && EmptyTemplate != null)
096 {
097 this.Controls.Clear();
098
099 // Instantiate Header Template When Item count 0
100 if (ShowHeaderWhenEmpty == true)
101 {
102 HeaderTemplate.InstantiateIn(this);
103 }
104
105 EmptyTemplate.InstantiateIn(this);
106 }
107 }
108
109 #endregion
110 }
111 }

Summary : In this post I have explained how you can customize your repeater control by adding must needed features likes EmptyTemplate, ShowHeaderWhenEmpty,ShowFooterWhenEmpty,ShowCount.

Getting Added And Deleted Items In A List Using LINQ

16 Mar

Most the time when we work with a list object, finding a newly added items or deleted items becomes a very trivial part of the logic. Sometimes, we endup writing sophisticated logic or loops to get this done. Below code will demonstrate how this can be easily done using LINQ.

Lets assume that we have a list as below.

 

1
2
3
4
List actualList = new List();
actualList.Add(new MyClass() { Id = 1, FirstName = "First Name1", LastName = "Last Name1" });
actualList.Add(new MyClass() { Id = 2, FirstName = "First Name2", LastName = "Last Name2" });
actualList.Add(new MyClass() { Id = 3, FirstName = "First Name3", LastName = "Last Name3" });

Below is the list which will mimic as we have removed 2 items from the list and added 1 item.

 

1
2
3
4
5
List<MyClass> updatedList = new List<MyClass>();
updatedList.AddRange(actualList);
updatedList.RemoveAt(0);
updatedList.RemoveAt(1);
updatedList.Add(new MyClass() { Id = 4, FirstName = "First Name4", LastName = "Last Name4" });

Below LINQ query will give you deleted items from the orginal list.

 

1
2
3
4
5
IEnumerable<MyClass> deletedItems = (IEnumerable<MyClass>)from actualItem in actualList
where !
(from newItem in updatedList select newItem.Id)
Contains(actualItem.Id)
select actualItem;

Below LINQ query will give you added items to the orginal list.

1
2
3
4
5
IEnumerable<MyClass> addedItems = (IEnumerable<MyClass>)from actualItem in updatedList
where !
(from newItem in actualList select newItem.Id)
Contains(actualItem.Id)
select actualItem;

 

Display custom messages or images when there is no records in GridView Data Source

16 Mar

This is a very frequent requirements to display Custom Messages or Images when there is no records in Grid View. I found people used custom code to achieve this. But ASP.NET Gridview having some inbuilt features to do the same.   You can use EmptyDataTemplate using GridView to display any custom message or Images or even web controls to add new records or whatever you want as per your requirements.

image

As shown in above image, I have show 3 different types of custom option ( Notation 3, 4, and 5 ) that you can display if you have no records in gridview .

Let’s have quick look into code snippet for displaying custom message if there is no records

1
2
3
4
5
6
7
8
9
<asp:GridView ID="GridView1"
runat="server"
BackColor="White"
BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4">
<EmptyDataTemplate>
No Records Available
</EmptyDataTemplate>
</asp:GridView>

image

Now if you want to display some images instead of message you have to use below code snippet

 

1
2
3
4
5
6
7
8
9
<asp:GridView ID="GridView1"
runat="server"
BackColor="White" BorderColor="#CC9966"
BorderStyle="None" BorderWidth="1px" CellPadding="4">
<EmptyDataTemplate>
<asp:Image ImageUrl="~/Images/NoRecords.png" runat="server" />
<a href="Default.aspx">Try to Reload</a>
</EmptyDataTemplate>
</asp:GridView>

image

You have also noticed that, not only showing the images, I have given some hyperlink to reload the data, that link can be anything that you wants.

And finally, you can give some option to add new records forms if there no records founds as shown in below snippets

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<EmptyDataTemplate>
<table border="0" cellpadding="0" cellspacing="0">
<tr>
<td colspan="2">
<b> <span style="color:red;" >No Records Founds</span>. Add New Records</b>
</td>
</tr>
<tr>
<td>
Roll
</td>
<td>
<asp:TextBox ID="textRoll" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Name
</td>
<td>
<asp:TextBox ID="textName" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Address
</td>
<td>
<asp:TextBox ID="textAddress" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td colspan="2">
<asp:Button ID="buttonAdd" runat="server" Text="Add New Records" OnClick="AddRecords />
</td>
</tr>
</table>
</EmptyDataTemplate>

image

 

How to expand specific Tree View Node programmatically in ASP.NET ?

16 Mar

ASP.NET TreeView control is a server side control for displaying data in a hierarchical formats. TreeView  contains multiple nodes and sub nodes. Many times we bind a large number of data with tree view for users to navigate data, pages, or displaying any other details information. If there are many nodes and sub nodes in TreeView, sometime  it’s quite difficult for a user  to find out a specific nodes. On that kind of situation we can give a functionally to user so that they can search for the tree node and can be expand automatically if its found.

image

In this case you can use FindNode() method to find a particular node and then use Expand() method to expand that particular node.  FindNode() take node name as argument and return TreeNode if it’s found. You may even use ExpandAll() method to expand all the subsequent child nodes.

Expanding Specific Node using Expand() Method

 

 protected void buttonSearch_Click(object sender, EventArgs e)
    {
        aspTreeView.CollapseAll();
         TreeNode searchNode = aspTreeView.FindNode(textSearch.Text);
        if (searchNode != null)
            searchNode.Expand();

    }

image

 

Expanding all subsequent Child Nodes using ExpandAll() Method

 

 protected void buttonSearch_Click(object sender, EventArgs e)
    {
        aspTreeView.CollapseAll();
         TreeNode searchNode = aspTreeView.FindNode(textSearch.Text);
        if (searchNode != null)
            searchNode.ExpandAll();

    }

image

 

ASP.NET Validation Control with Images Notification

16 Mar

Most of the time we used simple text messages for error notifications when ASP.NET validator  control fails the validation. But the interesting things with ASP.NET validation controls is instead of simple text we can display images as error notification. Not only images we can embed sounds or we can display some html format text as well.

To achieve instead of  setting ErrorMessage property of an Validation control, you need to set Text Property with proper HTML content.

image

image

Not only images, you can also display additional information as an html content or normal text message.

image

image

 

How to Display “Yes” or “No” Instead of Checkbox while binding Boolean value with GridView

16 Mar

If you are binding some data source in grid view which having any field type of Boolean then Grid View Rendered it as “Checkbox” . But sometime we may required to display either Yes/ No or “1/0” instead of Checked/ Unchecked Text Box.   Here is an quick tip which described how you can override the checkbox to your required  value in  GridView RowDataBound events.

Let’s consider you have a simple class “Student” with some student records.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
/// <summary>
/// Student Class
/// </summary>
public class Student
{
public int Roll { get; set; }
public string Name { get; set; }
public bool Status { get; set; }
}
/// <summary>
/// Handles the Load event of the Page control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
protected void Page_Load(object sender, EventArgs e)
{
List<Student> students = new List<Student>();
students.Add(new Student { Roll = 1, Name = "Abhijit", Status=true});
students.Add(new Student {Roll=2,Name="Manish",Status=false});
students.Add(new Student { Roll = 3, Name = "Atul", Status = true });
GridView2.DataSource = students;
GridView2.DataBind();
}

Now if you run the application you will get below out put Which is the default behavior of GridView

 

clip_image001

Now Change the binding during on RowDataBound of GridView

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
/// <summary>
/// Handles the RowDataBound event of the GridView2 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Web.UI.WebControls.GridViewRowEventArgs"/> instance containing the event data.</param>
protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowType == DataControlRowType.DataRow)
{
Student s = (Student)e.Row.DataItem;
if (s.Status == true)
{
e.Row.Cells[2].Text = "1";
}
else
{
e.Row.Cells[2].Text = "0";
}
}
}

 

Now if you run the application, your output will be looks like below.

clip_image003

Instead of 1/0 you can use “Yes/No”  or whatever value you want instead of Checkbox.

 

Session in ASP.Net

16 Mar


What is Session ?

Web is Stateless, which means a new instance of the web page class is re-created each time the page is posted to the server. As we all know HTTP is a stateless protocol, it can’t hold the client information on page. If user inserts some information, and move to the next page, that data will be lost and user would not able to retrieve the information. So what we need? we need to store information. Session provides that facility to store information on server memory. It can support any type of object to store along with our custom object. For every client Session data store separately, means session data is stored as per client basis. Have a look at the following diagram.

explor2.jpg

Fig : For every client session data store separately

State Management using session is one of the asp.net best features, because it is secure, transparent from users and we can store any kind of object with in it. Along with advantages, some times session can causes performance issue for heavy traffic sites because its stored on server memory and clients read data from the server itself. Now lets have a look at the advantages and disadvantages of using session in our web application.

Advantages and Disadvantages of Session ?

Following are the basic advantages and disadvantages of using session. I have describe in details with each type of session at later point of time.

Advantages :

  • It helps to maintain user states and data to all over the application.
  • It can easily be implemented and we can store any kind of object.
  • Stores every client data separately.
  • Session is secure and transparent from user.

Disadvantages :

  • Performance overhead in case of large volume of user, because of session data stored in server memory.
  • Overhead involved in serializing and De-Serializing session Data. because In case of StateServer and SQLServer session mode we need to serialize the object before store.

Besides these, there are many advantages and disadvantages of session that are based of session Types. I have Discussed all of them.

Storing and Retrieving values  from Session

Storing and Retrieving values in session are quite similar with ViewState. We can interact with Session State with  System.Web.SessionState.HttpSessionState class, because this provides built in Session Object with Asp.Net Pages.

Following code is used for storing a value to session

Collapse
       //Storing UserName in Session
       Session["UserName"] = txtUser.Text;

Now, let see how we can retrieve values from Session

Collapse
//Check weather session variable null or not
        if (Session["UserName"] != null)
        {
            //Retrieving UserName from Session
            lblWelcome.Text = "Welcome : " + Session["UserName"];
        }
        else
        {
         //Do Something else
        }

we can also store some other object in Session. Following Example shows how to store a DataSet in session.

Collapse
         //Storing dataset on Session
        Session["DataSet"] = _objDataSet;

and following code shows how we can retrieve that dataset from the session

Collapse
//Check weather session variable null or not
        if (Session["DataSet"] != null)
        {
            //Retrieving UserName from Session
            DataSet _MyDs = (DataSet)Session["DataSet"];
        }
        else
        {
            //Do Something else
        }

Ref & for more Information: Read Session Variable Section

Session ID

Asp.Net use 120 bit identifier to track each session. This is secure enough and can’t be reverse engineered. When client communicate with server, only  session id is transmitted, between them. When client request for data, ASP.NET looks on to session ID and retrieves corresponding data. This is done in following steps,

  • Client hits web site and some information is stored in session.
  • Server creates a unique session ID for that clients and stored in Session State Provider .
  • Again client request For some information with that unique session ID from Server.
  • Server,looks on Session Providers, and retrieve the serialized data from state server  and type cast the object .

Just have a look on the pictorial flow,

Fig : Communication of Client, web server, and State Provider

Ref. & for more Information: SessionID in MSDN

Session Mode  and State Provider

In ASP.NET there are following session mode available,

  • InProc
  • StateServer
  • SQLServer
  • Custom

For every session State, there is Session Provider. Following diagram will show you how they are related.

Fig : Session State Architecture

we can choose the session State Provider based on which session state we are selecting. When ASP.NET request for any information based on session ID, session state and its corresponding provider are responsible for sending the proper information based on user. Following tables show, the session mode along with there provider Name.

Session State Mode State Provider
InProc In-Memory Object
StateServer Aspnet_state.exe
SQLServer DataBase
Custom CustomProvider

apart from that, there is another mode, "Off". If we select this option the session will be disabled for the application. But our objective is to use session, so we will look into that four session State Mode.

Ref. & for more Information: Session State Providers

Session States

If we consider about session state, It means all the settings that you have made for your web application for maintaining the session. Session State, it self is a big thing, It says all about your session configuration, Either in web.config or from code behind. In web.config, <SessionState> elements used for setting the configuration of session. Some of them are Mode, Timeout, StateConnectionStringCustom provider etc. I have discussed about each and ever section of connection string. Before I discussed Session Mode, just take a brief overview of Session Event

Session Event

There are two types of session events available in asp.net

  • Session_Start
  • Session_End

you  can handle both this event in  global.asax file of  your web application. When a new session initiate session_start event raised and Session_End event raised when a session is abandoned or expired.

Collapse
  void Session_Start(object sender, EventArgs e)
    {
        // Code that runs when a new session is started

    }

    void Session_End(object sender, EventArgs e)
    {
        // Code that runs when a session ends. 

    }

Ref. and for more Information : Application and Session Events

Session Mode

I have already discussed about the session mode in ASP.NET, Following are the different types of session modes available in ASP.Net.

  • Off
  • InProc
  • StateServer
  • SQLServer
  • Custom

If we set Session Mode="off" in web.config, Session will be disabled to all over the application. For this we need to configure web.config in following way

InPorc Session Mode :

This is the default session mode in Asp.Net. Its stores session Information in Current Application Domain. This is the best session mode which is based on web application Performance. But main disadvantage is that, It will lose the data if we restart the server. There are some more advantages and disadvantages of InProc session mode. I will come to those points again .

Overview of InProc Session Mode :

As I have already discussed  InProc mode session data will be stored on the current application domain. So It is easily and quickly available.

So, InProc session mode store its session data in a memory object on that application domain. This is handled by worker process in application pool. So If we restart the server we will lose the session data. If Client request for the data , state provide read the data from In-Memory Object and return it to the client. In web.config we have to mention Session mode  and also we have to set the Timeout.

explor3.gif

This Session TimeOut Setting keeps session alive for 30 minute. This can be configurable from Code behind too.

Collapse
Session.TimeOut=30;

There are two type of session events available in asp.net Session_Start() and Session_End. It is the only mode that supports the Session_End() event. These events will call after the session timeout period is over. The general flow for the InProc Session State is some thing like this.

Now, when the Session_End() will call that depends on Session Time Out. This is a very fast mechanism because no serialization occurs for storing and retrieving data, and data are staying inside the same application domain.

When Should we use InProc Session Mode ?

InProc is the default session mode. It can be very helpful for a small web sites and where the number of user are very less, We should avoid InProc in case of Web Garden (I will come to this topic in details) Scenario .

Advantages and Disadvantages

Advantages :

  • It store Session data in memory object of current application domain. So  accessing data is very fast and data is easily available.
  • There is not requirements of serialization to store data in InProc Session Mode.
  • Implementation is very easy, just similar to using View State.

Disadvantages :

although InProc Session is fastest, common and default mechanism, It has lots of limitation.

  • If the worker Process or application domain recycles all session data will be lost.
  • Though its fastest, but more session data and more users can affects performance, because of memory.
  • we can’t use it in web Garden scenarios .
  • This session mode is not suitable for web farm scenarios also.

So as per above discussion, we can conclude InProc is very fast session storing mechanism but suitable for small web application. InProc Session Data will get lost if we Restart the server, application domain recycles It is also not suitable for Web Farm and Web Garden Scenarios.

Now have a look that what are the other option  available to overcome these problem. First Come to StateServer Mode.

StateServer Session Mode :

Overview of StateServer Session Mode :

This is also called Out-Proc session mode. StateServer uses a stand-alone Windows Services, which is Independent to IIS and can also run on a separate server. This session state is totally managed by aspnet_state.exe. This server may runs on the same system, but it’s out side of that main  application domain where your web application is running. This allow if you restart your asp.net process restarted your session data will be alive. This approaches has several disadvantages due to the overhead of serialization and de-serialization, its also increases the cost of data access because of every time when user retrieves session data, our application hits a different process.

Configuration for StateServer Session Mode

In StateServer the Session data is stored in a separate Server which is Independent to IIS and Its handled by aspnet_state.exe. This process is run as windows Services. you can start this service from windows MMC or from command prompt.

By default  “Startup Type” of ASP.NET state service is set to manual, we have to set it as  “Automatic”  startup type.

from command from just typing "net start aspnet_state". By default this services listen TCP Port 42424 , but we can change the port from registry editor as given in below picture .

Now have a look on the web.config configuration for StateServer Setting. For State Server Setting we need have to specify the stateConnectionString. This will identify the system that is running state server. By default stateConnectionString used ip as 127.0.0.1 (localhost) and Port 42424.

explor9.gif
When we are using StateServer, we can configure stateNetworkTimeOut attributes to specify the maximum number of seconds to wait for the service to respond before canceling the request. Default time is 10 seconds.

explor10.gif

For using StateServer, the object which we are going to store that should be serialized and at the time of retrieving  we need to De-Serialize. I have described it with an Example.

How StateServer Session Mode Works?

We used StateServer Session Mode to avoid unnecessary session data loss during restart of web Server. StateServer is maintained by process aspnet_state.exe as a windows Services. This process maintains the all the session data. But need to serialize the data before storing it in StateServer Session Mode.

As shown in above figure, that client request to the web server, then web server stores the session data on state server. StateServer may be the current system or may be the different system. But it is totally independent of IIS. Destination of StateServer will  depend on the web.config stateConnectionString attribute settings. If we set it as 127.0.0.1:42424, It will store data on that local system itself. For change the StateServer destination, we need to change the IP. and make sure, aspnet_state.exe is up and running on that system. other wise you will get the following exception while trying to store data on session.

When we are storing any object on session, that should be serialized. That data will be stored to StateServer system using State Provider. and at the time of retrieving the data, State provider will return the data. The complete flow is given in the below picture.

Example Of StateServer Session Mode :

Here is one simple example of  using StateServer Session mode. I have created this sample web application directly on the IIS so that we can easily understand its usage.

Step 1 : Open Visual Studio > File > New > Web Sites . Choose Location as HTTP and create the web application .

Now if you open the IIS you will see a Virtual Directory created with the name of your web application , as in my case it is StateServer.

Step 2 : Create s simple UI that will take Roll No and Name of a student . We will store the name and roll in a state server session. I have also create one same class “StudentInfo" .  This class is given below

Collapse
[Serializable]
public class StudentInfo
{
    //Default Constructor
    public StudentInfo()
    {

    }
    /// <summary>
	/// Create object of student Class
	/// </summary>
	/// <param name="intRoll">Int RollNumber</param>
	/// <param name="strName">String Name</param>
    public StudentInfo(int intRoll, string strName)
	{
        this.Roll = intRoll;
        this.Name = strName;
	}

    private int intRoll;
    private string strName;
    public int Roll
    {
        get
        {
            return intRoll;
        }
        set
        {
            intRoll = value;
        }
    }

    public string Name
    {
        get
        {
            return strName;
        }
        set
        {
            strName = value;
        }
    }
}

Now , have a look on the code behind code. I have just added two button one for storing session and another for retrieving session.

Collapse
protected void btnSubmit_Click(object sender, EventArgs e)
    {

        StudentInfo _objStudentInfo = new StudentInfo(Int32.Parse( txtRoll.Text) ,txtUserName.Text);
        Session["objStudentInfo"] = _objStudentInfo;
        ResetField();
    }
    protected void btnRestore_Click(object sender, EventArgs e)
    {
        StudentInfo _objStudentInfo = (StudentInfo) Session["objStudentInfo"];
        txtRoll.Text = _objStudentInfo.Roll.ToString();
        txtUserName.Text = _objStudentInfo.Name;

    }

Step 3 : Please Configure your web.config for state server. As I have already discussed.  And Please make sure aspnet_state.exe is up and running on that configured server.

Step 4 : Run the Application

Enter the data, Click on Submit.

Now there are following Test that I have made which will totally clear your doubts that how exactly StateServer is useful.

First :Remove the [ Serializable ] key word from the studentinfo class and try to run the application. When you will click on Submit Button you will get following error

Which clearly says that you should have to serialize the object before store.

Second: Run the Application, Store data by clicking on Submit Button. Restart IIS

Now, In case of InProc, you have already lost your session data, But Its StateServer, Click on Restore Session, You will get your original data. Because State server data does not depend on IIS. Its keeps it separately.

Third : Stop the aspnet_state.exe from the Windows Services MMC and Submit the Data. You will get following error,

Because your State Server Process is not running.

So, Please keep in mind about those three points .

Advantages and Disadvantages.

So based on the above discussion

Advantages :

  • Its keeps the data separate from IIS so, any Issue with IIS does not hamper Session data.
  • It is useful in web farm and web garden scenarios.

Disadvantages :

  • Process is slow due to Serialization and De-Serialization
  • State Server always need to be up and running.

Now, I am stopping here on StateServer, You will find some more interesting points on Load balancer, Web Farm, Web Garden Section.

Ref & for more Information:

SQL Server Session Mode :

Overview of SQL Server Session Mode :

This session mode provide us more secure and reliable Session management in asp.net. In this session  mode, the Session data is serialized and stored in the SQL Server database.  Main disadvantages of this session storage methods is overhead related with Data Serialization and De-Serialization. It is the best option for using in the web farms.

To setup SQL Server we need to take help of  two sql Script.

  • For Installing: InstallSqlState.sql
  • For Un-Installing: UninstallSQLState.sql

The most easiest way to configure SQL Server, is using aspnet_regsql command.

I have explained the detailed use of these file in configuration section. This is the most useful state management in the web farm scenario.

When should we use SQL Server Session Mode ?

  • SQL Server Session mode is more reliable and secure session state management.
  • Its keeps data in a centralized location (database).
  • We should use SQL server session mode when we need to implement Session with some more security.
  • If  there happens to be  frequent server Restart we can implement SQL server.
  • This is perfect mode that fits in web farm and web garden scenarios (I have explained in details later) .
  • we can use SQL server Session mode when we need to share session between two different application .

Configuration for SQL Server Session Mode

In SQL Server  Session mode, we are storing session data in a SQL Server, so we need to first provide the database connection string in web.config . sqlConnectionString attribute is used to provide the connection string in web.config.

After setup the connection string we need to configure the SQL Server. I am explaining how to configure your your SQL server using aspnet_regsql command.

Step 1: From Command prompt, Go to your Framework Version Directory

E.g :c:\windows\microsoft.net\framework\<version>.

Step 2 : Run aspnet_regsql command with following parameters

Have a look on the parameter and there uses

Parameters Description
-ssadd Add support for SQLServer mode session state.
-sstype p P is stands for Persisted. Its persist the session data on server
-S Specify Server Name
-U Specify User Name
-P Specify Password

After run you will get the following message,

that’s all .

Step 3 : Open SQL Server Management Studio, Check, A new database ASPState has been created  and there should be two tables,

  • ASPStateTempApplications
  • ASPStateTempSessions

Now, Just change the configuration string of the State Server Example and Run the same application that  I have explained in State Server.

Just store Roll and User Name and Click on Submit button, and open ASPStateTempSessions Table from SQL Server Management Studio.. WoW… here is your session data,

Now. do the following Test that I have already explained in State Server Mode.

  1. Remove The Serialize Key word from StydentInfo Class
  2. Reset IIS and Click on Restore Session
  3. Stop the SQL Server Services

I think I have explained the SQL Server Session mode well.

Advantages and Disadvantages

Advantages :

  • Session data do not  affected if we restart the IIS.
  • It is the most reliable and secure session management.
  • It keeps data located centrally ,  It can be easily accessible from other application.
  • It is  very useful in web farm and web garden scenarios.

Disadvantages :

  • Processing is very slow in nature.
  • Object serialization and de-serialization creates overhead  for application.
  • As the session data is handled in different server, so we have to take care of SQL server. It should be always up and running.

Ref & for more Information : Read SQL Server Mode

Custom Session Mode

Overview of Custom Session Mode :

Generally we use either of InProc, StateServer or SQL Server  Session mode for our application, but we also  need to know the fundamental of Custom Session mode. This session mode is quite interesting, because Custom session gives full control to us to create every thing even session ID. you can write your own algorithm to generate session ID.

You can implement custom providers that store session data in other storage mechanisms simply by deriving from SessionStateStoreProviderBase Class. You can also Generate New Session Id by Implementing ISessionIDManager.

This are the following methods  are called  during  implementation of Custom Session

In Initialize methods we can set the Custom Provider. This will initialize the connection with that specified provider. SetItemExpireCallback used to set SessionTimeOut, we can register any methods that will call at the time of session expire. InitializeRequest is called on every request and CreateNewStoreData used to create a new instance of SessionStateStoreData .

When should we use Custom Session Mode ?

we can use custom session mode in following of the cases,

  • We want to store session data rather than SQL Server.
  • When we have to use some Existing table to store session data.
  • When we need to create our own session ID.

What configuration do we need for it?

We need to configure our web.config like below,

If you want to Explore some thing more please Check Further study section

Advantages and Disadvantages

Advantages :

  • We can use some existing Table for the store session data, It is useful when we have to use some old database rather than SQL Server.
  • It’s not depending on IIS , So Restarting web server does not make any effects on session data.
  • We can crate our own algorithm for generating Session ID.

Disadvantages :

  • Processing of Data is very slow.
  • Creating a custom state provider is a low-level task that needs to be handled carefully to ensure security.

Its always recommended to use any third party provider rather than creating your own.

Ref and More Information : Custom Mode

If you want to know more about details session Mode please Read this MSDN Article

Overview of Production Deployment

Generally Production environments means when we deploy the application on our live production server. This is a major and Big Challenge for the web developer to deploy there application on Live Server. because in a Big production environment there are no of user and its not possible to handle the load of so many users by a single server. Here the concepts came of Web Farm, Load Balancer , Web Garden etc.

Just few month back I have deployed one of our web application In a live production environment which is accessible by  million of user and there were more than 10 Active Directory, more than 10 Web Server Over  Load Balancer and Many DB Server, Exchange  Server, LCS Server etc. If we look at the number of web server, this is multiple. The major risk involves in multiple server is Session Management. Following picture shows the general diagram for a Production environments.

I will try to explain the different scenario that you need to keep in mind while deploying your application.

Application Pool :

This is one of the most important thing that you should create for your own application in Production environment. Application pools used to separate sets of IIS worker processes that share the same configuration. Application pools enable us to isolate our web application for better security, reliability, and availability. The worker process serves as the process boundary that separates each application pool so that when one worker process or application is having an issue or recycles, other applications or worker processes are not affected.

Identity Of Application Pool

Application pool identity configuration is an important aspect of security in IIS 6.0  and IIS 7.0, because it determines the identity of the worker process when the process is accessing resource. This Settings comes from IIS 6.0 In IIS 7.0 there are Three predefine Identity , that are same with IIS 6.0.

Applicationpool Identity Description
LocalSystem LocalSystem is a built-in account that has administrative privileges on the server. It can access both local and remote resources. For any kind accessing of server files or resources we have to set the Identity of application pool to Local System.
LocalServices LocalServices Built-in account has privileges of an authenticated local user account. It does not have any network access permission
NetworkServices This is the default Identity of Application Pool NetworkServices has privileges of authenticated local user account.

Creating and Assigning Application Pool

Open IIS Console, Right Click on Application Pool Folder > Create New

Give the Application Pool ID and Click Ok.

Now, Right Click on the Virtual Directory (I am using StateServer Web sites) and assign the StateServerAppPool to StateServer Virtual Directory.

So, this StateServer Web sites  will run independently with StateServerAppPool. So any problem related with other application does not affects your Application. This is the main advantages of creating application pool separately.

Web Garden

By default Each Application Pool runs with a Single Worker Process (W3Wp.exe). We can Assign multiple Worker Process With a Single Application Pool. An Application Poll with multiple Worker process called Web Gardens.  Many worker processes with same Application Pool can sometimes provide better throughput performance and application response time. And Each Worker Process Should have there own Thread and Own Memory space.

As Given in Picture, in IIS Server there may be multiple Applicationpool and each application pool having at least a single Worker Process. Web Garden should contain multiple Worker process.

There are some Certain Restriction to use Web Garden with your web application. If we use Session Mode to "in proc", our application will not work correctly because session will be handled by different Worker Process. For Avoid this Type of problem we should have to use Session Mode “out proc" and we can use “Session State Server” or “SQL-Server Session State“.

Main Advantage : The worker processes in a Web garden share the requests that arrive for that particular application pool. If a worker process fails, another worker process can continue to process requests.

How To Create Web Garden ?

Right Click on the Application Pool > Go To Performance Tab > Check Web Garden Section (Highlighted in Picture )

By default it would be 1 , Just change it to more than one .

How Session Depends on Web Garden ?

I have already discuss that, InProc is handled by Worker Process. Its keeps data insides its memory object. Now If we have multiple Worker Process, then It would be very difficult to handled the session . because, Each and every Worker process has it own memory, so If my first request goes to WP1 and its keep my session data and Second Request goes to WP2 and I am trying to retrieve session data, it will not able to return . Which will throw error. So please avoid Web Garden in InProc Session Mode.

we can use StateServer or SQLServer Session mode in case of Web Garden , because I have already explained these two session mode does  not depends on Worker Process . In my example, I have also explain, If you restart the IIS then also you are able to get session data.

In Short ,

Session Mode Recommended
InProc No
StateServer Yes
SQLServer Yes

Web Farm and Load Balancer:

This is the most common term that is used in production deployment . This terms comes, when we are using Multiple Web Server for deploying our product. The main reason behind the scene is to distribute the load over the multiple server. Load balancer is used to distribute the load on those server.

If we check the diagram, Client request the url and it will hit a Load Balancer, which decides which server to access.  Load balancer will distribute the traffic over the all web server.

Now how does it affects  session

Handling Session in Web Farm and Load Balancer Scenarios

Handling session is one of the most challenging job in web farm .

InProc : In InProc session mode, session data stored in In-Memory Object of worker process.  So each and every server have its own Worker process and they keep session data inside the memory.

If One server is  down in time and request come to different server, user is not able to get session data. So, it is not recommended to use InProc in Web Farm .

StateServer :I have already explained that what a state server is, how to configure a  StateServer etc. Now From this Web farm scenarios you can easily understand that how much it is important, because all session data will be stored in a Single location .

Remember, In a web farm, make sure you have the same <machinekey> in all your web servers. and Other things are all same as I have describe earlier.  All web.config having the same configuration (stateConnectionString) for Session State.

SQL Server : This is another approach  even best one that we can use in web farm. We need to configure the data base first. The steps I have already covered .

explor37.jpg

as shown in the above picture, all web server session data will be stored in a single SQL Server Database. And it can be easily accessible. Keep one thing in mind, you should serialize object in both state server and SQL Server mode. Any time if one of the web server goes down, Load balancer distribute the loads to other server and that user can able to read session data from server, because data is stored in a centralized DB server.

In summary, we can use either of state server or SQL server session mode in web farm . We should avoid the InProc

Session And Cookies

Clients use cookies to work with session. because the client needs to present the appropriate session ID with each request. we can do it in following ways

Using cookies: ASP.NET creates a special cookies named ASP.NET_SessionId automatically when the session collection is used. This is the default. Session ID is transmitted through that cookies .

Cookie Munging : Some older browser doest not support cookies or user may disable cookies in there browser, in that case ASP.Net  transmitted session ID  in a specially modified (or “munged”) URL.

How Cookie Munging Works ?

When user request for a page on a server, Server  encoded the session id and add it with every  href link  in page. When user click any links ASP.NET decodes that session id and passes it to the page that user requesting. Now the requesting page can retrieve any session variable. This all happens automatically, if ASP.NET detects that the users browser does not support cookies.

How to Implement Cookie Munging ?

For that we have to make session state  Cookie less.

Removing Session From Session Variable

Following are the list of methods that are used to removing the session .

Method Description
Session.Remove(strSessionName); Remove an Item from Session State Collection
Session.RemoveAll() Remove all items from session collection
Session.Clear() Remove all items from session collection  Note: There is no difference between Clear and RemoveAll. RemoveAll() calls Clear(), internally.
Session.Abandon() Cancels the Current Session

Enabling and Disabling Session :

For performance optimization we can enable or disable session. because each and every page read and write access of the page, and this involves some performance overhead. So its always better to enable and disable session based on requirements rather than make it enable always. we can  enable and disable the session State in two ways:

  • Page Level
  • Application Level

Page Level :

we can disable session state in page level using EnableSessionState attributes with in Page directive.

explor38.gif

This will disable the session activities for that particular page

Same way we can make it read only also , It will permit to access session data, but it will not allow writing data on session.

explor39.gif

Application Level :

Session state can be disabled for all over the web application using EnableSessionState property in Web.Config .

explor40.gif

Generally we are use Page level, because some of page may not require any session data or may be only read the session data.

MVC Architecture Model In ASP.NET

16 Mar

Model View Controller architecture (or pattern) allows us to separate different parts of our applications into tiers to fulfill this need.

MVC Overview

Model View Controller architecture aims to separate an application into three parts:

Model: It is the business logic of an application. From an object oriented perspective it would consist of a set of classes that implement the critical functionality of an application from a business point of view.

View: It can consist of every type of interface given to the user. In ASP.NET the view is the set of web pages presented by a web application.

Controller: This part of the architecture is the most difficult to explain, hence the most difficult to implement in many platforms. The controller is the object that allows the manipulation of the view. Usually many applications implement Model-Controller tiers that contain the business logic along with the necessary code to manipulate a user interface. In an ASP.NET application the controller is implicitly represented by the code-behind or the server side code that generates the HTML presented to the user.

Implementing MVC in ASP.NET

A basic diagram that would help us understand perfectly the specific parts that implement the Model View Controller architecture in an ASP.NET application is presented below:

MVC implementation in ASP.NET

MVC Model Implementation

When implementing the business logic of an application it is a must to use a Class Library project in order to generate a .dll file that will encapsulate all the functionality. This is critical as we as professional developers would not like to jeopardize the source code of a software product by placing the actual .cs files as a reference in a web application.

This type of project can be easily created in Visual Studio 2005 under the Visual C# or Visual Basic tabs:

Creating a Class Library Project

As a tutorial example we will develop a simple calculator under a new namespace we will call “Math”.

Once the project is created we will add a class called Calculator:

Adding Calculator class

As the code is very simple and a sample is provided in this tutorial we will not get into much detail as far as how it is developed. The only important thing we need to mention is the way errors have to be handled in this class. Take a look at the following code:

protected float Divide(float fNumber1, float fNumber2)
{
if (fNumber2 == 0)
{
throw new Exception( “Second number cannot be equal to zero.”);
}

return (fNumber1 / fNumber2);

}

When implementing the Divide function we need to ensure that the user would not be able to set the “fNumber2” parameter (line 1) to zero as a division between zero does not exist. The validation statement in lines 3-6 takes care of this case but the important fact we need to notice is that this class will NEVER use specific methods to present errors like message boxes or writing into labels. Errors captured in the model part of the architecture ALWAYS have to be presented in the form of exceptions (line 5). This will allow us to use this object in several types of applications like ASP.NET applications, Windows applications, Web services, etc.

Once we have finished coding our Calculator class the project has to be built in order to get the .dll file we will use in our Web application.

MVC View-Controller Implementation

The View and the Controller objects will be implemented by using a common ASP.NET Website. Once we have created our project we need to add the reference to the .dll file we created before.

The option to do this can be found in the context menu when right-clicking the project in the solution explorer:

Adding the a reference

We can find the file in the path “\bin\Release” (or “\bin\Debug” depending on how you build your class library) inside our main folder containing the math class library project:

Adding Math.dll reference

Once we have referenced our library we will create a simple web page that will allow us to choose between the four basic arithmetic operations and type two different numbers to operate.

The web page will look like this:

Calculator Web page

In the code behind we need to reference the Math namespace in order to use our Calculator class. The following statement will do that:

using Math;

As the code for this application is also simple we will only explain the method called when the “Operate!” button is clicked:

1. protected void btnOperate_Click(object sender, EventArgs e)
2. {
3.   if (pbValidateNumbers())
4.   {
5.        Calculator cOperator = new Calculator();
6.         try
7.         {
8.               txtResult.Text = cOperator.Operate(float.Parse(txtNumber1.Text.Trim()), float.Parse(txtNumber2.Text.Trim()), Convert.ToInt16(rblOperations.SelectedValue)).ToString();
9.               lbError.Text = “”;
10.        }
11.        catch (Exception ex)

12.        {
13.              txtResult.Text = “”;
14.              lbError.Text = ex.Message;
15.        }
16.  }
17.}

In line 3 we call the bool function “pbValidateNumbers” that will return true if the numbers typed in both textboxes are valid. These types of validations have to be performed by the controller object as they allow the interface to work properly and have nothing to do with the business logic.
In line 5 we create an instance of our Calculator class so we can perform the arithmetic operation. We call the method “Operate” (line 8) and return the value in another textbox. An important thing to mention is that we have to use a try-catch statement (lines 6-15) to handle any exception that could be thrown by our method “Operate” as every error caught in our Calculator class is handled by throwing a “digested” exception that is readable to the user.

In the code above we can appreciate how well encapsulated the business logic is, hence it can be reused in several applications without having to code it again.

Advantages of using MVC in ASP.NET

  • There’s no duplicated code.
  • The business logic is encapsulated; hence the controller code is transparent and safer.
  • The business logic can be used in several front ends like Web pages, Web services, Windows applications, services, etc.
  • Exception handling is well managed showing the user only digested error messages.
  • Testing every part of an application is easier as it can be done separately using automated methods.
  • Application changes are easier to apply as they are focused in one part of the architecture only.