MasterPage


For example, you might have a master page named MasterPage.master that is the class name MasterPage_master. You might create @ Page and @ MasterType directives that look like the following:
<%@ Page  masterPageFile="~/MasterPage.master"%>
<%@ MasterType  virtualPath="~/MasterPage.master"%>
When you use a @ MasterType directive, such as the one in the example, you can reference members on the master page as in the following example:

EncryptRJ256

 public string UpdateLeaderBoard(string pname, string fscore, string ipaddress, string gameid)
        {
            string timestamp = DateTime.Now.ToShortTimeString();
            lboardparameters = fscore + "," + timestamp + "," + ipaddress + "," + gameid;
            string sKy = "go!Animate@2010Cart00nNetw@rk!!!";

            string sIV = "go!Animate@2010Cart00nNetw@rk!!!";


            lboardparameters = EncryptRJ256(sKy, sIV, lboardparameters);
            // string url = "http://www.cartoonnetworkasia.com/contest/2010/09_hp_smart_numbers_up/gameSubmit.php?lboardparameters=" + lboardparameters;
            return lboardparameters;
            //openurl();
        }

        public static string EncryptRJ256(string prm_key, string prm_iv, string prm_text_to_encrypt)
        {

            string sToEncrypt = prm_text_to_encrypt;

            RijndaelManaged myRijndael = new RijndaelManaged();
            myRijndael.Padding = PaddingMode.Zeros;
            myRijndael.Mode = CipherMode.CBC;
            myRijndael.KeySize = 256;
            myRijndael.BlockSize = 256;

            byte[] encrypted = null;
            byte[] toEncrypt = null;
            byte[] key = null;
            byte[] IV = null;

            key = System.Text.Encoding.ASCII.GetBytes(prm_key);
            IV = System.Text.Encoding.ASCII.GetBytes(prm_iv);

            ICryptoTransform encryptor = myRijndael.CreateEncryptor(key, IV);

            MemoryStream msEncrypt = new MemoryStream();
            CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write);

            toEncrypt = System.Text.Encoding.ASCII.GetBytes(sToEncrypt);

            csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
            csEncrypt.FlushFinalBlock();

            encrypted = msEncrypt.ToArray();

            return (Convert.ToBase64String(encrypted));

        }

Encryption and decryption in SHA1Managed

private string Encrypt(string Data)
{
 SHA1Managed shaM = new SHA1Managed();
 Convert.ToBase64String(shaM.ComputeHash(Encoding.ASCII.GetBytes(Data)));
 byte[] eNC_data = ASCIIEncoding.ASCII.GetBytes(Data);
 string eNC_str = Convert.ToBase64String(eNC_data);
 return eNC_str;
}
//Encrypt

private string Decrypt(string Data)
{
 byte[] dEC_data = Convert.FromBase64String(Data);
 string dEC_Str = ASCIIEncoding.ASCII.GetString(dEC_data);
 return dEC_Str;
}
//Decrypt
 
 
 
 
 

C# SHA-2 Cryptography: SHA-256, SHA-384, SHA-512

Here are some crypto methods for SHA256, SHA384, and SHA512 which I had not posted about before. This is the class I am using.

using System.Security.Cryptography;
using System.Text;

public class clsCrypto {
public clsCrypto() {
}
public static string md5encrypt(string phrase) {
UTF8Encoding encoder = new UTF8Encoding();
MD5CryptoServiceProvider md5hasher = new MD5CryptoServiceProvider();
byte[] hashedDataBytes = md5hasher.ComputeHash(encoder.GetBytes(phrase));
return byteArrayToString(hashedDataBytes);
}
public static string sha1encrypt(string phrase) {
UTF8Encoding encoder = new UTF8Encoding();
SHA1CryptoServiceProvider sha1hasher = new SHA1CryptoServiceProvider();
byte[] hashedDataBytes = sha1hasher.ComputeHash(encoder.GetBytes(phrase));
return byteArrayToString(hashedDataBytes);
}
public static string sha256encrypt(string phrase) {
UTF8Encoding encoder = new UTF8Encoding();
SHA256Managed sha256hasher = new SHA256Managed();
byte[] hashedDataBytes = sha256hasher.ComputeHash(encoder.GetBytes(phrase));
return byteArrayToString(hashedDataBytes);
}
public static string sha384encrypt(string phrase) {
UTF8Encoding encoder = new UTF8Encoding();
SHA384Managed sha384hasher = new SHA384Managed();
byte[] hashedDataBytes = sha384hasher.ComputeHash(encoder.GetBytes(phrase));
return byteArrayToString(hashedDataBytes);
}
public static string sha512encrypt(string phrase) {
UTF8Encoding encoder = new UTF8Encoding();
SHA512Managed sha512hasher = new SHA512Managed();
byte[] hashedDataBytes = sha512hasher.ComputeHash(encoder.GetBytes(phrase));
return byteArrayToString(hashedDataBytes);
}
public static string byteArrayToString(byte[] inputArray) {
StringBuilder output = new StringBuilder("");
for (int i = 0; i < inputArray.Length; i++) {
output.Append(inputArray[i].ToString("X2"));
}
return output.ToString();
}
}
 

Difference between managed code and unmanaged code

Managed Code:
Code that runs under a "contract of cooperation" with the common language runtime. Managed code must supply the metadata necessary for the runtime to provide services such as memory management, cross-language integration, code access security, and
automatic lifetime control of objects. All code based on Microsoft intermediate language (MSIL) executes as managed code.

Un-Managed Code:
Code that is created without regard for the conventions and requirements of the common language runtime. Unmanaged code executes in the common language runtime environment with minimal services (for example, no garbage collection, limited debugging, and so on).


Managed Code:-
Managed code is code written in one of over twenty high-level programming languages that are available for use with the Microsoft® .NET Framework, including C#, J#, Microsoft Visual Basic® .NET, Microsoft JScript® .NET, and C++. All of these languages share a unified set of class libraries and can be encoded into an Intermediate Language (IL). A runtime-aware compiler compiles the IL into native executable code within a managed execution environment that ensures type safety, array bound and index checking, exception handling, and garbage collection.

By using managed code and compiling in this managed execution environment, you can avoid many typical programming mistakes that lead to security holes and unstable applications. Also, many unproductive programming tasks are automatically taken care of, such as type safety checking, memory management, and destruction of unneeded objects. You can therefore focus on the business logic of your applications and write them using fewer lines of code. The result is shorter development time and more secure and stable applications.

UnManaged Code
The Microsoft .NET Framework promotes interaction with COM components, COM+ services, external type libraries, and many operating system services. Data types, method signatures, and error-handling mechanisms vary between managed and unmanaged object models. To simplify interoperation between .NET Framework components and unmanaged code and to ease the migration path, the common language runtime conceals from both clients and servers the differences in these object models.

Code executing under the control of the runtime is called managed code. Conversely, code that runs outside the runtime is called unmanaged code. COM components, ActiveX interfaces, and Win32 API functions are examples of unmanaged code.



difference between custom control and user control

User control

1) Reusability web page
2) We can’t add to toolbox
3) Just drag and drop from solution explorer to page (aspx)
4) U can register user control to. Aspx page by Register tag
5) A separate copy of the control is required in each application
6) Good for static layout
7) Easier to create
8)Not complied into DLL
9) Here page (user page) can be converted as control then
We can use as control in aspx

Custom controls

1) Reusability of control (or extend functionalities of existing control)
2) We can add toolbox
3) Just drag and drop from toolbox
4) U can register user control to. Aspx page by Register tag
5) A single copy of the control is required in each application
6) Good for dynamics layout
7) Hard to create
8) Compiled in to dll
  
When to use?

Good question: "When to use a Custom Control?" Haven't you got the inner meaning of it yet? OK, read the summarized points below:
  • When you have a rapid and fixed content in your UI, use UserControl.
  • When you want to separate some basic functionality of your main view to some smaller pieces with reusability, use UserControl.
  • When you want to use your control in different projects and each project may want to change the look, use CustomControl.
  • When you want to implement some additional functionality for a control, create a CustomControl derived from the base control.
  • When you want to apply themes to your controls, use CustomControl.
  • When you want to add toolbox support for your control, so that your user will be able to do drag and drop to the designer, use CustomControl.

 

Difference between COM Component and .Net component

COM componets contains unmanaged code where as .NET Components comes with managed code.

We can call a dotnet component from COM Component Vice versa

.NET componets are called as Assemblies and these are DLL files.these files are pre compiled.

COM components are binary standurd (platform dependent) towards windows platform where as .NET components are platform independent.

for coming to the memory management,CLR doesn't provide any memory management features to COM components becose these belongs unmanaged code.

 
Unlike pure .NET Components COM components must register before they can be used.After
Registered these components need to be imported by using Type library Importer Tool (Tlbimp.exe).

COM components cannot support Shared/Static members

COM does't support the parameterized constructor

COM cann't support the Inheritance

Operating systems other than windows don't have a registry.So very less portablity .

SQL function

CREATE FUNCTION ISOweek  (@DATE datetime)
RETURNS int
AS
BEGIN
   DECLARE @ISOweek int
   SET @ISOweek= DATEPART(wk,@DATE)+1
      -DATEPART(wk,CAST(DATEPART(yy,@DATE) as CHAR(4))+'0104')
--Special cases: Jan 1-3 may belong to the previous year
   IF (@ISOweek=0)
      SET @ISOweek=dbo.ISOweek(CAST(DATEPART(yy,@DATE)-1
         AS CHAR(4))+'12'+ CAST(24+DATEPART(DAY,@DATE) AS CHAR(2)))+1
--Special case: Dec 29-31 may belong to the next year
   IF ((DATEPART(mm,@DATE)=12) AND
      ((DATEPART(dd,@DATE)-DATEPART(dw,@DATE))>= 28))
      SET @ISOweek=1
   RETURN(@ISOweek)
END

SET DATEFIRST 1
SELECT employee.dbo.ISOweek('12/26/1999') AS 'ISO Week'



create function employeefun()
returns table
as
return(select * from employee)
 
select * from employeefun()



create function employeeupdate()
returns int
as
begin
DECLARE @id int
set @id=(select id from employee where id=1)
return @id
end


select  employee.dbo.employeeupdate() as no
select * from  employee where id=employee.dbo.employeeupdate() 






CREATE TABLE employees (empid nchar(5) PRIMARY KEY,
      empname nvarchar(50),
      mgrid nchar(5) REFERENCES employees(empid),
      title nvarchar(30)
      )

select * from employees

CREATE FUNCTION fn_FindReports (@InEmpId nchar(5))
RETURNS @retFindReports TABLE (empid nchar(5) primary key,
   empname nvarchar(50) NOT NULL,
   mgrid nchar(5),
   title nvarchar(30))
/*Returns a result set that lists all the employees who report to given
employee directly or indirectly.*/
AS
BEGIN
   DECLARE @RowsAdded int
   -- table variable to hold accumulated results
   DECLARE @reports TABLE (empid nchar(5) primary key,
      empname nvarchar(50) NOT NULL,
      mgrid nchar(5),
      title nvarchar(30),
      processed tinyint default 0)
-- initialize @Reports with direct reports of the given employee
   INSERT @reports
   SELECT empid, empname, mgrid, title, 0
   FROM employees
   WHERE empid = @InEmpId
   SET @RowsAdded = @@rowcount
   -- While new employees were added in the previous iteration
   WHILE @RowsAdded > 0
   BEGIN
      /*Mark all employee records whose direct reports are going to be
   found in this iteration with processed=1.*/
      UPDATE @reports
      SET processed = 1
      WHERE processed = 0
      -- Insert employees who report to employees marked 1.
      INSERT @reports
      SELECT e.empid, e.empname, e.mgrid, e.title, 0
      FROM employees e, @reports r
      WHERE e.mgrid=r.empid and e.mgrid <> e.empid and r.processed = 1
      SET @RowsAdded = @@rowcount
      /*Mark all employee records whose direct reports have been found
   in this iteration.*/
      UPDATE @reports
      SET processed = 2
      WHERE processed = 1
   END
  
   -- copy to the result of the function the required columns
   INSERT @retFindReports
   SELECT empid, empname, mgrid, title
   FROM @reports
   RETURN
END
GO

SELECT *
FROM fn_FindReports('1')

Abstract and interface

Abstract Class vs an Interface.

I normally used this “What is the difference between an Abstract Class and an Interface” as a quick way to gauge someone.
At the top level, the are a few basic difference. Abstract classes allow for default function definition. This means that whatever class extends the abstract class will have access to this. If we have a base class where all the classes will perform the same function, then we can define that in our Abstract class. An interface is a list of functions or properties that if a class implements it, it will have to have those functions defined within it. However, I want to know why one would want to use an interface over an abstract class, and vice versa.

When to prefer an interface

Lets say you have an interface for a Director and another interface for a Actor.
public interface Actor{
   Performance say(Line l);
}
public interface Director{
   Movie direct(boolean goodmovie);
}
 
In reality, there are Actors who are also Directors. If we are using interfaces rather than abstract classes, we can implement both Actor and Director. We could even define an ActorDirector interface that extends both like this:

public interface ActorDirector extends Actor, Director{
...
}
 
We could achieve the same thing using abstract classes. Unfortunately the alternative would require up to 2^n (where n is the number of attributes) possible combinations in order to support all possibilities.

When to prefer an Abstract class

Abstract classes allow you to provide default functionality for the subclasses. Common knowledge at this point. Why is this extremely important though? If you plan on updating this base class throughout the life of your program, it is best to allow that base class to be an abstract class. Why? Because you can make a change to it and all of the inheriting classes will now have this new functionality. If the base class will be changing often and an interface was used instead of an abstract class, we are going to run into problems. Once an interface is changed, any class that implements that will be broken. Now if its just you working on the project, that’s no big deal. However, once your interface is published to the client, that interface needs to be locked down. At that point, you will be breaking the clients code.

 Another general rule is if you are creating something that provides common functionality to unrelated classes, use an interface. If you are creating something for objects that are closely related in a hierarchy, use an abstract class. An example of this would be something like a business rules engine. This engine would take in multiple BusinessRules as classes perhaps? Each one of these classes will have an analyze function on it.

public interface BusinessRule{
   Boolean analyze(Object o);
}
 
This can be used ANYWHERE. It can be used to verify the state of your application. Verify data is correct. Verify that the user is logged in. Each one of these classes just needs to implement the analyze function, which will be different for each rule.
Where as if we were creating a generic List object, the use of abstract classes would be better. Every single List object is going to display the data in a list in some form or another. The base functionality would be to have it go through its dataprovider and build that list. If we want to change that List object, we just extend it, override our build list function, change what we want and call super.buildList();
Almost everyone knows that interfaces means you are just defining a list of functions and that abstract classes has the option of providing default functionality. The snags come when you drop the ‘why would I use one over the other?’.

 What is an Abstract Class?

An abstract class is a special kind of class that cannot be instantiated. So the question is why we need a class that cannot be instantiated? An abstract class is only to be sub-classed (inherited from). In other words, it only allows other classes to inherit from it but cannot be instantiated. The advantage is that it enforces certain hierarchies for all the subclasses. In simple words, it is a kind of contract that forces all the subclasses to carry on the same hierarchies or standards.

 What is an Interface?

An interface is not a class. It is an entity that is defined by the word Interface. An interface has no implementation; it only has the signature or in other words, just the definition of the methods without the body. As one of the similarities to Abstract class, it is a contract that is used to define hierarchies for all subclasses or it defines specific set of methods and their arguments. The main difference between them is that a class can implement more than one interface but can only inherit from one abstract class. Since C# doesn�t support multiple inheritance, interfaces are used to implement multiple inheritance.

Both Together

When we create an interface, we are basically creating a set of methods without any implementation that must be overridden by the implemented classes. The advantage is that it provides a way for a class to be a part of two classes: one from inheritance hierarchy and one from the interface.
When we create an abstract class, we are creating a base class that might have one or more completed methods but at least one or more methods are left uncompleted and declared abstract. If all the methods of an abstract class are uncompleted then it is same as an interface. The purpose of an abstract class is to provide a base class definition for how a set of derived classes will work and then allow the programmers to fill the implementation in the derived classes.
There are some similarities and differences between an interface and an abstract class that I have arranged in a table for easier comparison:
Feature
Interface
Abstract class
Multiple inheritance
A class may inherit several interfaces.
A class may inherit only one abstract class.
Default implementation
An interface cannot provide any code, just the signature.
An abstract class can provide complete, default code and/or just the details that have to be overridden.
Access Modfiers An interface cannot have access modifiers for the subs, functions, properties etc everything is assumed as public An abstract class can contain access modifiers for the subs, functions, properties
Core VS Peripheral
Interfaces are used to define the peripheral abilities of a class. In other words both Human and Vehicle can inherit from a IMovable interface.
An abstract class defines the core identity of a class and there it is used for objects of the same type.
Homogeneity
If various implementations only share method signatures then it is better to use Interfaces.
If various implementations are of the same kind and use common behaviour or status then abstract class is better to use.
Speed
Requires more time to find the actual method in the corresponding classes.
Fast
Adding functionality (Versioning)
If we add a new method to an Interface then we have to track down all the implementations of the interface and define implementation for the new method.
If we add a new method to an abstract class then we have the option of providing default implementation and therefore all the existing code might work properly.
Fields and Constants No fields can be defined in interfaces An abstract class can have fields and constrants defined

N-Tier architecture

What is n-Tier Architecture?

This is a very important topic to consider when developing an application. Many elements need to be considered when deciding on the architecture of the application, such as performance, scalability and future development issues. When you are deciding on which architecture to use, first decide on which of the three aforementioned elements you think is most valuable -- as some choices you make will impact on others. For example, some choices that boost performance will impact on the scalability or future development of your design, etc.
Here we will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures you can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.

Firstly, what is n-Tier architecture? N-Tier architecture refers to the architecture of an application that has at least 3 "logical" layers -- or parts -- that are separate. Each layer interacts with only the layer directly below, and has specific function that it is responsible for.

Why use n-Tier architecture? Because each layer can be located on physically different servers with only minor code changes, hence they scale out and handle more server load. Also, what each layer does internally is completely hidden to other layers and this makes it possible to change or update one layer without recompiling or modifying other layers.

This is a very powerful feature of n-Tier architecture, as additional features or change to a layer can be done without redeploying the whole application. For example, by separating data access code from the business logic code, when the database servers change you only needs to change the data access code. Because business logic code stays the same, the business logic code does not need to be modified or recompiled.

[Note] tier and layer mean the same thing [End Note]

An n-Tier application usually has three tiers, and they are called the presentation tier, the business tier and the data tier. Let's have a look at what each tier is responsible for.

Presentation Layer
Presentation Layer is the layer responsible for displaying user interface and "driving" that interface using business tier classes and objects. In ASP.NET it includes ASPX pages, user controls, server controls and sometimes security related classes and objects.

Business Tier
Business Tier is the layer responsible for accessing the data tier to retrieve, modify and delete data to and from the data tier and send the results to the presentation tier. This layer is also responsible for processing the data retrieved and sent to the presentation layer.

In ASP.NET it includes using SqlClient or OleDb objects to retrieve, update and delete data from SQL Server or Access databases, and also passing the data retrieved to the presentation layer in a DataReader or DataSet object, or a custom collection object. It might also include the sending of just an integer, but the integer would have been calculated using the data in the data tier such as the number of records a table has.

BLL and DAL
Often this layer is divided into two sub layers: the Business Logic Layer (BLL), and the Data Access Layers (DAL). Business Logic Layers are above Data Access Layers, meaning BLL uses DAL classes and objects. DAL is responsible for accessing data and forwarding it to BLL.

In ASP.NET it might be using SqlClient or OleDb to retrieve the data and sending it to BLL in the form of a DataSet or DataReader. BLL is responsible for preparing or processing the data retrieved and sends it to the presentation layer. In ASP.NET it might be using the DataSet and DataReader objects to fill up a custom collection or process it to come up with a value, and then sending it to Presentation Layer. BLL sometimes works as just transparent layer. For example, if you want to pass a DataSet or DataReader object directly to the presentation layer.

Data Tier
Data tier is the database or the source of the data itself. Often in .NET it's an SQL Server or Access database, however it's not limited to just those. It could also be Oracle, mySQL or even XML. In this article we will focus on SQL Server, as it has been proven to be the fastest database within a .NET Application.

Logical Layers vs. Physical Layers (Distributed)
Logical Layers and Physical Layers are the ones that confuse people. Firstly, a logical layer means that layers are separate in terms of assembly or sets of classes, but are still hosted on the same server. Physical layer means that those assemblies or sets of classes are hosted on different servers with some additional code to handle the communication between the layers. E.g. remoting and web services.

Deciding to separate the layers physically or not is very important. It really depends on the load your application expects to get. I think it's worth mentioning some of the facts that might affect your decision.

Please DO note that separating the layers physically WILL slow your application down due to the delay in communicating between the servers throughout the network, so if you are using the physical layer approach, make sure the performance gain is worth the performance loss from this.

Hopefully you would have designed your application using the n-Tier approach. If this is the case, then note that you can separate the layers in the future.

Cost for deploying and maintaining physically separated applications is much greater. First of all, you will need more servers. You also need network hardware connecting them. At this point, deploying the application becomes more complex too! So decide if these things will be worth it or not.

Another fact that might affect your decision is how each of the tiers in the application are going to be used. You will probably want to host a tier on a separate server if more than 1 service is dependent on it, e.g. You might want to host business logic somewhere else if you have multiple presentation layers for different clients. You might also want a separate SQL server if you have other applications using the same data.

Performance, Scalability and Future Development

As I said earlier, each choice you make in the architecture will affect one of the following:
  • Performance
  • Scalability
  • or Future Development.
Here we will look at the most common choices you have to make in a typical ASP.NET application. I'll present you with some of the available options, cons and pros of each.
[Note] You should develop an application bottom up. This means build the data tier layer first. You should always design all three layers before building the actual application. [End Note]

Performance vs. Scalability vs. Future Development
When deciding on your architecture, decide what your priority is going to be. If your application is time critical, then you might have to sacrifice its scalability and extendibility just because you need more procedural like class design, which will offer that.
If you want scalability then you might have to sacrifice performance, because the scalability comes from scaling out and scaling out means communicating through a slower medium such as a LAN. Extensibility is a good thing to have but what's the point if you won’t be updating the application in the future, but instead be rewriting the whole thing? Think about whether you need extensibility or not because it can affect performance due to having more round trips to the database and also due to the simple fact that the size of the application will be bigger.

Think about what you really need for the project you are doing not what other people are doing for their projects. Architecture is a topic that really doesn't have best practices so rather than going for architecture for all of your applications, think about different architecture for each of your applications.

Presentation Tier Issues
The presentation layer must be well planned before building it. If this layer is badly designed, it could impact on the applications performance and future development paths. I'll explain why.

Firstly, let's start with performance. Remember how I said that the presentation layer 'uses' BLL to do any operations that need interaction with the data tier? No matter how well you've designed your BLL to reduce the round trips or unnecessary trips to the data tier, if the presentation layer code calls that method one or more times unnecessarily, you are still doing a round trip to the data tier. This impacts on your applications overall performance.

Performance is also affected by the different types of controls you decide to use. For example, using a DataGrid instead of a DataList or Repeater will make a noticeable performance difference. So, when do you use a DataGrid and when do you use others? We will discuss this in a minute.

Secondly, future development is also impacted upon if the presentation layer is badly designed. How? If you have repetitive HTML code in all pages of your website, what happens if you want to change a color of a table or something? Do you go to each page and change it? What would you do if your boss said "No, I don't like that... Change it back!"? You really need to implement a template system into your web pages, so when you make one change to your site design, it's propagated to all pages.

Although not related to performance and future development, the presentation layer has another role in ASP.NET applications – security. You have 4 security options in ASP.NET, and we will have a look at each option in detail shortly. Before that though, let's get back to the DataGrid, DataList and Repeater issue.

Data Grid, Data List, Repeater
Knowing the differences between these controls is very important because they are very different controls made for different uses, but people tend to get them confused.

Performance wise, you must always use a Repeater wherever possible. It is the fastest control out of the three. Unfortunately, it is also very limited in what it can do. All a repeater can do is iterate through the data source and display its properties.


A data source can be a data object such as a DataReader or dataset, but it can also be your custom collection that implements the IEnumerable and/or the IEnumerator interface. This is very good for displaying read only items such as list of news headlines, a summary of recent articles, etc.

There are times when you want to be able to "select" a row. When the row is selected, you want different item templates to be displayed. This situation is when you use a data list. DataLists allow you to select a row and display data using different templates. This is very useful for items that might need some frequent modification such as a list of news headlines for administrators where you want administrators to be able to edit headlines, etc.

The DataGrid is an interesting control. I always use it when I have a dataset as my data source. Although it's really slow, it is very flexible. It's also capable of producing a professional looking list or grid automatically. It knows the database's schema. It knows the type of fields and displays them accordingly. But one of the best features it has is its ability to allow editing of the data without having us code any postback functions, etc.

3 tire architecture in asp.net

Introduction

3-Tier architecture generally contains UI or Presentation Layer, Business Access Layer (BAL) or Business Logic Layer and Data Access Layer (DAL).

Presentation Layer (UI)
Presentation layer cotains pages like .aspx or windows form where data is presented to the user or input is taken from the user.

Business Access Layer (BAL) or Business Logic Layer
BAL contains business logic, validations or calculations related with the data, if needed. I will call it Business Access Layer in my demo.

Data Access Layer (DAL)
DAL contains methods that helps business layer to connect the data and perform required action, might be returning data or manipulating data (insert, update, delete etc). For this demo application, I have taken a very simple example. I am assuming that I have to play with record of persons (FirstName, LastName, Age) and I will refer only these data through out this article.
Designing 3-Tier Architecture

For the ease of understanding, I have created BAL, DAL into the App_Code folder. In real scenario, you should create separate projects for BAL, DAL (as Class Library) and UI (as Web project) and reference your BAL into UI.



Data Access Layer
Lets proceed with desiging 3-Tier architecture. To do that lets proceed with DAL, BAL and then UI. Add a class named by right clicking App_Code folder. (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for DAL and add reference of this project into your BAL.) and copy-paste folowing code (Your can overwrite your default written code for the class file by pasting this code). Here, I have assumed that you will create the respective stored procedure yourself into the database or you may download attachment from http://www.dotnetfunda.com/articles/article18.aspx article and look for App_Data folder for complete database structure and stored procedure for this article.

Data Access Layer (DAL)

Code for Data Access Layer
using System;

using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
    /// <summary>
    /// Summary description for PersonDAL3
    /// </summary>

    public class PersonDAL3
    {
        string connStr = ConfigurationManager.ConnectionStrings["TutTestConn"].ToString();
        public PersonDAL3()
        {
        }
        /// <summary>
        /// Used to insert records into database
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="age"></param>
        /// <returns></returns>
        public int Insert(string firstName, string lastName, int age)
        {
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand dCmd = new SqlCommand("InsertData", conn);
            dCmd.CommandType = CommandType.StoredProcedure;
            try
            {
                dCmd.Parameters.AddWithValue("@firstName", firstName);
                dCmd.Parameters.AddWithValue("@lastName", lastName);
                dCmd.Parameters.AddWithValue("@age", age);
                return dCmd.ExecuteNonQuery();
            }
            catch
            {
                throw;
            }
            finally
            {
                dCmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
        /// <summary>
        /// Update record into database
        /// </summary>
        /// <param name="personID"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="age"></param>
        /// <returns></returns>
        public int Update(int personID, string firstName, string lastName, int age)
        {
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand dCmd = new SqlCommand("UpdateData", conn);
            dCmd.CommandType = CommandType.StoredProcedure;
            try
            {
                dCmd.Parameters.AddWithValue("@firstName", firstName);
                dCmd.Parameters.AddWithValue("@lastName", lastName);
                dCmd.Parameters.AddWithValue("@age", age);
                dCmd.Parameters.AddWithValue("@personID", personID);
                return dCmd.ExecuteNonQuery();
            }
            catch
            {
                throw;
            }
            finally
            {
                dCmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }

        /// <summary>
        /// Load all records from database
       /// </summary>
        /// <returns></returns>
        public DataTable Load()
        {
            SqlConnection conn = new SqlConnection(connStr);
            SqlDataAdapter dAd = new SqlDataAdapter("LoadAll", conn);
            dAd.SelectCommand.CommandType = CommandType.StoredProcedure;
            DataSet dSet = new DataSet();
            try
            {
                dAd.Fill(dSet, "PersonTable");
                return dSet.Tables["PersonTable"];
            }
            catch
            {
                throw;
            }
            finally
            {
                dSet.Dispose();
                dAd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
        /// <summary>
        /// Delete record from database
        /// </summary>
        /// <param name="personID"></param>
        /// <returns></returns>
        public int Delete(int personID)
        {
            SqlConnection conn = new SqlConnection(connStr);
            conn.Open();
            SqlCommand dCmd = new SqlCommand("DeleteData", conn);
            dCmd.CommandType = CommandType.StoredProcedure;
            try
            {
                dCmd.Parameters.AddWithValue("@personID", personID);
                return dCmd.ExecuteNonQuery();
            }
            catch
            {
                throw;
            }
            finally
            {
                dCmd.Dispose();
                conn.Close();
                conn.Dispose();
            }
        }
    }

In the above code, I have a member variable called connStr that is getting database connection string from my web.config file that is being used through out the class. I have separate method for inserting, deleting, updating records into database and loading records from database. I am not goint into details of how I am connecting database and manipulating the data just to make this tutorials short.

Business Access Layer (BAL)

Now, create a class named PersonBAL3 into App_Code folder by right clicking it and write respective methods for calling Insert, Delete, Update and Load methods of Data Access Layer class file (PersonDAL3) (In my case I have a 3-Tier folder inside App_Code folder, you can directly add inside App_Code or you can create a separate project for BAL and add reference of this project into your Presentation Layer). As we don't have any business logic here so simply instantiate the PersonDAL3 class of DAL and call methods. Below is the code for BAL (Your can overwrite your default written code for the class file by pasting this code).

Code for Business Access Layer
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

    /// <summary>
    /// Summary description for PersonBAL3
    /// </summary>
    public class PersonBAL3
    {
        public PersonBAL3()
        {

        }

        /// <summary>
        /// insert records into database
        /// </summary>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="age"></param>
        /// <returns></returns>
        public int Insert(string firstName, string lastName, int age)
        {
            PersonDAL3 pDAL = new PersonDAL3();
            try
            {
                return pDAL.Insert(firstName, lastName, age);
            }
            catch
            {
                throw;
            }
            finally
            {
                pDAL = null;
            }
        }

        /// <summary>
        /// Update records into database
        /// </summary>
        /// <param name="personID"></param>
        /// <param name="firstName"></param>
        /// <param name="lastName"></param>
        /// <param name="age"></param>
        /// <returns></returns>
        public int Update(int personID, string firstName, string lastName, int age)
        {
            PersonDAL3 pDAL = new PersonDAL3();
            try
            {
                return pDAL.Update(personID, firstName, lastName, age);
            }
            catch
            {
                throw;
            }
            finally
            {
                pDAL = null;
            }
        }

        /// <summary>
        /// Load records from database
        /// </summary>
        /// <returns></returns>
        public DataTable Load()
        {
            PersonDAL3 pDAL = new PersonDAL3();
            try
            {
                return pDAL.Load();
            }
            catch
            {
                throw;
            }
            finally
            {
                pDAL = null;
            }
        }

        /// <summary>
        /// Delete record from database
        /// </summary>
        /// <param name="personID"></param>
        /// <returns></returns>
        public int Delete(int personID)
        {
            PersonDAL3 pDAL = new PersonDAL3();
            try
            {
                return pDAL.Delete(personID);
            }
            catch
            {
                throw;
            }
            finally
            {
                pDAL = null;
            }
        }

    }

Till now we haev our Business Access Layer and Database Access Layer ready. Now we have to write our Presentation Layer that will use our Business Access Layer methods. Lets create a form that will have three textboxes for FirstName, LastName and Age.

Presentation Layer




Create an Insert.aspx page (make is as Startup page) and copy paste following code to bring the insert form something like displaying in the picture.
Code for Insert Record form
<asp:Label ID="lblMessage" runat="Server" ForeColor="red" EnableViewState="False"></asp:Label>
        <table style="border:2px solid #cccccc;">
            <tr style="background-color:#507CD1;color:White;">
                <th colspan="3">Add Records</th>
            </tr>
            <tr>
                <td>
                    First Name:
                </td>
                <td>
                    <asp:TextBox ID="txtFirstName" runat="Server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="req1" runat="Server" Text="*" ControlToValidate="txtFirstName" 
                         Display="dynamic"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Last Name:
                </td>
                <td>
                    <asp:TextBox ID="txtLastName" runat="Server"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="req2" runat="Server" Text="*" ControlToValidate="txtLastName" 
                      Display="dynamic"></asp:RequiredFieldValidator>
                </td>
            </tr>
            <tr>
                <td>
                    Age:
                </td>
                <td>
                    <asp:TextBox ID="txtAge" runat="Server" Columns="4"></asp:TextBox>
                </td>
                <td>
                    <asp:RequiredFieldValidator ID="req3" runat="Server" Text="*" ControlToValidate="txtAge" 
                        Display="dynamic"></asp:RequiredFieldValidator>
                    <asp:CompareValidator ID="Comp1" runat="Server" Text="Only integer" ControlToValidate="txtAge" 
                       Operator="DataTypeCheck" Type="Integer"></asp:CompareValidator>
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td>
                    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="AddRecords" />
                </td>
            </tr>
        </table>


Now, lets write method that will fire when Submit button will be clicked on the from.
Code for AddRecords method
protected void AddRecords(object sender, EventArgs e)
    {
        //Lets validate the page first
        if (!Page.IsValid)
           return;

        int intResult = 0;
        // Page is valid, lets go ahead and insert records
        // Instantiate BAL object
        PersonBAL3 pBAL = new PersonBAL3();
        // Instantiate the object we have to deal with
        string firstName = txtFirstName.Text;
        string lastName = txtLastName.Text;
        int age = Int32.Parse(txtAge.Text);
        
        try
        {
            intResult = pBAL.Insert(firstName, lastName, age);
            if (intResult > 0)
                lblMessage.Text = "New record inserted successfully.";
            else
                lblMessage.Text = "FirstName [<b>"+ txtFirstName.Text +"</b>] alredy exists, try another name";

        }
        catch (Exception ee)
        {
            lblMessage.Text = ee.Message.ToString();
        }
        finally
        {
            pBAL = null;
        }        
    }

In the above code, first I am validating the page by using Page.IsValid method just to check if correct data has been entered. Then I have instantiated PersonBAL3 and calling Insert method of it (pBAL.Insert) by passing firstName, lastName, age as parameter.

Dispalying Records into GridView



Create a .aspx file called List.aspx and create a GridView something like displayed into the picture. To list the record into GridView that will also enable us to Edit, Delete record, copy paste following code.

Code for GridView
<asp:GridView ID="GridView1" runat="server" CellPadding="4" ForeColor="#333333" GridLines="None"
         DataKeyNames="PersonID" AutoGenerateEditButton="True" AutoGenerateColumns="False"
          OnRowEditing="EditRecord" OnRowUpdating="UpdateRecord" OnRowCancelingEdit="CancelRecord"
           OnRowDeleting="DeleteRecord" PageSize="5" >
            <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <RowStyle BackColor="#EFF3FB" />
            <EditRowStyle BackColor="#2ff1BF" />
            <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" />
            <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
            <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
            <AlternatingRowStyle BackColor="White" />
            <Columns>
                <asp:BoundField DataField="PersonID" HeaderText="Person ID" ReadOnly="True"  SortExpression="PersonID" />
                <asp:TemplateField HeaderText="First Name" SortExpression="FirstName">
                    <ItemTemplate>
                        <%# Eval("FirstName") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtFName" runat="Server" Text='<%# Eval("FirstName") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Last Name" SortExpression="LastName">
                    <ItemTemplate>
                        <%# Eval("LastName") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtLName" runat="Server" Text='<%# Eval("LastName") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Age" SortExpression="Age">
                    <ItemTemplate>
                        <%# Eval("Age") %>
                    </ItemTemplate>
                    <EditItemTemplate>
                        <asp:TextBox ID="txtAge" runat="Server" Text='<%# Eval("Age") %>'></asp:TextBox>
                    </EditItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Delete?">
                    <ItemTemplate>
                        <span onclick="return confirm('Are you sure to Delete?')">
                            <asp:LinkButton ID="lnBD" runat="server" Text="Delete" CommandName="Delete"></asp:LinkButton>
                        </span>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>


Code to Load records and Displaying Records into GridView
private DataTable BindGrid()
    {
        PersonBAL3 p = new PersonBAL3();
        try
        {
            DataTable dTable = p.Load();
            GridView1.DataSource = dTable;
            GridView1.DataBind();
        }
        catch (Exception ee)
        {
            lblMessage.Text = ee.Message.ToString();
        }
        finally
        {
            p = null;
        }

        return dTable;
    }

In the above method I am instantiating PersonBAL3 class and calling Load method to get the record into DataTable and binding it into GridView.

Code to Delete Records

protected void DeleteRecord(object sender, GridViewDeleteEventArgs e)
    {
        int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString()); 
        // instantiate BAL
        PersonBAL3 pBAL = new PersonBAL3();
        try
        {
            pBAL.Delete(personID);
            lblMessage.Text = "Record Deleted Successfully.";
        }
        catch (Exception ee)
        {
            lblMessage.Text = ee.Message.ToString();
        }
        finally
        {
            pBAL = null;
        }

        GridView1.EditIndex = -1;
        // Refresh the list
        BindGrid();
    }

Above method will fire when Delete link will be clicked on the GridView. In the above code, I am instantiating PersonBAL3 and calling Delete method by passing personID as parameter so that select reocrds will be deleted from datbase.

Code to Update records

protected void UpdateRecord(object sender, GridViewUpdateEventArgs e)
    {
        int personID = Int32.Parse(GridView1.DataKeys[e.RowIndex].Value.ToString());
        int intResult = 0;
        GridViewRow row = GridView1.Rows[e.RowIndex];

        TextBox tFN = (TextBox) row.FindControl("txtFName");
        TextBox tLN = (TextBox)row.FindControl("txtLName");
        TextBox tAge = (TextBox)row.FindControl("txtAge");

        // instantiate BAL
        PersonBAL3 pBAL = new PersonBAL3();

        try
        {
            intResult = pBAL.Update(personID, tFN.Text, tLN.Text, int.Parse(tAge.Text));
            if (intResult > 0)
                lblMessage.Text = "Record Updated Successfully.";
            else
                lblMessage.Text = "Record couldn't updated";
        }
        catch (Exception ee)
        {
            lblMessage.Text = ee.Message.ToString();
        }        finally
        {
            pBAL = null;
        }

        GridView1.EditIndex = -1;
        // Refresh the list
        BindGrid();
    }

Above method will fire when Update link will be clicked for a particular row of the GridView in edit mode. In the above method, I am instantiating PersonBAL3 and calling the Update method by p[assing required parameters.

Now we have all set to go, now just run your project and try inserting records. You can also navigate to another page your created (list.aspx) and try updating, deleting records.

Conclusion

By using 3-Tier architecture in your project you can achive

1. Seperation - the functionality is seperated from the data access and presentation so that it is more maintainable
2. Independence - layers are established so that if one is modified (to some extent) it will not affect other layers.
3. Reusability - As the layers are seperated, it can exist as a module that can be reused by other application by referencing it.

Hope this article helped you understanding 3-Tier architecture and desiging it.

Thanks and Happy Coding !!!
http://www.dotnetfunda.com/articles/article71.aspx

Disable back button in of the browser

In this article, I am discussing how to prevent user from navigate to previous page using back button of the browser or the back option in the context menu.
One cannot disable the browser back button functionality only thing that can be done is prevent them.
Below is the JavaScript snippets that needs to be placed in the head section of the page where you don’t want the user to revisit using the back button
<script type = "text/javascript" >
   function preventBack(){window.history.forward();}
    setTimeout("preventBack()", 0);
    window.onunload=function(){null};
</script>

Suppose there are two pages Page1.aspx and Page2.aspx and Page1.aspx redirects to Page2.aspx
Hence to prevent user from visiting Page1.aspx using Back Button you will need to place the above script in the head section of Page1.aspx as shown below.


Writing the code to disable back button

I have tested the script in the following browsers
1.     Internet Explorer 5.55
2.     Internet Explorer 6
3.     Internet Explorer 7
4.     Mozilla Firefox 3
5.     Opera 9
6.     Safari 4
7.     Google Chrome

Page life cycle


The life cycle starts when a user requests a web page through his/her browser. The Web server than process the page through a sequence of steps before response is sent back to the user's browser. The steps are as:
  1. Page Request
  2. Start
  3. Page Initialization
  4. Load
  5. Validation
  6. PostBack Event Handling
  7. Render
  8. Unload
The below figure shows the Page Life Cycle of an ASP.NET and its controls
Life-cycle.gif

Page Request
The page request occurs before the page life cycle begins. When a user requests the page, ASP.NET determines whether the page needs to be parsed and compiled (therefore beginning the life of a page), or whether a cached version of the page can be sent in response without running the page.

Start
In the start step, page properties such as Request and Response are set. At this stage, the page also determines whether the request is a postback or a new request and sets the IsPostBack property. Additionally, during the start step, the page's UICulture property is set.

Page Initialization

During page initialization, controls on the page are available and each control's UniqueID are generated but not their properties. Any themes are also applied to the page.

Developers have access to the Init, InitComplete and PreLoad methods in this stage. The methods are as follows:

  • Init: This event is raised after all controls have been initialized and any skin settings have been applied. This event is used to read or initialize control properties.
  • InitComplete: The Page object raises this event. This event is used for processing tasks that require completion of all initialization.
  • PreLoad: Use this event if you need to perform processing on your page or control before the Load event. After the Page raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.
Load

During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state. The OnLoad event method is fired during this stage.

This is where you will want to set properties for all of the server controls on your page, request query strings, and establish database connections.

Validation

During validation, the Validate method of all validator controls is called, which sets the IsValid property of individual validator controls and of the page.

PostBack Event Handling

If the request is a postback, any event handlers are called. The event handling for server controls occurs during this stage.

Render

During rendering, view state is saved to the page and then the page calls on each control to contribute its rendered output to the OutputStream of the page's Response property. Render is not really an event. The HTML of the page and all controls are sent to the browser for rendering.

Unload

Unload is called when the page has been fully rendered, sent to the client, and is ready to be discarded. At this point, page properties such as Response and Request are unloaded and any cleanup is performed. The cleanup includes routines such as closing database connections and file streams, or, event logging and other tasks.

Conclusion

When a Web page is requested, the server creates objects associated with the page and all of its child controls objects and uses these to render the page to the browser. Once the final stage is complete, the web server destroys these objects, to free up resource to handle additional request.

I hope that this article would have helped you in understanding the Page Life Cycle in ASP.NET and its controls. Your feedback and constructive contributions are welcome.