June 13, 2011

REST based web services and it's implementation using .net technology

Introduction:
   REST (REpresentational State Transfer) is an architectural approach to design web services that are accessed using HTTP requests and verbs. It applies the architecture of the web to web service. In REST each resource is treated as a distinct resource and provides the functionality for bookmarking , caching etc. Depending on the use of HTTP verbs (GET, POST, DELETE, PUT) REST is divided into two types i.e. HI-REST and LO-REST.
    In HI-REST it uses the verbs (GET, POST, DELETE, PUT) for a particular operations as the following way
    GET : to fetch resource from server
    POST: append to the resource
    PUT:insert and update the resource
    DELETE: to delete the resource
But in the case of LO-REST POST verb is used for insert, update, delete and fetch of the resource.

Implementation:
    Microsoft .net framework introduces a binding called webHttpBinding in Windows Communication Foundation(WCF) for creating and consuming REST based web services. To create a REST based web service we have to follow the below processes.
  • We have to decorate the operation contracts we have defined in our service interface either with WebGet or WebInvoke attribute to make it REST enable (to access this attribute we have to reference System.ServiceModel.Web namespace)
  • Set the binding of endpoint to webHttpBinding in the configuration file.
  • Add a behavior under the endPointBehaviors element that has a webHttp child element
  • Add a behavior configuration to your endpoint that references the endpoint behavior.
When we are using the WebGet attribute the method to access the service method is GET. So we can access it from any browser using the URL like http://localhost/RESTTest/ClientService.svc/Clients/

But when we use the WebInvoke attribute to decorate our operation contract to make it REST enable we have to specify the method of accessing it (i.e. GET, POST, PUT, DELETE). 


Example of Service Interface :
[ServiceContract]
    public interface IProcess
    {
        [OperationContract, WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, Method = "GET",
             RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "Client/{clientID}")]
         ClientBO Process(string clientID);

         [OperationContract, WebGet(BodyStyle = WebMessageBodyStyle.Bare,
              RequestFormat = WebMessageFormat.Xml, ResponseFormat = WebMessageFormat.Xml, UriTemplate = "Clients/")]
          IEnumerable<ClientBO> Process1();

          [OperationContract, WebInvoke(BodyStyle = WebMessageBodyStyle.Bare, Method = "POST",
               ResponseFormat = WebMessageFormat.Xml, UriTemplate = "AddClient/")]
           bool AddClient(Stream client);
    }
Configuration File Setting:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <system.web>
        <compilation debug="true" targetFramework="4.0" />
    </system.web>
    <system.serviceModel>
        <services>
            <service name="RepPoC.RESTService.Process">
                <endpoint address="" binding="webHttpBinding" contract="RepPoC.RESTService.IProcess"
            behaviorConfiguration ="WebBehavior" />
            </service>
        </services>
        <behaviors>
            <endpointBehaviors>
                <behavior name="WebBehavior">
                    <webHttp />
                </behavior>
            </endpointBehaviors>
        </behaviors>
    </system.serviceModel>
</configuration>

Code to Call REST Service:
//GetSerializedData basically takes your object as parameter and serialize it and return the byte array. We need to pass it
//with request
Byte[] postData = GetSerializedData(client);
WebRequest request = WebRequest.Create(new Uri("http://localhost/RESTService/Process.svc/AddClient/"));
request.Method = "POST";
request.ContentLength = postData.Length;
request.ContentType = "text/plain";
Stream postStream ;
postStream = request.GetRequestStream();
postStream.Write(postData, 0, postData.Length );
WebResponse response = request.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
Response.Write(reader.ReadToEnd());


 Advantages of REST:
  •  Provides improved response time and reduces server load due to it's support of caching 
  • Improves server scalability by reducing the need of maintaining session state
  • Does not require a separate resource discovery mechanism , due to the use of hyperlink in representation
  • Network admin can easyly understand what operation is going on the server by looking the URLs
  • Easier to use compared to SOAP based services.
  • Lightweight - Output are in plain XML, not extra markup in output like SOAP
Drawbacks:
  • REST is certainly not a replacement for Web services, as it doesn’t provide the     
    breadth of features like security, quality of service, transactions, queuing etc.
  • Doesn't provide any metadata. The user has implicitly know what a service requires.

May 04, 2011

MVVM design pattern implementation using Silverlight

Introduction:
This article is mainly as per my understanding about the MVVM pattern, and may be I am not correct at every point, So your input are greatly appreciated. After reading few articles on the net I just try to explain this pattern with a simple example in silver light 4 (using visual studio 2010).

Description:
MVVM stands for Model-View-VewModel. It is based on the  MVC design pattern and targeted at modern User Interface development platforms like WPF and Silverlight and helps us building a true application that is more readable, easily testable, re-usable and maintainable. 
One of the main goal of the MVVM pattern is to create an application that is loosely coupled. MVVM pattern mainly built of using three components View, ViewModel and Model.


MVVM Pattern (in this diagram i have included service that is used to communicate with web service/database to fetch data.)




View:
These are the Silverlight/WPF screens and does not contains any code behind. Views in MVVM pattern communicate in the application based on the bindings and commands that are contained in the ViewModel.


Model:
This part holds the data entities, business logic and it is completely independent of the View.


ViewModel:
 This component is responsible for exposing the data objects from the model in such a way that these objects are easily managed and consumes by the view. It acts like a value converter, which converts the raw data from the the Model and make it View friendly and vice-versa. Along with providing data for the Views it also  contains the commands the View can use for interaction in the application.


Note: The key thing of ViewModel is that you have one and only one ViewModel per View.


How it works?:
The ViewModel is typically contains the properties/Collections for the data that is going to be shown by the View. These properties/Collections raises notifications when the data changes. So when the data changes the View can receive the notification to update itself. The View Uses the powerful data binding features provided by the Silverlight/WPF to bind these properties exposed by the ViewModel with the controls that the view is composed of. User events that are captured by the view are sent to the ViewModel by the commands properties, and these commands executes a method in the ViewModel, which in result either sent a request to the Model to process some business logic  or update its own properties so that the View can update automatically.


Why to use MVVM Pattern?:
  • It allows a developer to create an application with no user interface.
  • A designer able to create User Interface without writing a single line of code.
  • As the UI is loosely coupled, It can be changed without changing any code.
Implementation MVVM Pattern using Silverlight:
    Here i am showing a simple example in Silverlight that implements the MVVM pattern. In this example I provide the searching on the employee based on name. So in my screen there are three controls one text box that is used to enter the search text and a button that will do the search operation and a grid to show the result employee list. But in this example i am not using the text box data for searching and just showing some hard coded data, because my purpose here to show the MVVM Pattern implementation.
Silverlight Application

Model Implementation:
    In this example I have used the model as a data entity. Here i have created a base class for model that implements the INotifyPropertyChanged and IDisposable interface. INotifyPropertyChanged Interface is used to notify the view that the property is changed and it have to update itself and the IDisposable interface to provide the dispose functionality to my class.

Model base class code:
public class BaseModel: INotifyPropertyChanged, IDisposable
    {
        #region IDisposable Members
        public void Dispose()
        {
            this.OnDispose();
        }
        public virtual void OnDispose()
        {

        }
        #endregion

        #region INotifyPropertyChanged Members
        /// <summary>
        /// This event is used to notify differnet silverlight binding that the data in changed for one
        /// or more properties so that control can be updated automatically.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// This method is used to raise the PropertyChanged event.
        /// </summary>
        /// <param name="propertyName"></param>
        protected void OnNotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
        #endregion
    }
Model Code:

public class EmployeeModel : BaseModel
    {
        #region [Properties]
        private string firstName;
        public string FirstName
        {
            get
            {
                return firstName;
            }
            set
            {
                firstName = value;
                OnNotifyPropertyChanged("FirstName");
            }
        }

        private string lastName;
        public string LastName
        {
            get
            {
                return lastName;
            }
            set
            {
                lastName = value;
                OnNotifyPropertyChanged("LastName");
            }
        }

        private Int32 age;
        public Int32 Age
        {
            get
            {
                return age;
            }
            set
            {
                age = value;
                OnNotifyPropertyChanged("Age");
            }
        }
        #endregion
       
        #region [Constructors]
        public EmployeeModel(string fName, string lName, Int32 age)
        {
            FirstName = fName;
            LastName = lName;
            Age = age;
        }
        #endregion
    }
Service Implementation:
Service class is used here for communication with the data source or the web service/REST service to retrieve data and set/update the model. In this example i am not using any code for data access or calling any web service. For display purpose i have fixed some data that i can show in this example. You can change this code and try your own.

Employee service interface code:

  public interface IEmpService
    {
        ObservableCollection<EmployeeModel> GetEmployees(string name);
    }
Employee Service Code:

public class EmpService : IEmpService
    {
        #region IEmpService Members
        public System.Collections.ObjectModel.ObservableCollection<Model.EmployeeModel> GetEmployees(string name)
        {
            ObservableCollection<EmployeeModel> empList = new ObservableCollection<EmployeeModel>();

            empList.Add(new EmployeeModel("Prasant", "Swain", 99));
            empList.Add(new EmployeeModel("Prakash", "Samal", 99));

            return empList;
        }
        #endregion
    }

ViewModel Implementation:
Like the implementation of Model here also we have created a base class for all the ViewModel class. It implements the INotifyPropertyChanged interface to provide the functionality to notify the bindings of the View to update itself when any property changes along with this we have defined another class called ProcessCommand that implements the ICommand interface. This class is basically used to bind the events in the View with the ViewModel.


BaseModel Class Code:
public abstract class BaseViewModel:INotifyPropertyChanged
    {
        /// <summary>
        /// This event is used to notify differnet silverlight binding that the data in changed for one
        /// or more properties so that control can be updated automatically.
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;

        /// <summary>
        /// This method is used to raise the PropertyChanged event.
        /// </summary>
        /// <param name="propertyName"></param>
        protected void OnNotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        public bool IsDesignTime
        {
            get
            {
                return DesignerProperties.IsInDesignTool;
                //return (Application.Current == null) || (Application.Current.GetType() == typeof(Application));
            }
        }
    }

ProcessCommand Class Code:
    public class ProcessCommand : ICommand
    {
        #region ICommand Members
        Func<object, bool> canExecute;
        Action<object> execute;
        bool canExecuteFlag;

        public ProcessCommand(Action<object> executeAction)
        {
            this.execute = executeAction;
            this.canExecute = (p) => { return true; };
        }

        public ProcessCommand(Action<object> executeAction, Func<object, bool> canExecute)
        {
            this.canExecute = canExecute;
            this.execute = executeAction;
        }
       
        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            bool tempCanExecute = canExecute(parameter);
            if (this.canExecuteFlag != tempCanExecute)
            {
                this.canExecuteFlag = tempCanExecute;
                if (CanExecuteChanged != null)
                {
                    CanExecuteChanged(this, new EventArgs());
                }
            }
            return tempCanExecute;
        }

        public void Execute(object parameter)
        {
            execute(parameter);
        }
        #endregion
    }
EmployeeViewModel Code:
  public class EmployeeViewModel:BaseViewModel
    {
        #region [Properties]
        private ObservableCollection<EmployeeModel> employees;
        public ObservableCollection<EmployeeModel> Employees
        {
            get
            {
                return employees;
            }
            set
            {
                employees = value;
                OnNotifyPropertyChanged("Employees");
            }
        }

        private EmployeeModel currentEmployee;
        public EmployeeModel CurrentEmployee
        {
            get { return currentEmployee; }
            set
            {
                    currentEmployee = value;
                    OnNotifyPropertyChanged("CurrentEmployee");
            }
        }

        private string searchName;
        public string SearchName
        {
            get
            {
                return searchName;
            }
            set
            {
                if (searchName != value)
                {
                    searchName = value;
                    OnNotifyPropertyChanged("SearchName");
                }
            }
        }

        public ICommand SearchCmd
        {
            get {return new ProcessCommand(SearchCommand, (e) => { return true; });}
        }
        #endregion

        #region [Methods]
        public void SearchCommand(object objParam)
        {
            IEmpService empService = new EmpService();
            Employees = (ObservableCollection<EmployeeModel>)empService.GetEmployees(SearchName);

            CurrentEmployee = employees[0];
        }
        #endregion
    }
View Implementation:
As described above in my view i have used three controls for this example a text box (not using it in this example), a button and a data grid. button is bind with the SearchCmd property and the data grid is bind with the employee list (Employees) which is implemented as a Observable collection.
View Code:
<UserControl x:Class="MVVMPoC.App.MainPage"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:ViewModel="clr-namespace:MVVMPoC.ViewModel;assembly=MVVMPoC.ViewModel"
    mc:Ignorable="d"
    d:DesignHeight="300" d:DesignWidth="400" xmlns:my="clr-namespace:MVVMPoC.App.Controls" xmlns:sdk="http://schemas.microsoft.com/winfx/2006/xaml/presentation/sdk">
    <UserControl.Resources>
        <ViewModel:EmployeeViewModel x:Key="empVM"/>
    </UserControl.Resources>

        <Grid x:Name="LayoutRoot" Background="White" DataContext="{Binding Source={StaticResource empVM}}" Height="247" Width="400">
        <TextBox Height="23" HorizontalAlignment="Left" Margin="42,25,0,0" Name="textBox1" VerticalAlignment="Top" Width="129" DataContext="{Binding Path=SearchCmd, Mode=TwoWay}" />
        <Button Content="Search" Height="23" HorizontalAlignment="Left" Margin="177,25,0,0" Name="button1" VerticalAlignment="Top" Width="75" Command="{Binding Path=SearchCmd}" />
        <sdk:DataGrid AutoGenerateColumns="True" Height="140" HorizontalAlignment="Left" Margin="42,54,0,0" Name="dataGrid1" VerticalAlignment="Top" Width="338" ItemsSource="{Binding Path=Employees, Mode=TwoWay}" />
    </Grid>
</UserControl> 

April 29, 2011

Dispose Vs Finalize

Dispose method is mainly controlled by the developer, and it frees all the resource upon the completion of the event. While Finalize method is controlled by the Garbage Collector(GC) and there is no predictability as to when the GC will call the finalize method to free the resources.


Finalize method cannot be overridden or called explicitly. It is basically used for implicit resource clean-up.


C# provides a USING statement , which ensures that Dispose() method will be called at the earliest possible time (Dispose method is automatically called if the class implements IDisposable and used in USING statement).



April 25, 2011

IDisposable Interface (Disposable Pattern)


Introduction:
    IDisposable Interface is primarily designed to provide a standard way to manage the unmanged resources in the .net applications.
  
Description:
    We know that Garbage Collector(GC) is designed to manage memory allocation in .net applications. So developer have no headache to manage the managed resources as GC manage it implicitly. But when it comes about the unmanaged resources GC have no control over it, because GC is not designed to deal with unmanaged resources, so it is the developers responsibility to manage this unmanaged resources.
   A developer can achieve this by overriding the Finalize method, but the problem with finalize method is that as Garbage Collector does not run in deterministically and in result the object may be wait for finalization for a longer period of time. And this situation becomes more complected if our object is using expensive resources like database connection or file handles, then waiting a long period of time to free these resource is not acceptable. To avoid this waiting of Garbage Collection for an indeterminate amount of time to free resource Disposable Pattern (IDisposable pattern) is used.
      
This Disposable Pattern/IDisposable Interface is basically designed to ensure predictable and reliable cleanup of resource to prevent resource leak and to provide a standard pattern for disposable classes. IDisposable interface defines a single method called Dispose() that need to be implemented by the implemented class. And the developers have to ensure that they implements clean up code using this method.

Example:

   public class MyDisposableClass : IDisposable
    {
        private bool isDisposted = false;

        ~MyDisposableClass()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
        }

        private void Dispose(bool disposing)
        {
            if (!isDisposted)
            {
                if (disposing)
                {
                    //TODO: Wtire your clean up code here
                   
                    //This will remove the object from the finalization queue as the clean up
                    //is already done and finaliztion is not required.
                    GC.SuppressFinalize(this);

                }
                // flag set to ture as dispose is done
                isDisposted = true;
            }
        }
    }



April 21, 2011

HTTP Modules Vs Global.asax File

Differences:
    If you view the functionality provided by the HTTP Modules and the Global.asax file you find both are almost similar, But the advantage of using the HTTP Module over Global.aspx file is that they can be re-used by adding them to the GAC (Global Assembly Cache) and registering in the Machine.config file you can use it across all the application running on that server, while global.asax files are application specific.

   And the advantage of using Global.asax file over HTTP Modules is that it provides some extra events that can not be available during  in the HTTP Module implementation. Those events are :
                            1. Application_start
                            2. Session_Start
                            3. Session_End
                            4. Application_End
Along with this Global.asax also enables you to declare and initialize your global objects in your application. 

Another difference is that you can have one Global.asax file in your application and you have to implement all your required logic on that, But in the case of HTTP Module you can divide your required logic in different modules and can have more than one HTTP Module attached in your application.


April 20, 2011

MVP Design Pattern Implementation using ASP.NET/Win Form

Introduction:
    We have given a task to implement our next project in two different interfaces, One using traditional ASP.NET web pages and another one using the new rich silver-light user interface . And we have to follow the MVP design pattern to implement this. During this process I have gone through the MVP design pattern documents and implementation processes and writing this blog to provide a little bit introductory idea about what is MVP pattern and a simple example to implement this using a web and windows application.


    I have not used the silver-light in this example, because CLR for web application and silver-light CLR are completely different. To implement this you have to develop separate set of view, presenter and model component for web application and for silver-light. There is a trick to solve this by developing the different components for Web application  first and later adding parallel components for silver-light by just adding the link of all the classes and interfaces developed for respective web application components. But my main purpose is to focus on the MVP pattern, so i have taken a example of windows application in place of silver-light.

Description:
MVP pattern stand for Model-View-Presenter design pattern. It is basically built of using three components View, Model and Presenter. It is a derivative of the MVC (Model-View-Control) pattern. 



Model-View-Presenter Pattern




View: It represents the applications presentation layer and responsible for displaying and receiving the user inputs  and handling the user events (i.e. mouse clicks, key down, click etc.) on the controls only. Views does not call directly to the  Models, Instead it invokes the Presenter methods which in-turn calls the Model to get the data and in return updates the view. All concrete view components must implement an interface which defines all the methods and properties which required to be implemented.



Presenter: This component basically communicates with the view to accept user inputs for processing, connect to the model to retrieve the required data or process the requested  business logic and return the view the desired data to show. Presenter have access to the interface of the view. It has no idea about the implementation.


Model: It contains all the business logic of the application. It processes the request from the presenter and do the processing to return it's result to the presenter.


Implementation:
    To describe MVP implementation using asp.net i have created a small application (for giving a general idea of implementation) that search employee by employee code and display employee information on the page. At this moment i have not implemented any logic at model level and just returning a hard coded value for testing purpose. Later we have used the model, view and presenter to implement the same functionality on a windows application without making any change on the core components (Model, View and Presenter).


Implementation Using ASP.NET (Web Page)


Implementation using Windows Application (Win Form)

Creating & Implementing View in Web and Windows application:
   View is basically defines an interface which need to be implemented by the UI layer. This interface is later used by the presenter. This provides the way to lose coupling between view and presenter. Here I have created an interface called IEmpView. This is the interface that is going to be implemented by both the web application and windows application.

Code (IEmpView):
  public interface IEmpView
    {
        string Code { get; }
        string EmpName { set;  }
        string Address { set; }
    }
  
Code (Aspx page code behind): 
  In the code behind of the web application we have implemented the IEmpView interface and implemented the properties exposed by it. And in the Click event of the search button it instantiate the presenter class and call the required method for processing.


  public partial class EmployeeInfo : System.Web.UI.Page, IEmpView
    {
        public string Code
        {
            get  { return txtCode.Text ; }
        }

        public string EmpName
        {
            set { lblName.Text = value; }
        }

        public string Address
        {
            set { lblAddress.Text = value; }
        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            mvpPresenter.EmpPresenter empPresenter = new mvpPresenter.EmpPresenter(this);
            empPresenter.BindData();
        }
    }

Code (Windows application):
    In this section i have used the same interface to develop the application using Windows Form. Similar like the above implementation in web form the windows form implements the IEmpView and implements the properties.
     public partial class EmployeeForm : Form, IEmpView
    {
        public string Code
        {
            get { return txtCode.Text; }
        }

        public string EmpName
        {
            set { lblName.Text = value;}
        }

        public string Address
        {
            set { lblAddress.Text = value; }
        }
        
        private void btnSearch_Click(object sender, EventArgs e)
        {
            mvpPresenter.EmpPresenter empPresenter = new mvpPresenter.EmpPresenter(this);
            empPresenter.BindData();
        }
    }

Creating the Presenter:
    Presenter have no idea about the UI. It does not know the view interface it is interacting is implemented by a windows or web application.Its constructor takes the IEmpView (interface) as parameter.

Code (Presenter):
    public class EmpPresenter
    {
        private readonly IEmpView empView;

        public EmpPresenter(IEmpView view)
        {
            empView = view;
        }

        public void BindData()
        {
            EmpModel model = new EmpModel();
            EmpDTO employee = model.GetEmployee(empView.Code);
            empView.EmpName = employee.Name;
            empView.Address = employee.Address;
        }
    }

This is the DTO class I have used to transfer data between the Model and Presenter.

Code (Employee DTO): 
    public class EmpDTO
    {
        public string Code { set; get; }
        public string Name { set; get; }
        public string Address { set; get; }
        public EmpDTO(string code, string name, string address)
        {
            Code = code;
            Name = name;
            Address = address;
        }
    }

Creating Model: 
    Model class basically holds the business logic of the application. In this example i have hard coded the process logic of GetEmployee() method and it will be replaced by the code to fetch data from database or some external source by communicating with the respective layer.

Code (Interface of Model):
 public interface IEmpModel
    {
        EmpDTO GetEmployee(string empCode);
    }

Code (Concrete Model Class):
    public class EmpModel:IEmpModel
    {
        public EmpModel()
        {
        }

        public EmpDTO GetEmployee(string empCode)
        {
            return new EmpDTO(
empCode, "Prasant Swain", "Kolkata");
        }
    }

So you have noticed that we have implemented our application using different UI without modifying our core components (Model, View and Presenter).



Advantages:
1. Provide the ability to test all the code in the application except the visual appearance and the interaction.
2. Ability to interchange view without modification on the code (Example. it can be easily changed the presentation layer from the web page to a windows form without modification in the core components ( Presenter and Model Component.).
3. It simplifies the testing process.

April 16, 2011

Steps to create a HTTP Handler

Description:
    In this article I am just trying to writing down the steps with code example (C#) to create a simple custom HTTP handler. and configure it on IIS 5.1. The detail description about the HTTP Handler are described on this blog "HTTP Handlers (ASP.NET)"


Step 1: Creation of Handler:
     1. Create a web application (in this example i have created with name HTTPHandlerTest).
     2. Add a class to (I have used MyTestHandler in this example) your application and implement the IHttpHandler Interface. You can also implement the IRequireSessionState Interface if you want to access the session and IReadOnlySessionState if you want to access session data in read only mode.
     3. Implement the ProcessRequest() method and IsReusable Property. IsReusable property  determines whether the handler is pooled or not. If it returns true then the handler is kept on the pool for further user and the ProcessRequest() method to the processing.


    4. Modify the web.config file to register the handler. In this example i have registered the handler to process the the files having extension .test.



<httpHandlers>
    <add verb="*" path="*.test" type="HTTPHandlerTest.MyTestHandler, HTTPHandlerTest"/>
</httpHandlers>


Step 2: Configure the IIS 5.1
     1. Open the Internet Information Services (Control Panel--> Administrative Tool-->Internet Information Services).
     2. Go to "Default Web Site", Right click on it and open Properties.
     3. On the Properties window click on the "Home Directory" tab and click on the "Configuration" Button.
     4. Click on the "Add" button to register the new mapping. 
         In the Executable text box browse the path of the "aspnet_isapi.dll" files location on your machine (i.e. C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\aspnet_isapi.dll) and in the Extension text box enter the extension of the file that is going to process (i.e. i have used .test extension). Press OK to save setting.

Step 3: Testing Your Handler
    1. Add a file with extension .test to your application to test the application (I have added a file called MyTest.test to test it).
    2. Run the application and type "http://localhost:4611/MyTest.test" as URL.

April 13, 2011

HTTP Handlers (ASP.NET)

Description:
    HTTP handlers are .net components that is used the process the incoming request based on the mapped file name extension  in the configuration files (machine.config or web.config). ASP.NET framework defines some built-in handlers for processing. 


Example:
     ASP.NET Page Handler: Handles the request from ASP.NET web pages having extention .aspx
      Web Service Handler: Handlers the web service files having extenstion (*.asmx)
      User Control Handler: Handlers user controls files with extension (*.ascx)
        
List of the mapped HTTP Handler you will find in the config file

HTTP handlers are divided in to two types depending upon the way of generating output of the incoming request.
          1. Synchronous HTTP Handler
          2. Asynchronous HTTP Handler

Synchronous handlers does not return it's processed output until it finishes complete processing of the request, while asynchronous handlers runs a separate process independently to send the response back to user asynchronously.



Creating Custom HTTP Handler:
    To create a custom synchronous HTTP handler you need to implement the IHttpHandler interface and similarly for creating a custom asynchronous HTTP handler it is required to implement IHttpAsyncHandler interface. In both the cases it is required to implement the IsReusable property and ProcessRequest() method. 


IsReusable property determines whether the handler is placed in pool for re-use  or it is re-created every time it is required and ProcessRequest() method do the processing of each request.


Note: Session state is not by default enabled for HTTP Handlers, to enable it you have to implement the IRequiresSessionState or IReadOnlySessionState interface. These two are marker interfaces and there is no method to implement.


Configuring Custom HTTP Handler:
    After creating custom HTTP handler it is required to configure the web server and application to map the incoming request to be handled by the handler.


Steps to configure:
    1. Map the file extension that is going to be processed by your custom handler to ASP.NET ISAPI dll  (aspnet_isapi.dll) in the Internet Service Manager.
    2. Modify the web.config or machine.config file to register your handler.


Note: I have described steps to create a HTTP Handler on this post "Steps to create HTTP Handler"

April 12, 2011

Control State in ASP.NET

Description:
    Sometimes a control needs to store some essential data to work properly. For this purpose we can use view state to store the information. But one of the disadvantages of using view state is that it has the functionality that it can be turned off at control level as well as page level. So you cannot trust on view state to store control’s essential data as you have no control of the page where your control is going to be placed, you have to take care of this to preserve the data required to function control properly. To handle this situation ASP.NET page framework provides a feature called Control State.
    Control state works similar to view state but you cannot disable it like you allowed doing for view state. And it shares the same location with view state in the page to store its data (__VIEWSTATE hidden field).

Implementation:
To implement this you have to follow the following steps.
  1. Override the OnInit() Method and invoke the RegisterRequiredsControlState() method to register the page to participate in control state.
  2. Override the SaveControlState() method to save the control state data.
  3. Override the LoadControlState() method to load the control state data.
Example:
 
Advantages:
     1.       Other user using your control cannot disable the control state.
     2.       Disabling view state will not affect the control.
     3.       Server resource is not required as data is stored on the page.
Disadvantages:
     1.       It is not fully ready made; you have to write a little bit of code to implement this.
     2.       Like the same as view state, if large amount of data is stored then it will affect page performance as these data will travel with the page.

April 10, 2011

State Management in ASP.NET

Description:
    This is the process of maintaining the state of the page information over multiple requests. As we know web pages developed in ASP.NET uses HTTP protocol which is state less. It means each web request is treated as a new request at the web server end. So to build an interactive web application it is very much necessary  to keep the state of the page and user information.
    Depending upon the storage location and process of storage state management is divided in to two categories. 
                        1. Client side state management.
                        2. Server side state management.


Client side state management:
    Client side state management involves storing information on the client side inside the pages or on the client machine. The different types of client side state management options available in ASP.NET are
                                     1. View State
                                     2. Control State
                                     3. Cookies
                                     4. Query String
                                     5. Hidden Field


View State: 
    View State is the technique used by ASP.NET to keep the state of the page across post backs. This section is explained on this blog What is view state and its advantages and disadvantages.


Control State:
    This is almost similar to the view state but its functionality is independent of view state,    it cannot be turned off like we did in view state. This state is mainly designed to keep the essential information of the custom controls. The information of this state are stored in the same hidden field that is used to store the view state data. 


Hidden Fields:
    Hidden fields  provides a way to store information without displaying. It stores a single value in its value field and stores information in HTML format inside the page. This is not a secure way as it can be easily tampered.


Cookies:
    Cookies are basically designed to store small amount of information  that frequently changes. This data are always sent with the request to the web server. Cookies are stored as a text file in the clients file system (persistent cookie) or in memory in the client browser session (temporary cookie). And ASP.NET allow users to set the expiration policy on them. The main disadvantage of using cookie are the size limitation (4096 bytes, new versions of browser now starting supports of 8MB size) which is restricted by most of the browsers. And the other one is user have the option to disallowing cookies on their machine, in this situation cookies have no use.


Query String:
    This is the process of sending information on the URL. The query string data is appended at the end of the URL. This is basically used to submit information back to the current page or to another page. Similar to the cookies query string have also a size limitation on its length and another one is it is not much secure as it is visible in the URL.


Server side state management:
    Server side state management involves storing data at the server end. This technique has high security compared to the client side state management options. But the main disadvantage is that it uses server resource to store information, increase in storage data volume affects the server performance.
    The different server side state management options available in ASP.NET are.
                           1. Application State
                           2. Session State
                           3. Profile Properties
                           4. Database Supports


Application State:
     An application state is basically used to store global application specific information. These are available by the entire application and not user specific like the session data. ASP.NET provides Application state via the HttpApplicationState class.


Session State:
    Session state is used to store the user specific data in the server. It is described in details in the article "What is a session in ASP.NET". 


Profile Properties:
    Like the session state profile properties provide the functionality to store user specific  information. But the difference between them are session data expires with the expiration of the session or on the restart of the application and server while the profile data is never lost, even if on the restarts of application and server. ASP.NET profiler allows to easily mange user information without requiring you to create and maintain your own database. 


Database Support:
    This is in use when you require to persist large amount of information which need to be preserved regardless of application  and server restarts.