Sunday, 30 December 2012

ASP.NET



ASP.NET

·         ASP.NET is a web application framework developed and marketed by Microsoft to allow programmers to build dynamic web sites.
·         ASP.Net is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web application for PC, as well as mobile devices.
·         ASP.Net works on top of the HTTP protocol and uses the HTTP commands and policies to set a browser-to-server two-way communication and cooperation.
·         ASP.Net is a part of Microsoft .Net platform. ASP.Net applications are complied codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework.
·         The ASP.Net application codes could be written in either of the following languages:
C#,Visual Basic .Net,Jscript and J#
·         ASP.Net is used to produce interactive, data-driven web applications over the internet. It consists of a large number of controls like text boxes, buttons and labels for assembling, configuring and manipulating code to create HTML pages.
ASP.Net Web Forms Model:
ASP.Net web forms extend the event-driven model of interaction to the web applications. The browser submits a web form to the web server and the server returns a full markup page or HTML page in response.
All client side user activities are forwarded to the server for stateful processing. The server processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. ASP.Net framework helps in storing the information regarding the state of the application, which consists of:
  • Page state
  • Session state
The page state is the state of the client, i.e., the content of various input fields in the web form. The session state is the collective obtained from various pages the user visited and worked with, i.e., the overall session state. To clear the concept, let us take up an example of a shopping cart as follows.
User adds items to a shopping cart. Items are selected from a page, say the items page, and the total collected items and price are shown in a different page, say the cart page. Only HTTP cannot keep track of all the information coming from various pages. ASP.Net session state and server side infrastructure keeps track of the information collected globally over a session.
The ASP.Net runtime carries the page state to and from the server across page requests while generating the ASP.Net runtime codes and incorporates the state of the server side components in hidden fields.
This way the server becomes aware of the overall application state and operates in a two-tiered connected way.
ASP.Net Component Model:
The ASP.Net component model provides various building blocks of ASP.Net pages. Basically it is an object model, which describes:
  • Server side counterparts of almost all HTML elements or tags, like <form> and <input>.
  • Server controls, which help in developing complex user-interface for example the Calendar control or the Gridview control.
Components of .Net Framework 3.5
Before going to the next session on Visual Studio.Net, let us look at the various components of the .Net framework 3.5. The following table describes the components of the .Net framework 3.5 and the job they perform:
Components and their Description
(1) Common Language Runtime or CLR
It performs memory management, exception handling, debugging, security checking, thread execution, code execution, code safety, verification and compilation.Those codes which are directly managed by the CLR are called the managed code. When the managed code is compiled, the compiler converts the source code into a CPU independent intermediate language (IL) code. A Just in time compiler (JIT) compiles the IL code into native code, which is CPU specific.
(2) .Net Framework Class Library
It contains a huge library of reusable types . classes, interfaces, structures and enumerated values, which are collectively called types.
(3) Common Language Specification
It contains the specifications for the .Net supported languages and implementation of language integration.
(4) Common Type System
It provides guidelines for declaring, using and managing types at runtime, and cross-language communication.
Metadata and Assemblies
Metadata is the binary information describing the program, which is either stored in a portable executable file (PE) or in the memory. Assembly is a logical unit consisting of the assembly manifest, type metadata, IL code and set of resources like image files etc.
(5) Windows Forms
This contains the graphical representation of any window displayed in the application.
(6) ASP.Net and ASP.Net AJAX
ASP.Net is the web development model and AJAX is an extension of ASP.Net for developing and implementing AJAX functionality. ASP.Net AJAX contains the components that allow the developer to update data on a website without a complete reload of the page.
(7) ADO.Net
It is the technology used for working with data and databases. It provides accesses to data sources like SQL server, OLE DB, XML etc. The ADO .Net allows connection to data sources for retrieving, manipulating and updating data.
(8) Windows Workflow Foundation (WF)
It helps in building workflow based applications in Windows. It contains activities, workflow runtime, workflow designer and a rules engine.
(9)Windows Presentation Foundation
It provides a separation between the user interface and the business logic. It helps in developing visually stunning interfaces using documents, media, two and three dimensional graphics, animations and more.
(10) Windows Communication Foundation (WCF)
It is the technology used for building and running connected systems.
(11) Windows CardSpace
It provides safety of accessing resources and sharing personal information on the internet.
(12) LINQ
It imparts data querying capabilities to .Net languages using a syntax which is similar to the tradition query language SQL.


ASP.Net Page Life Cycle:

Following are the different stages of an ASP.Net page:
·         Page request . when ASP.Net gets a page request, it decides whether to parse and compile the page or there would be a cached version of the page; accordingly the response is sent
·         Starting of page life cycle . at this stage, the Request and Response objects are set. If the request is an old request or post back, the IsPostBack property of the page is set to true. The UICulture property of the page is also set.
·         Page initialization . at this stage, the controls on the page are assigned unique ID by setting the UniqueID property and themes are applied. For a new request postback data is loaded and the control properties are restored to the view-state values.
·         Page load . at this stage, control properties are set using the view state and control state values.
·         Validation . Validate method of the validation control is called and if it runs successfully, the IsValid property of the page is set to true.
·         Postback event handling . if the request is a postback (old request), the related event handler is called.
·         Page rendering . at this stage, view state for the page and all controls are saved. The page calls the Render method for each control and the output of rendering is written to the OutputStream class of the Page's Response property.
·         Unload . the rendered page is sent to the client and page properties, such as Response and Request are unloaded and all cleanup done.
Advantages:
*
Rich controls - the framework comes with a large set of very robust and useful server and client side controls for creating interactive grids, calendars, wizards, and much more. Many of these have a lot of functionality right out of the box. There is also support for defining your own controls.

* Rapid development - you can generally throw a fairly dynamic website together pretty quickly with ASP.NET.

* Automatic statefullness - the viewstate structure will automatically save the state of controls and other fields for you so you don't have to manage that behind the scenes. This is a big time saver but can have performance ramifications (see below).

* Abstracts the webiness away from web programming - the framework treats web forms a lot like Windows Forms (if you're familiar with those) where you have a bunch of controls on a page and each one has one or more events associated with it (like OnClick or OnChange) and you simply provide the code to handle those events. All of the mapping up from the web page to your code-behind events is done for you by the framework. Some people see this as a bad thing (see below).

* Built in security - there is out of the box support for authentication, authorization, and various options for implementation with NTLM, Kerberos, and other standards.

Disadvantages:
*
Does not allow for easy unit tests - the framework tends not to support automatic unit testing with tools like NUnit very well, which makes test-driven development difficult. MVC based frameworks like Struts or ASP.NET MVC do a better job of this.

* View state - often times viewstate can get really large or have negative effects on performance. This is especially true for some of the more complex server controls.

* Abstracts the webiness away from web programming - some people feel that ASP.NET does not fit the general architecture of internet and web based applications. They feel like Microsoft tried to follow the Windows Forms desktop paradigm too closely and it makes for developers that don't have a good grasp on how web apps are different than desktop apps.

An ASP.Net page is also a server side file saved with the .aspx extension. It is modular in nature and can be divided into the following core sections:
·         Page directives
·         Code Section
·         Page Layout

Page directives:

The page directives set up the environments for the page to run. The @Page directive defines page-specific attributes used by the ASP.Net page parser and compiler. Page directives specify how the page should be processed, and which assumptions are to be taken about the page.
It allows importing namespaces, loading assemblies and registering new controls with custom tag names and namespace prefixes. We will discuss all of these concepts in due time.

Code Section:

The code section provides the handlers for the page and control events along with other functions required. We mentioned that, ASP.Net follows an object model. Now, these objects raises events when something happens on the user interface, like a user clicks a button or moves the cursor. How these events should be handled? That code is provided in the event handlers of the controls, which are nothing but functions bound to the controls.
The code section or the code behind file provides all these event handler routines, and other functions used by the developer. The page code could be precompiled and deployed in the form of a binary assembly.

Page Layout:

The page layout provides the interface of the page. It contains the server controls, text, inline JavaScript and HTML tags:
The following code snippet provides a sample ASP.Net page explaining pafe directives, code section and page layout written in C#:
<!-- directives -->
<% @Page Language="C#" %>
 
<!-- code section -->
<script runat="server">
private void convertoupper(object sender, EventArgs e)
{
        string str = mytext.Value;
        changed_text.InnerHtml = str.ToUpper();
}
</script>
 
<!-- Layout -->
<html>
<head> <title> Change to Upper Case </title> </head>
<body>
<h3> Conversion to Upper Case </h3>
<form runat="server">
        <input runat="server" id="mytext" type="text" />
        <input runat="server" id="button1" type="submit" 
    value="Enter..." OnServerClick="convertoupper"/>
<hr />
<h3> Results: </h3>
<span runat="server" id="changed_text" />
</form>
</body>
</html>
What is an Event?
Event is an action or occurrence like mouse click, key press, mouse movements, or any system generated notification. The processes communicate through events. For example, Interrupts are system generated events. When events occur the application should be able to respond to it.
In ASP.Net an event is raised on the client, and handled in the server. For example, a user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side event by posting it to the server.
The server has a subroutine describing what to do when the event is raised; it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks whether the Click event has an associated event handler, and if it has, the event handler is executed.
Event Arguments:
ASP.Net event handlers generally take two parameters and return void. The first parameter represents the object raising the event and the second parameter is called the event argument.
The general syntax of an event is:
private void EventName (object sender, EventArgs e);
Application and Session Events:
The most important application events are:
  • Application_Start . it is raised when the application/website is started
  • Application_End . it is raised when the application/website is stopped
Similarly, the most used Session events are:
  • Session_Start . it is raised when a user first requests a page from the application
  • Session_End . it is raised when the session ends
Page and Control Events:
Common page and control events are:
  • DataBinding . raised when a control bind to a data source
  • Disposed . when the page or the control is released
  • Error . it is an page event, occurs when an unhandled exception is thrown
  • Init . raised when the page or the control is initialized
  • Load . raised when the page or a control is loaded
  • PreRender . raised when the page or the control is to be rendered
  • Unload . raised when the page or control is unloaded from memory
Event Handling Using Controls:
All ASP.Net controls are implemented as classes, and they have events which are fired when user performs certain action on them. For example, when a user clicks a button the 'Click' event is generated. For handling these events there are in-built attributes and event handlers. To respond to an event, the event handler is coded.
By default Visual Studio creates an event handler by including a Handles clause on the Sub procedure. This clause names the control and event that the procedure handles.
The asp tag for a button control:
<asp:Button ID="btnCancel" runat="server" Text="Cancel" />
The event handler for the Click event:
Protected Sub btnCancel_Click(ByVal sender As Object,
                              ByVal e As System.EventArgs)
                              Handles btnCancel.Click
End Sub
An event can also be coded without a Handles clause. Then the handler must be named according to the appropriate event attribute of the control.
The asp tag for a button control:
<asp:Button ID="btnCancel" runat="server" Text="Cancel"
                              Onclick="btnCancel_Click" />
The event handler for the Click event:
Protected Sub btnCancel_Click(ByVal sender As Object,
                              ByVal e As System.EventArgs)
End Sub
The common control events are:
Event
Attribute
Controls
Click
OnClick
Button, image button, link button, image map
Command
OnCommand
Button, image button, link button
TextChanged
OnTextChanged
Text box
SelectedIndexChanged
OnSelectedIndexChanged
Drop-down list, list box, radio button list, check box list.
CheckedChanged
OnCheckedChanged
Check box, radio button
Some events cause the form to be posted back to the server immediately, these are called the postback events. For example, the click events like, Button.Click. Some events are not posted back to the server immediately, these are called non-postback events.
For example, the change events or selection events, such as, TextBox.TextChanged or CheckBox.CheckedChanged. The nonpostback events could be made to post back immediately by setting their AutoPostBack property to true.
Default Events:
The default event for the Page object is the Load event. Similarly every control has a default event. For example, default event for the button control is the Click event.
The default event handler could be created in Visual Studio, just by double clicking the control in design view. The following table shows some of the default events for common controls:
Control
Default Event
AdRotator
AdCreated
BulletedList
Click
Button
Click
Calender
SelectionChanged
CheckBox
CheckedChanged
CheckBoxList
SelectedIndexChanged
DataGrid
SelectedIndexChanged
DataList
SelectedIndexChanged
DropDownList
SelectedIndexChanged
HyperLink
Click
ImageButton
Click
ImageMap
Click
LinkButton
Click
ListBox
SelectedIndexChanged
Menu
MenuItemClick
RadioButton
CheckedChanged
RadioButtonList
SelectedIndexChange

ASP.NET - Server Controls
Controls are small building blocks of the graphical user interface, which includes text boxes, buttons, check boxes, list boxes, labels and numerous other tools, using which users can enter data, make selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating master pages, data manipulation.
ASP.Net uses five types of web controls, which are:
  • HTML controls
  • HTML Server controls
  • ASP.Net Server controls
  • ASP.Net Ajax Server controls
  • User controls and custom controls
ASP.Net server controls are the primary controls used in ASP.Net. These controls again could be grouped into the following categories:
  • Validation controls - these are used to validate user input and work by running client-side script
  • Data source controls - these controls provides data binding to different data sources
  • Data view controls - these are various lists and tables, which can bind to data from data sources for display
  • Personalization controls - these are used for personalization of a page according to the user's preference, based on user information
  • Login and security controls - these controls provide user authentication
  • Master pages - these provides consistent layout and interface throughout the application
  • Navigation controls - these helps in navigation, for example, the menus, tree view etc.
  • Rich controls - these implements special features, for example, AdRotator control, FileUpload control, Calendar control etc.
The basic syntax for using server controls is:
<asp:controlType  ID ="ControlID"
                     runat="server"
                     Property1=value1  [Property2=value2] />
ASP.NET - Managing State
ASP.Net manages four types of state:
1.      View State
2.      Control State
3.      Session State
4.      Application State
View State:
The View State is the state of the page and all its controls. It is automatically maintained across posts by the ASP.Net framework.
When a page is sent back to the client, the changes in the properties of the page and its controls are determined and stored in the value of a hidden input field named _VIEWSTATE. When the page is again post back the _VIEWSTATE field is sent to the server with the HTTP request.
The view state could be enabled or disabled for:
  • The entire application - by setting the EnableViewState property in the <pages> section of web.config file
  • A page - by setting the EnableViewState attribute of the Page directive, as <%@ Page Language="C#" EnableViewState="false" %>
  • A control - by setting the Control.EnableViewState property.
Control State:
·         Control state cannot be modified, accessed directly or disabled.
Session State:
·         When a user connects to an ASP.Net website, a new session object is created. When session state is turned on, a new session state object is created for each new request. This session state object becomes part of the context and it is available through the page.
·         Session state is generally used for storing application data like inventory or supplier list, or a customer record or shopping cart. It can also keep information about the user and his preference and keep track of pending operations.
·         Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie or a modified URL. The SessionID is globally unique and random.
·         The session state object is created from the HttpSessionState class, which defines a collection of session state items.
Application State
·         An ASP.Net application is the collection of all web pages, code and other files within a single virtual directory on a web server. When information is stored in application state, it is available to all the users.
·         To provide for the use of application state, ASP.Net creates an application state object for each application from the HTTPApplicationState class and stores this object in server memory. This object is represented by class file global.asax.
·         Application State is mostly used to store hit counters and other statistical data, global application data like tax rate, discount rate etc and to keep track of users visiting the site.


2 comments:

  1. I am searching about PHP and ASP.NET development services and found this blog I think you really maintain this blog very well because it has some good information which I like it.
    Malaysia Website Design Company | Offshore Software Development Services

    ReplyDelete
  2. Really nice blog post.provided a helpful information.I hope that you will post more updates like this
    Dot NET Online Training Hyderabad

    ReplyDelete