14 May 2010

Form Authentication.

Security is one of the most important components of any application. Security is even more important when you are making a web application which is exposed to millions of users. Asp.net provides classes and methods that ensure that the application is secure from outside attacks. In this article we will investigate the Forms authentication in Asp.net which provides a powerful way of securing applications
Every one familiar what authentication is and what ASP .NET is, I just want to share my experience with it and how we implimented in our application.Ok, as a ground work let me directly jump to the different types of  Authentication options we have.
The three main types of authentication available in ASP .NET are:
1) Windows Authentication
2) Forms Authentication
3) Passport Authentication
Now let’s check how authentication takes place with ASP.NET
1) The request is first served by IIS server. IIS check for the IP of incoming request and allow or deny access according to the allowable domain access configuration.
2) Next thing is IIS will perform it’s authentication it is configured to do. By default it allows all access but you can always go back and change it per application.
3) Once this is done request is passed to ASP .NET application itself where the authentication of the user is performed according to the setting made in WEB.CONFIG and further the resources are allowed or denied to the user. Please see the besideflow chart for more details.
Now we will go back to the Authentication technique.Just want to explain two lines.
Windows Authentication: will allow you to authenticate user on windows account and credentials. IIS does this for you and passes and credential to code page if required. This is used when the application is an INTRANET application and uses are fixed.
Passport Authentication: uses Microsoft passport services to authenticate user. This is used when you have different application hosed on a server and you want to provide single time authentication to user. What I mean is once he/she is authenticated he/she will be authorized to access other applications without any authentication process which has passport authentication as its authentication method.
Forms Authentication: This is the most commonly used method of authentication. Simple THML forms are used to collect user data and they are validated against your database and custom configuration for specific user.
Well ,now let me go ahead and share my experience with Forms Authentication.
Forms (Cookie)
The Forms authentication provider is an authentication scheme that makes it possible for the application to collect credentials using an HTML form directly from the client. The client submits credentials directly to your application code for authentication. If your application authenticates the client, it issues a cookie to the client that the client presents on subsequent requests. If a request for a protected resource does not contain the cookie, the application redirects the client to the logon page.
Now lets go ahead and impliment the same :
By default it is set to the Windows authentication mode in order to change this to forms authentication you will just need to change the windows to forms as I have shown below:.To implement forms authentication you must create your own logon page and redirect URL for unauthenticated clients. You must also create your own scheme for account authentication. The following is an example of a Web.config configuration using Forms authentication:

Okay so now you have set your application to use the features of the forms authentication instead of the windows authentication.This Login.aspx form should ask for whatever credentials you want (username/password for example) and validate them against the logic that we have given. Once they have been validated you only need to execute the following code to have the user redirected back to the page they were originally trying to access. Simple right ?
How the Control Flow in Forms Authentication ?
The sequence diagram shows the sequence of events that occur during forms authentication. In our Application we are making LDAP call to authenticate the user.So the logic for validating the user against Active Directory will be happening Login.aspx Login button click.If Login successful proceed to default.aspx page else throw message to user in Login page.aspx only.

12 May 2010

Microsoft Enterprise Library 5.0 Release

Microsoft Enterprise Library is a popular collection of reusable software components (called application blocks) designed to address common cross-cutting concerns of enterprise application developers (such as logging, validation, data access, exception handling, and more). Entlib is provided as source code, test cases, and documentation that can be used "as is" or extended, and encapsulates the Microsoft recommended and proven practices for .NET application development.Well,just heard about Microsoft has released its Enterprise Library 5.0 (April 2010).Was eager to look in the new blocks shiped with it and want to share the same with you.
History
I was just going through the older versions of releases and found:
There have been several versions of the Microsoft Enterprise Library:
• Enterprise Library 5.0 (April 2010) - Current
• Enterprise Library 4.1 (October 2008) - Active
• Enterprise Library 4.0 (May 2008) - Active
• Enterprise Library 3.1 (May 2007) - Active
• Enterprise Library 3.0 (April 2007) - Deprecated
• Enterprise Library 2.0 (January 2006) - Active/Retired
• Enterprise Library 1.1 (June 2005) - Deprecated
• Enterprise Library 1.0 (January 2005) - Deprecated
What’s new in v 5.0?
Version 5.0 does not add any new Application Blocks, but instead concentrates on improving what was there in v 4.1. The available application blocks are:
• Caching Application Block
• Cryptography Application Block
• Data Access Application Block
• Exception Handling Application Block
• Logging Application Block
• Policy Injection Application Block
• Security Application Block
• Unity Application Block
• Validation Application Block
Microsoft has released Enterprise Library 5.0 and it’s available for  download now.
Just to describe in little more words According to MSDN site
• Major architectural refactoring that provides improved testability and maintainability through full support of the dependency injection style of development
• Dependency injection container independence (Unity ships with Enterprise Library, but you can replace Unity with a container of your choice)
• Programmatic configuration support, including a fluent configuration interface and an XSD schema to enable IntelliSense
• Redesign of the configuration tool to provide:
  -  A more usable and intuitive look and feel
  - Extensibility improvements through meta-data driven configuration visualizations that replace the requirement to write design time code
  - A wizard framework that can help to simplify complex configuration tasks
• Data accessors for more intuitive processing of data query results
• Asynchronous data access support
• Honoring validation attributes between Validation Application Block attributes and DataAnnotations
• Integration with Windows Presentation Foundation (WPF) validation mechanisms
• Support for complex configuration scenarios, including additive merge from multiple configuration sources and hierarchical merge
• Optimized cache scavenging
• Better performance when logging
• Support for the .NET 4.0 Framework and integration with Microsoft Visual Studio 2010
• Improvements to Unity
• A reduction of the number of assemblies
More information please visit below link.

11 May 2010

Web Development Improvements with VS 2010

There are many more features shipped with Visual studio 2010 which helps you to develope web application. I was just going through some of the features that provided by VS2010 as well as ASP 4.0.
ASP.NET MVC
ASP.NET MVC was introduced as an add-on framework to ASP.NET 3.5 SP1 in March 2009. Visual Studio 2010 includes ASP.NET MVC 2, which includes new features and capabilities.This let you group controllers and views into sections of a large application in relative isolation from other sections. Each area can be implemented as a separate ASP.NET MVC project that can then be referenced by the main application. This helps manage complexity when you build a large application and makes it easier for multiple teams to work together on a single application.
This will be a very small piece of ice berg. Well, I am going to have a separate thread on ASP.NET MVC.
IntelliSense Enhancements - JavaScript
VS 2010 has come up with rich developer experience in JavaScript writing. They have included intelligence to recognize objects that have been dynamically generated by methods such as register Namespace and by similar techniques used by other JavaScript frameworks. They also addressed the performance of display IntelliSense with little or no processing delay. Documentation comments are now parsed as you type and are immediately leveraged by IntelliSense.
HTML and JavaScript Snippets
In the HTML editor, IntelliSense auto-completes tag names. The IntelliSense Snippets feature auto-completes entire tags and more. Visual Studio 2010 includes over 200 snippets that help you auto-complete common ASP.NET and HTML tags, including required attributes (such as runat="server") and common attributes specific to a tag (such as ID, Text etc).It is also support download of additional snippets, including you can write your own snippets that encapsulate the blocks of markup that you or your team use for common tasks.
CSS Improvements
One of the major areas of work in 2010 has been to help render HTML that is compliant with the latest HTML standards. This includes changes to how ASP.NET Web server controls use CSS styles.
New Project Templates
In earlier version of ASP.NET when we create a web application it creates only minimal files.Ex: Web.Config, app_data ,Default.aspx etc. With VS 2010 they have shipped new project templates that contain major changes. The following figure shows the project layout that is created when you create a new Web Application project. (The layout for a Web Site project is virtually identical.)
























The project includes a number of files that were not created in earlier versions. In addition, the new Web Application project is configured with basic membership functionality, which lets you quickly get started in securing access to the new application. The intention of these changes to the project templates is to provide guidance on how to start building a new Web application. With semantically correct. , the pages in the templates represent best practices for building ASP.NET 4 Web applications. The default pages also have a two-column layout that you can easily customize.We can then go into the Site.css file and modify CSS class definitions to change the background color of the page as well as that of the header, as in the following example.
Web.config File Refactoring
The web.config file has grown big over the past release of web frame work as to include new features. With Asp.NET 4 as VS 2010 , the major configuration elements have been moved to the machine.config file, and applications now inherit these settings. This allows the Web.config file in ASP.NET 4 applications either to be empty.
jQuery Included with Web Forms and MVC
The Visual Studio templates for both Web Forms and MVC include the open-source jQuery library.
Enabling View State for Individual Controls
By default, view state is enabled for the page, with the result that each control on the page potentially stores view state even if it is not required for the application.In earlier versions of ASP.NET, developers could disable view state for individual controls in order to reduce page size, but had to do so explicitly for individual controls. In ASP.NET 4, Web server controls include a ViewStateMode property that lets you disable view state by default and then enable it only for the controls that require it in the page.
ASP.NET Chart Conrol
The ASP.NET Chart control expands the data-visualization offerings in the .NET Framework. Using the Chart control, you can easily create ASP.NET pages that have intuitive and visually compelling charts for complex statistical or financial analysis.
Well , I know that blog is not going to cover all features that shipped with VS 2010 as well as ASP 4.0.I am planning spent some time and take up one by one features and come up with detailed code samples for each.

08 May 2010

Time Stamp (Row Version) Implementation.

Problem defanition
We are in to a application where we have more than 100 clients talking to a server same time. How we are going to address the concurrency at DB level? There are many concurrency control techniques like locks, Timestamps, or Tickets. Here I would like to explain Time Stamps as a concurrency control technique that we have used in our WPF application.
Timestamp (Row Version)
The timestamp column of a table can be used to determine whether any value in the table row has changed since the last time the table was read. This article describes a way to use the timestamp column of a table for optimistic concurrency control in Microsoft SQL Server 2005.And in future they are going to change the name to ‘Row Version’.
The important thing to know about timestamps is that they are automatically updated every time a row containing a timestamp column is inserted or updated. Values in timestamp columns are not datetime data, but binary(8) varbinary(8) data. The timestamp datatype has no relation to the system time, it is simply a monotonically increasing counter whose values will always be unique within a database (making it basically a unique random number.)
You can add a timestamp column to a table to help maintain the integrity of the database when multiple users are updating rows at the same time. You may also want to know how many rows and which rows were updated without re-querying the table.
CREATE TABLE EMPLOYE (EMP_NUMBER int PRIMARY KEY,   EMP_NAME VARCHAR(100), timestamp)
GO
INSERT INTO EMPLOYE (EMP_NUMBER, EMP_NAME) VALUES (1, 'Jijo')
GO
INSERT INTO EMPLOYE (EMP_NUMBER, EMP_NAME) VALUES (2, 'Venginikkadan')
GO
Now when we are going ahead to update the table we can implement the logic something like this.It is a usual upate statement:
BEGIN TRY
  UPDATE EMPLOYE SET EMP_NAME = 'Jijo venginikkadan' WHERE myKey = 1
IF @@RowCount=0
   RAISERROR('Concurrent update error. Updated aborted.', 16, 2)
END TRY
Remember that the values in a timestamp column are automatically maintained by the database -- you don't have to do anything. In fact, you couldn't update a timestamp column directly if you tried! When you insert a record, a timestamp is automatically assigned for that record. When a record with a timestamp is updated, the timestamp changes. We said earlier that the value of the timestamp will be unique. This means that if you know the value of the timestamp before the update, you can easily be able to tell if the record has been updated by another user between the time you retrieved the information and the time you are trying to save your changes. In fact, SQL Server has a special error message it sends when this type of interim update has happened, so you can specifically trap this occurance!Timestamp is the synonym for the rowversion data type and is subject to the behavior of data type synonyms. If you do not specify a column name, the SQL Server Database Engine generates the timestamp column name; however, the rowversion synonym does not follow this behavior. When you use rowversion, you must specify a column name, for example:
CREATE TABLE EMPLOYE (EMP_NUMBER int PRIMARY KEY,   EMP_NAME VARCHAR(100), VerCol rowversion)
Now let us give the real time example to explain how we have implimnted the timestamp logic as well:
Assume you are developing a program in C# to update the name of the Employee . There will be 100 users who can perform this application function. How can you be sure that while staff 1 typing in the change, staff 2 is not changing the same row?
Here is the logic:
1. Read the name from EMPLOYE table including the timestamp. You display the info to the user for update and save the timestamp.
2. Certain amount of time later, like 2 minutes, the user presses the submit button after changes were typed in.
3. Open a transaction with Begin Transaction
4. Read the timestamp of the name and address row
5. Now compare the current timestamp to the saved timestamp.
6. If the timestamps are same, you update the row and commit the transaction
7. If timestamps are different, you roll back the transaction and notify the user about the fact that the data was changed by someone else. You can let the user decide what to do or follow the appropriate company business rule for data entry conflict resolution.
Sounds good right? Now go ahead and revisit the concurrency control techniques that you already implemented in your application.

07 May 2010

Singleton Pattern in WCF Service

Sometimes it's appropriate to have exactly one instance of a class: window managers, print spoolers, and file systems are prototypical examples. Typically, those types of objects—known as singletons—are accessed by disparate objects throughout a software system, and therefore require a global point of access. Of course, just when you're certain you will never need more than one instance, it's a good bet you'll change your mind. As a part of performance tuning with our WCF application it is observed that we need to make sure only one instance of service is running and it is not trying to create each instance while making each service call.
The Solution:
The singleton pattern is one of the best-known patterns in software engineering. Essentially, a singleton is a class which only allows a single instance of itself to be created, and usually gives simple access to that instance. A single service instance no matter how many clients call the service might seem like an interesting option since it won’t use up many resources. The drawback however is that you can have multiple calls from multiple clients at the same time. All those calls will be handled by the same service instance. If you only allow one single thread to access the service instance this will drastically reduce the performance. To speed things up you quickly wind up dealing with multiple threads and the obligatory synchronization that ensues.








Singleton Services
The singleton service is the ultimate shareable service. When a service is configured as a singleton, all clients get connected to the same single well-known instance independently of each other, regardless of which endpoint of the service they connect to. The singleton service lives forever, and is only disposed of once the host shuts down. The singleton is created exactly once when the host is created.You can configureasingleton service by setting the InstanceContextMode property to InstanceContextMode.Single:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single,
        ConcurrencyMode = ConcurrencyMode.Multiple)]

Also please see the sample code for implementing

     public class Singleton
     {
       private static Singleton objInstance;
        private Singleton()
        {

        }
        public static Singleton GetInstance()
        {
            if (objInstance == null)
            {
                objInstance = new Singleton();
            }
            return objInstance;
        }
    }
 While every application is unique when it comes to scalability, performance, and throughput, Windows Communication Foundation does offer canonical instance management techniques that are applicable across the range of applications, thus enabling a wide variety of scenarios and programming models. Understanding Windows Communication Foundation instance management and choosing the right activation mode is critical.WE have taken this approach to address the issues in our application.

Query Active directory using C#

Requirement definition
There was a requirement where we are dealing with a web based application and have to authenticate our logged in user against the LAN ID. The LAN ID information is maintained by Microsoft Active Directory.Active Directory is a technology by Microsoft that provides a variety of services. So here the issue is how we are going to communicate with ADI and get the information’s using our application.
Solution
This article describes how to use .NET framework to manage resources under Windows Active Directory Services. Microsoft provides ADSI (Active Directory Services Interface) which can interact with many providers including IIS (Internet Information Services), LDAP (Lightweight Directory Access Protocol), WinNT and NDS (Novell Netware Directory Service). Using the classes provided under .NET System.DirectoryServices namespace. To access these classes add System.DirectoryServices.dll to the references. The System.DirectoryServices namespaces provides two important classes DirectoryEntry and DirectorySearcher to work with the Active Directory. The DirectoryEntry class represents a resource in the Active Directory and the DirectorySearcher class is used to query the Active Directory. The DirectorySearcher class uses a search root which is a server where the search begins and a LDAP filter string (which is analogous to where clause in SQL) to query the Active Directory resources. A condition is enclosed by parenthesis and an operator precedes 2 conditions. Eg. (& (Condition1)(Condition2)) The statement is equivalent to saying A and B. Remember the parenthesis. Another example ((& (Condition1)(Condition2) ) (Condition3) ) should be interpreted as (Condition1 and Condition2) or (Condition3).
After a couple of days of Research I have successfully accomplished the tasks of querying for and updating users. I will share some basic functionality for those of you that are interested. It might be useful to read up on LDAP to get a good understanding of what it is and how it works with Active Directory.
public static DirectoryEntry GetDirectoryService()
{
      de.Path = ldap://OU=Domain,DC=YourDomain,DC=com/;
      de.AuthenticationType = AuthenticationTypes.Secure;
     

      DirectoryEntry de = new DirectoryEntry();
      return de;
}
 public bool UserExists(string username)
{
     DirectoryEntry dr = GetDirectoryService();
    DirectorySearcher drSearch = new DirectorySearcher();"(&(objectClass=user) (cn=" + username + "))";
    SearchResultCollection results = drSearch.FindAll();
    return results;
}
Read the result :
foreach (SearchResult result in results)
{
    string userNmae = result.Properties["samaccountname"][0];
}
Now if needed we can add more filter conditions here based on your requirement. Here by some examples are given.
adSearch.PropertiesToLoad.Add("cn");
adSearch.PropertiesToLoad.Add("givenname");
adSearch.PropertiesToLoad.Add("displayname");
adSearch.PropertiesToLoad.Add("employeenumber");
adSearch.PropertiesToLoad.Add("samaccountname");
adSearch.PropertiesToLoad.Add("countrycode");
adSearch.PropertiesToLoad.Add("memberof");
If you want to serch based on Group then :

adSearch.Filter =
"(&(objectCategory=user)(|(memberOf="+Constants.GROUP_GUEST+")(memberOf="+ Constants.GROUP_TL + ")))";
This is going to be a very small part of ADI access through C#.Basically I just want to explain how we addressed our requirment of pulling ADI data from C# to meet our authentication requirments.

06 May 2010

WPF Dispatcher

Dispatcher
Windows presentation foundation (WPF) has come up with extensive support for threading. Here I would like to share my experience with threading in WPF.Basically on what situation I have preferred to go with WPF Dispatcher with a code sample.
Define the problem:
We have a requirement in our application that need a mechanism to respond to user and system input such as mouse clicks, key presses, and system events basically having business logic in all these actions also there was a LDAP call to populate the users and cache it and we are making some WCF service call as well to the DB, these operations are going to take time and from the UI the user cannot do any operations till this complete. Not sounds good right. Yes we need to avoid this delay experience to the user while doing all these time consuming business operations.
Technical Solution:
Well , I think from the defanition it is clear that we are not going to address some application specific issue and this might be alredy addressed by any one who come across development of enterprise applications. We have addressed these issues using WPF Dispatcher.Thanks for Microsoft for introducing such a simple way of addressing this issue.
Working with Dispatcher
WPF applications start their lives with two threads: 1) the UI thread which updates the windows, controls, and visual elements of your app, and 2) the BackgroundWorker threads waiting to help you perform the heavy lifting. The ideal approach is illustrated in the very simple diagram below. The UI thread queues work items inside an object called a Dispatcher. The Dispatcher selects work items on a priority basis and runs each one to completion. Every UI thread must have at least one Dispatcher and each Dispatcher can execute work items in exactly one thread.
Basically in .net 2.0 one thread cannot access another thread’s objects directly. If a background thread does attempt to update the UI thread directly, an access violation in the form of an exception is thrown. Dispatcher provides the methods Invoke and Begin Invoke, which a background thread can use to schedule tasks on the UI thread and to specify delegates the dispatcher can use to modify the target object. Messages passed to the dispatcher are marked with a priority level and placed in a queue managed by the dispatcher.
Here I am just giving you a sample code for how UI element is getting updated using dispatcher.
public DispacherTestClass()
{
Thread thread = new System.Threading.Thread(new System.Threading.ThreadStart(delegate()DispatcherOperationdispatcher = textBox1.Dispatcher.BeginInvoke(
System.Windows.Threading.
{
textBox1.Text = "Updated Text from Thread";
}
));
dispatcher.Completed += += new EventHandler(dispatcher_Completed);
}
));
thread.Start();
}
}
void dispatcher_Completed(object sender, EventArgs e)

{
MessageBox.Show("The textbox has finished being updated!");
}
Also if we want to do a background process the code is going to be something like this:

Dispatcher.CurrentDispatcher.BeginInvoke(DispatcherPriority.Render , AsyncLoadCurrentStaffView, true);

And  in the delegete we need to show the method that we want to put in dispatcher que.

new AsyncLoadCurrentStaffViewDelegate(LoadCurrentStaffView);

03 May 2010

Automate unit testing with VisualStudio 2008

Automate Unit Tests
As soon as the developer finishes the code, the developer wants to know if it is producing the expected result before getting into any more detailed testing or handing over the component to the tester. The type of testing performed by the developers to test their own code is called Unit testing. Mainly because it's an automated way to make sure it is always behaving the way it is supposed to behave. This way we can make changes to the code and refractor pieces of the application without the fear of breaking something somewhere else in the application.Well here comes the definition now :- "Unit testing is a procedure used to validate that individual units of source code are working properly. A unit is the smallest part of an application. In object-oriented programming the smallest unit is method”
Like all my other blogs, here also I don’t want to explain what is unit testing and why we do it. More specifically I want to explain how practically we automated our application.
Creating a test project
One of the great improvements of Visual Studio 2008 brought to developers is the built in support for unit testing. With Unit Testing support, it is very easy for developer to create, execute and repeat unit test cases.Setting up a test project in Visual Studio 2008 is extremely easy. All it requires is adding a test project into a solution by selecting Test Project template under Test project type. Let’s create our test project in the File> New> Project, and selecting the test> Test Project. At this point the project template will create a solution with projects with default class.A test class is generated once the Test project is created. Visual studio automatically marks the test class and method with TestClassAttribute and TestMethodAttribute.
Adding unit test
It is recommended to create one test class per class to be tested. A test class can be added by either selecting from Add New Test popup or by selecting Unit Test from Add menu.



















Alternatively, Unit test can be added by right clicking the method name and select “Create Unit Tests” in context menu. This brings up the Create Unit Tests screen where multiple methods to be tested can be selected.
Click on settings will give another screen were we can set configurations:



















Unit testing support for ASP.NET
Visual Studio 2008 allows developers create test cases for methods defined in ASP.NET website or applications. Even better, tests are running under ASP.NET context which means settings from Web.config file are automatically picked up once the test case starts running.It worth pointing out two attributes HostTypeAttribute and UrlToTestAttribute. HostType makes sure that test case is running ASP.NET host process. UrlToTest specifies URL to test when test is run.
[TestMethod()]
HostType("ASP.NET")]AspNetDevelopmentServerHost("C:\\DemoCompany\\SourceCode\\WebApplication\\DemoWeb", "/")]UrlToTest("http://localhost:4480/")]DeploymentItem("DemoWeb.dll")]
public void GetMnemonicsTest()
   Search_Accessor target = new Search_Accessor(); // TODO: Initialize to an appropriate value
   target.GetMnemonics();
}
Yet another normal method:
[TestMethod]

public void OnNameChanged_MoreThan20Chars_TakesFirst20Chars()
{
     string testName = "JijoVenginikkadan";Customer customer = new Customer();
    string expectedName = "JijoVenginikkadanGopalakrishnan";
    Assert.AreEqual(expectedName, customer.CompanyName,"OnNameChanging should take only first 20 characters");
}
Execute test method
Test method can be started by right clicking the test method name and select Run Tests. Visual Studio 2008 displays test results in Test Result output window.The result is afcource going to be failed here based on the test case that we provided.
Assert.Inconclusive("A method that does not return a value cannot be verified.");

Debugging support in Unit Testing
All test classes/methods can be run under debug mode. Simply put a break point where the code needs to stop and start the test by clicking “Debug Tests in Current Context” button located in the toolbar or “Tests in Current Context” menu of Debug option under Test menu.

02 May 2010

Pagination in asp.net

Requirement :
There was a functional; requirement to pull the customer data from the database and display on a web page. But in one query itself will return 1000 records at a time. Seeing 1000 records a t a time was not handy for the user as well as it will be a major hit for the performance aspect. So the requirement was to provide something a kind of page like feeling to the user for the bulk record user where user can see a page at a time where he can go next and previous page same as in a book.

Solutions:
Well, this is not something new to scratch the head. Microsoft has addressed as well as provided solutions for this- nothing but pagination. Basically, you show just one page on screen and provide a navigation bar on top or on bottom of the page (or both) so user can navigate to other pages if wants. The paging can be implemented 2 of the below ways.

• Default Paging – can be implemented by simply checking the Enable Paging option in the data Web control’s smart tag; however, whenever viewing a page of data, the ObjectDataSource retrieves all of the records, even though only a subset of them are displayed in the page
• Custom Paging – improves the performance of default paging by retrieving only those records from the database that need to be displayed for the particular page of data requested by the user; however, custom paging involves a bit more effort to implement than default paging
Default Paging:
To enable default paging we need to explicitly set AllowPaging property of DataGrid control to True. Use PageSize property to set the number of records to be displayed per page. PageSize has a default value of 10. DataGrid control has a property CurrentPageIndex which gives the index of current page being displayed i.e. for the first Page DataGrod1.CurrentPageIndex will be zero. Another property PageCount exposes the total number of pages. In other words PageCount indicates the number of pages in DataGrid control to display all the data from the data source. We will make use of above properties to implement paging in our ASPX page. When the user clicks on a page hyperlink on the ASPX web form, postback operation is performed. On postback, PageIndexChanged Event of DataGrid is called. What all we need to do is implement an eventhandler for the PageIndexChanged event as follows.
Custom Paging:
One problem with Default Paging is, every time we request for a page in the DataGrid, it retrieves complete data from the database. This problem can be a bottle neck if the volume of date we are working with is huge. A genuine suggestion to this problem which comes into mind immediately is to fetch only that data which we need to display on the page. This is what custom paging is all about i.e. fetching only required data from database. To enable Custom paging we need to explicitly set AllowCustomPaging property of DataGrid control to True. Use PageSize property to set the number of records to be displayed per page. We need to set VirtualItemCount property of DataGrid control. This property tells the DataGrid
Pagination using object data source:
I have explored some features of ObjectDataSource control with GridView, which is shipped with ASP.net 2.0. The ObjectDataSource control is used to bind the controls to middle-tier busines objects.it will help us in implementing the custom paging mechanism very easily without the need to build page numbers separately i.e. we can still use inbuilt paging feature of GridView to display page numbers and we can use ObjectDataSource control to fetch the records that is required only for that page.WE have implimented paging using this in our application.Here for example given below we need to pass the parameteres of startindex,pagesize as well as page size as a parameter to selected method as well as sql query.Here also I have passed sort directins also.






Experience 3 tier architecture

There are lot internet information’s on 3 tier architecture. I don’t want to add one more on top of it to spam a Google query! This is only to drow my experience on 3 tier architechure.
Dot NET framework and Visual Studio present many choices for choosing the right architecture from placing the data access code directly in the UI through datasets as well as separating all these code in a reusable component nothing called layers. Like any other developer I also come across to select 3 tiers in my application so want to share my experiences in this. Here I need to come up with an application where the presentation layer needs to extract information from a backend database, the presentation would utilize a series of layers to retrieve the data, rather than having the database calls embedded directly within itself. So that I can use be reused this components as well as will end up an easy maintaince.There may be also chances was there but some of the functionality may later be moved to a smart client application. Portions of an application may be split between a web site and a web or windows service that runs on a server.Likewice so many reasons was there to select three tiers as application architecture for our development. Rather than explain the reason I would like to take you how we went ahead and implemented in our application.
As one of the greatest advantages we have split the layers between developers across the location and started development parallel among 12 member team. As each layer complete with their development we have integrated the code and shaped to complete application! Simple approach right? The below diagram will give more clear picture.

As every other 3 tier application we too have ,Tier 1 or GUI tier with a form will be called FrmCompanyGUI, tier 2 or business logic will be called BO Company short for Business Object Company and finally the tier 3 or the data tier will be called CompanyDAL short for Data Access Company. I have compiled all the 3 tiers in the same project for ease of work.
User Interface tier :
User Interface layer is nothing but UI. Please see the below image, just a proto type.Dont want to give real UI image or code here as I want to keep the confidentiality of the real time application as well as client.

This is a chunk of code from the user interface. I am only including the functions that are used to call the middle tier or the business logic layer. I am keeping a reference to business logic layer as CompanyBO.
protected void Page_Load(object sender, EventArgs e)
{

DataSet ds = new DataSet();

CompanyBO objStudentBO = new CompanyBO ();

ds = CompanyBO.GetCompanyDetails();

grdStudentDetails.DataSource = ds.StudentDetails;

grdCompanyDetails.DataBind();

}

Business Logic layer :
Here, I am including all the code for this tier. Basically it has properties that are needed to define the compny object. But as I mentioned it is just a dummy company and many other properties can be added if required. It also has all the methods including Add, update, find that are required to maintain customer details.
This is the middle tier and acts between the GUI and the Data access layer. It keeps a reference to the data access tier as companyDA = new companyDA (). It also has a reference to System.Data namespace as sometimes it returns details in the form of DataSet to the GUI tier.
We have a defined properties of the business objects ,May be some time we can keep it on property layer if required.
public class Companypublic CompanyDS GetCompanyDetails(long searchID)

{

private string CompanyName { get; set; }

private string CompanyID { get; set; }

private string CompanyAddress1 { get; set; }

public Company()

{

}

public string CompanyName

{

get{return CompanyName;}

set{CompanyName = value;}

}

public string CompanyID

{

get { return CompanyID; }

set { CompanyID = value; }

}

}
operations:
{

CompanyDS companyDS = new CompanyDS();

try

{

CompanySummaryDM objComSumDAL = new CompanySummaryDM();

companyDS = objComSumDAL.GetCompanyDetails(searchID, isCoSeqId);

return companyDS.CompanyDetails;

}

catch (DatabaseException ex)

{

throw ex;

}

catch (Exception ex)

{

throw new BusinessException(ex);

}

}
Data Access Layer :
The data tier has details to manipulate an SQL database. However, all these details are transparent and do not affect the business logic layer. This module has a reference to the business logic layer as ComapnyBO objCompanyBO. To make the usage easier and be supported by any other database I have created some constants including the database name and field name that need to be changed as per the customer table details. This is an usable module for any database after making these changes.
public CompanyDS GetCompanyDetails()

{

DataSet ds = new DataSet();

CompanyDS companyDS = new CompanyDS();

IDbConnection conn = DataFactory.CreateConnection();

conn.ConnectionString = this.ConnectionString;

IDbDataParameter[] commandParameters = new IDbDataParameter[1];

commandParameters[0]= DataHelper.CreateParameter("@SearchID", DbType.Int64, ParameterDirection.Input, CompanyID);
try

{

ds=DataHelper.ExecuteDataset(conn, CommandType.StoredProcedure,"CompanyDetails", commandParameters);

ds.Tables[0].TableName = "CompanyDetails";

companyDS.Merge(ds);

return companyDS;

}

catch (Exception ex)

{

throw new DatabaseException(ex);

}

finally

{

conn.Close();

}

}

Deployment:
Yes we have completed all the three layers. Now the time for deployment. Yes it’s too simple. Using a separation of layers can aid in development of distributed applications. Because the code is broken up into layers, a layer that facilitates the use of web services can be added to the project, with a minimal amount of work.
In 3 tier architecture there are basically two types of assemblies .One is for Business Layer and other for Data access layer. In our particular example we have CompanyUI.dll ,CompanyBO.dll and ComapnyDA.dll
If we have to deploy these on three different server than We need to do something like rather we did same.
Server 1: Database server: (SQL Server / Oracle)
Server 2: Business Server: Contain Assemblies and
Communicate to Presentation layer using web service or WCF.
Server 3: Presentation Server: Contain the UI part to display data fetched from Business layer consuming the Web service or WCF.