Thursday, January 28, 2010

Difference between session and viewstate

1. Session state is a server based state management. It can be accessible from all pages in web application. It is scoped to current browser session only. It's structured as a key/value dictionary for storing session specific info that needs to be maintained between server round trips.

2. SESSION Variables are stored on the server, can hold any type of data including references, they are similar to global variables in a windows application and use HTTP cookies to store a key with which to locate user's session variables.

3. VIEWSTATE Variables are stored in the browser (not as cookies) but in a hidden field in the browser. Also Viewstate can hold only string data or serializable objects.

4. ViewState persist the values of controls of particular page in the client (browser) when post back operation done. When user requests another page previous page data no longer available.

5. SessionState persist the data of particular user in the server. This data available till user close the browser or session time completes.

6. Viewstate is particular to a control/page whereas session is for the whole application. You can access the session data stored in page A in page B but viewstate does not behave so.

7. ViewState is maintained at client side whereas session is maintained at server side

8. Since viewstate is maintained at client, it does not have a concept of expiry but session will expire after the stipulated time

9. You can enable/disable view state for specific controls but you can't do that for session.

What is ViewState?

ViewState
ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. ViewState is transported to the client and back to the server, and is not stored on the server or any other external source. ViewState is used the retain the state of server-side objects between postabacks.

When to use the ViewState
View state is a good way to store data in between postbacks, because it doesn't take up any memory on the server side and it doesn't impose any arbitrary usage limits (such as a timeout). So, what might force you to abandon view state for another type of state management? Here are three possible reasons:
  • You need to store mission-critical data that the user cannot be allowed to tamper with. (An ingenious user could modify the view state information in a postback request.) In this case, consider session state.
  • You need to store information that will be used by multiple pages. In this case, consider session state, cookies, or the query string.
  • You need to store an extremely large amount of information, and you don't want to slow down page transmission times. In this case, consider using a database, or possibly session state.
Remember, any data that you put in the view state will be part of the data stream that goes to the client and then comes back to the server, so be very careful while putting large chunks of data in the ViewState!

Problems with ViewState
Viewstate has lots of advantages and as well as disadvantages, so you need to weigh carefully before making the decision to use it. As I told you early, view state doesnt require any server resources for its operation. It is passed to the client during every postback as an hidden element. Since it is added with every page, it adds few Kbytes to the page. This effects the loading of the page in the client. Other main problem with Viewstate is, since it is passed as plain text to the client. Anybody can tamper this value, because of this you shouldnt store any important data in the viewstate. View state is one of the most important features of ASP.NET, not so much because of its technical relevance, but more because it makes the magic of the Web Forms model possible. However, if used carelessly, view state can easily become a burden. Although ViewState is freely accessible in a hidden field called __VIEWSTATE, the view state information is not clear text. By default, a machine-specific authentication code is calculated on the data and appended to the view state string. The resulting text is then Base64 encoded only, but not encrypted. In order to make the view state more secure, the ASP.NET @Page directive supports an attribute called EnableViewStateMac whose only purpose is detecting any possible attempt at corrupting original data.

Tuesday, January 26, 2010

Logical Layers vs. Physical Layers

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.

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.

What is n-Tier Architecture?

n-Tier Architecture
We will talk generally about what n-Tier architecture is, and then we will have a look at different n-Tier architectures we can use to develop ASP.NET applications and issues that arise relating to performance, scalability and future development issues for each one.

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.
N-Tier the word means Multiple Tier.
N-Tier Architecture is nothing but splitting your solution into different project based on the business requirement.
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.

Advantage:
  1. Reduce the business and the programming complexity.
  2. Easy to process

Note: tier and layer mean the same thing

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.

Often this layer is divided into two sub layers
BLL and DAL
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.

Some reasons for data tier is ;
  • Security
  • Code Maintenance and Reuse
  • Scalability

How to Implement N-Tier Architecture in Web Application?
To  work with n-Tier system
  1. Create a solution.
  2. Include a web application project in it and name it as "PRESENTATION LAYER"
  3. Include a Class Library Project and name it as "DATALAYER"




  4. Include a Class Library Project and name it as "BUSINESSLAYER"
  5. Now we have 3 project in single solution
  6. Build the DataLayer.
  7. Go to Business layer and right click on reference and in reference go to Project's. Here we can see the Datalayer. Click on that and include as reference.
  8. Now in the Business Layer reference we can see the DataLayer assembly
  9. Go to Presentationlayer and right click on reference and in reference go to Project's. Here we can see the BusinessLayer. Click on that and include as reference.
  10. Now we can see the BusinessLayer Assembly in the Presentation Layer.
  11. Now we can access all the methods
    DataLayer in Business Layer
    BusinessLayer in PresentationLayer



  12. This is the way we build our N-Tier Application. For example, this is a 3 Tier System.

Monday, January 25, 2010

What is the difference between Dataset and Recordset?

Below is the differences between Dataset and Recordset?

  • Dataset is a disconnected architecture
  • Dataset can be connect two database example oracle,sql table
  • DataSet is Xml Based and faster
  • Performancewise DataSet is better than recordset
  • Data Set is main for storage tool in ADO.Net
  • A DataSet can represent an entire relational database in memory, complete with tables, relations, and views.
  • Data in a DataSet is bulk-loaded, rather than being loaded on demand.
  • There's no concept of cursor types in a DataSet.
  • DataSets have no current record pointer You can use For Each loops to move through the data.
  • You can store many edits in a DataSet, and write them to the original data source in a single operation.

  • Recordset provides data one row at a time.
  • Record Set is a Connected Architecture
  • Recordset connect only one database
  • RecordSet is one (1) table that contains all the data
  • Retrieving data from more than one table or source requires a database JOIN.

Thursday, January 21, 2010

Binding Grid view with datasource and handling paging option

We have two steps for binding gridview with datasource and handling paging option

Step 1:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
GridView1.DataSource = ds
GridView1.DataBind()
end sub

Step 2:
Protected Sub GridView1_PageIndexChanging(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.GridViewPageEventArgs) Handles GridView1.PageIndexChanging
GridView1.PageIndex = e.NewPageIndex
GridView1.DataBind()
End Sub

Wednesday, January 20, 2010

ASP.Net Page Life Cycle Events

Page life-cycle events that we use most frequently. There are more events than those listed; however, they are not used for most page processing scenarios. If we want to write our own ASP.NET server controls, we need to understand more about these events.

1. PreInit
Use this event for the following:
  • Check the IsPostBack property to determine whether this is the first time the page is being processed.
  • Create or re-create dynamic controls.
  • Set a master page dynamically.
  • Set the Theme property dynamically.
  • Read or set profile property values.
Note:
If the request is a postback, the values of the controls have not yet been restored from view state. If you set a control property at this stage, its value might be overwritten in the next event.

2. Init
Raised after all controls have been initialized and any skin settings have been applied. Use this event to read or initialize control properties.

3. InitComplete
Raised by the Page object. Use this event for processing tasks that require all initialization be complete.

4. PreLoad
Use this event if you need to perform processing on your page or control before the Load event. Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance.

5. Load
The Page calls the OnLoad event method on the Page, then recursively does the same for each child control, which does the same for each of its child controls until the page and all controls are loaded. Use the OnLoad event method to set properties in controls and establish database connections.

6. Control Events
Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.
Note:
In a postback request, if the page contains validator controls, check the IsValid property of the Page and of individual validation controls before performing any processing.

7. LoadComplete
Use this event for tasks that require that all other controls on the page be loaded.

8. PreRender
Before this event occurs:
  • The Page object calls EnsureChildControls for each control and for the page.
  • Each data bound control whose DataSourceID property is set calls its DataBind method. For more information, see Data Binding Events for Data-Bound Controls later in this topic.
The PreRender event occurs for each control on the page. Use the event to make final changes to the contents of the page or its controls.

9. SaveStateComplete
Before this event occurs, ViewState has been saved for the page and for all controls. Any changes to the page or controls at this point will be ignored. Use this event perform tasks that require view state to be saved, but that do not make any changes to controls.

10. Render
This is not an event; instead, at this stage of processing, the Page object calls this method on each control. All ASP.NET Web server controls have a Render method that writes out the control's markup that is sent to the browser.

If you create a custom control, you typically override this method to output the control's markup. However, if your custom control incorporates only standard ASP.NET Web server controls and no custom markup, you do not need to override the Render method. For more information, see Developing Custom ASP.NET Server Controls.

A user control (an .ascx file) automatically incorporates rendering, so you do not need to explicitly render the control in code.

11. Unload
This event occurs for each control and then for the page. In controls, use this event to do final cleanup for specific controls, such as closing control-specific database connections.

For the page itself, use this event to do final cleanup work, such as closing open files and database connections, or finishing up logging or other request-specific tasks.

Note:
During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. If you attempt to call a method such as the Response.Write method, the page will throw an exception.

ASP.Net Page Life Cycle Stages

Below is the ASP.NET Application Page Life Cycle Stages for IIS 7.0

1. Page Request
The page request occurs before the page life cycle begins. When the page is requested by a user, 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.

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

3. Page Initialization
During page initialization, controls on the page are available and each control's UniqueID property is set. Any themes are also applied to the page. If the current request is a postback, the postback data has not yet been loaded and control property values have not been restored to the values from view state.

4. Load
During load, if the current request is a postback, control properties are loaded with information recovered from view state and control state.

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

6. Postback Event Handling
If the request is a postback, any event handlers are called.

7. Rendering
Before rendering, view state is saved for the page and all controls. During the rendering phase, the page calls the Render method for each control, providing a text writer that writes its output to the OutputStream of the page's Response property.

8. Unload
Unload is called after 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.

Tuesday, January 19, 2010

Memory Leak in Dot Net

Memory leaks can occur either in the stack, unmanaged heap, or the managed heap. There are many ways to find out that memory is leaking, like memory increasing in the Task Manager. Before starting to correct the memory problem, you need to determine the kind of memory which is leaking. Perfmon can be used to examine counters such as Process/Private bytes, .NET CLR Memory/# bytes in all heaps, and the .NET CLR LocksAndThreads/# of the current logical thread. If the .NET CLR LocksAndThreads/# is increasing unexpectedly, then the thread stack is leaking. If only Process/Private bytes are increasing but the .NET CLR Memory is not increasing, then unmanaged memory is leaking, else if both are increasing, then managed memory is leaking.

Stack memory
Stack memory gets reclaimed after the method returns. Stack memory can get leaked in two ways. First, a method call consumes a significant amount of stack resources that never returns, thereby never releasing the associated stack frame. The other is by creating background threads and never terminating them, thus leaking the thread stack.

Unmanaged Heap Memory
If the total memory usage is increasing but the .NET CLR memory is not increasing, then unmanaged memory is leaking. Unmanaged memory can leak in several ways - if the managed code is interoperating with unmanaged code and a leak exists in the unmanaged code. .NET doesn't make any guarantee that the finalizer for each object will get called. In the current implementation, .NET has one finalizer thread. If there exists a finalizer which blocks this thread, then the other finalizer will never get called and the unmanaged memory will leak which was supposed to be released. When an AppDomain is torn down, the CLR tries to run all the finalizers, but if a blocking finalizer exists, then it can prevent the CLR from completing the AppDomain tear down. To prevent this, the CLR implements a timeout on the process, after which it stops the finalization process, and the unmanaged memory which was supposed to be removed is left leaked.

Managed Heap Memory
Managed memory can also get leaked by several ways like fragmentation of the Large Object Heap. The memory in the Large Object Heap never gets compacted, so there is a loss in memory over there. Also, if there exist some objects which are not needed, but there exists a reference to the objects, then GC never claims the memory assigned to these objects.

Example:
static object someObj;

static void SomeMethod()
{
someObj = new Object();
}

The GC would not be able to collect the allocated object until someObj was set equal to null. This is because the static someObj reference is always reachable from code.

MVC Architecture in ASP.net

Model View Controller architecture aims to separate an application into three parts:

Model:
It is the business logic of an application. From an object oriented perspective it would consist of a set of classes that implement the critical functionality of an application from a business point of view.
View: It can consist of every type of interface given to the user. In ASP.NET the view is the set of web pages presented by a web application.
Controller: This part of the architecture is the most difficult to explain, hence the most difficult to implement in many platforms. The controller is the object that allows the manipulation of the view. Usually many applications implement Model-Controller tiers that contain the business logic along with the necessary code to manipulate a user interface. In an ASP.NET application the controller is implicitly represented by the code-behind or the server side code that generates the HTML presented to the user.

A basic diagram that would help us understand perfectly the specific parts that implement the Model View Controller architecture in an ASP.NET application is presented below:

-----------------------------------------------------------------------------------
  
Advantages:
1. Layering Approach helps us a lot and we need to enhance it to get full customizability.
2. We need to enhance this with all our design knowledge.
3. No IDE enforces these patterns, it is up to us to do clean and disciplined way of coding.
4. Once we are used to these approaches / patterns then we are addicted to it.

References: 
http://www.techbubbles.com/aspnet/aspnet-35-mvc-application/

Thursday, January 7, 2010

What is the difference between datatable and dataset?

Dataset
dataset is collection of data table and it is provide interface between database and datatable. dataset consist multiple table. A Dataset is an in-memory representation of a collection of Database objects including tables of a relational database schema. Dataset represents an in-memory cache of data. The dataset contains a collection of Tables, Relations, constraints etc., The dataset contains all the objects as a Collection of objects. For example it contains the Database Tables as DataTable objects. Dataset is a collection of tables, which is used in disconnected architecture. Generally to fill dataset we use fill method of dataadapter.

It can be used for manipulating the data remotely and finally updating the database with the modified data. This way it enables disconnected means of working with data. This improves performance in terms of reducing the number of times a database is accessed for data manipulations.

Example for dataset:
using System.Data.SqlClient;
using System.Data;

string strDBConnection = "server=(local);database=DatabaseName;user id=UserName;password=Pwd;connection reset=false;connection lifetime=5;Trusted_Connection=Yes;"
SqlConnection dbConnection;
dbConnection = new SqlConnection(strDBConnection);

string strSelectSql = "Select * from [DatabaseName].[OwnerName].[TableName] order by FieldName";

//Open the connection
dbConnection.Open();

//Create a command
SqlCommand selectSqlCommand = new SqlCommand(strSelectSql,dbConnection);
SqlDataAdapter sqlData = new SqlDataAdapter(selectSqlCommand);
DataSet dsSelectData = new DataSet();
sqlData.Fill(dsSelectData);


Data Table
Data table is a collection of records that consist the single table. You can get datatable from dataset as follows.

DataTable tbl = DataSet.Tables["Tablename" or Table instance number]

Datatable represents one table of in-memory data. Datatable is a single table. datatable is just like table which has columns and rows. A DataTable is an in-memory representation of data, typically retrieved from a database or XML source.