0% found this document useful (0 votes)
66 views

Unit 2.intro To

The document provides an overview of the .NET framework including its history, components, supported programming languages, and garbage collection. It discusses the Common Language Runtime, Framework Class Library, and versions of the .NET framework and their compatibility with Windows versions.

Uploaded by

Adinath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
66 views

Unit 2.intro To

The document provides an overview of the .NET framework including its history, components, supported programming languages, and garbage collection. It discusses the Common Language Runtime, Framework Class Library, and versions of the .NET framework and their compatibility with Windows versions.

Uploaded by

Adinath
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Introduction to .

NET Framework
2.1. DOT NET Framework

.NET is a software framework that is designed and developed by Microsoft. The


first version of the .Net framework was 1.0 which came in the year 2002. In easy
words, it is a virtual machine for compiling and executing programs written in
different languages like C#, VB.Net, etc.
It is used to develop Form-based applications, Web-based applications, and Web
services. There is a variety of programming languages available on the .Net
platform, VB.Net and C# being the most common ones. It is used to build
applications for Windows, phones, web, etc. It provides a lot of functionalities and
also supports industry standards.
.NET Framework supports more than 60 programming languages in which 11
programming languages are designed and developed by Microsoft. The
remaining Non-Microsoft Languages are supported by .NET Framework but not
designed and developed by Microsoft.
There are three significant phases of the development of .NET technology.
 OLE Technology
 COM Technology
 .NET Technology

OLE Technology: OLE (Object Linking and Embedding) is one of the


technologies of Microsoft’s component document. Basically, its main purpose is to
link elements from different applications within each other.
COM Technology: The technology of the Microsoft Windows family of the
operating system, Microsoft COM (Common Object Model) enables various
software components to communicate. COM is mostly used by developers for
various purposes like creating reusable software components, linking components
together to build applications, and also taking advantage of Windows services. The
objects of COM can be created with a wide range of programming languages.
.NET Technology: .NET technology of collection or set of technologies to
develop and windows and web applications. The technology of .Net is developed
by Microsoft and was launched in Feb. 2002, by basic definition, Microsoft’s new
Internet Strategy. It was originally called NGWS (Next Generation Web Services).
It is considered to be as one of the powerful, popular and very much useful Internet
Technology available today.
11 Programming Languages which are designed and developed by Microsoft
are:
 C#.NET
 VB.NET
 C++.NET
 J#.NET
 F#.NET
 JSCRIPT.NET
 WINDOWS POWERSHELL
 IRON RUBY
 IRON PYTHON
 C OMEGA
 ASML(Abstract State Machine Language)

Main Components of .NET Framework

Common Language Runtime(CLR): CLR is the basic and Virtual Machine


component of the .NET Framework. It is the run-time environment in the .NET
Framework that runs the codes and helps in making the development process easier
by providing various services such as remoting, thread management, type-safety,
memory management, robustness, etc.. Basically, it is responsible for managing the
execution of .NET programs regardless of any .NET programming language. It
also helps in the management of code, as code that targets the runtime is known as
the Managed Code, and code that doesn’t target to runtime is known as
Unmanaged code.
Framework Class Library(FCL): It is the collection of reusable, object-oriented
class libraries and methods, etc that can be integrated with CLR. Also called the
Assemblies. It is just like the header files in C/C++ and packages in java. Installing
the .NET framework basically is the installation of CLR and FCL into the system.
Below is the overview of the .NET Framework
Is .NET application platform dependent or platform independent?

The combination of Operating System Architecture and CPU Architecture is


known as the platform. Platform dependent means the programming language code
will run only on particular Operating System. A .NET application is platform-
dependent because of the .NET framework which is only able to run on the
Windows-based operating system. The .Net application is platform-independent
also because of the Mono framework. Using the Mono framework the .Net
application can run on any Operating System including windows. Mono
framework is a third-party software developed by Novell Company which is now
a part of Micro Focus Company. It is a paid framework.
Release History of .NET Framework and its compatibility with the different
Windows version
.NET CLR Windows
Development tool
Version Version Support

1.0 1.0 Visual Studio .NET XP SP1

1.1 1.1 Visual Studio .NET 2003 XP SP2, SP3

2.0 2.0 Visual Studio 2005 N/A

3.0 2.0 Expression Blend Vista

3.5 2.0 Visual Studio 2008 7, 8, 8.1, 10

4.0 4 Visual Studio 2010 N/A

4.5 4 Visual Studio 2012 8

4.5.1 4 Visual Studio 2013 8.1

4.5.2 4 N/A N/A

4.6 4 Visual Studio 2015 10 v1507

Visual Studio 2015 Update


4.6.1 4 1 10 v1511

4.6.2 4 N/A 10 v1607

4.7 4 Visual Studio 2017 10 v1703


.NET CLR Windows
Development tool
Version Version Support

4.7.1 4 Visual Studio 2017 10 v1709

4.7.2 4 Visual Studio 2017 10v 1803

Important Points:

 Visual Studio is the development tool that is used to design and develop .NET
applications. For using Visual Studio, the user has to first install the .NET
framework on the system.
 In the older version of Windows OS like XP SP1, SP2, or SP3, the .NET
framework was integrated with the installation media.
 Windows 8, 8.1, or 10 do not provide a pre-installed version 3.5 or later of
.NET Framework. Therefore, a version higher than 3.5 must be installed either
from a Windows installation media or from the Internet on demand. Windows
update will give recommendations to install the .NET framework.

Garbage collection:-
Garbage Collection is a technique introduced in Microsoft .NET that manages
memory automatically. This article discusses the concepts of Garbage Collection
and the strategies adopted by Microsoft .NET for handling managed memory
efficiently. It also discusses the methods and properties of the System. GC class,
the class that is responsible for controlling the garbage collector in the .NET
environment.
What is Garbage Collection?
The Common Language Runtime (CLR) requires that you create objects in the
managed heap, but you do not have to bother with cleaning up the memory once
the object goes out of the scope or is no longer needed. This is unlike the
strategies adopted in programming languages like C and C++ where you needed to
cleanup the heap memory explicitly using a free function of C and delete operator
of C++. Garbage collection refers to the strategy adapted by Microsoft .NET to
free unused objects or objects that go out of the scope automatically.
A "garbage" object is one that is no longer needed, is unreachable from the root or
goes out of the scope in which it is created. Microsoft .NET uses the information
in the metadata to trace the object graph and detect the objects that need to be
garbage collected. Objects that are not reachable from the root are referred to as
garbage objects and are marked for garbage collection. It is to be noted here that
there is a time gap between the time when an object is identified as garbage and the
time when the object is actually collected. It is also to be noted that objects in the
managed heap are stored in sequential memory locations. This is unlike C and
C++ and makes allocation and de-allocation of objects faster.
Strong and Weak References
The garbage collector can reclaim only objects that have no references. An object
that is reachable cannot be garbage collected by the garbage collector. Such a
reference is known as a strong reference. An object can also be referred to as a
weak reference; another term for a weak reference is the target. An object is
eligible for garbage collection if it does not contain any strong references,
irrespective of the number of weak references it contains. Weak references are of
the following types:
· Short Weak Reference
· Long Weak Reference
A short weak reference does not track resurrection while a long weak reference
tracks resurrection. The primary advantage of maintaining weak references to an
object is that it allows the garbage collector to collect or reclaim memory of the
object if it runs out of memory in the managed heap.
The System.GC class
The System. GC class represents the garbage collector and contains many of
methods and properties that are described in this section.
GC.Collect Method
This method is used to force a garbage collection of all the generations. It can also
force a garbage collection of a particular generation passed to it as a
parameter. The signatures of the overloaded Collect methods are:

public static void Collect();


public static void Collect(Integer int);
GC.GetTotalMemory Method
This method returns the total number of bytes that is allocated in the managed
memory. This method accepts a boolean parameter. If the parameter is true, it
indicates that it should wait for the garbage collector to finish.
GC.KeepAlive Method
This method extends the life time of an object passed to it as a parameter. The
signature of this method is as follows:
public static void KeepAlive(object objToKeepAlive);
GC.ReRegisterForFinalize Method
This method re-registers an object for finalization, i.e., makes an object eligible for
finalization. The method signature is as follows:
public static void ReRegisterForFinalize(objectobjToRegister);
GC.SupressFinalize Method
This method suppresses the finalization on an object. The prototype of this method
is:
public static void SupressFinalize(object obj);
GC.GetGeneration Method
This method returns the current generation of an object or the same of the target of
the weak reference. The signature of this overloaded method is:
System.GC.GetGeneration(object obj);
System.GC.GetGeneration(WeakReferenceweakReference);
GC.MaxGeneration Property
This property returns the maximum number of generations available.
GC.WaitForPendingFinalizers Method
This method blocks the current thread till the execution of all the pending finalizers
is over. The signature of this method is:
public static void WaitForPendingFinalizers();
The Mark and Compact Strategy
The most commonly used strategy involves the mark and compact algorithm. This
occurs in two phases, Mark and Compact.
Mark
The garbage collector identifies the reachable objects by starting from the
application’s root and builds a graph of the reachable objects. In order to handle
cycles, the garbage collector ignores adding objects to the graph that have already
been added. The objects that are not reachable from the root are considered
garbage.
Compact
In this phase the garbage collector scans the managed heap, moves the free or
available memory to the top and the objects to the bottom of the heap. The
memory holes or free spaces are properly compacted and the object references
updated as necessary. A pointer to the next object in the managed heap is set up
that then indicates that the next object will be created at that memory location in
the heap.
Finalization
When an object of a class is created in the heap that implements a finalize method,
a pointer to the object is stored in the finalization queue. The garbage collector
periodically scans this finalization queue to get the pointers. When it identifies
one, it removes the same from the finalization queue and adds the pointer to the
reachable queue. Then the finalize method is called on the object and the
reachable queue is emptied.
Generations
A generational garbage collector collects the short-lived objects more frequently
than the longer lived ones. Short-lived objects are stored in the first generation,
generation 0. The longer-lived objects are pushed into the higher generations, 1 or
2. The garbage collector works more frequently in the lower generations than in
the higher ones.
When an object is first created, it is put into generation 0. When the generation 0
is filled up, the garbage collector is invoked. The objects that survive the garbage
collection in the first generation are promoted onto the next higher generation,
generation 1. The objects that survive garbage collection in generation 1 are
promoted onto the next and the highest generation, generation 2. This algorithm
works efficiently for garbage collection of objects, as it is fast. Note that
generation 2 is the highest generation that is supported by the garbage collector.
MSIL:-

- MSIL stands for Microsoft Intermediate Language.


- The .NET compatible application will get converted to MSIL compilation.
- It gets converted into machine language or native code by JIT compiler.
- It supports for different runtime environments.
- It provides language interoperability as the code in any
.NET language is compiled into MSIL.
- It includes instructions for loading, storing, initializing.
- MSIL produces metadata that describes the types in your code.

A web service is a web-based functionality accessed using the protocols of the web
to be used by the web applications. There are three aspects of web service
development:
 Creating the web service
 Creating a proxy
 Consuming the web service
Creating a Web Service
A web service is a web application which is basically a class consisting of methods
that could be used by other applications. It also follows a code-behind architecture
such as the ASP.NET web pages, although it does not have a user interface.
To understand the concept let us create a web service to provide stock price
information. The clients can query about the name and price of a stock based on
the stock symbol. To keep this example simple, the values are hardcoded in a two-
dimensional array. This web service has three methods:
 A default HelloWorld method
 A GetName Method
 A GetPrice Method
Take the following steps to create the web service:
Step (1) : Select File -> New -> Web Site in Visual Studio, and then select
ASP.NET Web Service.
Step (2) : A web service file called Service.asmx and its code behind file,
Service.cs is created in the App_Code directory of the project.
Step (3) : Change the names of the files to StockService.asmx and StockService.cs.
Step (4) : The .asmx file has simply a WebService directive on it:
<%@ WebService Language="C#" CodeBehind="~/App_Code/StockService.cs"
Class="StockService" %>
Step (5) : Open the StockService.cs file, the code generated in it is the basic Hello
World service. The default web service code behind file looks like the following:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;

using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Xml.Linq;

namespace StockService
{
// <summary>
// Summary description for Service1
// <summary>

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]

// To allow this Web Service to be called from script,


// using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]
public class Service1 : System.Web.Services.WebService
{
[WebMethod]

public string HelloWorld()


{
return "Hello World";
}
}
}
Step (6) : Change the code behind file to add the two dimensional array of strings
for stock symbol, name and price and two web methods for getting the stock
information.
using System;
using System.Linq;

using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;

using System.Xml.Linq;

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

// To allow this Web Service to be called from script,


// using ASP.NET AJAX, uncomment the following line.
// [System.Web.Script.Services.ScriptService]

public class StockService : System.Web.Services.WebService


{
public StockService () {
//Uncomment the following if using designed components
//InitializeComponent();
}

string[,] stocks =
{
{"RELIND", "Reliance Industries", "1060.15"},
{"ICICI", "ICICI Bank", "911.55"},
{"JSW", "JSW Steel", "1201.25"},
{"WIPRO", "Wipro Limited", "1194.65"},
{"SATYAM", "Satyam Computers", "91.10"}
};

[WebMethod]
public string HelloWorld() {
return "Hello World";
}

[WebMethod]
public double GetPrice(string symbol)
{
//it takes the symbol as parameter and returns price
for (int i = 0; i < stocks.GetLength(0); i++)
{
if (String.Compare(symbol, stocks[i, 0], true) == 0)
return Convert.ToDouble(stocks[i, 2]);
}

return 0;
}

[WebMethod]
public string GetName(string symbol)
{
// It takes the symbol as parameter and
// returns name of the stock
for (int i = 0; i < stocks.GetLength(0); i++)
{
if (String.Compare(symbol, stocks[i, 0], true) == 0)
return stocks[i, 1];
}

return "Stock Not Found";


}
}
Step (7) : Running the web service application gives a web service test page,
which allows testing the service methods.

Step (8) : Click on a method name, and check whether it runs properly.

Step (9) : For testing the GetName method, provide one of the stock symbols,
which are hard coded, it returns the name of the stock
Consuming the Web Service
For using the web service, create a web site under the same solution. This could be
done by right clicking on the Solution name in the Solution Explorer. The web
page calling the web service should have a label control to display the returned
results and two button controls one for post back and another for calling the
service.
The content file for the web application is as follows:
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="Default.aspx.cs" Inherits="wsclient._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">
<title>
Untitled Page
</title>
</head>

<body>

<form id="form1" runat="server">


<div>

<h3>Using the Stock Service</h3>

<br /> <br />

<asp:Label ID="lblmessage" runat="server"></asp:Label>

<br /> <br />

<asp:Button ID="btnpostback" runat="server" onclick="Button1_Click"


Text="Post Back" style="width:132px" />
<asp:Button ID="btnservice" runat="server" onclick="btnservice_Click"
Text="Get Stock" style="width:99px" />

</div>
</form>

</body>
</html>
The code behind file for the web application is as follows:
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;

using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

//this is the proxy


using localhost;

namespace wsclient
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
lblmessage.Text = "First Loading Time: " +
DateTime.Now.ToLongTimeString
}
else
{
lblmessage.Text = "PostBack at: " + DateTime.Now.ToLongTimeString();
}
}

protected void btnservice_Click(object sender, EventArgs e)


{
StockService proxy = new StockService();
lblmessage.Text = String.Format("Current SATYAM Price:{0}",
proxy.GetPrice("SATYAM").ToString());
}
}
}

Creating the Proxy


A proxy is a stand-in for the web service codes. Before using the web service, a
proxy must be created. The proxy is registered with the client application. Then the
client application makes the calls to the web service as it were using a local
method.
The proxy takes the calls, wraps it in proper format and sends it as a SOAP request
to the server. SOAP stands for Simple Object Access Protocol. This protocol is
used for exchanging web service data.
When the server returns the SOAP package to the client, the proxy decodes
everything and presents it to the client application.
Before calling the web service using the btnservice_Click, a web reference should
be added to the application. This creates a proxy class transparently, which is used
by the btnservice_Click event.
protected void btnservice_Click(object sender, EventArgs e)
{
StockService proxy = new StockService();
lblmessage.Text = String.Format("Current SATYAM Price: {0}",
proxy.GetPrice("SATYAM").ToString());
}
Take the following steps for creating the proxy:
Step (1) : Right click on the web application entry in the Solution Explorer and
click on 'Add Web Reference'.

Step (2) : Select 'Web Services in this solution'. It returns the StockService
reference.

Step (3) : Clicking on the service opens the test web page. By default the proxy
created is called 'localhost', you can rename it. Click on 'Add Reference' to add the
proxy to the client application.
Include the proxy in the code behind file by adding:
using localhost;

ASP.NET

It is a web framework designed and developed by Microsoft. It is used to develop


websites, web applications and web services. It provides fantastic integration of
HTML, CSS and JavaScript. It was first released in January 2002. It is built on the
Common Language Runtime (CLR) and allows programmers to write code using
any supported .NET language.

ASP.NET is a part of Microsoft .NET Framework. The following image shows the
component stack.
Fig: .NET framework components

ASP.NET Versions History

The following table shows the versions and features included in ASP.NET.

46.5M

823

Prime Ministers of India | List of Prime Minister of India (1947-2020)


Date Version Features

January 16, 1.0 Object-oriented Web application development


2002 supporting inheritance, polymorphism and
other standard OOP features.

April 24, 1.1 Mobile controls and Automatic input


2003 validation.

November 2.0 New data controls (GridView, FormView,


7, 2005 DetailsView)
New technique for declarative data access
(SqlDataSource, ObjectDataSource,
XmlDataSource controls)
Navigation controls
Master pages
Login controls
Themes
Skins
Web parts
Personalization services
Full pre-compilation
New localization technique
Support for 64-bit processors
Provider class model

November 3.0 Windows Presentation Foundation (WPF)


21, 2006 Windows Workflow Foundation (WF)
Windows Communication Foundation, which
can use ASP.NET to host services
Windows CardSpace, which uses ASP.NET
for login roles
November 3.5 New data controls (ListView, DataPager)
19, 2007 ASP.NET AJAX included as part of the
framework
Support for HTTP pipelining and syndication
feeds.
WCF support for RSS, JSON, POX and Partial
Trust
All the .NET Framework 3.5 changes, like
LINQ etc.

August 11, 3.5 Service Incorporation of ASP.NET Dynamic Data


2008 Pack1 Support for controlling browser history in an
ASP.NET AJAX application
Ability to combine multiple JavaScript files
into one file for more efficient downloading
New namespaces System.Web.Abstractions
and System.Web.Routing

April 12, 4.0 The two new properties added in the Page
2010 class are MetaKeyword and MetaDescription.

August 15, 4.5


2012

October 17, 4.5.1 Bootstrap 3.0


2013 Web API 2: OAuth 2.0, OData improvements,
CORS
MVC 5: Attribute routing, authentication
filters and filter overrides
EF 6
SignalR
OWIN
May 5, 2014 4.5.2 Higher reliability HTTP header inspection and
modification methods
New way to schedule background
asynchronous worker tasks

July 20, 4.6 HTTP/2 support when running on Windows 10


2015 More async task-returning APIs

ASP.NET provides three development styles for creating web applications:

1. Web Forms
2. ASP.NET MVC
3. ASP.NET Web Pages

Web Forms

It is an event driven development framework. It is used to develop application with


powerful data access. It provides server side controls and events to create web
application. It is part of the ASP.NET framework. We will discuss it further in next
chapters.

ASP.NET MVC

It gives us a MVC (Model View Controller), patterns-based way to build dynamic


websites. It enables a clean separation of concerns and that gives you full control
over markup for enjoyable, agile development. It also provides many features that
enable fast development for creating outstanding applications. We will discuss it
further in next chapters.

ASP.NET Web Pages

It is used to create dynamic web pages. It provides fast and lightweight way to
combine server code with HTML. It helps to add video, link to the social sites. It
also provides other features like you can create beautiful sites that conform to the
latest web standards.
All these are stable and well equipped frameworks. We can create web applications
with any of them. These are also based on the .NET Framework and share core
functionalities of .NET and ASP.NET.

We can use any development style to create application. The selection of style is
depends on the skills and experience of the programmer.

Although each framework is independent to other, we can combine and use any of
that at any level of our application. For example, to develop client interaction
module, we can use MVC and for data control, we can use Web Forms.

The following table illustrates each development model.

Model Skills Development style Experience

Web Win Rapid development using a rich Mid-Level,


Forms Forms, library of controls that encapsulate Advanced
WPF, HTML markup RAD
.NET

MVC Ruby on Full control over HTML markup, Mid-Level,


Rails, code and markup separated, and Advanced
.NET easy to write tests. The best choice
for mobile and single-page
applications (SPA).

Web Classic HTML markup and your code New, Mid-


Pages ASP, together in the same file Level
PHP
ASP.NET Page Lifecycle
In ASP.NET, a web page has execution lifecycle that includes various phases.
These phases include initialization, instantiation, restoring and maintaining state
etc. it is required to understand the page lifecycle so that we can put custom code at
any stage to perform our business logic.

Page Lifecycle stages

The following table contains the lifecycle stages of ASP.NET web page.

Stage Description

Page request This stage occurs before the lifecycle begins. When a
page is requested by the user, ASP.NET parses and
compiles that page.

Start In this stage, page properties such as Request and


response are set. It also determines the Request type.

Initialization In this stage, each control's UniqueID property is set.


Master page is applied to the page.

Load During this phase, if page request is postback, control


properties are loaded with information.

Postback In this stage, event handler is called if page request is


event handling postback. After that, the Validate method of all validator
controls is called.

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

Unload At this stage the requested page has been fully rendered
and is ready to terminate.at this stage all properties are
unloaded and cleanup is performed.

A requested page first loaded into the server memory after that processes and sent
to the bowser. At last it is unloaded from the server memory. ASP.NET provides
methods and events at each stage of the page lifecycle that we can use in our
application. In the following table, we are tabled events.

ASP.NET Life Cycle Events


Page Event Typical Use

PreInit This event is raised after the start stage is complete


and before the initialization stage.

Init This event occurs after all controls have been


initialized.
We can use this event to read or initialize control
properties.

InitComplete This event occurs at the end of the page's


initialization stage.
We can use this event to make changes to view state
that we want to make sure are persisted after the next
postback.

PreLoad This event is occurs before the post back data is


loaded in the controls.
Load This event is raised for the page first time and then
recursively for all child controls.

Control events This event is used to handle specific control events


such as Button control' Click event.

LoadComplete This event occurs at the end of the event-handling


stage.
We can use this event for tasks that require all other
controls on the page be loaded.

PreRender This event occurs after the page object has created
all controls that are required in order to render the
page.

PreRenderComplete This event occurs after each data bound control


whose DataSourceID property is set calls its
DataBind method.

SaveStateComplete It is raised after view state and control state have


been saved for the page and for all controls.

Render This is not an event; instead, at this stage of


processing, the Page object calls this method on each
control.

Unload This event raised for each control and then for the
page.

ASP.NET Web Forms


Web Forms are web pages built on the ASP.NET Technology. It executes on the
server and generates output to the browser. It is compatible to any browser to any
language supported by .NET common language runtime. It is flexible and allows
us to create and add custom controls.

We can use Visual Studio to create ASP.NET Web Forms. It is an IDE (Integrated
Development Environment) that allows us to drag and drop server controls to the
web forms. It also allows us to set properties, events and methods for the controls.
To write business logic, we can choose any .NET language like: Visual Basic or
Visual C#.

Web Forms are made up of two components: the visual portion (the ASPX file),
and the code behind the form, which resides in a separate class file.

Fig: This diagram shows the components of the ASP.NET

44.1MHistory of Java

The main purpose of Web Forms is to overcome the limitations of ASP and
separate view from the application logic.

ASP.NET provides various controls like: server controls and HTML controls for
the Web Forms. We have tables all these controls below.
Server Controls

The following table contains the server-side controls for the Web Forms.

Control Name Applicable Events Description

Label None It is used to display text on


the HTML page.

TextBox TextChanged It is used to create a text


input in the form.

Button Click, Command It is used to create a button.

LinkButton Click, Command It is used to create a button


that looks similar to the
hyperlink.

ImageButton Click It is used to create an


imagesButton. Here, an
image works as a Button.

Hyperlink None It is used to create a


hyperlink control that
responds to a click event.

DropDownList SelectedIndexChanged It is used to create a


dropdown list control.

ListBox SelectedIndexCnhaged It is used to create a ListBox


control like the HTML
control.
DataGrid CancelCommand, It used to create a frid that is
EditCommand, used to show data. We can
DeleteCommand, also perform paging, sorting,
ItemCommand, and formatting very easily
SelectedIndexChanged, with this control.
PageIndexChanged,
SortCommand,
UpdateCommand,
ItemCreated,
ItemDataBound

DataList CancelCommand, It is used to create datalist


EditCommand, that is non-tabular and used
DeleteCommand, to show data.
ItemCommand,
SelectedIndexChanged,
UpdateCommand,
ItemCreated,
ItemDataBound

Repeater ItemCommand, It allows us to create a non-


ItemCreated, tabular type of format for
ItemDataBound data. You can bind the data to
template items, which are
like bits of HTML put
together in a specific
repeating format.

CheckBox CheckChanged It is used to create checkbox.

CheckBoxList SelectedIndexChanged It is used to create a group of


check boxes that all work
together.

RadioButton CheckChanged It is used to create radio


button.

RadioButtonList SelectedIndexChanged It is used to create a group of


radio button controls that all
work together.

Image None It is used to show image


within the page.

Panel None It is used to create a panel


that works as a container.

PlaceHolder None It is used to set placeholder


for the control.

Calendar SelectionChanged, It is used to create a calendar.


VisibleMonthChanged, We can set the default date,
DayRender move forward and backward
etc.

AdRotator AdCreated It allows us to specify a list


of ads to display. Each time
the user re-displays the page.

Table None It is used to create table.

XML None It is used to display XML


documents within the HTML.
Literal None It is like a label in that it
displays a literal, but allows
us to create new literals at
runtime and place them into
this control.

HTML Controls

These controls render by the browser. We can also make HTML controls as server
control. we will discuss about this in further our tutorial.

Controls Description
Name

Button It is used to create HTML button.

Reset Resets all other HTML form elements on a form to a default


Button value

Submit Automatically POSTs the form data to the specified page


Button listed in the Action attribute in the FORM tag

Text Field Gives the user an input area on an HTML form

Text Area Used for multi-line input on an HTML form

File Field Places a text field and a Browse button on a form and allows
the user to select a file name from their local machine when
the Browse button is clicked

Password An input area on an HTML form, although any characters


Field typed into this field are displayed as asterisks

CheckBox Gives the user a check box that they can select or clear

Radio Used two or more to a form, and allows the user to choose
Button one of the controls

Table Allows you to present information in a tabular format

Image Displays an image on an HTML form

ListBox Displays a list of items to the user. You can set the size from
two or more to specify how many items you wish show. If
there are more items than will fit within this limit, a scroll
bar is automatically added to this control.

Dropdown Displays a list of items to the user, but only one item at a
time will appear. The user can click a down arrow from the
side of this control and a list of items will be displayed.

Horizontal Displays a horizontal line across the HTML page


Rule

ASP.NET Web Forms Events Handling:

Events:
Event is an action or occurrence such as a mouse click, key press and mouse
movements, or any system generated notifications.

Event in asp.net raised at the client machine and handled at the server machine
The server has a subroutine describing what to do when the event is raised; it is
called the event handler.

ASP.NET provides important feature event handling to Web Forms. It let us to


implement event-based model for our application. As a simple example, we can
add a button to an ASP.NET Web Forms page and then write an event handler for
the button's click event. ASP.NET Web Forms allows events on both client and
server sides.

In ASP.NET Web Forms pages, however, events associated with server controls
originate on the client but are handled on the Web server by the ASP.NET.

ASP.NET Web Forms follow a standard .NET Framework pattern for event-
handler methods. All events pass two arguments: an object representing the object
that raised the event, and an event object containing any event-specific
information.

Example: Creating Event Handler

Here, we are creating an event handler for click event. In this example, when user
click on the button, an event fires and handler code executes at server side.

// EventHandling.aspx

1. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="EnventHandl


ing.aspx.cs"
2. Inherits="asp.netexample.EnventHandling" %>
3. <!DOCTYPE html>
4. <html xmlns="http://www.w3.org/1999/xhtml">
5. <head runat="server">
6. <title></title>
7. <style type="text/css">
8. .auto-style1 {
9. width: 100%;
10. }
11..auto-style2 {
12.width: 108px;
13. }
14.</style>
15.</head>
16.<body>
17.<form id="form1" runat="server">
18.<div>
19.<table class="auto-style1">
20.<tr>
21.<td class="auto-style2">First value</td>
22.<td>
23.<asp:TextBox ID="firstvalue" runat="server"></asp:TextBox>
24.</td>
25.</tr>
26.<tr>
27.<td class="auto-style2">Second value</td>
28.<td>
29.<asp:TextBox ID="secondvalue" runat="server"></asp:TextBox>
30.</td>
31.</tr>
32.<tr>
33.<td class="auto-style2">Sum</td>
34.<td>
35.<asp:TextBox ID="total" runat="server"></asp:TextBox>
36.</td>
37.</tr>
38.<tr>
39.<td class="auto-style2"> </td>
40.<td>
41.<br/>
42.<asp:Button ID="Button1" runat="server" OnClick="Button1_Click"Text="Sum"
/>
43.</td>
44.</tr>
45.</table>
46.</div>
47.</form>
48.</body>
49.</html>
Code Behind

// EventHandling.aspx.cs

1. using System;
2. using System.Collections.Generic;
3. using System.Linq;
4. using System.Web;
5. using System.Web.UI;
6. using System.Web.UI.WebControls;
7. namespace asp.netexample
8. {
9. public partial class EnventHandling : System.Web.UI.Page
10. {
11.protected void Button1_Click(object sender, EventArgs e)
12. {
13.int a = Convert.ToInt32(firstvalue.Text);
14.int b = Convert.ToInt32(secondvalue.Text);
15. total.Text = (a + b).ToString();
16. }
17. }
18.}

Output:

You might also like