Three Tier Architecture in ASP.NET

Three Tier Architecture in ASP.NET

3-tier application is a program which is organized into three major disjunctive tiers on layers. Here we can see that how these layers increase the reusability of codes.
These layers are described below.
1. Application layer or Business layer
2. Business layer
    a. Property layer(Sub layer of business layer)
3. data layer

Advantages of three Tier Architecture.

The main characteristic of a Host Architecture is that the application and databases reside on the same host computer and the user interacts with the host using an unfriendly and dump terminal. This architecture does not support distributed computing (the host applications are not able to connect a database of a strategically allied partner). Some managers found that developing a host application take too long and it is expensive. Consequently led these disadvantages to Client-Server architecture.
Client-Server architecture is 2-Tier architecture because the client does not distinguish between Presentation layer and business layer. The increasing demands on GUI controls caused difficulty to manage the mixture of source code from GUI and Business Logic (Spaghetti Code). Further, Client Server Architecture does not support enough the Change Management. Let suppose that the government increases the Entertainment tax rate from 4% to 8 %, then in the Client-Server case, we have to send an update to each clients and they must update synchronously on a specific time otherwise we may store invalid or wrong information. The Client-Server Architecture is also a burden to network traffic and resources. Let us assume that about five hundred clients are working on a data server then we will have five hundred ODBC connections and several ruffian record sets, which must be transported from the server to the clients (because the Business layer is stayed in the client side). The fact that Client-Server does not have any caching facilities like in ASP.NET, caused additional traffic in the network. Normally, a server has a better hardware than client therefore it is able compute algorithms faster than a client, so this fact is also an additional pro argument for the 3.Tier Architecture. This categorization of the application makes the function more reusable easily and it becomes too easy to find the functions which have been written previously. If programmer wants to make further update in the application then he easily can understand the previous written code and can update easily.

Application layer or Presentation layer

Application layer is the form which provides the user interface to either programmer of end user. Programmer uses this layer for designing purpose and to get or set the data back and forth.

Business layer

This layer is a class which we use to write the function which works as a mediator to transfer the data from Application or presentation layer data layer. In the three tier architecture we never let the data access layer to interact with the presentation layer.

a. Property Layer

This layer is also a class where we declare the variable corresponding to the fields of the database which can be required for the application and make the properties so that we can get or set the data using these properties into the variables. These properties are public so that we can access its values.

Data Access Layer

This layer is also a class which we use to get or set the data to the database back and forth. This layer only interacts with the database. We write the database queries or use stored procedures to access the data from the database or to perform any operation to the database.

Summary

o        Application layer is the form where we design using the controls like textbox, labels, command buttons etc.
o        Business layer is the class where we write the functions which get the data from the application layer and passes through the data access layer.
o        Data layer is also the class which gets the data from the business layer and sends it to the database or gets the data from the database and sends it to the business layer.
o        Property layer is the sub layer of the business layer in which we make the properties to sent or get the values from the application layer. These properties help to sustain the value in a object so that we can get these values till the object destroy.

Data flow from application layer to data layer

You can download sample three tier project, used for this tutorial. Here we are passing the code of the student to the business layer and on the behalf of that getting the data from the database which is being displayed on the application layer.
Presentation Layer:
private void DataGrid1_SelectedIndexChanged(object sender, System.EventArgs e)
{
// Object of the Property layer
       clsStudent objproperty=new clsStudent();

// Object of the business layer
       clsStudentInfo objbs=new clsStudentInfo();           

// Object of the dataset in which we receive the data sent by the business layer
       DataSet ds=new DataSet();                                                

// here we are placing the value in the property “IDâ€
 using the object of the  
   property layer
       objproperty.id=int.Parse(DataGrid1.SelectedItem.Cells[1].Text.ToString());

// In ths following code we are calling a function from the business layer and    passing the object of the property layer which will carry the ID till the 
   database.
              ds=objbs.GetAllStudentBsIDWise(objproperty);

// What ever the data has been returned by the above function into the dataset is
   being populate through the presentation laye.
              txtId.Text=ds.Tables[0].Rows[0][0].ToString();
             txtFname.Text=ds.Tables[0].Rows[0][1].ToString();
             txtAddress.Text=ds.Tables[0].Rows[0][2].ToString();
             txtemail.Text=ds.Tables[0].Rows[0][3].ToString();
             Image1.ImageUrl=ds.Tables[0].Rows[0][4].ToString();
}
Property Layer
// These are the properties has been defined in the property layer. Using the object of the property layer we can set or get the data to or from these properties.
public class clsStudent    // Class for Student Table
       {
             private int _id;
             private string _Name;
             private string _Address;
             private string _Email;
             private string _Picture;
            
             public int id // Property to set or get the value into _id variable
             {
                    get{return _id;}
                    set{_id=value;}
             }
      
             public string Name
             {
                    get{return _Name;}
                    set{_Name=value;}
             }

             public string Address
             {
                    get{return _Address;}
                    set{_Address=value;}
             }
            
             public string Email
             {
                    get{return _Email;}
                    set{_Email=value;}
             }

             public string Picture
             {
                    get{return _Picture;}
                    set{ _Picture=value;}
             }
       }
Business Layer:
"Obj" is the object of the clsStudent class has been defined in the property layer. This function is receiving the property object and passing it to the datalayer class
// this is the function of the business layer which accepts the data from the application layer and passes it to the data layer.
 
public class clsStudentInfo
{
public DataSet GetAllStudentBsIDWise(clsStudent obj)
{
       DataSet ds=new DataSet();
ds=objdt.getdata_dtIDWise(obj);// Calling of Data layer function
       return ds;                        
}
}
Datalayer Layer
// this is the datalayer function which is receiving the data from the business layer and
   performing the required operation into the database

public class clsStudentData // Data layer class
{
   public DataSet getdata_dtIDWise(clsStudent obj) // object of property layer class
       {
       DataSet ds;
       string sql;
       sql="select * from student where StudentId="+obj.id+" order by StudentId";
       ds=new DataSet();
// this is the datalayer function which accepts trhe sql query and performs the
   corresponding operation
       ds=objdt.ExecuteSql(sql);
       return ds;
       }
}

SESSION in asp.net

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.

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. 

Out-Proc Or StateServer Session Mode :  

er 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.

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.

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

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.

net framework

The Microsoft .NET Framework is a software framework that can be installed on computers running Microsoft Windows operating systems. It includes a large library of coded solutions to common programming problems and a virtual machine that manages the execution of programs written specifically for the framework. The .NET Framework supports multiple programming languages in a manner that allows language interoperability, whereby each language can utilize code written in other languages; in particular, the .NET library is available to all the programming languages that .NET encompasses.

how to send email by gmail account with asp.net

Here is an example on how to send HTML email from your ASP.NET page using your Google account.

(This setup can be easily used to send messages via any other SMTP server that requires authentication).

Note: the code snippet assumes you have a Label component on Page with named lblMsg that will show
success/failure message to the user that is sending email.
(But this can be easily changed).
                SmtpClient client = new SmtpClient();
                client.DeliveryMethod = SmtpDeliveryMethod.Network;
                client.EnableSsl = true;
                client.Host = "smtp.gmail.com";
                client.Port = 587;
 
                // setup Smtp authentication
                System.Net.NetworkCredential credentials = 

                    new System.Net.NetworkCredential("your_account@gmail.com", "yourpassword");
                client.UseDefaultCredentials = false;
                client.Credentials = credentials;                
 
                MailMessage msg = new MailMessage();
                msg.From = new MailAddress("your_account@gmail.com");
                msg.To.Add(new MailAddress("destination_address@someserver.com"));
 
                msg.Subject = "This is a test Email subject";
                msg.IsBodyHtml = true;
                msg.Body = string.Format("<html><head></head><body><b>Test HTML Email</b></body>");
 
                try
                {
                    client.Send(msg);
                    lblMsg.Text = "Your message has been successfully sent.";
                }
                catch (Exception ex)
                {
                    lblMsg.ForeColor = Color.Red;
                    lblMsg.Text = "Error occured while sending your message." + ex.Message;
                }


Just make sure you dont overuse it, Google is our friend

how to caputure user cantrol button click event in aspx page

how to caputure user cantrol button click event in aspx page

in ascx page


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class WebUserControl : System.Web.UI.UserControl
{
public event EventHandler obj;


public string st
{
get
{
return this.TextBox1.Text;
}

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

}
protected void Button1_Click(object sender, EventArgs e)
{
obj(sender, e);
}
}


In aspx page


protected void Page_Load(object sender, EventArgs e)
{
WebUserControl1.obj += new EventHandler(Button1_Click);
}

protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = WebUserControl1.st;

}

Handle back button of the browser

Introduction
How many time, it has happened with you that when your client has asked you to that end-user should not be allowed to go back to previous page using browsers back button? But the actual problem is we don't have any control on the browser's back button. The “Back” browser button cannot be actually disabled by a web application as the browser security will not allow this. But yes there are number of workarounds using which we can achieve this functionality.

Solutions
Using JavaScript, we can forward the user to the same page if user presses the back button of the browser. See the code below :

 <script type="text/javascript" language="javascript">
    
    function GoBack()
    {
        window.history.forward();
    }
    </script>
Call this JavaScript function on the onload event of body tag.

<body onload="GoBack();">
This method will always redirect to the user on the current page itself.
For example, user is on page 1 and there is a link on Page 1 which takes user to Page 2. Now when user clicks on the link, browser redirects the control to Page 2. Now from page 2 if user press back button of the browser then user will be redirect to the page 2 itself.
window.history contains the collection of the page visited by the user for particular browser session. As an alternative of window.history.forward(), one can also use window.history.go(+1). As both are same.
But if we want to display web page expired warning on the click of back button as we normally see in all banking sites? Actually what happens is, when you press the back button, browser takes the page from cache and display it on screen. So if we want to show web page expired warning, we should not allow the browser to cache the page. We can achieve this via ASP.NET.
protected void Page_Load(object sender, EventArgs e)
{  
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
}
This code will not allow page to be cached. But one problem with this approach is that this will only work when there are some dynamic content in the page. i.e. change any drop down box value and then try to press back button.
Conclusion
Your comments are always appreciated. If you can find out better solution then this please let me also know.

Enjoy...

execute scaler and execute non querry

ExecuteNonQuery expects to run a command, or a stored procedure, that affects the state of the specified table. This means anything but a query command. You normally use this method to issue an INSERT, UPDATE, DELETE, CREATE, and SET statement.
ExecuteNonQuery returns only the number of rows affected by the command execution, or –1 should this information be unavailable. It doesn’t give you a chance to access any result set generated by the statement or the stored procedure. Actually, there’s really nothing to prevent you from using this method for a query command, but in this case you get neither the resultset nor the number of the affected rows.
cmd.Connection.Open();
nRecsAffected = cmd.ExecuteNonQuery();
cmd.Connection.Close();
// check the record(s) affected here

The number of affected rows is also made available through the RecordsAffected property of the SqlCommand object. This property equals –1 in case of errors or if a query command is executed.
ExecuteScalar expects to run a query command, or more likely a stored procedure, that returns data. However, this method is different from ExecuteReader in that it just makes available, as a scalar value, the first column on the first row of the selected resultset.
cmd.Connection.Open();
Object o = cmd.ExecuteScalar(); cmd.Connection.Close();
// work on the scalar here

The method returns the value as a boxed object. It’s then up to you to unbox or cast that value to the proper, expected type.
ExecuteScalar turns out to be particularly useful when you have statistical or aggregate operations to accomplish on a certain amount of data. In these and similar circumstances, there is just one value that you might want to return back to the caller. Because of its use cases, you normally use this method on more or less complex stored procedures rather than on single SQL statements.


Difference between Varchar & Nvarchar in Sqlserver

NCHAR and NVARCHAR data types are both Unicode character data types with a maximum length of 4,000 characters.  The main difference between these 2 data types is that an NCHAR data type is fixed-length while an NVARCHAR is variable-length.  If the number of characters entered in an NCHAR data type column is less than the specified column length, spaces are appended to it to fill up the whole length.
Another difference is in the storage size wherein the storage size for NCHAR is two times n bytes while for NVARCHAR is two times the number of characters entered (in bytes).
You should use NCHAR data type when the data values in a column are expected to be consistently close to the same size.  On the other hand, you should use NVARCHAR when the data values in a column are expected to vary considerably in size.

Varchar means Variable-length Character string.
Nvarchar will store Unicode characters.Both will be used all most for the same purpose but with little difference.
Varchar will store the 8-bit data in database where as Nvarchar will be stored as 16-bit data in Database.
In Sql server 2005

The size for a table page is 8,196 bytes, and no one row in a table can be more than 8,060 characters.
This in turn limits the maximum size of a VARCHAR to 8,000 bytes.
Varchar (MAX) and Nvarchar (MAX). Varchar (MAX) can hold max of 2,147,483,648 characters and NVARCHAR (MAX) can hold 1,073,741,823 characters. We use Varchar instead of TEXT and NTEXT which cannot be used to passed as variables in a stored procedure where as Varchar (MAX) or Nvarchar (MAX) cannot have such restriction.

If you're in the process of migrating an existing data design for SQL Server 2005, it might make sense to migrate some TEXT / NTEXT fields to VARCHAR (MAX) / NVARCHAR (MAX) types when appropriate.

If you need Unicode support for a given data type, either now or soon enough, go with NVARCHAR. If you're sticking with 8-bit data for design or storage reasons, go with VARCHAR. Note that you can always migrate from VARCHAR to NVARCHAR at the cost of some room -- but you can't go the other way 'round. Also, because NVARCHAR involves fetching that much more data, it may prove to be slower depending on how many table pages must be retrieved for any given operation.

varchar uses 8 bits per character. nvarchar is UNICODE, a double-byte
character set, requiring 16 bits to store each character. UNICODE can
handle languages that are difficult to impossible with single-byte
character sets such as ASCII. If you must support many languages
UNICODE is a very clean way to do it.

A delegate in C#

A delegate in C# is similar to a function pointer in C or C++. Using a delegate allows the programmer to encapsulate a reference to a method inside a delegate object. The delegate object can then be passed to code which can call the referenced method, without having to know at compile time which method will be invoked. Unlike function pointers in C or C++, delegates are object-oriented, type-safe, and secure.
A delegate declaration defines a type that encapsulates a method with a particular set of arguments and return type. For static methods, a delegate object encapsulates the method to be called. For instance methods, a delegate object encapsulates both an instance and a method on the instance. If you have a delegate object and an appropriate set of arguments, you can invoke the delegate with the arguments.
An interesting and useful property of a delegate is that it does not know or care about the class of the object that it references. Any object will do; all that matters is that the method's argument types and return type match the delegate's. This makes delegates perfectly suited for "anonymous" invocation.

Note   Delegates run under the caller's security permissions, not the declarer's permissions.
This tutorial includes two examples:
  • Example 1 shows how to declare, instantiate, and call a delegate.
  • Example 2 shows how to combine two delegates.
In addition, it discusses the following topics:
  • Delegates and Events
  • Delegates vs. Interfaces

Example 1

The following example illustrates declaring, instantiating, and using a delegate. The BookDB class encapsulates a bookstore database that maintains a database of books. It exposes a method ProcessPaperbackBooks, which finds all paperback books in the database and calls a delegate for each one. The delegate type used is called ProcessBookDelegate. The Test class uses this class to print out the titles and average price of the paperback books.
The use of delegates promotes good separation of functionality between the bookstore database and the client code. The client code has no knowledge of how the books are stored or how the bookstore code finds paperback books. The bookstore code has no knowledge of what processing is done on the paperback books after it finds them.



// bookstore.cs
using System;

// A set of classes for handling a bookstore:
namespace Bookstore
{
   using System.Collections;

   // Describes a book in the book list:
   public struct Book
   {
      public string Title;        // Title of the book.
      public string Author;       // Author of the book.
      public decimal Price;       // Price of the book.
      public bool Paperback;      // Is it paperback?

      public Book(string title, string author, decimal price, bool paperBack)
      {
         Title = title;
         Author = author;
         Price = price;
         Paperback = paperBack;
      }
   }

   // Declare a delegate type for processing a book:
   public delegate void ProcessBookDelegate(Book book);

   // Maintains a book database.
   public class BookDB
   {
      // List of all books in the database:
      ArrayList list = new ArrayList();  

      // Add a book to the database:
      public void AddBook(string title, string author, decimal price, bool paperBack)
      {
         list.Add(new Book(title, author, price, paperBack));
      }

      // Call a passed-in delegate on each paperback book to process it:
      public void ProcessPaperbackBooks(ProcessBookDelegate processBook)
      {
         foreach (Book b in list)
         {
            if (b.Paperback)
            // Calling the delegate:
               processBook(b);
         }
      }
   }
}

// Using the Bookstore classes:
namespace BookTestClient
{
   using Bookstore;

   // Class to total and average prices of books:
   class PriceTotaller
   {
      int countBooks = 0;
      decimal priceBooks = 0.0m;

      internal void AddBookToTotal(Book book)
      {
         countBooks += 1;
         priceBooks += book.Price;
      }

      internal decimal AveragePrice()
      {
         return priceBooks / countBooks;
      }
   }

   // Class to test the book database:
   class Test
   {
      // Print the title of the book.
      static void PrintTitle(Book b)
      {
         Console.WriteLine("   {0}", b.Title);
      }

      // Execution starts here.
      static void Main()
      {
         BookDB bookDB = new BookDB();

         // Initialize the database with some books:
         AddBooks(bookDB);     

         // Print all the titles of paperbacks:
         Console.WriteLine("Paperback Book Titles:");
         // Create a new delegate object associated with the static
         // method Test.PrintTitle:
         bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(PrintTitle));

         // Get the average price of a paperback by using
         // a PriceTotaller object:
         PriceTotaller totaller = new PriceTotaller();
         // Create a new delegate object associated with the nonstatic
         // method AddBookToTotal on the object totaller:
         bookDB.ProcessPaperbackBooks(new ProcessBookDelegate(totaller.AddBookToTotal));
         Console.WriteLine("Average Paperback Book Price: ${0:#.##}",
            totaller.AveragePrice());
      }

      // Initialize the book database with some test books:
      static void AddBooks(BookDB bookDB)
      {
         bookDB.AddBook("The C Programming Language",
            "Brian W. Kernighan and Dennis M. Ritchie", 19.95m, true);
         bookDB.AddBook("The Unicode Standard 2.0",
            "The Unicode Consortium", 39.95m, true);
         bookDB.AddBook("The MS-DOS Encyclopedia",
            "Ray Duncan", 129.95m, false);
         bookDB.AddBook("Dogbert's Clues for the Clueless",
            "Scott Adams", 12.00m, true);
      }
   }
}