Friday, 5 December 2014

Friend Function in ASP .Net

Friend Function:-

 If  a function is defined as friend function then it can access all private and protected members of the class.Friend fuction is the friend of the class so it can access all the memeber of the class .it can define outside of the class.

EXAMPLE:-

#include <iostream>
 
using namespace std;
 
class Box
{
   double width;
public:
   friend void printWidth( Box box );
   void setWidth( double wid );
};

// Member function definition
void Box::setWidth( double wid )
{
    width = wid;
}

// Note: printWidth() is not a member function of any class.
void printWidth( Box box )
{
   /* Because printWidth() is a friend of Box, it can
    directly access any member of this class */
   cout << "Width of box : " << box.width <<endl;
}
 
// Main function for the program
int main( )
{
   Box box;
 
   // set box width without member function
   box.setWidth(10.0);
   
   // Use friend function to print the wdith.
   printWidth( box );
 
   return 0;
}

Difference between Virtual Method and Abstract Method in ASP .Net


Virtual methods have an implementation and provide the derived classes with the option of overriding it. Abstract methods do not provide an implementation and forces the derived classes to override the method.
So, abstract methods have no actual code in them, and subclasses HAVE TO override the method. Virtual methods can have code, which is usually a default implementation of something, and any subclasses CAN override the method using the override modifier and provide a custom implementation.
public abstract class E
{
    public abstract void AbstractMethod(int i);

    public virtual void VirtualMethod(int i)
    {
        // Default implementation which can be overridden by subclasses.
    }
}

public class D : E
{
    public override void AbstractMethod(int i)
    {
        // You HAVE to override this method
    }
    public override void VirtualMethod(int i)
    {
        // You are allowed to override this method.
    }
}

Abstract Method in Asp .Net

Abstract Method :-

If method is define as abstract method then it can not contain a implementation but it can forcely allow to derived class to override that method.


 EXAMPLE:-


public abstract class Shape
{
   public abstract void Paint(Graphics g, Rectangle r);
}
public class Ellipse: Shape
{
   public override void Paint(Graphics g, Rectangle r) {
      g.DrawEllipse(r);
   }
}
public class Box: Shape
{
   public override void Paint(Graphics g, Rectangle r) {
      g.DrawRect(r);
   }
}

Virtual function in Asp.Net

Virtual function in Asp.Net :-

 If method is define as a virtual method in base class then we can allow the derived class to override that method.


Example of Virtual Method in .Net:


Class parent
{
virtual void hello()
{ Console.WriteLine(“Hello from Parent”); }
}

Class child : parent
{
override void hello()
{ Console.WriteLine(“Hello from Child”); }
}

static void main()
{
parent objParent = new child();
objParent.hello();
}

//Output
Hello from Child.



Difference between Function and Store Procedure in Sql Server

Basic Difference:-

  1. Function must return a value but in Stored Procedure it is optional( Procedure can return zero or n values).
  2. Functions can have only input parameters for it whereas Procedures can have input/output parameters .
  3. Functions can be called from Procedure whereas Procedures cannot be called from Function.

Constructor and Destructor:-

1)Constructor:-

It is a member function having same name as it’s class and which is used to initialize the objects of that class type with a legel initial value. Constructor is automatically called when object is created.

 

Types of Constructor

Default Constructor-: A constructor that accepts no parameters is known as default constructor. If no constructor is defined then the compiler supplies a default constructor.
Circle :: Circle()
{
    radius = 0;
}
Parameterized Constructor -: A constructor that receives arguments/parameters, is called parameterized constructor.
Circle :: Circle(double r)
{
    radius = r; 
}
Copy Constructor-: A constructor that initializes an object using values of another object passed to it as parameter, is called copy constructor. It creates the copy of the passed object.

Circle :: Circle(Circle &t)
{
    radius = t.radius; 
}

There can be multiple constructors of the same class, provided they have different signatures.

2)Destructor

A destructor is a member function having sane name as that of its class preceded by ~(tilde) sign and which is used to destroy the objects that have been created by a constructor. It gets invoked when an object’s scope is over.
~Circle() {}

Example : In the following program constructors, destructor and other member functions are defined inside class definitions. Since we are using multiple constructor in class so this example also illustrates the concept of constructor overloading
#include<iostream>
using namespace std;
 
class Circle //specify a class
{
    private :
        double radius; //class data members
    public:
        Circle() //default constructor
        {
            radius = 0;
        }
        Circle(double r) //parameterized constructor
        {
            radius = r;
        }
        Circle(Circle &t) //copy constructor
        {
            radius = t.radius;
        }
        void setRadius(double r) //function to set data
        {
            radius = r;
        }
        double getArea()
        {
            return 3.14 * radius * radius;
        }
        ~Circle() //destructor
        {} 
};
 
int main()
{
    Circle c1; //defalut constructor invoked
    Circle c2(2.5); //parmeterized constructor invoked
    Circle c3(c2); //copy constructor invoked
    cout << c1.getArea()<<endl;
    cout << c2.getArea()<<endl;
    cout << c3.getArea()<<endl;
    return 0;
}
 

Difference between convert.tostring() and .tostring() in Asp.Net

Convert.tostring() :-  

                                   It can handle null values.


.tostring():-  


                                   It cannot handle null values.

Tuesday, 2 December 2014

State Management

Types of state management  

There are two types of state management techniques: client side and server side.


-:Client side:-

  1. Hidden Field
  2. View State
  3. Cookies
  4. Control State
  5. Query Strings

-:Server side:-

  1. Session
  2. Application

-:Client Side Methods:-

1. Hidden field:-

Hidden field is a control provided by ASP.NET which is used to store small amounts of data on the client. It store one value for the variable and it is a preferable way when a variable's value is changed frequently. Hidden field control is not rendered to the client (browser) and it is invisible on the browser. A hidden field travels with every request like a standard control’s value.
Let us see with a simple example how to use a hidden field. These examples increase a value by 1 on every "No Action Button" click. The source of the hidden field control is.
 


Example:- 
<asp:HiddenField ID="HiddenField1" runat="server"  /> 
 

In the code-behind page:
protected void Page_Load(object sender, EventArgs e)
{
   if (HiddenField1.Value != null)
   {
    int val= Convert.ToInt32(HiddenField1.Value) + 1;
    HiddenField1.Value = val.ToString();
    Label1.Text = val.ToString();
   }
}
protected void Button1_Click(object sender, EventArgs e)
{
  //this is No Action Button Click
}

2. View state:-

View state is another client side state management mechanism provided by ASP.NET to store user's data, i.e., sometimes the user needs to preserve data temporarily after a post back, then the view state is the preferred way for doing it. It stores data in the generated HTML using hidden field not on the server.
View State provides page level state management i.e., as long as the user is on the current page, state is available and the user redirects to the next page and the current page state is lost. View State can store any type of data because it is object type but it is preferable not to store a complex type of data due to the need for serialization and deserilization on each post back. View state is enabled by default for all server side controls of ASP.NET with a property EnableviewState set to true.
Let us see how ViewState is used with the help of the following example. In the example we try to save the number of postbacks on button click.
 


protected void Page_Load(object sender, EventArgs e)
{
    if (IsPostBack)
    {
        if (ViewState["count"] != null)
        {
            int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
            Label1.Text = ViewstateVal.ToString();
            ViewState["count"]=ViewstateVal.ToString();
        }
        else
        {
            ViewState["count"] = "1";
        }
    }
}
protected void Button1_Click(object sender, EventArgs e)
{
       Label1.Text=ViewState["count"].ToString();
}

3)Cookies:-

Cookie is a small text file which is created by the client's browser and also stored on the client hard disk by the browser. It does not use server memory. Generally a cookie is used to identify users.
A cookie is a small file that stores user information. Whenever a user makes a request for a page the first time, the server creates a cookie and sends it to the client along with the requested page and the client browser receives that cookie and stores it on the client machine either permanently or temporarily (persistent or non persistence). The next time the user makes a request for the same site, either the same or another page, the browser checks the existence of the cookie for that site in the folder. If the cookie exists it sends a request with the same cookie, else that request is treated as a new request.


Types of Cookies:-

1. Persistence Cookie: Cookies which you can set an expiry date time are called persistence cookies. Persistence cookies are permanently stored till the time you set.
Let us see how to create persistence cookies. There are two ways, the first one is:
 


Response.Cookies["nameWithPCookies"].Value = "This is A Persistance Cookie";
Response.Cookies["nameWithPCookies"].Expires = DateTime.Now.AddSeconds(10); 

And the second one is:
 


HttpCookie aCookieValPer = new HttpCookie("Persistance");
aCookieValPer.Value = "This is A Persistance Cookie";
aCookieValPer.Expires = DateTime.Now.AddSeconds(10);
Response.Cookies.Add(aCookieValPer);
 

2. Non-Persistence Cookie: Non persistence cookies are not permanently stored on the user client hard disk folder. It maintains user information as long as the user accesses the same browser. When user closes the browser the cookie will be discarded. Non Persistence cookies are useful for public computers.
Let us see how to create a non persistence cookies. There are two ways, the first one is:
 


Response.Cookies["nameWithNPCookies"].Value = "This is A 
Non Persistance Cookie";

And the second way is:
 


HttpCookie aCookieValNonPer = new HttpCookie("NonPersistance");
aCookieValNonPer.Value = "This is A Non Persistance Cookie;
Response.Cookies.Add(aCookieValNonPer);how to create cookie : 

How to read a cookie:
 


if (Request.Cookies["NonPersistance"] != null)
Label2.Text = Request.Cookies["NonPersistance"].Value;

Let's understand persistence and non persistence cookies more clearly with a diagram:

Limitation of cookies: The number of cookies allowed is limited and varies according to the browser. Most browsers allow 20 cookies per server in a client's hard disk folder and the size of a cookie is not more than 4096 bytes or 4 KB of data that also includes name and value data.


4. Control State:-

Control State is another client side state management technique. Whenever we develop a custom control and want to preserve some information, we can use view state but suppose view state is disabled explicitly by the user, the control will not work as expected. For expected results for the control we have to use Control State property. Control state is separate from view state.
How to use control state property: Control state implementation is simple. First override the OnInit() method of the control and add a call for the Page.RegisterRequiresControlState() method with the instance of the control to register. Then override LoadControlState and SaveControlState in order to save the required state information.



-:Server side:-

1. Session:-

Session management is a very strong technique to maintain state. Generally session is used to store user's information and/or uniquely identify a user (or say browser). The server maintains the state of user information by using a session ID. When users makes a request without a session ID, ASP.NET creates a session ID and sends it with every request and response to the same user.
How to get and set value in Session:
 


Session["Count"] = Convert.ToInt32(Session["Count"]) + 1; 
//Set Value to The Session
Label2.Text = Session["Count"].ToString(); //Get Value from the Sesion 
 

Let us see an example where we save the count of button clicks in a session, and save the “number of redirects to the same page” button click in a query string. Here I have set the expiry to 10 minutes. After starting the application, the application variable exists till the end of the application. A session variable will expire after 10 minutes (if it is idle). A query string contains the value in URL so it won’t depend on the user idle time and could be used by the server anytime it is passed with a request.


Session Events in ASP.NET  :-

To manage a session, ASP.NET provides two events: session_start and session_end that is written in a special file called Global.asax in the root directory of the project.

Session_Start: The Session_start event is raised every time a new user makes a request without a session ID, i.e., new browser accesses the application, then a session_start event raised. Let's see the Global.asax file.
 


void Session_Start(object sender, EventArgs e)
{
   Session["Count"] = 0;  // Code that runs when a new session is started
}
 

Session_End: The Session_End event is raised when session ends either because of a time out expiry or explicitly by using Session.Abandon(). The Session_End event is raised only in the case of In proc mode not in the state server and SQL Server modes.
There are four session storage mechanisms provided by ASP.NET:
  • In Proc mode 
  • State Server mode  
  • SQL Server mode 
  • Custom mode  
In Process mode: In proc mode is the default mode provided by ASP.NET. In this mode, session values are stored in the web server's memory (in IIS). If there are more than one IIS servers then session values are stored in each server separately on which request has been made. Since the session values are stored in server, whenever server is restarted the session values will be lost.
 


<configuration>
 <sessionstate mode="InProc" cookieless="false" timeout="10" 
    stateConnectionString="tcpip=127.0.0.1:80808" 
    sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;
                                     Password=password"/>
</configuration> 
 

In State Server mode: This mode could store session in the web server but out of the application pool. But usually if this mode is used there will be a separate server for storing sessions, i.e., stateServer. The benefit is that when IIS restarts the session is available. It stores session in a separate Windows service. For State server session mode, we have to configure it explicitly in the web config file and start the aspnet_state service.
 


<configuration><sessionstate mode="stateserver" cookieless="false" 
   timeout="10"  stateConnectionString="tcpip=127.0.0.1:42424"  
   sqlConnectionString="Data Source=.\SqlDataSource;User ID=userid;
                                    Password=password"/> </configuration> 
 

In SQL Server mode: Session is stored in a SQL Server database. This kind of session mode is also separate from IIS, i.e., session is available even after restarting the IIS server. This mode is highly secure and reliable but also has a disadvantage that there is overhead from serialization and deserialization of session data. This mode should be used when reliability is more important than performance.

<configuration>
    <sessionstate mode="sqlserver" cookieless="false" timeout="10" 
       stateConnectionString="tcpip=127.0.0.1:4  2424" 
       sqlConnectionString="Data Source=.\SqlDataSource;
                          User ID=userid;Password=password"/>
</configuration>
 
Custom Session mode: Generally we should prefer in proc state server mode or SQL Server mode but if you need to store session data using other than these techniques then ASP.NET provides a custom session mode. This way we have to maintain everything customized even generating session ID, data store, and also security.
Attributes  Description 
Cookieless true/false  Indicates that the session is used with or without cookie. cookieless set to true indicates sessions without cookies is used and cookieless set to false indicates sessions with cookies is used. cookieless set to false is the default set. 
timeout Indicates the session will abound if it is idle before session is abounded explicitly (the default time is 20 min).
StateConnectionStringIndicates the session state is stored on the remote computer (server). This attribute is required when session mode is StateServer
SqlConnectionStringIndicates the session state is stored in the database. This attribute is required when session mode is SqlServer



2. Application:-

Application state is a server side state management technique. The date stored in application state is common for all users of that particular ASP.NET application and can be accessed anywhere in the application. It is also called application level state management. Data stored in the application should be of small size.
How to get and set a value in the application object:
 


Application["Count"] = Convert.ToInt32(Application["Count"]) + 1;
 //Set Value to The Application Object
Label1.Text = Application["Count"].ToString();
 //Get Value from the Application Object 

Application events in ASP.NET:-

There are three types of events in ASP.NET. Application event is written in a special file called Global.asax. This file is not created by default, it is created explicitly by the developer in the root directory. An application can create more than one Global.asax file but only the root one is read by ASP.NET.
Application_start: The Application_Start event is raised when an app domain starts. When the first request is raised to an application then the Application_Start event is raised. Let's see the Global.asax file.
 


void Application_Start(object sender, EventArgs e)
{
    Application["Count"] = 0;
}
 

Application_Error: It is raised when an unhandled exception occurs, and we can manage the exception in this event.
Application_End: The Application_End event is raised just before an application domain ends because of any reason, may IIS server restarting or making some changes in an application cycle.
So we have talked about various types of state management techniques in this article. I have tried to touch several topics in this article but the main intention for this article was to get the user familiar with the various state management techniques that exist in ASP.NET. The details for all these techniques will make a complete article by itself which I will try to post in future.

OOPS Concept

-:Classes and Objects in OOPS:-

Classes are the most important constituents of Object Oriented Programming.

A class is just a template which contains the various attributes and functions of an object of the class.

For example,
Consider a class bird.
A bird class will have the following attributes:
1. Color
2. Height
3. Weight
4. Habitat
5. nature
It will also have the following functions
1. Flight
2. Sound
etc.,

A class gives you only the attributes.

If you ask 10 different persons to think of a bird and describe, each one will describe it differently. Because it is just a general name.

An object is a run-time entity of a class.
Say, you create an object parrot from the class bird. Then you know the value for all the parameters for this particular object. If you create another object duck, then this object will also have all the parameters defined for the class bird. But, the values for the parameters would be different from that of the object parrot.

 

-:Encapsulation:-

Encapsulation is the first pillar or principle of object-oriented programming. In simple words, “Encapsulation is a process of binding data members (variables, properties) and member functions (methods) into a single unit”. And Class is the best example of encapsulation.

"Wraping up data into single unit is know as a Encapsulation "

 

Need or purpose of encapsulation:-

  • To hide and prevent code (data) from the outside world (here the world means other classes and assemblies).
  • To prevent code (data) from accidental corruption due to programming errors so that we can deliver expected output. Due to programming mistakes, code may not behave properly and it has an effect on data and then it will affect the functionality of the system. With encapsulation we can make variables, properties, and methods private so it is not accessible to all but accessible through proper channels only to protect it from accidental corruption from other classes.

-:Polymorphism:-


Polymorphism means one name many forms. Polymorphism means one object behaving as multiple forms. One function behaves in different forms. In other words, "Many forms of a single object is called Polymorphism."

 

Real World Example of Polymorphism

Example 1

  • A Teacher behaves with student.
  • A Teacher behaves with his/her seniors.
Here teacher is an object but the attitude is different in different situations.

Example 2

  • Person behaves as a SON in house, at the same time that person behaves like an EMPLOYEE in the office.

Example 3

Your mobile phone, one name but many forms:
  • As phone
  • As camera
  • As mp3 player
  • As radio
With polymorphism, the same method or property can perform different actions depending on the run-time type of the instance that invokes it.
There are two types of polymorphism:
  1. Static or compile time polymorphism
  2. Dynamic or runtime polymorphism


  • Function Overloading:-  

                    Function name is same but argument or data type must be different in same class.


  • Function Overriding:-  

              Function name is same and argument or data type also must be same but they are in different class.


    -:Inheritance:-


    Inheritance is a mechanism of acquiring the features and behaviors of a class by another class. The class whose members are inherited is called the base class, and the class that inherits those members is called the derived class. Inheritance implements the IS-A relationship.

    For example, mammal IS-A animal, dog IS-A mammal; Hence dog IS-A animal as well.

     

    Advantages:-

  1. Reduce code redundancy.
  2. Provides code reusability.
  3. Reduces source code size and improves code readability.
  4. Code is easy to manage and divided into parent and child classes.
  5. Supports code extensibility by overriding the base class functionality within child classes.

     Disadvantages

  1. In Inheritance base class and child classes are tightly coupled. Hence If you change the code of parent class, it will get affects to the all the child classes.
  2. In class hierarchy many data members remain unused and the memory allocated to them is not utilized. Hence affect performance of your program if you have not implemented inheritance correctly.

   -:Different Types of Inheritance:-

   OOPs supports the six types of inheritance as given below-

   1)Single inheritance:-

    In this inheritance, a derived class is created from a single base class.
 

2)Multi-level inheritance:-


In this inheritance, a derived class is created from another derived class.

3)Multiple inheritance:-


In this inheritance, a derived class is created from more than one base class. This inheritance is not supported by .NET Languages like C#, F# etc.
 

4)Multipath inheritance:-


In this inheritance, a derived class is created from another derived classes and the same base class of another derived classes. This inheritance is not supported by .NET Languages like C#, F# etc.
 

5)Hierarchical inheritance:-


In this inheritance, more than one derived classes are created from a single base.

6)Hybrid inheritance:-


This is combination of more than one inheritance. Hence, it may be a combination of Multilevel and Multiple inheritance or Hierarchical and Multilevel inheritance or Hierarchical and Multipath inheritance or Hierarchical, Multilevel and Multiple inheritance.
Since .NET Languages like C#, F# etc. does not support multiple and multipath inheritance. Hence hybrid inheritance with a combination of multiple or multipath inheritance is not supported by .NET Languages.

Authentication and Authorization

Difference between authentication and authorization in asp.net

Asp .net architecture

-:Asp .Net Architecture:


1)CLR(Common Language Runtime)

 
  




Introduction :
CLR: Common Language Runtime is the heart of .NET Framework used to manage the program written in .NET Framework compatible language (Eg. C#, Vb.NET, J# etc.). In other words, CLR is Execution Engine which executes the program for .NET Framework.
CLR: Common Language Runtime is the heart of .NET Framework used to manage the program written in .NET Framework compatible language (Eg. C#, Vb.NET, J# etc.). In other words,  CLR is Execution Engine which executes the program for .NET Framework.
Let's see some other definitions of CLR:
The common language runtime is the execution engine for .NET Framework applications.
It provides a number of services, including the following:
  • Code management (loading and execution)
  • Application memory isolation
  • Verification of type safety
  • Conversion of IL to native code
  • Access to metadata (enhanced type information)
  • Managing memory for managed objects
  • Enforcement of code access security
  • Exception handling, including cross-language exceptions
  • Interoperation between managed code, COM objects, and pre-existing DLLs (unmanaged code and data)
  • Automation of object layout
  • Support for developer services (profiling, debugging, and so on)
    (Source MSDN)
The Common Language Runtime (CLR) is the virtual machine component of Microsoft''s .NET initiative. It is Microsoft''s implementation of the Common Language Infrastructure (CLI) standard, which defines an execution environment for program code. The CLR runs a form of byte code called the Common Intermediate Language (CIL, previously known as MSIL (Microsoft Intermediate Language)
(source Wikipedia).


How CLR Works?

When we write a program in .NET compatible language, then the compiler for C#(csc) or VB.NET(vbc) compiles the code in IL (Intermediate Language) or MSIL(Microsoft Intermediate Language) and then IL will be the input of CLR's component Just In Time compiler to produce machine independent code.
Apart from the above CLR is also responsible for:
Memory management
Thread management
Exception handling
Garbage collection
Security


 



2)CLS(Common Language Specification)


CLS: It is a set of base rules, all .Net languages has to adopt to interoperate with each other. Most importantly after compilation any .Net language program has to generate the same type of output code known as Common Intermediate Language code as shown below.
                                  



3)CTS(Common Type System)


CTS: According to CTS(Common Type System), all .Net languages has to adopt uniform data structure i.e., similar types must be uniform in size in all languages of .Net. 

Most of the languages under .Net are derived from same existing language, so names of the data types will be differ from language to language. Even if the names are different  similar data types will always be same in size. 

A data type that is used in any language after compilation will be converted into IL type where in IL format all similar types will be same as following.
                            




4)FCL(Framework class Library)


The .Net Framework class library (FCL) provides the core functionality of .Net Framework architecture . The .Net Framework Class Library (FCL) includes a huge collection of reusable classes , interfaces, and value types that expedite and optimize the development process and provide access to system functionality.

The .Net Framework class library (FCL) organized in a hierarchical tree structure and it is divided into Namespaces. Namespaces is a logical grouping of types for the purpose of identification. Framework class library (FCL) provides the consistent base types that are used across all .NET enabled languages. The Classes are accessed by namespaces, which reside within Assemblies. The System Namespace is the root for types in the .NET Framework. The .Net Framework class library (FCL) classes are managed classes that provide access to System Services . The .Net Framework class library (FCL) classes are object oriented and easy to use in program developments. Moreover, third-party components can integrate with the classes in the .NET Framework.

Difference between Web.config and Machine.config

There are two types of configuration files supported by ASP.Net. Configuration files are used to control and manage the behavior of a web application.
  1. Machine.config
  2. Web.config
Difference between Machine.Config and Web.Config


Machine.Config:-

  1. This is automatically installed when you install Visual Studio. Net.
  2. This is also called machine level configuration file.
  3. Only one machine.config file exists on a server.
  4. This file is at the highest level in the configuration hierarchy.

Web.Config:-

  1. This is automatically created when you create an ASP.Net web application project.
  2. This is also called application level configuration file.
  3. This file inherits setting from the machine.config

3-Tier Architecture in asp.net using c#

3 tier architecture example in asp.net with C#:-


Introduction


Here I will explain about uses of 3-Tier architecture and how to create or implement 3-tier architecture for our project in asp.net 


Description

1.    What is the use of 3-tier architecture and why we go for that architecture? 
2.    First we need to know what 3-Tier architecture is. 
3.    How to create 3-Tier architecture for our project?

 Uses of 3-Tier Architecture

  

1.    To make application more understandable. 
2.    Easy to maintain, easy to modify application and we can maintain good look of architecture.
   If we use this 3-Tier application we can maintain our application in consistency manner.   
Basically 3-Tier architecture contains 3 layers
1.    Application Layer or Presentation Layer 
2.    Business Access Layer(BAL) or Business Logic Layer(BLL) 
3.    Data Access Layer(DAL)
Here I will explain each layer with simple example that is User Registration



1)Application Layer or Presentation Layer

Presentation layer contains UI part of our application i.e., our aspx pages or input is taken from the user. This layer mainly used for design purpose and get or set the data back and forth. Here I have designed my registration aspx page like this

This is Presentation Layer for our project Design your page like this and double click on button save now in code behind we need to write statements to insert data into database this entire process related to Business Logic Layer and Data Access Layer.
Now we will discuss about Business Access Layer or Business Logic Layer 



2)Business Access Layer (BAL) or Business Logic Layer (BLL)

 
This layer contains our business logic, calculations related with the data like insert data, retrieve data and validating the data. This acts as a interface between Application layer and Data Access Layer
Now I will explain this business logic layer with my sample
I have already finished form design (Application Layer) now I need to insert user details into database if user click on button save. Here user entering details regarding Username, password, Firstname, Lastname, Email, phone no, Location. I need to insert all these 7 parameters to database. Here we are placing all of our database actions into data access layer (DAL) in this case we need to pass all these 7 parameters to data access layers.
In this situation we will write one function and we will pass these 7 parameters to function like this
String Username= InserDetails (string Username, string Password, string Email, string Firstname, string Lastname, string phnno, string Location)
If we need this functionality in another button click there also we need to declare the parameters like string Username, string Password like this rite. If we place all these parameters into one place and use these parameters to pass values from application layer to data access layer by using single object to whenever we require how much coding will reduce think about it for this reason we will create entity layer or property layer this layer comes under sub of group of our Business Logic layer
Don't get confuse just follow my instructions enough
How we have to create entity layer it is very simple 
Right click on your project web application---> select add new item ----> select class file in wizard ---> give name as BEL.CS because here I am using this name click ok
 Open the BEL.CS class file declare the parameters like this in entity layer 
Don’t worry about code it’s very simple for looking it’s very big nothing is there just parameters declaration that’s all check I have declared whatever the parameters I need to pass to data access layer I have declared those parameters only 
BEL.CS

#region Variables
/// <summary>
/// User Registration Variables
/// </summary>
private string _UserName;
private string _Password;
private string _FirstName;
private string _LastName;
private string _Email;
private string _Phoneno;
private string _Location;
private string _Created_By;
#endregion
/// <summary>
/// Gets or sets the <b>_UserName</b> attribute value.
/// </summary>
/// <value>The <b>_UserName</b> attribute value.</value>
public string UserName
{
get
{
return _UserName;
}
set
{
_UserName = value;
}
}
/// <summary>
/// Gets or sets the <b>_Password</b> attribute value.
/// </summary>
/// <value>The <b>_Password</b> attribute value.</value>
public string Password
{
get
{
return _Password;
}
set
{
_Password = value;
}
}
/// <summary>
/// Gets or sets the <b>_FirstName</b> attribute value.
/// </summary>
/// <value>The <b>_FirstName</b> attribute value.</value>
public string FirstName
{
get
{
return _FirstName;
}
set
{
_FirstName = value;
}
}
/// <summary>
/// Gets or sets the <b>_LastName</b> attribute value.
/// </summary>
/// <value>The <b>_LastName</b> attribute value.</value>
public string LastName
{
get
{
return _LastName;
}
set
{
_LastName = value;
}
}
/// <summary>
/// Gets or sets the <b>_Email</b> attribute value.
/// </summary>
/// <value>The <b>_Email</b> attribute value.</value>
public string Email
{
get
{
return _Email;
}
set
{
_Email = value;
}
}
/// <summary>
/// Gets or sets the <b>_Phoneno</b> attribute value.
/// </summary>
/// <value>The <b>_Phoneno</b> attribute value.</value>
public string Phoneno
{
get
{
return _Phoneno;
}
set
{
_Phoneno = value;
}
}
/// <summary>
/// Gets or sets the <b>_Location</b> attribute value.
/// </summary>
/// <value>The <b>_Location</b> attribute value.</value>
public string Location
{
get
{
return _Location;
}
set
{
_Location = value;
}
}
/// <summary>
/// Gets or sets the <b>_Created_By</b> attribute value.
/// </summary>
/// <value>The <b>_Created_By</b> attribute value.</value>
public string Created_By
{
get
{
return _Created_By;
}
set
{
_Created_By = value;
}
Our parameters declaration is finished now I need to create Business logic layer how I have create it follow same process for add one class file now give name called BLL.CS. Here one point don’t forget this layer will act as only mediator between application layer and data access layer based on this assume what this layer contains. Now I am writing the following BLL.CS(Business Logic layer)

#region Insert UserInformationDetails
/// <summary>
/// Insert UserDetails
/// </summary>
/// <param name="objUserBEL"></param>
/// <returns></returns>
public string InsertUserDetails(BEL objUserDetails)
{
DAL objUserDAL = new DAL();
try
{
return objUserDAL.InsertUserInformation(objUserDetails);
}
catch (Exception ex)
{
throw ex;
}
finally
{
objUserDAL = null;
}
}
#endregion
Here if you observe above code you will get doubt regarding these
what is
BEL objUserDetails
DAL objUserDAL = new DAL();
and how this method comes
return objUserDAL.InsertUserInformation(objUserDetails);
Here BEL objUserDetails means we already created one class file called BEL.CS with some parameters have you got it now I am passing all these parameters to Data access Layer by simply create one object for our BEL class file 
What is about these statements I will explain about it in data access layer
DAL objUserDAL = new DAL();
return objUserDAL.InsertUserInformation(objUserDetails);
this DAL related our Data access layer. Check below information to know about that function and Data access layer



3)Data Access Layer(DAL)

 
Data Access Layer contains methods to connect with database and to perform insert,update,delete,get data from database based on our input data
I think it’s to much data now directly I will enter into DAL
Create one more class file like same as above process and give name as DAL.CS
Write the following code in DAL class file

//SQL Connection string
string ConnectionString = ConfigurationManager.AppSettings["LocalConnection"].ToString();
#region Insert User Details
/// <summary>
/// Insert Job Details
/// </summary>
/// <param name="objBELJobs"></param>
/// <returns></returns>
public string InsertUserInformation(BEL objBELUserDetails)
{
SqlConnection con = new SqlConnection(ConnectionString);
con.Open();
SqlCommand cmd = new SqlCommand("sp_userinformation", con);
cmd.CommandType = CommandType.StoredProcedure;
try
{
cmd.Parameters.AddWithValue("@UserName",objBELUserDetails.UserName);
cmd.Parameters.AddWithValue("@Password", objBELUserDetails.Password);
cmd.Parameters.AddWithValue("@FirstName", objBELUserDetails.FirstName);
cmd.Parameters.AddWithValue("@LastName", objBELUserDetails.LastName);
cmd.Parameters.AddWithValue("@Email", objBELUserDetails.Email);
cmd.Parameters.AddWithValue("@PhoneNo", objBELUserDetails.Phoneno);
cmd.Parameters.AddWithValue("@Location", objBELUserDetails.Location);
cmd.Parameters.AddWithValue("@Created_By", objBELUserDetails.Created_By);
cmd.Parameters.Add("@ERROR", SqlDbType.Char, 500);
cmd.Parameters["@ERROR"].Direction = ParameterDirection.Output;
cmd.ExecuteNonQuery();
string strMessage = (string) cmd.Parameters["@ERROR"].Value;
con.Close();
return strMessage;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
con.Close();
con.Dispose();
}
}
#endregion
Here if you observe above functionality I am getting all the parameters by simply creating BEL objBELUserDetails. If we create one entity file we can access all parameters through out our project by simply creation of one object for that entity class based on this we can reduce redundancy of code and increase re usability
Observe above code have u seen this function before? in BLL.CS i said i will explain it later got it in DAL.CS I have created one function InsertUserInformation and using this one in BLL.CS by simply creating one object of DAL in BLL.CS.
Here you will get one doubt that is why BLL.CS we can use this DAL.CS directly into our code behind  we already discuss Business logic layer provide interface between DAL and Application layer by using this we can maintain consistency to our application.
Now our Business Logic Layer is ready and our Data access layer is ready now how we can use this in our application layer write following code in your save button click like this

protected void btnsubmit_Click(object sender, EventArgs e)
{
string Output = string.Empty;
if (txtpwd.Text == txtcnmpwd.Text)
{
BEL objUserBEL = new BEL();
objUserBEL.UserName = txtuser.Text;
objUserBEL.Password = txtpwd.Text;
objUserBEL.FirstName = txtfname.Text;
objUserBEL.LastName = txtlname.Text;
objUserBEL.Email = txtEmail.Text;
objUserBEL.Phoneno = txtphone.Text;
objUserBEL.Location = txtlocation.Text;
objUserBEL.Created_By = txtuser.Text;
BLL objUserBLL = new BLL();
Output = objUserBLL.InsertUserDetails(objUserBEL);
}
else
{
Page.RegisterStartupScript("UserMsg", "<Script language='javascript'>alert('" + "Password mismatch" + "');</script>");
}
lblErrorMsg.Text = Output;
}
Here if you observe I am passing all parameters using this BEL(Entity Layer) and we are calling the method InsertUserDetails by using this BLL(Business Logic Layer)
Now run your applciation test with debugger you can get idea clearly.
I hope it helps you.