0% found this document useful (0 votes)
175 views230 pages

012 - AWT MATERIAL For Cs Students

Advanced web technology meterial for computer Science students

Uploaded by

Boobesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
175 views230 pages

012 - AWT MATERIAL For Cs Students

Advanced web technology meterial for computer Science students

Uploaded by

Boobesh
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 230

MUTHAYAMMAL COLLEGE OF ARTS & SCIENCE

SEMESTER II
Core Course - VII –ADVANCED WEB TECHNOLOGY

UNIT - I
OVERVIEW OF ASP.NET - The .NET framework – Learning the.NET languages Data types –
Declaring variables - Scope and Accessibility- Variable operations- Object Based manipulation -
Conditional Structures - Loop Structures- Functions and Subroutines. Types, Objects and
Namespaces : The Basics about Classes- Value types and Reference types - Advanced class
programming - Understanding name spaces and assemblies - Setting up ASP.NET and IIS.

UNIT – II
DevelopingASP.NETApplications-ASP.NETApplications:ASP.NET Code behind- The Global.asax
application file - Understanding ASP.NET Classes- ASP.NET Configuration. Web Form
fundamentals: A simple page applet-Improving the currency converter- HTML control classes- The
page class- Accessing HTML server controls. Web controls: Web Control Classes –Auto Post Back
and Web Control events- Accessing web controls. Using Visual Studio.NET: Starting a Visual
Studio.NET Project- Web form Designer- Writing code- Visual studio.NET debugging. Validation and
Rich Controls: Validation- A simple Validation example- Understanding regular expressions- A
validated customer form. State management - Tracing, Logging, and Error Handling.

UNIT – III
Working with Data - Overview of ADO.NET - ADO.NET and data management- Characteristics of
ADO.NET-ADO.NET object model. ADO.NET data access : SQL basics– Select , Update, Insert,
Delete statements- Accessing data- Creating a connection- Using a command with a Data Reader -
Accessing Disconnected data - Selecting multiple tables – Updating Disconnected data. Data
binding: Single value Data Binding- Repeated value data binding- Data binding with data bases.
Data list – Data grid – Repeater – Files, Streams and Email – Using XML.

UNIT - IV
Web Services - Web services Architecture: Internet programming then and now- WSDL– SOAP-
Communicating with a web service-Web service discovery and UDDI. Creating Web services: Web
service basics- The Stock Quote web service – Documenting the web service- Testing the web
service- Web service Data types- ASP.NET intrinsic objects. Using web services: Consuming aweb
service- Using the proxy class- An example with Terra Service.

UNIT – V
Advanced ASP.NET - Component Based Programming: Creating a simple component – Properties
and state- Database components- Using COM components. Custom controls: User Controls-
Deriving Custom controls. Caching and Performance Tuning: Designing and scalability–
Profiling- Caching- Output caching- Data caching – Object Caching. Implementing security:
Determining security requirements- The ASP.NET security model- Forms authentication-
Windows authentication.
ADVANCED WEB TECHNOLOGY UNIT - I
OVERVIEW OF ASP.NET
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 applications 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 bilateral communication and cooperation.
ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled 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 can be written in any of the following languages:
 C#
 Visual Basic.Net
 Jscript
 J#

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 postback. After that, the
event Validate method of all validator controls is called.
handling

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.

PreRenderComplet This event occurs after each data bound control whose DataSourceID
e 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
 The main purpose of Web Forms is to overcome the limitations of ASP and separate view
from the application logic.
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, EditCommand, It used to create a frid that is used to


DeleteCommand, show data. We can also perform
ItemCommand,
SelectedIndexChanged,

PageIndexChanged,
SortCommand, paging, sorting, and formatting very
easily with this control.
UpdateCommand, ItemCreated,
ItemDataBound
DataList CancelCommand, EditCommand, It is used to create datalist that is
DeleteCommand, non- tabular and used to show data.

ItemCommand, SelectedIndexChanged,
UpdateCommand, ItemCreated,
ItemDataBound
Repeater ItemCommand, ItemCreated, It allows us to create a non-tabular
ItemDataBound type of format for 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. We
can set the default date, move
VisibleMonthChanged, DayRender 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 Button Resets all other HTML form elements on a form to a default value

Submit Automatically POSTs the form data to the specified page listed in the Action attribute
Button 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

Passwor An input area on an HTML form, although any characters typed into this field are
d Field 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 one of the controls
Butto
n
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 Features


ASP.NET is full of features and provides an awesome platform to create and develop web
application. Here, we are discussing these features of Web Forms.
o Server Controls
o Master Pages
o Working with data
o Membership
o Client Script and Client Frameworks
o Routing
o State Management
o Security
o Performance
o Error
Handling Server
Controls
Web Forms provides rich set of server controls. These controls are objects that run when the page
is requested and render markup to the browser. Some Web server controls are similar to familiar
HTML elements, such as buttons and text boxes. It also provides controls that we can use to connect
to data sources and display data.
Master Pages
It allowsus to create a consistent layout for the pages in our application. This page defines the look
and feel and standard behavior that we want for all of the pages in our application. When users
request the content pages, they merge with the master page to produce output that combines the
layout of the master page with the content from the content page.
Working with Data
In an ASP.NET Web Forms application, we use data-bound controls to automate the presentation or
input of data in web page UI elements such as tables and text boxes and drop-down lists.
Membership
Project's Account folder contains the files that implement the various parts of membership:
registering, logging in, changing a password, and authorizing access. Additionally, ASP.NET Web
Forms supports OAuth and OpenID. These authentication enhancements allow users to log into
your site using existing credentials, from such accounts as Facebook, Twitter and Google.
Client Script and Client Frameworks
We can enhance the server-based features of ASP.NET by including client-script functionality in
ASP.NET Web Form pages. We can use client script to provide a richer, more responsive user
interface to the users. We can also use client script to make asynchronous calls to the Web server
while a page is running in the browser.
Routing
We can configure URL routing of our application. A request URL is simply the URL a user enters
into their browser to find a page on our web site. We use routing to define URLs that are
semantically meaningful to users and that can help with search-engine optimization (SEO).
State Management
ASP.NET Web Forms includes several options that help you preserve data on both a per-page basis
and an application-wide basis.
Security
Developing a secure application is most important aspect of software development process.
ASP.NET Web Forms allow us to add extensibility points and configuration options that enable us
to customize various security behaviors in the application.
Performance
Web Forms provides good performance and allows us to modify performance related to page and
server control processing, state management, data access, application configuration and loading,
and efficient coding practices.
Debugging and Error Handling
We can diagnose problems that occur in our Web Forms application. Debugging and error handling
are well supported within ASP.NET Web Forms so that our applications compile and run
effectively.
Data Types
A data type specifies the type of data that a variable can store such as integer, floating, character etc.

There are 3 types of data types in C# language.

Types Data Types

Value Data Type short, int, char, float, double etc

Reference Data Type String, Class, Object and Interface

Pointer Data Type Pointers

Value Data Type


The value data types are integer-based and floating-point based. C# language supports both signed
and unsigned literals.
There are 2 types of value data type in C# language.
1) Predefined Data Types - such as Integer, Boolean, Float, etc.
2) User defined Data Types - such as Structure, Enumerations, etc.
The memory size of data types may change according to 32 or 64 bit operating
system. Let's see the value data types. It size is given according to 32 bit OS.
Data Types Memory Size Range

char 1 byte -128 to 127

signed char 1 byte -128 to 127

unsigned char 1 byte 0 to 127

short 2 byte -32,768 to 32,767

signed short 2 byte -32,768 to 32,767

unsigned short 2 byte 0 to 65,535

int 4 byte -2,147,483,648 to -2,147,483,647

signed int 4 byte -2,147,483,648 to -2,147,483,647

unsigned int 4 byte 0 to 4,294,967,295

long 8 byte ?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

signed long 8 byte ?9,223,372,036,854,775,808 to 9,223,372,036,854,775,807

unsigned long 8 byte 0 - 18,446,744,073,709,551,615

float 4 byte 1.5 * 10-45 - 3.4 * 1038, 7-digit precision

double 8 byte 5.0 * 10-324 - 1.7 * 10308, 15-digit precision

decimal 16 byte at least -7.9 * 10?28 - 7.9 * 1028, with at least 28-digit precision

Reference Data Type


The reference data types do not contain the actual data stored in a variable, but they contain a
reference to the variables.
If the data is changed by one of the variables, the other variable automatically reflects this change
in value. There are 2 types of reference data type in C# language.
1) Predefined Types - such as Objects, String.
2) User defined Types - such as Classes, Interface.
Pointer Data Type
The pointer in C# language is a variable, it is also known as locator or indicator that points to an
address of a value.
Variable
A variable is a name of memory location. It is used to store data. Its value can be changed and it can
be reused many times.
It is a way to represent memory location through symbol so that it can be easily
identified. The basic variable type available in C# can be categorized as:
Variable Type Example

Decimal types Decimal

Boolean types True or false value, as assigned

Integral types int, char, byte, short, long

Floating point types float and double

Nullable types Nullable data types

The syntax to declare a variable:


type variable_list;
The example of declaring variable is given below:
int i, j;
double
d; float f;
char ch;
Here, i, j, d, f, ch are variables and int, double, float, char are data types.
We can also provide values while declaring the variables as given
below:
int i=2,j=4; //declaring 2 variable of integer type
float f=40.2;
char ch='B';
Rules for defining variables
 A variable can have alphabets, digits and underscore.
 A variable name can start with alphabet and underscore only. It can't start with digit.
 No white space is allowed within variable name.
 A variable name must not be any reserved word or keyword e.g. char, float
etc. Valid variable names:
int x;
int _x;
int
k20;
Invalid variable names:
int 4;
int x y;
int double;

operators
An operator is simply a symbol that is used to perform operations. There can be many types of
operations like arithmetic, logical, bitwise etc.
There are following types of operators to perform different types of operations in C# language.
o Arithmetic Operators
o Relational Operators
o Logical Operators
o Bitwise Operators
o Assignment Operators
o Unary Operators
o Ternary Operators
o Misc Operators

Precedence of Operators in C#
The precedence of operator specifies that which operator will be evaluated first and next. The
associativity specifies the operators direction to be evaluated, it may be left to right or right to left.
Let's understand the precedence by the example given below:
int data= 10+ 5*5
The "data" variable will contain 35 because * (multiplicative operator) is evaluated before +
(additive operator).
The precedence and associativity of C# operators is given below:

Category (By Precedence) Operator(s) Associativity

Unary + - ! ~ ++ -- (type)* & sizeof Right to Left

Additive +- Left to Right

Multiplicative %/* Left to Right

Relational < > <= >= Left to Right

Shift << >> Left to Right


Equality == != Right to Left

Logical AND & Left to Right

Logical OR | Left to Right

Logical XOR ^ Left to Right

Conditional OR || Left to Right

Conditional AND && Left to Right

Null Coalescing ?? Left to Right

Ternary ?: Right to Left

Assignment = *= /= %= += - = <<= >>= &= ^= |= => Right to Left

C# if-else
In C# programming, the if statement is used to test the condition. There are various types of if
statements in C#.
o if statement
o if-else statement
o nested if statement
o if-else-if ladder
C# IF Statement
The C# if statement tests the condition. It is executed if condition is true.
Syntax:
if(condition){
//code to be executed}
If Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 10;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}

}
}
Output:
It is even number

IF-else Statement
The C# if-else statement also tests the condition. It executes the if block if condition is true
otherwise else block is executed.
Syntax:
1. if(condition){
2. //code if condition is true
3. }else{
4. //code if condition is
false 5. }

If-else Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
int num = 11;
if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}
Output:
It is odd number

C# If-else Example: with input from user


In this example, we are getting input from the user using Console.ReadLine() method. It returns
string. For numeric value, you need to convert it into int using Convert.ToInt32() method.
using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

if (num % 2 == 0)
{
Console.WriteLine("It is even number");
}
else
{
Console.WriteLine("It is odd number");
}

}
}
Output
Enter a number:11
It is odd number
:
Enter a number:12
It is even number
Output

IF-else-if ladder Statement


The C# if-else-if ladder statement executes one condition from multiple statements.
Syntax:
if(condition1){
//code to be executed if condition1 is true
}else if(condition2){
//code to be executed if condition2 is true
}
else if(condition3){
//code to be executed if condition3 is true
}
...
else{
//code to be executed if all the conditions are false
}

C# If else-if Example
using System;
public class IfExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number to check grade:");
int num = Convert.ToInt32(Console.ReadLine());

if (num <0 || num >100)


{
Console.WriteLine("wrong number");
}
else if(num >= 0 && num < 50)
{ Console.WriteLine("Fail");
}
else if (num >= 50 && num < 60)
{
Console.WriteLine("D Grade");
}
else if (num >= 60 && num < 70)
{
Console.WriteLine("C Grade");
}
else if (num >= 70 && num < 80)
{
Console.WriteLine("B Grade");
}
else if (num >= 80 && num < 90)
{
Console.WriteLine("A Grade");
}
else if (num >= 90 && num <= 100)
{
Console.WriteLine("A+ Grade");
}
}
}
Output
:

Enter a number to check grade:66


C Grade
Output:
Enter a number to check grade:-2
wrong number

C# switch
The C# switch statement executes one statement from multiple conditions. It is like if-else-if ladder
statement in C#.
Syntax:
switch(expression
){ case value1:
//code to be executed;
break;
case
value2:
//code to be executed;
break;
......

default:
//code to be executed if all cases are not matched;
break;
}
Switch Example
using System;
public class SwitchExample
{
public static void Main(string[] args)
{
Console.WriteLine("Enter a number:");
int num = Convert.ToInt32(Console.ReadLine());

switch (num)
{
case 10: Console.WriteLine("It is 10"); break;
case 20: Console.WriteLine("It is 20"); break;
case 30: Console.WriteLine("It is 30"); break;
default: Console.WriteLine("Not 10, 20 or 30"); break;
}
}
Output }
:

Enter a number:
10
It is 10
Output:
Enter a number:
55
Not 10, 20 or 30
C# For Loop
The C# for loop is used to iterate a part of the program several times. If the number of iteration is
fixed, it is recommended to use for loop than while or do-while loops.
The C# for loop is same as C/C++. We can initialize variable, check condition and
increment/decrement value.
Syntax:
for(initialization; condition; incr/decr){
//code to be executed
}

Flowchart:

For Loop Example


using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=10;i++)
{ Console.WriteLine(
i);
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

Nested For Loop


In C#, we can use for loop inside another for loop, it is known as nested for loop. The inner loop is
executed fully when outer loop is executed one time. So if outer loop and inner loop are executed 3
times, inner loop will be executed 3 times for each outer loop i.e. total 9 times.
Let's see a simple example of nested for loop in
C#. using System;
public class ForExample
{
public static void Main(string[] args)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++)
{ Console.WriteLine(i+" "+j);
}
}
}
}
Output:
11
12
13
21
22
23
31
32
33

Infinite For Loop


If we use double semicolon in for loop, it will be executed infinite times. Let's see a simple example
of infinite for loop in C#.
using System;
public class ForExample
{
public static void Main(string[] args)
{
for (; ;)
{
Console.WriteLine("Infinitive For Loop");
}
}
}
Output:
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
Infinitive For Loop
ctrl+c
C# While Loop
In C#, while loop is used to iterate a part of the program several times. If the number of iteration is
not fixed, it is recommended to use while loop than for loop.
Syntax:
1. while(condition){
2. //code to be
executed 3. }
Flowchart:

While Loop Example


Let's see a simple example of while loop to print table of
1. using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=10)
{
Console.WriteLine(i); i+
+;
}
}
}
Output:
1
2
3
4
5
6
7
8
9
10

Nested While Loop Example:


In C#, we can use while loop inside another while loop, it is known as nested while loop. The nested
while loop is executed fully when outer loop is executed once.
Let's see a simple example of nested while loop in C# programming language.
using System;
public class WhileExample
{
public static void Main(string[] args)
{
int i=1;
while(i<=3)
{
int j = 1;
while (j <= 3)
{
Console.WriteLine(i+" "+j);
j++;
}
i++;
}
}
}
Output:
11
12
13
21
22
23
31
32
33

Infinitive While Loop Example:


We can also create infinite while loop by passing true as the test
condition. using System;
public class WhileExample
{
public static void Main(string[] args)
{
while(true)
{
Console.WriteLine("Infinitive While Loop");
}
}
}
Output:
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
Infinitive While Loop
ctrl+c

C# Do-While Loop
The C# do-while loop is used to iterate a part of the program several times. If the number of
iteration is not fixed and you must have to execute the loop at least once, it is recommended to use
do-while loop.
The C# do-while loop is executed at least once because condition is checked after loop body.
Syntax:
do{
//code to be executed
}while(condition);
do-while Loop Example
Let's see a simple example of C# do-while loop to print the table of 1.
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i = 1;

do{
Console.WriteLine(i);
i++;
} while (i <= 10) ;

}
}
Output:
1
2
3
4
5
6
7
8
9
10

Nested do-while Loop


In C#, if you use do-while loop inside another do-while loop, it is known as nested do-while loop.
The nested do-while loop is executed fully for each outer do-while loop.
Let's see a simple example of nested do-while loop in C#.
using System;
public class DoWhileExample
{
public static void Main(string[] args)
{
int i=1;

do{
int j = 1;

do{
Console.WriteLine(i+" "+j); j+
+;
} while (j <=
3) ; i++;
} while (i <= 3) ;
}
}
Output:

11
12
13
21
22
23
31
32
33

Infinitive do-while Loop


In C#, if you pass true in the do-while loop, it will be infinitive do-while loop.
Syntax:
do{
//code to be executed
}while(true);
C# Infinitive do-while Loop Example
using System;
public class WhileExample
{
public static void Main(string[] args)
{

do{
Console.WriteLine("Infinitive do-while Loop");
} while(true);
}
}
Output
:
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
Infinitive do-while Loop
ctrl+c
C# Break Statement
The C# break is used to break loop or switch statement. It breaks the current flow of the program
at the given condition. In case of inner loop, it breaks only inner loop.
Syntax:
jump-statement;
break
; Flowchart:

Break Statement Example


Let's see a simple example of C# break statement which is used inside the loop.
using System;
public class BreakExample
{
public static void Main(string[] args)
{
for (int i = 1; i <= 10; i++)
{
if (i == 5)
{
break;
}
Console.WriteLine(i);
}
}
}
Output
:
1
2
3
4

Break Statement with Inner Loop


The C# break statement breaks inner loop only if you use break statement inside the inner loop.
Let's see the example code:
using System;
public class BreakExample
{
public static void Main(string[] args)
{
for(int i=1;i<=3;i++){
for(int j=1;j<=3;j++){
if(i==2&&j==2){
break;
}
Console.WriteLine(i+" "+j);
}
}
}
}
Output:
11
12
13
21
31
32
33

C# Continue Statement
The C# continue statement is used to continue loop. It continues the current flow of the program
and skips the remaining code at specified condition. In case of inner loop, it continues only inner
loop.
Syntax:
1. jump-statement;
2. continue;
C# Continue Statement Example
1. using System;
2. public class
ContinueExample 3. {
4. public static void Main(string[]
args) 5. {
6. for(int i=1;i<=10;i++){
7. if(i==5){
8. continue;
9. }
10. Console.WriteLine(i);
11. }
12. }
13. }
Output
:
1
2
3
4
6
7
8
9
10
C# Continue Statement with Inner Loop
C# Continue Statement continues inner loop only if you use continue statement inside the inner loop.
1. using System;
2. public class
ContinueExample 3. {
4. public static void Main(string[]
args) 5. {
6. for(int i=1;i<=3;i++){
7. for(int j=1;j<=3;j++){
8. if(i==2&&j==2){
9. continue;
10. }
11. Console.WriteLine(i+" "+j);
12. }
13. }
14. }
15. }
Output
:
11
12
13
21
23
31
32
33

C# Goto Statement
The C# goto statement is also known jump statement. It is used to transfer control to the other
part of the program. It unconditionally jumps to the specified label.
It can be used to transfer control from deeply nested loop or switch case label.
Currently, it is avoided to use goto statement in C# because it makes the program
complex. C# Goto Statement Example
Let's see the simple example of goto statement in C#.
1. using System;
2. public class
GotoExample 3. {
4. public static void Main(string[]
args) 5. {
6. ineligible:
7. Console.WriteLine("You are not eligible to
vote!"); 8.
9. Console.WriteLine("Enter your age:\n");
10. int age = Convert.ToInt32(Console.ReadLine());
11. if (age < 18){
12. goto ineligible;
13. }
14. else
15. {
16. Console.WriteLine("You are eligible to vote!");
17. }
18. }
19. }
Output
:
You are not eligible to vote!
Enter your age:
11
You are not eligible to vote!
Enter your age:
5
You are not eligible to vote!
Enter your age:
26
You are eligible to vote!

C# Comments
The C# comments are statements that are not executed by the compiler. The comments in C#
programming can be used to provide explanation of the code, variable, method or class. By the help
of comments, you can hide the program code also.
There are two types of comments in C#.
o Single Line comment
o Multi Line
comment C# Single Line
Comment
The single line comment starts with // (double slash). Let's see an example of single line comment in C#.
1. using System;
2. public class
CommentExample 3. {
4. public static void Main(string[]
args) 5. {
6. int x = 10;//Here, x is a variable
7. Console.WriteLine(x);8.
}
9. }
Output:
10
C# Multi Line Comment
The C# multi line comment is used to comment multiple lines of code. It is surrounded by slash and
asterisk (/* */). Let's see an example of multi line comment in C#.
1. using System;
2. public class
CommentExample 3. {
4. public static void Main(string[]
args) 5. {
6. /* Let's declare and
7. print variable in C#. */
8. int x=20;
9. Console.WriteLine(x);
10. }
11. }
Output
:
20

Functions and Subroutines:

A function is a procedure that returns a value to the caller. By "caller", we mean the place in the
ASP code where you invoke the procedure through a "function call". Functions are declared using
the Function statement and terminated with an End Function statement.
' A totally useless function to get the current date and time
Function TodaysDate

TodaysDate = Now()

End Function

Above, we have an example of a function definition that will return the current date and time
using the built-in function Now. By assigning a value to a variable which has the same name as
the function (TodaysDate), we return a value to the calling process. There is no return
statement like the PHP scripting language or in C programming.
This function can be declared anywhere in your web page and it will be made available for you
to call from within anywhere in the page. As we will see later, you can even place commonly
used procedures within a Server-Side Include page so that you don't have to write duplicate
procedures on multiple pages from your web site.
This function is totally useless because it's easier to just call the built-in function Now.
It is important to note that a procedure declaration like this will not do anything meaningful until
it is actually called. It simply declares a procedure which will do work when it is called.
Subroutines:

A subroutine is a procedure that does not return a value to the caller. Subroutines are declared
using the Sub statement and terminated with an End Sub statement.
' a subroutine to output today's date

Sub ShowDate

Response.Write("Today's Date is: ")

Response.Write(Now())
End Sub

The subroutine call above will output text that looks like "Today's Date is: Jan, 23 2004
06:43:12AM" when it is called. The location in the web page where this is output depends on
where the subroutine is called. You should call the subroutine at the exact point where you would
like it to output the text.
Unlike a function declaration, you are not allowed to assign a return value to the procedure name
(ShowDate). If you attempt to use a subroutine as a function, you will receive a runtime error.
The same is true when you try to use a function as a subroutine.
Types:

In ASP.Net framework, Data types play most importance role. A Variable must be declared with
the data type. There are mainly six Data Types in .NET Framework.

Integral Numbers:
Integral numbers are whole numbers that do not have decimal values. For instance: 1, 12353, and
–10. If you are familiar with computer programming, you’ll probably recognize the Byte, Short,
Integer, and Long data types. These are 8, 16, 32, and 64-bit integers respectively, and each
requires different amounts of memory. In other words, they can hold different ranges of
values. Such as the Integer data type can hold values from –2,147,483,648 to 2,147,483,647.
Example:
dim A, B as Integer

dim C as Integer

A=4

B= 6

C= A+B

Floating-Point Numbers:
Floating-point numbers are numbers with fractions or decimal points, such as 3.141592654 or –
0.45. The specific data types are Single (System.Single, 4 bytes), Double (System.Double, 8 bytes),
and Decimal (System.Decimal, 12 bytes).
Example:

dim X, Y as Single

dim Z as Single

X = 10.5

Y= 5.5

Z= X-Y

Strings:
The String data type that most programmers are familiar with is a class in VB.NET, rather than
a primitive. This enables you to create new instances, override, and inherit from a String,
which gives the programmer a lot of power when designing applications.
There is also the Char data type, which represents a single Unicode character because it is
Unicode, it can represent a lot more than just the alphanumeric characters.

Dates:
The DateTime data type can be in many formats: “5/6/01,” “Wednesday, July 4th, 2001,” or
“8:30:34 PM,” Such as- This provides you with great flexibility in representing your date valuesand
enables you to perform simple arithmetic (such as adding or subtracting days or hours) on your
values.

Booleans:
Booleans are simply true-or-false values, such as Yes / No, and so on. Although the Boolean
data type in VB.NET strictly uses true/false to represent data, you can easily convert it to the
other pairs of values.
Objects:
The Object data type is a generic type that’s used for a variable if no other type is specified.

Objects:
The Object data type is a generic type that’s used for a variable if no other type is specified.

Namespaces:
Namespaces is a “logical naming scheme for grouping related types“. What that means to us is
that all objects used in ASP.NET are grouped by type, which makes them easy to find and to
use. Imagine the .NET namespaces as a file cabinet.
Namespaces represent exactly the same concept. Like objects are grouped together, an
HTMLInputTextBox object is grouped in the same namespace as the HTMLAnchor object,
because they both represent HTML-user interface controls displayed to the user.
Example: To use a namespace in an ASP.NET page, you must use the Import directive.
<%@ Import Namespace="System.Data" %>

System Namespace:
The System namespace is the root namespace for the entire .NET Framework thus, it
contains all the basic and generic classes you’ll use in ASP.NET.These include the primitives
(integers, strings, and so on), as well as all of the other namespaces in .NET. Since it is the root
namespace.

The Basics about Classes:


The Types in .NET Framework are either treated by Value Type or by Reference Type. A Value
Type holds the data within its own memory allocation and a Reference Type contains a pointer to
another memory location that holds the real data. Reference Type variables are stored in the heap
while Value Type variables are stored in the stack.
Value Types:
A Value Type stores its contents in memory allocated on the stack. When you created a
Value Type, a single space in memory is allocated to store the value and that variable directly
holds a value. If you assign it to another variable, the value is copied directly and both
variables work independently. Predefined datatypes, structures, enums are also value types,
and work in the same way. Value types can be created at compile time and Stored in stack
memory, because of this, Garbage collector can't access the stack.
e.g. int x = 10;
Here the value 10 is stored in an area of memory called the stack.
Reference Types:
Reference Types are used by a reference which holds a reference (address) to the object but not
the object itself. Because reference types represent the address of the variable rather than the data
itself, assigning a reference variable to another doesn't copy the data. Instead it creates a second
copy of the reference, which refers to the same location of the heap as the original value.
Reference Type variables are stored in a different area of memory called the heap. This means
that when a reference type variable is no longer used, it can be marked for garbage collection.
Examples of reference types are Classes, Objects, Arrays, Indexers, Interfaces etc.
e.g. int[] iArray = new int[20];
In the above code the space required for the 20 integers that make up the array is allocated on the
heap.
Understanding name spaces and assemblies:
A namespace is a logical group of related classes that can be used by the languages targeting
the Microsoft .NET framework. Storing all the classes in the same location will create
difficulties in accessing and maintenance. Therefore, it is possible to use namespace as an
alternative. In other words, a namespace helps to group the classes logically. Also, it groups
the names and reduces the chance of name collisions.
The name of a class is specified by concatenating the names of all the related namespaces.
For example, assume System.Windows.Forms.TextBox. It describes that the TextBox class is
inside the Forms namespace. Moreover, the Forms namespace is inside the Windows
namespace while the Windows namespace is inside the System namespace.
Assemblies:
Assembly is a standard component of the Microsoft .NET framework. It can exist as an executable
(.exe) file or Dynamic Link Library (DLL) file. An assembly consists of all metadata about the
modules, types and other elements in the form of a manifest. Moreover, the assembly provides
multiple advantages. Generally, it helps deployment and version control and provides
reusability and security.
Generally, there are three types of assemblies. A private assembly is used only for a single
application. Moreover, it is necessary to place the files of an assembly in the same folder of the
application. Next, the shared assembly, which is used for sharing. In that case, it is necessary
to have a strict naming convention as it has to be unique across the whole system. Finally, the
satellite assembly is used as a deploying language and culture-specific resources for an
application.
Setting up ASP.NET and IIS:

How to create the virtual directory on the web server


1. To start IIS Manager, select Settings -> Control Panel -> Administrative Tools Internet Services
Manager from the Start menu.
2. The next step would be to create a virtual directory for an existing physical directory. For
this please expand the Web Sites item in the IIS tree, right-click the Default WebSite item and
choose New -> Virtual Directory from the menu (see Figure 2).

Figure 2. Creating a Virtual Directory

3. The first step in the wizard responsible with the virtual directory creation is to choose an
alias (see Figure 3). The alias is the name a user will use in his URL to access the files in this
virtual directory. For example, if your alias is MyApp and your computer is MyServer, you can
request pages using URLs such as http://MyServer/MyApp/MyPage.aspx.

Figure 3. Choosing an alias.


4. Click Next
5. The next step in this wizard is to provide an existing physical directory to which the virtual
directory will point to (see Figure 4). So, this physical directory will be exposed as a virtual
directory through its alias. For example, c:\Webs\WebApplication1 is the physical directory thatis
used by this virtual directory with the MyApplication alias.

Figure 4. Choosing a physical directory

6. The final step in this wizard is to choose your permissions for the virtual directory (see
Figure 5). Usually, to host an ASP.NET application, read and execute permissions are enough
(the first two check boxes). Of course, in order to fulfill your needs you can choose other
permissions too.

Figure 5.Setting permissions

7. Click Next and then Finish to create the virtual directory.


When you finish these steps, you'll see your new virtual directory appear in the list in IIS
Manager.

Copy the entire site (including subdirectories) to the virtual directory:


The deployment of the ASP.NET application on the production machine can be done in many
ways depending on the Internet hosting services.
You can use FTP to deploy the application, or if the development computer and the web server
are on the same internal network, you can use Windows explorer.
UNIT –II

Use Visual C# .NET to work with code-behind class files in an ASP.NET application5

This article describes how to develop .aspx pages that use code-behind class files in Microsoft
ASP.NET applications. The code samples in this article include the requirements for both code-
behind class files that are precompiled and code-behind class files that are compiled on demand.

Requirements

The following list outlines the recommended hardware, software, and network infrastructure that
you need:

 Windows
 .NET Framework
 Internet Information Services (IIS)

Create an ASP.NET web application by using Visual C# .NET

This section demonstrates how to create a new ASP.NET web application that is named
CodeBehindSamples.

1. Start Visual Studio .NET.


2. On the File menu, point to New, and then click Project.
3. Under Project Type, click Visual C# Projects. Under Templates, click ASP.NET Web
Application.
4. In the Name box, type CodeBehindSamples. In the Location box, type the
ServerName. If you are using the local server, leave
the Location as http://localhost.

Use code-behind class files

If you use code-behind class files with .aspx pages, you can separate the presentation code from the
core application logic (or code-behind). The code-behind class file is compiled so that it can be
created and used as an object. This allows access to its properties, its methods, and its event
handlers. For this to work, the .aspx page must specify to inherit from the code-behind base class.
To do this, use the Inherits attribute for the @
Page directive. The .aspx page inherits from the code-behind class, and the code-behind class
inherits from the Page class.
By default, if you are using Visual Studio .NET, a Codebehind attribute is added to the @ Page
directive. The .NET Framework does not actually use this attribute. Instead, Visual Studio .NET
uses this attribute to maintain a reference to the associated code- behind file for the .aspx page.

To demonstrate how Visual Studio .NET uses the Codebehind attribute, remove the
Codebehind attribute. You can no longer right-click the .aspx page and then
click View Code. This behavior occurs because Visual Studio .NET no longer contains a reference
for the class file it can use for the page. Remember that this is not how the .NET Framework uses
code-behind class files, but how Visual Studio .NET manages these project files.

Use the Inherits attribute with precompiled classes

If you precompile your code-behind classes into an assembly, you can use
the Inherits attribute to specify the class from which to inherit. In this scenario, you do not have to
include the actual code-behind class file when you deploy the application.
Instead, you must deploy the assembly and the .aspx page. You must put the assembly in the Bin
folder for the application when you deploy the application.

This section demonstrates how to create a new Web Form that uses the precompiled approach and
inherits from the code-behind class.

1. To add a new Web Form that is named InheritSample.aspx to your Visual Studio
.NET project, follow these steps:
1. In Solution Explorer, right-click the project node, click Add, and then click Add Web
Form.
2. In the Name box, type InheritSample.aspx, and then click Open.
2. Switch to Design view, and then add a Web Form Label control to the .aspx page.
3. Right-click the .aspx page, and then click View Code. The code-behind file opens in the
editor.
4. In the code-behind file, add the following code to the Page_Load event handler: C#

private void Page_Load(object sender, System.EventArgs e)


{
Label1.Text = "(Precompiled): Page_Load fired!";
}
5. Switch from the code-behind class file to the .aspx page in the editor, and then switch
to HTML view.
6. At the top of the page, review the code for the @ Page directive. The code should be similar
to the following default code:

ASP.NET (C#)
<%@ Page language="c#" Codebehind="InheritSample.aspx.cs" AutoEventWireup="false"
Inherits="CodeBehindSamples.InheritSample" %>

In this example, the .aspx page inherits from the code-behind class that is
named InheritSamples in the CodeBehindSamples namespace. By default, a web application
that is created in Visual Studio .NET uses
a ProjectName.ClassName structure for the Inherits attribute value.

7. On the File menu, click Save All to save the Web Form and other associated project files.
8. In the Visual Studio .NET IDE, on the Build menu, click Build to build the project.
9. On the Project menu, click Show All Files.
10. In Solution Explorer, click to expand the Bin folder. The assembly that is generated when
you compile the project from the previous section (which
is CodeBehindSamples.dll in this example) appears in the Bin folder.
11. In Visual Studio .NET, right-click the page in Solution Explorer, and then
click View in Browser to run the code. The label is populated with the following value:

Use the Src attribute and compile on demand

If your code-behind class files will be compiled on demand instead of precompiled, you must use
the Src attribute to specify the relative path of the code-behind class file. Make sure that you
include the actual class file when you use this method to deploy the application.

1. To add a new Web Form that is named SrcSample.aspx to your project in Visual
Studio .NET, follow these steps:
1. In Solution Explorer, right-click the project node, click Add, and then click Add Web
Form.
2. In the Name box, type SrcSample.aspx, and then click Open.
2. Switch to Design view, and then add a Web Form Label control to the .aspx page.
3. Right-click the .aspx page, and then click View Code. The code-behind file opens in the
editor.
4. In the code-behind file, add the following code to the Page_Load event:
C#
private void Page_Load(object sender, System.EventArgs e)
{
Label1.Text = "(Src): Page_Load fired!";
}

5. Switch from the code-behind class file to the .aspx page in the editor, and then switch to
HTML view.
6. At the top of the page, review the code for the @ Page directive. The code should be similar
to the following default code:

ASP.NET (C#)
<%@ Page language="c#" Codebehind="SrcSample.aspx.cs" AutoEventWireup="false"
Inherits="CodeBehindSamples.SrcSample"%>

7. To simplify this example, delete the Global.asax file from your project. This is only done in
this example to prevent additional errors that are related to the code-behind page of the
Global.asax file.
8. On the File menu, click Save All to save the Web Form and other associated project files.
9. If you followed the steps that are listed in the Use the Inherits attribute with
precompiled classes section, you must delete the assembly in the Bin directory of the
application before you follow the rest of the steps in this section.

For more information, visit the Troubleshooting section of this article.

10. To run the page, start Internet Explorer and then manually enter the URL of the page. Do
not select the View in Browser or the Browse With options from the Visual Studio .NET
IDE. Otherwise, if you are using Visual Studio .NET 2003, the code-behind page will be
precompiled into an assembly that is located in
the Bin directory by default. After viewing the page, you will receive an error message that
is similar as below:

Could not load type 'CodeBehindSamples.SrcSample'.

This error occurs because the code-behind class file is not yet compiled, and you have not
yet included the Src attribute to reference the code-behind class file.

11. Add the Src attribute to the @ Page directive as follows:

ASP.NET (C#)
<%@ Page language="c#" Codebehind="SrcSample.aspx.cs"
AutoEventWireup="false" Inherits="CodeBehindSamples.SrcSample" Src="SrcSample.aspx.cs"%>

The Src attribute is listed with the relative path of the code-behind class file (SrcSample.aspx.cs), and
the Inherits attribute value is set to
reference CodeBehindSamples.SrcSample.

12. On the File menu, click Save All to save the Web Form and other associated project files.
Remember, do not build the solution because you want the code-behind class file for this
sample to be compiled on demand.
13. To run the page, start Internet Explorer and then manually enter the URL of the page. Do
not select the View in Browser or the Browse With options from the Visual Studio .NET
IDE. Otherwise, if you are using Visual Studio .NET 2003, the code-behind page will be
precompiled into an assembly that is located in
the Bin directory by default. At this point, the page should be loaded in the browser, and the
label is populated with the following value:

(Src): Page_Load fired!

The code-behind class file has now been compiled on demand and functions correctly.

The Global.asax Application File:

What is Global.asax file: global.asax allows us to write event handlers that react to global events
in web applications.

How it gets called: Global.asax files are never called directly by the user, rather they are called
automatically in response to application events.

Point to remember about global.asax:

1. They do not contain any HTML or ASP.NET tags.


2. Contain methods with specific predefined names.
3. They defined methods for a single class, application class.
4. They are optional, but a web application has no more than one global.asax file.

How to add global.asax file:


Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio web
project model) and choose the Global Application Class template.

After you have added the global.asax file, you will find that Visual Studio has added
Application Event handlers:

1. <%@ Application Language="C#" %>


2. <script runat="server">
3. void Application_Start(object sender, EventArgs e)
4. {
5. // Code that runs on application startup
6. }
7. void Application_End(object sender, EventArgs e)
8. {
9. // Code that runs on application shutdown
10. }
11. void Application_Error(object sender, EventArgs e)
12. {
13. // Code that runs when an unhandled error occurs
14. }
15. void Session_Start(object sender, EventArgs e)
16. {
17. // Code that runs when a new session is started
18. }
19. void Session_End(object sender, EventArgs e)
20. {
21. // Code that runs when a session ends.
22. // Note: The Session_End event is raised only when the sessionstate mode
23. // is set to InProc in the Web.config file. If session mode is set to StateServer
24. // or SQLServer, the event is not raised.
25. }
26.</script>

Purpose of these application event handlers: To reach and handle any HttpApplication event.

If you want to know about HttpApplication events, see the MSDN article.

How these handler reach to HttpApplication Events

1. global.asax file aren't attached in the same way as the event handlers for ordinary
control events
2. Way to attach them is to use the recognized method name, i.e. for event handler
Application_OnEndRequest(), ASP.NET automatically calls this method when the
HttpApplication.EndRequest event occurs.

What kind of application event global.asax can handle:

Global.asax can handle 2 types of applications events

1) Events that occurs only under specific conditions, i.e. request / response related events.

Order in which application event handler executes;

Order Application Events What they do


This method is called at the start of
1 Application_BeginRequest()
every request.
This method is called just before
authentication is performed. This is time
2 Application_AuthenticateRequest()
and place where we can write our own
authentication codes.

After the user is authenticated


3 Application_AuthorizeRequest()
(identified), it's time to determine the
user's permissions. Here we can assign user
with special privileges
This method is commonly used in
4 Application_ResolveRequestCache()
conjunction with output caching.
This method is called just before session-
specific information is retrieved for the
5 Application_AcquireRequestState()
client and used to populate the Session
collection.

This method is called before the appropriate


6 Application_PreRequestHandlerExecute() HTTP handler executes the request.

This method is called just after the request


7 Application_PostRequestHandlerExecute()
is handled.
This method is called when the session-
specific information is about to be serialized
8 Application_ReleaseRequestState()
from the Session collection so that it's
available for the next request.

This method is called just before


9 Application_UpdateRequestCache() information is added to the output cache.

This method is called at the end of the


request, just before the objects are released
10 Application_EndRequest()
and reclaimed. It's a suitable point for
cleanup code.

2) Events that don't get fired with every request.

Order Application Events What they do


This method is invoked when the application first starts up and
the application domain is created. This event handler is a useful
place to provide application-wide initialization code. For
1 Application_Start()
example, at this point you might load and cache data that will
not change throughout the lifetime of an application, such as
navigation trees, static product catalogs, and so on.

This method is invoked each time a new session begins. This is


2 Session_Start()
often used to initialize user-specific information.
This method is invoked whenever an unhandled exception
3 Application_Error()
occurs in the application.
This method is invoked whenever the user's session ends. A
session ends when your code explicitly releases it or when it
4 Session_End() times out after there have been no more requests received
within a given timeout period (typically 20 minutes).

This method is invoked just before an application ends. The end


of an application can occur because IIS is being restarted or
5 Application_End() because the application is transitioning to a new application
domain in response to updated files or the process recycling
settings.

This method is invoked some time after the application has been
shut down and the .NET garbage collector is about to reclaim the
6 Application_Disposed() memory it occupies. This point is too late to perform critical
cleanup, but you can use it as a last-ditch failsafe to verify that
critical resources are released.

So now it's time to write codes under these event handlers. Let's

try for Application_Error

1. protected void Application_Error(Object sender, EventArgs e)


2. {
3. Response.Write("<font face=\"Tahoma\" size=\"2\" color=\"red\">");
4. Response.Write("Oops! Looks like an error occurred!!<hr></font>");
5. Response.Write("<font face=\"Arial\" size=\"2\">");
6. Response.Write(Server.GetLastError().Message.ToString());
7. Response.Write("<hr>" + Server.GetLastError().ToString());
8. any
So when Server.ClearError();
error happens, it get handled here with custom message.
9. }
Let's write code for Application_AuthenticateRequest , here we can write code our own
authentication codes, because this method is called just before authentication is performed.

protected void Application_AuthenticateRequest(Object sender, EventArgs e)

Response.Write("Authenticating request...<br>");

bool cookieFound = false;

HttpCookie authCookie = null;

HttpCookie cookie;

for (int i = 0; i < Request.Cookies.Count; i++)

cookie = Request.Cookies[i];

if (cookie.Name == FormsAuthentication.FormsCookieName)

{
cookieFound = true;

authCookie = cookie;

break;

// If the cookie has been found, it means it has been issued from either

// the windows authorisation site, is this forms auth site.

if (cookieFound)

// Extract the roles from the cookie, and assign to our current principal, which is at tached
to the

// HttpContext.

FormsAuthenticationTicket winAuthTicket = FormsAuthentication.Decrypt(auth


Cookie.Value);

string[] roles = winAuthTicket.UserData.Split(';');

FormsIdentity formsId = new FormsIdentity(winAuthTicket);

System.Security.Principal.GenericPrincipal princ = new System.Security.Principa


l.GenericPrincipal(formsId, roles);

HttpContext.Current.User = princ;

else

// No cookie found, we can redirect to the Windows auth site if we want, or let it p ass
through so

// that the forms auth system redirects to the logon page for us.
}

If there is no error, see below the order in which application events are handled.

As per your requirement, you can write your codes to use these application events
handlers.
ASP.NET - Configuration

The behavior of an ASP.NET application is affected by different settings in the configuration files:

 machine.config
 web.config
The machine.config file contains default and the machine-specific value for all supported settings.
The machine settings are controlled by the system administrator and applications are generally
not given access to this file.
An application however, can override the default values by creating web.config files in its roots
folder. The web.config file is a subset of the machine.config file.
If the application contains child directories, it can define a web.config file for each folder. Scope of
each configuration file is determined in a hierarchical top-down manner.
Any web.config file can locally extend, restrict, or override any settings defined on the upper level.
Visual Studio generates a default web.config file for each project. An application can execute
without a web.config file, however, you cannot debug an application without a web.config file.
The following figure shows the Solution Explorer for the sample example used in the web services
tutorial:

In this application, there are two web.config files for two projects i.e., the web service and the web
site calling the web service.
The web.config file has the configuration element as the root node. Information inside this element
is grouped into two main areas: the configuration section-handler declaration area, and the
configuration section settings area.
The following code snippet shows the basic syntax of a configuration file:

<configuration>

<!-- Configuration section-handler declaration area. -->


<configSections>
<section name="section1" type="section1Handler" />
<section name="section2" type="section2Handler" />
</configSections>
<!-- Configuration section settings area. -->
<section1>
<s1Setting1 attribute1="attr1" />
</section1>

<section2>
<s2Setting1 attribute1="attr1" />
</section2>

<system.web>
<authentication mode="Windows" />
</system.web>

</configuration>
Configuration Section Handler declarations
The configuration section handlers are contained within the <configSections> tags. Each
configuration handler specifies name of a configuration section, contained within the file, which
provides some configuration data. It has the following basic syntax:

<configSections>
<section />
<sectionGroup />
<remove />
<clear/>
</configSections>

It has the following elements:


 Clear - It removes all references to inherited sections and section groups.
 Remove - It removes a reference to an inherited section and section group.
 Section - It defines an association between a configuration section handler and a
configuration element.
 Section group - It defines an association between a configuration section handler and a
configuration section.

Application Settings
The application settings allow storing application-wide name-value pairs for read-only access.
For example, you can define a custom application setting as:

<configuration>
<appSettings>
<add key="Application Name" value="MyApplication" />
</appSettings>
</configuration>

For example, you can also store the name of a book and its ISBN number:

<configuration>
<appSettings>
<add key="appISBN" value="0-273-68726-3" />
<add key="appBook" value="Corporate Finance" />
</appSettings>
</configuration>

Connection Strings
The connection strings show which database connection strings are available to the website. For
example:

<connectionStrings>
<add name="ASPDotNetStepByStepConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=E:\\projects\datacaching\ / datacaching\
App_Data\ASPDotNetStepByStep.mdb"
providerName="System.Data.OleDb" />

<add name="booksConnectionString"
connectionString="Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=C:\ \databinding\App_Data\books.mdb"
providerName="System.Data.OleDb" />
</connectionStrings>

System.Web Element
The system.web element specifies the root element for the ASP.NET configuration section and
contains configuration elements that configure ASP.NET Web applications and control how the
applications behave.
It holds most of the configuration elements needed to be adjusted in common applications. The
basic syntax for the element is as given:

<system.web>
<anonymousIdentification>
<authentication>
<authorization>
<browserCaps>
<caching>
<clientTarget>
<compilation>
<customErrors>
<deployment>
<deviceFilters>
<globalization>
<healthMonitoring>
<hostingEnvironment>
<httpCookies>
<httpHandlers>
<httpModules>
<httpRuntime>
<identity>
<machineKey>
<membership>
<mobileControls>
<pages>
<processModel>
<profile>
<roleManager>
<securityPolicy>
<sessionPageState>
<sessionState>
<siteMap>
<trace>
<trust>
<urlMappings>
<webControls>
<webParts>
<webServices>
<xhtmlConformance>
</system.web>

The following table provides brief description of some of common sub elements of the
system.web element:
AnonymousIdentification
This is required to identify users who are not authenticated when authorization is required.

Authentication
It configures the authentication support. The basic syntax is as given:

<authentication mode="[Windows|Forms|Passport|None]">
<forms>...</forms>
<passport/>
</authentication>

Authorization
It configures the authorization support. The basic syntax is as given:

<authorization>
<allow .../>
<deny .../>
</authorization>

Caching
It Configures the cache settings. The basic syntax is as given:

<caching>
<cache>...</cache>
<outputCache>...</outputCache>
<outputCacheSettings>...</outputCacheSettings>
<sqlCacheDependency>...</sqlCacheDependency>
</caching>

CustomErrors
It defines custom error messages. The basic syntax is as given:

<customErrors defaultRedirect="url" mode="On|Off|RemoteOnly">


<error. . ./>
</customErrors>

Deployment
It defines configuration settings used for deployment. The basic syntax is as follows:

<deployment retail="true|false" />


HostingEnvironment
It defines configuration settings for hosting environment. The basic syntax is as follows:

<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"
shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" />

Identity
It configures the identity of the application. The basic syntax is as given:

<identity impersonate="true|false" userName="domain\username"


password="<secure password>"/>

MachineKey
It configures keys to use for encryption and decryption of Forms authentication cookie data.
It also allows configuring a validation key that performs message authentication checks on view-
state data and forms authentication tickets. The basic syntax is:

<machineKey validationKey="AutoGenerate,IsolateApps" [String]


decryptionKey="AutoGenerate,IsolateApps" [String]
validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 |
HMACSHA384 | HMACSHA512 | alg:algorithm_name]
decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]
/>

Membership
This configures parameters of managing and authenticating user accounts. The basic syntax is:

<membership defaultProvider="provider name"


userIsOnlineTimeWindow="number of minutes" hashAlgorithmType="SHA1">
<providers>...</providers>
</membership>

Pages
It provides page-specific configurations. The basic syntax is:

<pages asyncTimeout="number" autoEventWireup="[True|False]" buffer="[True|False]" clientIDM


controlRenderingCompatibilityVersion="[3.5|4.0]"
enableEventValidation="[True|False]"
enableSessionState="[True|False|ReadOnly]"
enableViewState="[True|False]"
enableViewStateMac="[True|False]"
maintainScrollPositionOnPostBack="[True|False]"
masterPageFile="file path"
maxPageStateFieldLength="number"
pageBaseType="typename, assembly"
pageParserFilterType="string" smartNavigation="[True|
False]" styleSheetTheme="string"
theme="string"
userControlBaseType="typename"
validateRequest="[True|False]"
viewStateEncryptionMode="[Always|Auto|Never]" >

<controls>...</controls>
<namespaces>...</namespaces>
<tagMapping>...</tagMapping>
<ignoreDeviceFilters>...</ignoreDeviceFilters>
</pages>

Profile
It configures user profile parameters. The basic syntax is:

<profile enabled="true|false" inherits="fully qualified type reference"


automaticSaveEnabled="true|false" defaultProvider="provider name">

<properties>...</properties>
<providers>...</providers>

</profile>

RoleManager
It configures settings for user roles. The basic syntax is:

<roleManager cacheRolesInCookie="true|false" cookieName="name" cookiePath="/" cookieProtec


cookieTimeout="number of minutes" createPersistentCookie="true|false" defaultProvider="pro
maxCachedResults="maximum number of role names cached"

<providers>...</providers>
</roleManager>

SecurityPolicy
It configures the security policy. The basic syntax is:

<securityPolicy>
<trustLevel />
</securityPolicy>

UrlMappings
It defines mappings to hide the original URL and provide a more user friendly URL. The basic
syntax is:

<urlMappings enabled="true|false">
<add.../>
<clear />
<remove.../>
</urlMappings>

WebControls
It provides the name of shared location for client scripts. The basic syntax is:

<webControls clientScriptsLocation="String" />

ASP.NET Applications:

When an ASP.Net application is launched, there are series of steps which are carried out. These
series of steps make up the lifecycle of the application.Let’s look at the various stages of a typical
page lifecycle of an ASP.Net Web Application.
1) Application Start – The life cycle of an ASP.NET application starts when a request is made by a
user. This request is to the Web server for the ASP.Net Application. This happens when the first
user normally goes to the home page for the application for the first time. During this time, there is
a method called Application_start which is executed by the web server. Usually, in this method, all
global variables are set to their default values.

2) Object creation – The next stage is the creation of the HttpContext, HttpRequest &
HttpResponse by the web server. The HttpContext is just the container for the HttpRequest and
HttpResponse objects. The HttpRequest object contains information about the current request,
including cookies and browser information. The HttpResponse object contains the response that is
sent to the client.

3) HttpApplication creation – This object is created by the web server. It is this object that is used
to process each subsequent request sent to the application. For example, let’s assume we have 2
web applications. One is a shopping cart application, and the other is a news website. For each
application, we would have 2 HttpApplication objects created. Any further requests to each website
would be processed by each HttpApplication respectively.

4) Dispose – This event is called before the application instance is destroyed. During this time, one
can use this method to manually release any unmanaged resources.

5) Application End – This is the final part of the application. In this part, the application is finally
unloaded from memory.

ASP.NET CodeBehind:

While our first example was fine, we unfortunately broke one of the coding principles of
ASP.NET: To separate markup and code. As you noticed, we added a scripting block (using
<% %>), where we wrote a line of C# code to use the label. While this is just fine for a small and
simple example like this, we would soon get a real mess with a bunch of C# code within an even
bigger amount of HTML code. If you throw in some JavaScript and some CSS as well, it will soon
become very chaotic to edit. That's why MS introduced CodeBehind, a technique which allows you
to completely separate markup (HTML, CSS
etc.) and code (C#, VB.NET etc.). So let's remove the script block (from <% to %>) and save the file.
As we talked about earlier, VS added a file called Default.aspx.cs. If you can't see it in the Solution
Explorer, then click the little plus sign left of the Default.aspx file. Open this file. Now, if you haven't
worked with .NET or another non-web programming language before, it might look a bit scary at
this point. It looks nothing like HTML. However, I will try to explain the different parts of the
content, and soon you will hopefully see that CodeBehind is a great tool to get a better overview of
your work. Here is a complete listing of the file as it looks right now:
usingSystem;
usingSystem.Data;
usingSystem.Configuration;
usingSystem.Web;
usingSystem.Web.Security;
usingSystem.Web.UI;
usingSystem.Web.UI.WebControls;
usingSystem.Web.UI.WebControls.WebParts;
usingSystem.Web.UI.HtmlControls;
publicpartialclass_Default:System.Web.UI.Page
{
protectedvoidPage_Load(objectsender,EventArgse)
{
}
}

The Global.asax Application file:

global.asax allows us to write event handlers that react to global events in web applications.

How it gets called: Global.asax files are never called directly by the user, rather they are called
automatically in response to application events.

Point to remember about global.asax:

1. They do not contain any HTML or ASP.NET tags.


2. Contain methods with specific predefined names.
3. They defined methods for a single class, application class.
4. They are optional, but a web application has no more than one global.asax file.

How to add global.asax file:


Select Website >>Add New Item (or Project >> Add New Item if you're using the Visual Studio web
project model) and choose the Global Application Class template.
After you have added the global.asax file, you will find that Visual Studio has added Application
Event handlers:

<%@ Application Language="C#" %>

<script runat="server">

void Application_Start(object sender, EventArgs e)


{
// Code that runs on application startup
}
void Application_End(object sender, EventArgs e)
{
// Code that runs on application shutdown
}
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
}
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
}
void Session_End(object sender, EventArgs e)
{
// Code that runs when a session ends.
Understanding ASP.NET Classes:

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.

A Simple page applet:

Improving the currency converter:

HTML Control Classes:

The HtmlControl class is the basis for all HTML server controls in Visual Basic. You don't use it
directly—instead, you use classes derived from it, or, more usually, classes derived from them.
Here are the classes derived from the HtmlControl class:
Object
Control
HtmlControl
HtmlContainerControl
HtmlImage
HtmlInputControl
The real purpose of the HtmlControl class is to provide a set of properties shared by all HTML
server controls:
 Attributes— Holds all attribute name and value pairs for the server control's HTML element.
 Disabled— Gets/sets whether the disabled attribute is included when an HTML control is
displayed in the browser.
 Style— Gets all cascading style sheet (CSS) properties for the specified HTML server control.
 TagName— Gets the element name that contains the runat=server attribute.
The classes derived from HtmlControl—in particular
the HtmlContainerControl and HtmlInputControl classes—form the basis of the HTML server
control classes.
The HtmlContainerControl Class
The HtmlContainerControl class defines the methods, properties, and events available to all
HTML server controls that can act as a container (in HTML terms, these elements all require a
closing tag). This class is the base class for
the HtmlTableCell, HtmlTable, HtmlTableRow, HtmlButton, HtmlForm, HtmlAnch or,
HtmlGenericControl, HtmlSelect, and HtmlTextArea classes, all of which share these properties:
InnerHtml— Gets/sets the content between the opening and closing tags of the HTML control.
InnerText— Gets/sets all text between the opening and closing tags of the specified HTML
control. (Note that unlike the InnerHtml property, InnerText supports automatic HTML
encoding and decoding.)
The HtmlInputControl Class
The HtmlInputControl class serves as the abstract base class that defines the methods, properties,
and events common to all HTML input controls, such as the <input type="text">, <input
type="submit">, and other elements that the user can enter data into.
The classes derived from the HtmlInputControl classarethe HtmlInputText,
HtmlInputButton, HtmlInputCheckBox, HtmlInputImage, Html InputHidden, HtmlInputFile,
and HtmlInputRadioButton classes, all of which share the following properties:
 Name— Gets/sets a unique name for the input control.
 Value— Gets/sets the contents of an input control.
 Type— Gets the type of an input control.
The HtmlImage Class
This class creates an HTML <img> element, used to display images. Using the properties of this
class, you change the image displayed and the image size, as well as the alignment of the image
with respect to other HTML elements.
The Page Class:

Accesssing HTML server controls:

HTML server controls are HTML elements that contain attributes to accessible at server side. By
default, HTML elements on an ASP.NET Web page are not available to the server. These
components are treated as simple text and pass through to the browser. We can convert an HTML
element to server control by adding a runat="server" and an id attribute to the component.
Example
<input id="UserName" type="text" size="50"runat="server" />
All the HTML Server controls can be accessed through the Request object.

Web Controls:
Web controls are basically HTML elements wrapped under easy to use scripting tags of ASP+ and
provide rich functionality in your FORMs or pages. Web controls range from simple text box to
advance girds and lists. Some of the controls like data grid can be bound to data sources much like
Visual Basic data bound controls.

Web Control Classes:


Web control classes are defined in the System.Web.UI.WebControls namespace. .
The web control hierarchy

This inheritance diagram includes some controls that you won't study in this chapter, including
the data controls, such as the GridView, DetailsView, and FormView, and the validation controls.

Auto Post Back and Web Control events:


If we create a web Page, which consists of one or more Web Controls that are configured to use
AutoPostBack (Every Web controls will have their own AutoPostBack property), the ASP.Net adds a
special JavaScipt function to the rendered HTML Page. This function is named _doPostBack() .
When Called, it triggers a PostBack, sending data back to the web Server.

ASP.NET also adds two additional hidden input fields that are used to pass information back to the
server. This information consists of ID of the Control that raised the event and any additional
information if needed. These fields will empty initially as shown below,

<input type="hidden" name=" EVENTTARGET" id=" EVENTTARGET" value="" />


<input type="hidden" name=" EVENTARGUMENT" id=" EVENTARGUMENT" val ue="" />
The _doPostBack() function has the responsibility for setting these values with the appropriate
information about the event and the submitting the form.

ASP.NET generates the _doPostBack() function automatically, provided at least one control
on the page uses automatic postbacks.

Any Control that has its AutoPostBack Property set to true is connected to the
_doPostBack() function using the onclick or onchange attributes. These attributes indicate what
action should Browser take in response to the Client-Side javascript events onclick and onchange.

In other words, ASP.Net automatically changes a client-side javascript event into a server-
side ASP.Net event, using the _doPostBack() function as an intermediary.

Web Control events:

Web control are processed at server side. This means that all the events generated by a control will
be handled at server end. The event handling has changed with ASP+.

Each event handler now has following syntax :

publicsubmyeventhandler(sourceasObject,evtasEventArgs)
'accessyourwebcontrolshereand'manipulatetheirproperties end
sub

Here, source is the object which caused the event to be raised and evt is an object providing more
information about the event.

Accessing Web Controls:

Using Visual Studio.NET:

Starting a Visual Studio.NET Project:

First, you'll create a .NET Core console application project. The project type comes with all the
template files you'll need, before you've even added anything!

1. Open Visual Studio.

If the start window is not open, choose File > Start Window.

2. On the start window, choose Create a new project.


3. On the Create a new project window, enter, or type console in the search box. Next, choose
Visual Basic from the Language list, and then choose Windows from the Platform list.

After you apply the language and platform filters, choose the Console
Application template for .NET Core, and then choose Next.

4. In the Configure your new project window, type or enter get-started-debugging in the
Project name box. Then, choose Next.
5. On the Additional Information window, ensure the recommended target framework is
(.NET 6.0), and then choose Create.

Visual Studio opens your new project.

Web Form Designer:

Writing Code:

In Program.vb, replace all of the default code with the following code instead: Imports

System

Class ArrayExample

Public Shared Sub Main()

Dim letters As Char() = {"f"c, "r"c, "e"c, "d"c, " "c, "s"c, "m"c, "i"c, "t"c, "h"c} Dim name As

String = ""
Dim a As Integer() = New Integer(9) {}

For i As Integer = 0 To letters.Length - 1 name +=

letters(i)

a(i) = i + 1

SendMessage(name, a(i))

Next Console.ReadKey()

End Sub

Private Shared Sub SendMessage(ByVal name As String, ByVal msg As Integer) Console.WriteLine("Hello,

" & name & "! Count to " & msg)

End Sub

End Class

Visual Studio.NET debugging:

1. Press F5 (Debug > Start Debugging) or select the green Start Debugging button in the
Debug Toolbar.

F5 starts the app with the debugger attached to the app process, but right now we haven't
done anything special to examine the code. So the app just loads and you see the console
output.

Hello, f! Count to 1 Hello, fr!

Count to 2 Hello, fre! Count

to 3 Hello, fred! Count to 4

Hello, fred ! Count to 5 Hello,

fred s! Count to 6 Hello, fred

sm! Count to 7
Hello, fred smi! Count to 8 Hello,

fred smit! Count to 9 Hello, fred

smith! Count to 10

2.Stop the debugger by pressing (Shift + F5) or select the red Stop Debugging button in the
Debug Toolbar.

3.In the console window, press a key to close the console window.

Validation and Rich Controls:

An important aspect of creating ASP.NET Web pages for user input is to be able to check that
the information users enter is valid. ASP.NET provides a set of validation controls that provide an
easy-to-use but powerful way to check for errors and, if necessary, display messages to the user.

There are six types of validation controls in ASP.NET RequiredFieldValidation

Control

CompareValidator Control RangeValidator

Control RegularExpressionValidator Control

CustomValidator Control ValidationSummary

The below table describes the controls and their work,

Validation Control Description

RequiredFieldValidation Makes an input control a required field

Compares the value of one input control to the value of another


CompareValidator
input control or to a fixed value

Checks that the user enters a value that falls between two values
RangeValidator

Ensures that the value of an input control matches a specified


RegularExpressionValidator
pattern

Allows you to write a method to handle the validation of the value


CustomValidator
entered

Displays a report of all validation errors occurred in a Web page


ValidationSummary
All validation controls are rendered in form as <span> (label are referred as <span> on client by
server)

Important points for validation controls

ControlToValidate property is mandatory to all validate controls.

One validation control will validate only one input control but multiple validate control can be
assigned to a input control.

Rich Controls:

ASP.NET provides large set of controls. These controls are divided into different categories,
depends upon their functionalities. The followings control comes under the rich controls
category.

FileUpload control

Calendar control

AdRotator control

MultiView control

Wizard control

Validation:
ASP.NET validation controls validate the data entered by the user. If the data does not pass validation, it will
display an error message to the user.

CompareValidator: This validator validates the value of one input with the value of another input.
ControlToValidate, ControlToComapre, ValueToCompare and ErrorMessage are the properties of
CompareValidator.
RangeValidator: This validator determines whether the values entered by the users fall between
two values. ControlToValidate, MaximumValue, MinimumValue and ErrorMessage are properties of
RangeValidator.

RequiredFieldValidator: This validator makes an input control a required field. ControlToValidate


and ErrorMessage are properties of the RequiredFieldValidator.

CustomValidator: This validator allows the user to write a method to handle the validation of the
value entered. ControlToValidate, ClientValidationFunction, ErrorMessage and ServerValidate
event are properties of the CustomValidator.

RegularExpressionValidator: This validator ensures that the value of an input control matches a
specified pattern. ControlToValidate, ValidationExpression and ErrorMessage are properties of the
RegularExpressionValidator.

ValidationSummary: This validator displays a report of all validation errors that occurred on a web
page.

A simple Validation example:

Understanding regular expressions:

Regular expressions provide a powerful, flexible, and efficient method for processing text. The
extensive pattern-matching notation of regular expressions enables you to quickly parse large
amounts of text to:

 Find specific character patterns.


 Validate text to ensure that it matches a predefined pattern (such as an email address).
 Extract, edit, replace, or delete text substrings.
 Add extracted strings to a collection in order to generate a report.
For many applications that deal with strings or that parse large blocks of text, regular expressions
are an indispensable tool.

How regular expressions work

The centerpiece of text processing with regular expressions is the regular expression engine, which
is represented by the System.Text.RegularExpressions.Regex object in .NET. At a minimum,
processing text using regular expressions requires that the regular expression engine be provided
with the following two items of information:

 The regular expression pattern to identify in the text.

In .NET, regular expression patterns are defined by a special syntax or language, which is
compatible with Perl 5 regular expressions and adds some additional features such as right-
to-left matching. For more information, see Regular Expression Language - Quick Reference.

 The text to parse for the regular expression pattern.

A Validated customer form:

State management:

In ASP.NET there are the following 2 State Management methodologies:

Client-Side State Management

Whenever we use Client-Side State Management, the state related information will directly get
stored on the client-side. That specific information will travel back and communicate
with every request generated by the user then afterwards provides responses after server- side
communication.

This architecture is something like the following,

Server-Side State Management

Server-Side State Management is different from Client-Side State Management but the operations
and working is somewhat the same in functionality. In Server-Side State Management all the
information is stored in the user memory. Due to this functionality there is more secure domains at
the server side in comparison to Client-Side State Management.

The structure is something like the following,

State Management Techniques


State Management techniques are based on client side and server side. Their functionality differs
depending on the change in state, so here is the hierarchy:
Client-side | Techniques

Client-Side State Management techniques are,

 View State
 Hidden field
 Cookies
 Control State
 Query Strings

Server-side | Technique

Server-Side State Management techniques are,

 Session State
 Application State

Tracing,Logging, and Error Handling:

Tracing:

The other useful tool provided by ASP.NET for debugging is the trace feature. Tracing allows you,
through a simple configuration setting or page-level attribute, to have ASP.NET write a whole host
of information about the currently executing request to the page or to a trace log. This information
includes the SessionID; the time, type, and status code of the request; timing information for events
such as Init, PreRender, SaveViewState, and Render; a Control Tree of all controls in the page; and
the contents of the Cookies collection, the
HTTP Headers, the QueryString collection (if any QueryString values were passed), the Form
collection (if any form fields were passed), and the ServerVariables collection.
Essentially, tracing allows you to automatically write out the contents of all collections exposed by
the classic ASP Request object, plus some really useful additional information. This allows you to
examine a great deal of information about a request on a single page, which can assist greatly in
debugging.
More importantly, you can also write to the trace output using the Trace.Write and Trace.Warn
methods, which are exposed by the Trace property of the Page class. These methods can now be
used in place of Response.Write when you determine the value of a variable on a page at a certain
point in page execution or write out a notification that a certain point in the page has been hit. With
Trace.Write or Trace.Warn, once you've disabled tracing, you can leave the statements in your code
and you don't have to worry about anyone seeing the output. If you've ever deployed a page to
production without removing or commenting out your Response.Write statements used for
debugging, you'll be grateful for this feature.
Page-Level Tracing

Enabling tracing at the page level is very simple. Simply add the Trace attribute to the @ Page
directive and set its value to True, as shown in the following code snippet:

<%@ Page Language="VB" Trace="True" %>

This provides a quick and easy way to get an overview of what's going on for a given page. The
output from a page with tracing enabled looks similar to Figure 10-8.
Page-level tracing
One downside to enabling tracing at the page level is that if you use it with many pages, it's more
work to add and remove the Trace attribute for each page (or to set the attributes to False). This
can also make it more likely that you'll forget one and end up with trace information being written
out in a production application. Not what you want.

Application-Level Tracing
ASP.NET provides the ability to enable tracing at the application level throughthe
<trace> element in web.config. Application-level tracing makes it possible to disable tracing in a
single location in your application and makes it easier to enable tracing for multiple pages. Example
10-8 shows a web.config file with tracing enabled at the application level.
Logging:
ASP.NET Core has built-in support for logging, and allows developers to easily leverage their
preferred logging framework’s functionality as well. Implementing logging in your application
requires a minimal amount of setup code. Once this is in place, logging can be added wherever it is
desired.

Error Handling:

The goal of error handling (also known as exception handling) is quite simple: to prevent
exceptions or errors thrown during the execution of an application request from reaching users.
Ideally, users should not know that an exception occurred, or they should at least be provided with
an informative message that tells them what they can do to resolve the problem. ASP.NET provides
three techniques for achieving this goal:

Custom error pages

Allow you to assign one or more error pages to be displayed when an exception occurs.
Page_Error and Application_Error events

Writing event handlers for either or both of these events allows you to catch and handle
exceptions at the page or application level.
Structured exception handling

New to Visual Basic .NET, and also available in C#, this type of exception handling allows
exceptions to be caught and handled in particular blocks of code.
These three techniques provide broadest (custom error pages, which can handle exceptions from
any page in the application) to narrowest (structured exception handling, which handles
exceptions for a specific block of code) coverage for handling application
exceptions. Figure 10-1 illustrates the relationship of these exception handling techniques to both
the exception (shown at the center) and the user, who you're trying to prevent from encountering
the exception.
Exception handling techniques

The following sections describe these techniques and explain how they fit into an ASP.NET
application. Note that you can use all three techniques together, individually, or in whatever
combination you like. Using all three techniques in combination would provide broad coverage for
most exceptions and more robust specific exceptions handling, but at the cost of maintaining your
exception-handling logic in more places.
UNIT III

Overview of ADO.NET
ADO.NET Introduction

It is a module of .Net Framework which is used to establish connection between application and
data sources. Data sources can be such as SQL Server and XML. ADO.NET consists of classes that
can be used to connect, retrieve, insert and delete data.

All the ADO.NET classes are located into System.Data.dll and integrated with XML classes located
into System.Xml.dll.

ADO.NET has two main components that are used for accessing and manipulating data are the .NET
Framework data provider and the DataSet.

.NET Framework Data Providers

These are the components that are designed for data manipulation and fast access to data. It
provides various objects such as Connection, Command, DataReader and DataAdapter that are
used to perform database operations. We will have a detailed discussion about Data Providers in
new topic.

The DataSet

It is used to access data independently from any data resource. DataSet contains a collection of one or more
DataTable objects of data. The following diagram shows the relationship between .NET Framework

Data provider and dataset


ADO .NET and DATA MANAGEMENT
ADO.NET provides a bridge between the front end controls and the back end database. The
ADO.NET objects encapsulate all the data access operations and the controls interact with these
objects to display data, thus hiding the details of movement of data.
The following figure shows the ADO.NET objects at a glance:

The DataSet Class


The dataset represents a subset of the database. It does not have a continuous connection to the
database. To update the database a reconnection is required. The DataSet contains DataTable
objects and DataRelation objects. The DataRelation objects represent the relationship between
two tables.
Following table shows some important properties of the DataSet class:

Properties Descripti
on

CaseSensitive Indicates whether string comparisons within the data tables are case-
sensitive.

Container Gets the container for the component.

DataSetName Gets or sets the name of the current data set.

DefaultViewManager Returns a view of data in the data set.

DesignMode Indicates whether the component is currently in design mode.


EnforceConstraints Indicates whether constraint rules are followed when attempting any
update operation.

Events Gets the list of event handlers that are attached to this component.

ExtendedProperties Gets the collection of customized user information associated with the
DataSet.

HasErrors Indicates if there are any errors.

IsInitialized Indicates whether the DataSet is initialized.

Locale Gets or sets the locale information used to compare strings within the
table.

Namespace Gets or sets the namespace of the DataSet.

Prefix Gets or sets an XML prefix that aliases the namespace of the DataSet.

Relations Returns the collection of DataRelation objects.

Tables Returns the collection of DataTable objects.

The following table shows some important methods of the DataSet class:

Method Descripti
s on

AcceptChanges Accepts all changes made since the DataSet


was loaded or this method was called.

BeginInit Begins the initialization of the DataSet. The


initialization occurs at run time.

Clear Clears data.

Clone Copies the structure of the DataSet, including


all DataTable schemas, relations, and
constraints. Does not copy any data.

Copy Copies both structure and data.


CreateDataReader() Returns a DataTableReader with one result set
per DataTable, in the same sequence as the
tables appear in the Tables collection.

CreateDataReader(DataTable[]) Returns a DataTableReader with one result set


per DataTable.

EndInit Ends the initialization of the data set.

Equals(Object) Determines whether the specified Object is


equal to the current Object.

Finalize Free resources and perform other cleanups.

GetChanges Returns a copy of the DataSet with all changes


made since it was loaded or the AcceptChanges
method was called.

GetChanges(DataRowState) Gets a copy of DataSet with all changes made


since it was loaded or the AcceptChanges
method was called, filtered by DataRowState.

GetDataSetSchema Gets a copy of XmlSchemaSet for the DataSet.

GetObjectData Populates a serialization information object


with the data needed to serialize the DataSet.

GetType Gets the type of the current instance.

GetXML Returns the XML representation of the data.

GetXMLSchema Returns the XSD schema for the XML


representation of the data.

HasChanges() Gets a value indicating whether the DataSet


has changes, including new, deleted, or
modified rows.

HasChanges(DataRowState) Gets a value indicating whether the DataSet


has changes, including new, deleted, or
modified rows, filtered by DataRowState.
IsBinarySerialized Inspects the format of the serialized
representation of the DataSet.

Load(IDataReader, LoadOption, DataTable[]) Fills a DataSet with values from a data source
using the supplied IDataReader, using an array
of DataTable instances to supply the schema
and namespace information.

Load(IDataReader, LoadOption, String[]) Fills a DataSet with values from a data source
using the supplied IDataReader, using an
array of strings to supply the names for the
tables within the DataSet.
Merge() Merges the data with data from another
DataSet. This method has different overloaded
forms.
ReadXML() Reads an XML schema and data into the DataSet.
This method has different overloaded forms.

ReadXMLSchema(0) Reads an XML schema into the DataSet. This


method has different overloaded forms.

RejectChanges Rolls back all changes made since the last call
to AcceptChanges.

WriteXML() Writes an XML schema and data from the


DataSet. This method has different
overloaded forms.
WriteXMLSchema() Writes the structure of the DataSet as an XML
schema. This method has different overloaded
forms.

The DataTable Class


The DataTable class represents the tables in the database. It has the following important
properties; most of these properties are read only properties except the PrimaryKey property:

Properties Descripti
on

ChildRelations Returns the collection of child relationship.


Columns Returns the Columns collection.

Constraints Returns the Constraints collection.

DataSet Returns the parent DataSet.

DefaultView Returns a view of the table.

ParentRelations Returns the ParentRelations collection.

PrimaryKey Gets or sets an array of columns as the primary key for the table.

Rows Returns the Rows collection.

The following table shows some important methods of the DataTable class:

Method Descripti
s on

AcceptChanges Commits all changes since the last AcceptChanges.

Clear Clears all data from the table.

GetChanges Returns a copy of the DataTable with all changes made since the
AcceptChanges method was called.

GetErrors Returns an array of rows with errors.

ImportRows Copies a new row into the table.

LoadDataRow Finds and updates a specific row, or creates a new one, if not found any.

Merge Merges the table with another DataTable.

NewRow Creates a new DataRow.

RejectChanges Rolls back all changes made since the last call to AcceptChanges.
Reset Resets the table to its original state.

Select Returns an array of DataRow objects.

The DataRow Class


The DataRow object represents a row in a table. It has the following important properties:

Properties Descripti
on

HasErrors Indicates if there are any errors.

Items Gets or sets the data stored in a specific column.

ItemArrays Gets or sets all the values for the row.

Table Returns the parent table.

The following table shows some important methods of the DataRow class:

Method Descripti
s on

AcceptChanges Accepts all changes made since this method was called.

BeginEdit Begins edit operation.

CancelEdit Cancels edit operation.

Delete Deletes the DataRow.

EndEdit Ends the edit operation.

GetChildRows Gets the child rows of this row.

GetParentRow Gets the parent row.

GetParentRows Gets parent rows of DataRow object.


RejectChanges Rolls back all changes made since the last call to AcceptChanges.

The DataAdapter Object


The DataAdapter object acts as a mediator between the DataSet object and the database. This
helps the Dataset to contain data from multiple databases or other data source.

The DataReader Object


The DataReader object is an alternative to the DataSet and DataAdapter combination. This object
provides a connection oriented access to the data records in the database. These objects are
suitable for read-only access, such as populating a list and then breaking the connection.

DbCommand and DbConnection Objects


The DbConnection object represents a connection to the data source. The connection could be
shared among different command objects.
The DbCommand object represents the command or a stored procedure sent to the database from
retrieving or manipulating data.

Example
So far, we have used tables and databases already existing in our computer. In this example, we
will create a table, add column, rows and data into it and display the table using a GridView object.
The source file code is as given:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"


Inherits="createdatabase._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>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>

</form>
</body>
The code behind file is as given:
namespace createdatabase
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
GridView1.DataSource =
ds.Tables["Student"];
GridView1.DataBind();
}
}

private DataSet CreateDataSet()


{
//creating a DataSet object for
tables DataSet dataset = new
DataSet();

// creating the student table


DataTable Students = CreateStudentTable();
dataset.Tables.Add(Students);
return dataset;
}

private DataTable CreateStudentTable()


{
DataTable Students = new DataTable("Student");

// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "System.String", "StudentName");
AddNewColumn(Students, "System.String", "StudentCity");

// adding rows
AddNewRow(Students, 1, "M H Kabir", "Kolkata");
AddNewRow(Students, 1, "Shreya Sharma", "Delhi");
AddNewRow(Students, 1, "Rini Mukherjee",
"Hyderabad"); AddNewRow(Students, 1, "Sunil
Dubey", "Bikaner"); AddNewRow(Students, 1, "Rajat
Mishra", "Patna");

return Students;
}

private void AddNewColumn(DataTable table, string columnType, string columnName)


{
DataColumn column = table.Columns.Add(columnName, Type.GetType(columnType));
}

//adding data into the table


private void AddNewRow(DataTable table, int id, string name, string city)
{
DataRow newrow =
table.NewRow();
newrow["StudentID"] = id;
newrow["StudentName"] = name; newrow["StudentCity"] = city; table.Rows.Add(newrow);

}
}
}
When you execute the program, observe the following:
 The application first creates a data set and binds it with the grid view control using the
DataBind() method of the GridView control.
 The Createdataset() method is a user defined function, which creates a new DataSet object
and then calls another user defined method CreateStudentTable() to create the table and
add it to the Tables collection of the data set.
 The CreateStudentTable() method calls the user defined methods AddNewColumn() and
AddNewRow() to create the columns and rows of the table as well as to add data to the
rows.
When the page is executed, it returns the rows of the table as shown:

Characteristics Of ADO.NET

1. Bulk Copy Operation

• Bulk copying of data from a data source to another data source is a new feature added to
ADO.NET 2.0. Bulk copy classes provides the fastest way to transfer set of data from once
source to the other. Each ADO.NET data provider provides bulk copy classes. For example,
in SQL .NET data provider, the bulk copy operation is handled by SqlBulkCopy class, which
can read a DataSet, DataTable, DataReader, or XML objects.
2. Batch Update

• Batch update can provide a huge improvement in the performance by making just one
round trip to the server for multiple batch updates, instead of several trips if the database
server supports the batch update feature. The UpdateBatchSize property provides the
number of rows to be updated in a batch. This value can be set up to the limit of decimal.
3. Data Paging
• Now command object has a new execute method called ExecutePageReader. This method
takes three parameters - CommandBehavior, startIndex, and pageSize. So if we want to get
rows from 101 - 200, We can simply call this method with start index as 101 and page size
as 100.
4. Connection Details

• Now you can get more details about a connection by setting Connection's StatisticsEnabled
property to True. The Connection object provides two new methods - RetrieveStatistics
and ResetStatistics. The RetrieveStatistics method returns a HashTable object filled with
the information about the connection such as data transferred, user details, curser details,
buffer information and transactions.
5. DataSet.RemotingFormat Property

• When DataSet.RemotingFormat is set to binary, the DataSet is serialized in binary format


instead of XML tagged format, which improves the performance of serialization and
deserialization operations significantly
6. DataTable's Load and Save Method

• In previous version of ADO.NET, only DataSet had Load and Save methods. The Load
method can load data from objects such as XML into a DataSet object and Save method
saves the data to a persistent media. Now DataTable also supports these two methods.
• We can also load a DataReader object into a DataTable by using the Load method.
7. New Data Controls

• In Toolbox, We will see these new controls - DataGridView, DataConnector, and


DataNavigator. Now using these controls, we can provide navigation (paging) support to
the data in data bound controls.
8. DbProvidersFactories Class

• This class provides a list of available data providers on a machine. We can use this class
and its members to find out the best suited data provider for our database when writing a
database independent applications.
9. Customized Data Provider

• By providing the factory classes now ADO.NET extends its support to custom data
provider. Now we don't have to write a data provider dependent code. We use the base
classes of data provider and let the connection string does the trick for us.
10. DataReader's New Execute Methods
• Now command object supports more execute methods. Besides old ExecuteNonQuery,
ExecuteReader, ExecuteScaler, and ExecuteXmlReader, the new execute methods are
ExecutePageReader, ExecuteResultSet, and ExecuteRow.

The ADO.NET Object Model

The goal of ADO.NET is to provide a bridge between your objects in ASP.NET and your back-end
database. ADO.NET provides an object-oriented view into the database, encapsulating many of the
database properties and relationships within ADO.NET objects. Further, and in many ways most
important, the ADO.NET objects encapsulate and hide the details of database access; your objects
can interact with ADO.NET objects without you knowing or worrying about the details of how the
data is moved to and from the database.

 All ADO.NET related functionality appears under the System.Data namespace.


 Data Access in ADO.NET relies on two components :
1. .NET Data Providers.
2. DataSet

An overview of the ADO.NET architecture is shown in Figure 10-1. We will return to the aspects of
this figure throughout the chapter.

NET Data Providers:

 A .NET Data Provider is responsible for providing and maintaining the connection
to the database.
 Following are the various .NET Data Providers:

1. .NET Framework Data Provider for SQL Server.


2. .NET Framework Data Provider for Oracle.
3. .NET Framework Data Provider for OLE DB.
4. .NET Framework Data Provider for ODBC.
5. The .NET Framework Data Provider for SQL Server uses its own protocol to communicate
with SQL server. The classes for this provider are located in System.Data.SqlClient
namespace.
6. Each Data Provider provides the following core objects:
A. Connection
B. Command
C. Data Reader
D. Data Adapter
A. Connection:

o This is the object that allows you to establish a connection with the data source.
o Depending on the actual .NET Data Provider involved, connection objects
automatically pool physical databases connections for you.
o Examples of connection objects are OleDbConnection, SqlConnection,
OracleConnection and so on.
B. Command:

o This object represents an executable command on the underlying data source. The
command may or may not return any results. These commands can be used to
manipulate existing data.
o In addition, the commands can be used to manipulate underlying table structures.
o Examples of command objects are SqlCommand, OracleCommand and so on. A
Command needs to be able to accept parameters. The Parameter object of
ADO.NET allows commands to be more flexible and accept input values and act
accordingly.
C. Data Reader:

o This object is designed to help you retrieve and examine the rows returned by the
query as quickly as possible.
o DataReader object examines the results of a query one row at a time. When you
move forward to the next row, the contents of the previous row are discarded.
o The DataReader doesn’t support updating. The data returned by the DataReader is
read- only. Because the DataReader object supports such a minimal set of features,
it is extremely fast and lightweight.
o The disadvantage of using a DataReader object is that it requires an open
database connection and increases network activity.
D. DataAdapter:
o This object acts a gateway between the disconnected and connected flavours of
ADO.NET. The architecture of ADO.NET, in which connection must be opened to
access the data retrieved from the database is called as connected architecture
whereas as in a disconnected architecture data retrieved from database can be
accessed by holding it in a memory with the help of DataSet object even when the
connection is closed.
o Examples of DataAdapters are SqlDataAdapter, OracleDataAdapter and so on. It
has commands like Select, Insert, Update and Delete .
o Select command is used to retrieve data from the database and insert, update and
delete commands are used to send changes to the data in dataset to database.
DataSet :

 It is an in-memory cache of data retrieved from the data source. Data is organized into
multiple tables using DataTable objects, tables can be related using DataRelation objects
and data integrity can be enforced using the constraint objects like UnqueConstraint and
ForeignKeyConstraint.
 DataSet are also fully XML-featured. They contain methods such as GetXML and
WriteXML that respectively produce and comsume XML data easily.
 The DataSet object provides a consistent programming model that works with all the
current models of data storage: flat, relational and hierarchial.
 Another feature of DataSet is that it tracks changes that are made to the data it holds
before updating the source data.

1. DataTable : A DataSet object is made up of a collection of tables, relationships, and


constraints. In ADO.NET, DataTable objects are used to represent the tables in a DataSet
object.
2. DataColumn : Each DataTable object has a Columns collection, which is a container
for DataColumn objects. A DataColumn object corresponds to a column in a table.
3. DataRow : To access the actual values stored in a DataTable object, use the object’s
Rows collection, which contains a series of DataRow objects.
4. DataView : Once we have retrieved the results of a query into a DataTable object, we can
use a DataView object to view the data in different ways. In order to sort the content of
the DataTable object based on a column, simply set the DataView object’s Sort property to
the name of that column. Similarly the Filter property of the DataView can be used so that
only the rows that match certain criteria are visible.
5. DataRelation : A DataSet, like a database, might contain various interrelated tables. A
DataRelation object lets you specify relations between various tables that allow you
to both validate data across tables and browse parent and child rows in various Data
Tables.

ADO .NET Data Access


In the previous unit, we discussed the data base connectivity and VB .NET support for the data
access. We explored the role of connection how to create a connection, establish a connection and
close the same after use. We learn to phrase question using SQL to fetch data from the data base.
The support from data set and data adapter while accessing the database.
In this unit we will be discussing the ADO .NET in data base access. Manipulation of data means
adding, deleting and updating of data in the database also we are going to explore the navigation
methods to browse through the data bases. This unit is also discussing the ADO
.NET support with SQL server and the data binding technology with the controls.
Objectives:
After studying this unit, you will be able to:
 write the code to navigate the records
 discuss the add, update and delete operations of data.
 explain the class available with SQL Ado.NET
 discuss the technique of data binding with the controls

Record Navigation
Recording navigation is nothing but the moving of control across the database to view the
record. Generally navigation in any database is possible with the four operations they are,
move next, move previous, mover first and move last.

(i) Move Back One Record at a Time


To move backwards through the DataSet, we need to decrement the inc counter. This means deducting 1
from whatever is currently in inc.

But we also need to check that inc does not go past zero, which is the first record in the
DataSet. Here's the code to add to your btnPrevious

If inc > 0 Then inc = inc - 1


NavigateRecords() Else
MsgBox(‘First Record’) End If
So the If statement first checks that inc is greater than zero. If it is, inc gets 1 deducted from. Then
the NavigateRecords() subroutine gets called. If inc is zero or less, then we display a message.
When you have finished adding the code, you can test your program for output. Click the
Previous button first. The message box should display, even though no records have been loaded
into the textboxes. This is because the variable inc has a value of -1 when the form first loads. It
only gets moved on to zero when the Next button is clicked. You could amend your IF Statement
to this:
If inc > 0 Then inc = inc - 1 NavigateRecords()
ElseIf inc = -1 Then

MsgBox("No Records Yet") ElseIf inc = 0


Then MsgBox(‘First Record’) End If

This new If Statement now checks to see if inc is equal to minus 1, and displays a message if it
does. It also checks if inc is equal to zero, and displays the First Record message box.
(ii) Moving to the Last Record in the DataSet
To jump to the last record in the DataSet, you only need to know how many records have been
loaded into the DataSet - the MaxRows variable in our code. You can then set the inc counter to
that value, but minus 1. Here's the code to add to your btnLast:
If inc <> MaxRows - 1 Then inc = MaxRows
- 1 NavigateRecords()

End If

The reason we're saying MaxRows - 1 is that the row count might be 5, say, but the first record
in the DataSet starts at zero. So the total number of records would be zero to 4. Inside of the If
Statement, we're setting the inc counter to MaxRows - 1, then calling the NavigateRecords()
subroutine.
That's all we need to do. So run your program. Click the Last button, and you should see the last
record displayed in your textboxes.
(iii) Moving to the First Record in the DataSet
Moving to the first record is fairly straightforward. We only need to set the inc counter to zero, if
it's not already at that value. Then call the Sub:
If inc <> 0 Then inc = 0
NavigateRecords() End If

Add the code to your btnFirst. Run your program and test out all of your buttons. You should be
able to move through the names in the database, and jump to the first and last records.
As yet, though, we don't have a way to add new records, to update records, or to delete them. Let's do that
next.

Add, Update and Delete Records


In the previous section, you learned how to move through the records in your DataSet, and how to display
the records in Textboxes on your form. We also see how to add new records, how to delete them and how
to Update a records.
Before we start the coding for these new buttons, it's important to understand that the DataSet is
disconnected from the database. What this means is that if you're adding a new record, you're
not adding it to the database: you're adding it to the DataSet Similarly, if you're updating or
Deleting, you doing it to the DataSet, and NOT to the database. After you have made all of your
changes, you THEN commit these changes to the database. You do this by issuing a separate
command. But we'll see how it all works.
You will need to add a few more buttons to your form - five of them. Change the Name
properties of the new Buttons to the following:

btnAddNew

btnCommit

btnUpdate

btnDelete

btnClear

Change the Text properties of the buttons to "Add New Record ", "Commit Changes", "Update
Record ", "Delete Record", and "Clear/Cancel". Your form might look as depicted in figure 9.1.

Form design with updating controls

Updating record
To reference a particular column (item) in a row of the DataSet, the code is this:
ds.Tables("AddressBook").Rows(2).Item(1)
This will retrieve the data available from Item 1 on Row 2. You can also
set a value with the following syntax
ds.Tables("AddressBook").Rows(2).Item(1) = "Jane"

Now Item 1 Row 2 will consist of text "Jane". This will not affect the database. The alterations will
happen only in DataSet. To demonstrate this, enter the code to your btnUpdate

ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text
MsgBox("Data updated")
Execute your application, and click the Next Record button to move to the first record. "John"
should be displayed in your first textbox, and "Smith" in the second textbox. Click inside the
textboxes and change "John" to "Joan" and "Smith" to "Smithy". Now you can click your Update
Record button. Move to the next record by clicking your Next Record button, and then move
back to the first record. You should see that the first record is now "Joan Smithy".
Close the application and run it again. Click the Next Record button to move to the first record.
It will still be "John Smith". The data you updated has been lost: it is because
Changes are made to the DataSet, and NOT to the Database
You require some extra code In order to update the database,.
Dim cb As New OleDb.OleDbCommandBuilder(da)
ds.Tables("AddressBook").Rows(inc).Item(1) = txtFirstName.Text
ds.Tables("AddressBook").Rows(inc).Item(2) = txtSurname.Text

da.Update(ds, "AddressBook") MsgBox("Data updated")

The first new line is this:


Dim cb As New OleDb.OleDbCommandBuilder(da)

To update the database itself, you need something called a Command Builder. The Command
Builder will build a SQL string for you. In between round brackets, you type the name of your
Data Adapter, da in our case. The command builder is then stored in a variable, which we have
called cb.
The second new line is where the action is:
da.Update(ds, "AddressBook")

The da variable is holding our Data Adapter. One of the methods of the Data Adapter is Update.
In between the round brackets, you need the name of your DataSet (ds, for us). The AddressBook
part is optional. It's what we've called our DataSet, and is here to avoid any confusion.
But the Data Adapter will then contact the database. Because we have a Command Builder, the
Data Adapter can then update your database with the values from the DataSet.
Without the Command Builder, though, the Data Adapter can't do it's job. Try this. Comment out
the Command Builder line (put a single quote before the D of Dim). Run your program again, and
then try and update a record. You'll get this error message as shown in figure .
Error Message

The error is because you have not got a command builder - a Valid Update Command. Delete the
comment from your Command Builder line and the error message goes away. You should now be
able to make changes to the database itself (as long as the Access database isn't Read Only).

Try it out. Run your program, and change one of the records. Click the Update button. Then close the
program
down, and load it up again. You should see your new changes displayed in the textboxes.
Adding a new record
Adding a new record is slightly more complex. First, you have to add a new Row to the DataSet,
then commit the new Row to the Database.

But the Add New Record button on our form is quite simple. The only thing it does is to switch
off other buttons, and clear the textboxes, ready for a new entry. Here's the code for your Add
New Record button:
btnCommit.Enabled = True btnAddNew.Enabled
= False btnUpdate.Enabled = False
btnDelete.Enabled = False txtFirstName.Clear()
txtSurname.Clear()
So three buttons are switched off when the Add New Record button is clicked, and one is
switched on. The button that gets switched on is the Commit Changes button. The Enabled
property of btnCommit gets set to True. But, for this to work, you need to set it to False when
the form loads. So return to your Form. Click btnCommit to select it. Then locate the Enabled
Property in the Properties box. Set it to False. When the Form starts up, the button will be
switched off.
The Clear/Cancel button can be used to switch it back on again. So add this code to your btnClear:

btnCommit.Enabled = False btnAddNew.Enabled = True


btnUpdate.Enabled = True btnDelete.Enabled

= True inc = 0
NavigateRecords()
We're switching the Commit Changes button off, and the other three back on. The other two lines
just make sure that we display the first record again, after the Cancel button is clicked. Otherwise
the textboxes will all be blank.
To add a new record to the database, we'll use the Commit Changes button. So double click
your
btnCommit to access its code. Add the following:
If inc <> -1 Then
Dim cb As New OleDb.OleDbCommandBuilder(da) Dim dsNewRow As DataRow

dsNewRow = ds.Tables("AddressBook").NewRow() dsNewRow.Item("FirstName") =


txtFirstName.Text dsNewRow.Item("Surname") = txtSurname.Text
ds.Tables("AddressBook").Rows.Add(dsNewRow) da.Update(ds, "AddressBook")
MsgBox("New Record added to the Database") btnCommit.Enabled
= False btnAddNew.Enabled = True btnUpdate.Enabled =

True btnDelete.Enabled = True End If

The code is somewhat longer than usual, but we'll go through it.

The first line is an If Statement. We're just checking that there is a valid record to add. If there's
not, the inc variable will be on minus 1. Inside of the If Statement, we first set up a Command
Builder, as before. The next line is this:
Dim dsNewRow As DataRow

If you want to add a new row to your DataSet, you need a DataRow object. This line just sets up a variable
called
dsNewRow. The type of variable is a DataRow.
To create the new DataRow object, this line comes next: dsNewRow =
ds.Tables("AddressBook").NewRow()

We're just saying, Create a New Row object in the AddressBook DataSet, and store this in the
variable called dsNewRow. As you can see, NewRow() is a method of ds.Tables. Use this method
to add rows to your DataSet.
The actual values we want to store in the rows are coming from the textboxes. So we have these two lines:
dsNewRow.Item("FirstName") = txtFirstName.Text
dsNewRow.Item("Surname") = txtSurname.Text

The dsNewRow object we created has a Property called Item. This is like the Item property you
used earlier. It represents a column in your DataSet. We could have said this instead:
dsNewRow.Item(1) =
txtFirstName.Text
dsNewRow.Item(2) =
txtSurname.Text
The Item property is now using the index number of the DataSet columns, rather than the names.
The results is the same, though: to store new values in these properties. We're storing the text
from the textboxes to our new Row

We now only need to call the Method that actually adds the Row to the DataSet:
ds.Tables(‘AddressBook’).Rows.Add(dsNewRow)

To add the Row, you use the Add method of the Rows property of the DataSet. In between the
round brackets, you need the name of your DataRow (the variable dsNewRow, in our case).
You should know what the rest of the code does. Here's the next line:
da.Update(ds, "AddressBook")

Again, we're just using the Update method of the Data Adapter, just like last time. The rest of the
code just displays a message box, and resets the button.
But to add a new Row to a DataSet, here's a recap on what to do:
 Create a DataRow variable
 Create an Object from this variable by using the NewRow() method of the DataSet Tables
property
 Assign values to the Items in the new Row
 Use the Add method of the DataSet to add the new row

A little more complicated, but it does work Try your program out. Click your Add New Record
button. The textboxes should go blank, and three of the buttons will be switched off. Enter a new
First Name and Surname, and then
click the Commit Changes button. You should see the message box telling you that a new record
has been added to the database. To see the new record, close down your program, and run it
again. The new record will be there.
Deleting a record
The code to delete a record is a little easier than last time. Double click your btnDelete and add the
following:

Dim cb As New OleDb.OleDbCommandBuilder(da) ds.Tables("AddressBook").Rows(inc).Delete()


MaxRows = MaxRows - 1

inc = 0 NavigateRecords()
da.Update(ds, "AddressBook")
Here you should first set up a Command Builder. Then we have this line:
ds.Tables("AddressBook").Rows(inc).Delete()

Just as there is an Add method of the DataSet Rows property, so there is a Delete method. You
don't need anything between the round brackets, this time. We've specified the Row to delete
with:
Rows(inc)

The inc variable is setting which particular Row we're on. When the Delete method is called, it
is this row that will be deleted.
However, it will only be deleted from the DataSet. To delete the row from the underlying
database, we have this again:
da.Update(ds, "AddressBook")

The Command Builder, in conjunction with the Data Adapter, will take care of the deleting. All you
need to is call the Update method of the Data Adapter.
The MaxRows line in the code just deducts 1 from the variable. This just ensures that the
number of rows in the DataSet matches the number we have in the MaxRows variable.
We also reset the inc variable to zero, and call the NavigateRecords() subroutine. This will
mean that the first record is displayed, after a record has been deleted.
Try out your program. Click the Next Record button a few times to move to a valid record. Then
click the Delete Record button. The record will be deleted from the DataSet AND the database.
The record that is then displayed will be the first one.
There's another problem, though: if you click the Delete Record button before the Next Record
button, you'll get an error message. You can add an If Statement to check that the inc variable does
not equal minus 1.
Another thing you can do is to display a message box asking users if they really want to delete this
record as shown in figure 9.3.

Fig. 9.3: Delete confirmation window


To get this in your own programme, add the following code to the very top of your Delete button code:
If MessageBox.Show("Do you really want to Delete this Record?", _
"Delete", MessageBoxButtons.YesNo, _ MessageBoxIcon.Warning) =
DialogResult.No Then

MsgBox("Operation Cancelled") Exit

Sub End If

The first three lines of the code are really one line. The underscore has been used to spread it out,
so as to fit on this page.
But we're using the new message box function:
MessageBox.Show()

In between the round brackets, we specifying the message to display, followed by a caption for
the message box. We then have this:
MessageBoxButtons.YesNo

You won't have to type all that out; you'll be able to select it from a popup list. But what it does is
give you Yes and No buttons on your message box.

After typing a comma, we selected the MessageBoxIcon. Warning icon from the popup list. But you need
to
check which button the user clicked. This is done with this:
= DialogResult.No

Again, you select from a popup list. We want to check if the user clicked the No button. This will
mean a change of mind from the user. A value of No will then be returned, which is what we're
checking for in the If Statement.
The code for the If Statement itself is this:
MsgBox(‘Operation Cancelled’) Exit Sub
This will display another message for the user. But most importantly, the subroutine will be
exited: we don't want the rest of the Delete code to be executed, if the user clicked the No button.
And that's it for our introduction to database programming. You not only saw how to construct a
database program using the Wizard, but how to write code to do this yourself. There is an awful
lot more to database programming, and we've just scratched the surface. But in a beginner's
course, that's all we have time for.

SQL Server and ADO .NET


Now we are going to discuss the behavior and features that are related to ADO .NET data
provider for SQL server. The basic root namespace for
.NET is the System.Data. This supports the DataTable and DataSet objects to work with any data
type. Apart from this .Net supports two more namespaces for retrieving or accessing the data.

System.Data.OleDb: Supports OLE DB data source such as Oracle, Jet etc. This name space
includes OleDbCommand, OleDbDataReader, OleDbConnection and OleDbDataAdapter. Using
these object we accessed database, that we discussed in the last unit
System.Data.SqlClient: it supports with SQL server 6.5 and above versions. Includes
SqlCommand, SqlConnection, SqlDataAdapter and SqlDataReader objects.
SQL Connection class
SqlConnection class cannot be inherited and establish an open connection towards the SQL server
database. Public NotInheritable Class SqlConnection _
Inherits
DbConnection _
Implements
ICloneable

Has the SqlConnection constructor that initializes the instantiation of the SqlConnection class.
This constructor also accepts the connection string to establish a connection.
This class has methods that supports the database transitions like BeginTransaction,
changeDatabase, CreateCommand, GetSchema, GetType etc. Following are the list of events
supported by the SslConnection Such as Disposed, InfoMessage and StateChange.
SQLDataAdapter

The DataAdapter is an interface between the database and the dataset. It is located between the
connected and disconnected parts of Ado.Net as a connector. DataAdapter class will be
instantiated by the constructor that are generally overloaded. If we use the default constructor
for the DataAdapter, we need to specify the Command object for the actions performed. This
means that if we want to retrieve rows from the Data Source, we will have to set the Select
command property.
The DataAdapter class is not inheritable Declaration is
Punlic NotInheritable Class SqlDataAdapter Inherits DbDataAdapter_
Implements IDbDataAdapter, IDataAdapter,ICloneable
DataSet class
DataSet class consists of information about the set of tables and the relation among those set of
tables. Figure 9.4 depicts the DataSet and its related classes. DataSet will not have any idea about
the data source or the tables. This will be created dynamically whenever required based on the
data source. In SQL server provider, DataSet will be loaded with the help of SqlDataAdapter. Once
the data is loaded it is editable and we can manipulate the data without disturbing the data
source. Even the data base connectivity is not necessary for this action. When the process is over
we can create a new connection and update using the SqlDataAdapter object.

Model diagram for DataSet and related classes.

SQL Basics:

What is SQL used for?


Here are important reasons for using SQL

 It helps users to access data in the RDBMS system.


 It helps you to describe the data.
 It allows you to define the data in a database and manipulate that specific data.
 With the help of SQL, you can create and drop databases and tables.
 SQL offers you to use the function in a database, create a view, and stored procedure.
 You can set permissions on tables, procedures, and views.
A Brief History of SQL
Here are important landmarks from the history of SQL:

 1970 – Dr. Edgar F. “Ted” Codd described a relational model for databases.
 1974 – Structured Query Language appeared.
 1978 – IBM released a product called System/R.
 1986 – IBM developed the prototype of a relational database, which is standardized by
ANSI.
 1989 – First ever version launched of SQL
 1999 – SQL 3 launched with features like triggers, object-orientation, etc.
 SQL 2003 – window functions, XML-related features, etc.
 SQL 2006 – Support for XML Query Language
 SQL 2011 -improved support for temporal databases

Types of SQL Statements


Here are five types of widely used SQL queries.

 Data Definition Language (DDL)


 Data Manipulation Language (DML)
 Data Control Language (DCL)
 Transaction Control Language (TCL)
 Data Query Language (DQL)

List of SQL Commands


Here’s a list of some of the most commonly used SQL commands:

 CREATE – defines the database structure schema


 INSERT – inserts data into the row of a table
 UPDATE – updates data in a database
 DELETE – removes one or more rows from a table
 SELECT – selects the attribute based on the condition described by the WHERE clause
 DROP – removes tables and databases

SQL Process
When you want to execute an SQL command for any DBMS system, you need to find the best
method to carry out your request, and SQL engine determines how to interpret that specific task.

Important components included in this SQL process are:

 SQL Query Engine


 Optimization Engines
 Query Dispatcher
 Classic Query Engine

A classic query engine allows you to manage all the non-SQL queries.

SQL Process
SQL Commands

The standard SQL commands to interact with relational databases are CREATE, SELECT, INSERT,
UPDATE, DELETE and DROP. These commands can be classified into the following groups based
on their nature −

DDL - Data Definition Language

Sr.No Command &


. Description

CREATE
1
Creates a new table, a view of a table, or other object in the database.

ALTER
2
Modifies an existing database object, such as a table.
DROP
3 Deletes an entire table, a view of a table or other objects in the database.

DML - Data Manipulation Language

Sr.No Command &


. Description

1 SELECT
Retrieves certain records from one or more tables.

2 INSERT
Creates a record.

3 UPDATE
Modifies records.

4 DELETE
Deletes records.

DCL - Data Control Language

Sr.No Command &


. Description

1 GRANT
Gives a privilege to user.

2 REVOKE
Takes back privileges granted from user.

SELECT
The SQL SELECT statement is used to fetch the data from a database table which returns this data
in the form of a result table. These result tables are called result-sets.

Syntax
The basic syntax of the SELECT statement is as follows −
SELECT column1, column2, columnN FROM table_name;
Here, column1, column2... are the fields of a table whose values you want to fetch. If you want to
fetch all the fields available in the field, then you can use the following syntax.
SELECT * FROM table_name;

Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

The following code is an example, which would fetch the ID, Name and Salary fields of the
customers available in CUSTOMERS table.

SQL> SELECT ID, NAME, SALARY FROM CUSTOMERS;

This would produce the following result −


+ + + +
| ID | NAME | SALARY |
+ + + +
| 1 | Ramesh | 2000.00 |
| 2 | Khilan | 1500.00 |
| 3 | kaushik | 2000.00 |
| 4 | Chaitali | 6500.00 |
| 5 | Hardik | 8500.00 |
| 6 | Komal | 4500.00 |
| 7 | Muffy | 10000.00 |
+ + + +
If you want to fetch all the fields of the CUSTOMERS table, then you should use the following query.

SQL> SELECT * FROM CUSTOMERS;

This would produce the result as shown below.


+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

INSERT INTO

The SQL INSERT INTO Statement is used to add new rows of data to a table in the database.

Syntax
There are two basic syntaxes of the INSERT INTO statement which are shown below.
INSERT INTO TABLE_NAME (column1, column2, column3,...columnN)
VALUES (value1, value2, value3,...valueN);
Here, column1, column2, column3,...columnN are the names of the columns in the table into which
you want to insert the data.
You may not need to specify the column(s) name in the SQL query if you are adding values for all
the columns of the table. But make sure the order of the values is in the same order as the columns
in the table.
The SQL INSERT INTO syntax will be as follows −
INSERT INTO TABLE_NAME VALUES (value1,value2,value3,...valueN);

Example
The following statements would create six records in the CUSTOMERS table.
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)
VALUES (1, 'Ramesh', 32, 'Ahmedabad', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (2, 'Khilan', 25, 'Delhi', 1500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (3, 'kaushik', 23, 'Kota', 2000.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (4, 'Chaitali', 25, 'Mumbai', 6500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (5, 'Hardik', 27, 'Bhopal', 8500.00 );

INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY)


VALUES (6, 'Komal', 22, 'MP', 4500.00 );

You can create a record in the CUSTOMERS table by using the second syntax as shown below.
INSERT INTO CUSTOMERS
VALUES (7, 'Muffy', 24, 'Indore', 10000.00 );
All the above statements would produce the following records in the CUSTOMERS table as shown below.
++ +++ +
| ID | NAME | AGE | ADDRESS | SALARY |
++ +++ +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi| 1500.00 |
| 3 | kaushik | 23 | Kota| 2000.00 |
| 4 | Chaitali | 25 | Mumbai| 6500.00 |
| 5 | Hardik | 27 | Bhopal| 8500.00 |
| 6 | Komal| 22 | MP| 4500.00 |
| 7 | Muffy| 24 | Indore| 10000.00 |
+ ++ + ++

Populate one table using another table


You can populate the data into a table through the select statement over another table; provided
the other table has a set of fields, which are required to populate the first table.
Here is the syntax −
INSERT INTO first_table_name [(column1, column2, ...
columnN)] SELECT column1, column2, ...columnN
FROM second_table_name
[WHERE condition];

UPDATE
The SQL UPDATE Query is used to modify the existing records in a table. You can use the WHERE
clause with the UPDATE query to update the selected rows, otherwise all the rows would be
affected.

Syntax
The basic syntax of the UPDATE query with a WHERE clause is as follows −
UPDATE table_name
SET column1 = value1, column2 = value2. , columnN = valueN
WHERE [condition];
You can combine N number of conditions using the AND or the OR operators.

Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +

The following query will update the ADDRESS for a customer whose ID number is 6 in the table.
SQL> UPDATE CUSTOMERS

SET ADDRESS = 'Pune' WHERE ID = 6;

Now, the CUSTOMERS table would have the following records −


+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | Pune | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
If you want to modify all the ADDRESS and the SALARY column values in the CUSTOMERS table,
you do not need to use the WHERE clause as the UPDATE query would be enough as shown in the
following code block.
SQL> UPDATE CUSTOMERS
SET ADDRESS = 'Pune', SALARY = 1000.00;

Now, CUSTOMERS table would have the following records −


+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Pune | 1000.00 |
| 2 | Khilan | 25 | Pune| 1000.00 |
| 3 | kaushik | 23 | Pune | 1000.00 |
| 4 | Chaitali | 25 | Pune | 1000.00 |
| 5 | Hardik | 27 | Pune | 1000.00 |
| 6 | Komal | 22 | Pune | 1000.00 |
| 7 | Muffy | 24 | Pune | 1000.00 |

DELETE

The SQL DELETE Query is used to delete the existing records from a table.
You can use the WHERE clause with a DELETE query to delete the selected rows, otherwise all the
records would be deleted.

Syntax
The basic syntax of the DELETE query with the WHERE clause is as follows −
DELETE FROM table_name
WHERE [condition];
You can combine N number of conditions using AND or OR operators.

Example
Consider the CUSTOMERS table having the following records −
+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
The following code has a query, which will DELETE a customer, whose ID is 6.
SQL> DELETE FROM CUSTOMERS
WHERE ID = 6;

Now, the CUSTOMERS table would have the following records.


+ + + + + +
| ID | NAME | AGE | ADDRESS | SALARY |
+ + + + + +
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 7 | Muffy | 24 | Indore | 10000.00 |
+ + + + + +
If you want to DELETE all the records from the CUSTOMERS table, you do not need to use the
WHERE clause and the DELETE query would be as follows −

SQL> DELETE FROM CUSTOMERS;


Now, the CUSTOMERS table would not have any record.
ADO.NET Architecture

Connected and Disconnected Architectures

The following figure shows how to work with the connected and disconnected architectures.
Connected Architecture

1. In the connected architecture, connection with a data source is kept open constantly for
data access as well as data manipulation operations.
2. The ADO.NET Connected architecture considers mainly three types of objects.

o SqlConnection con;
o SqlCommand cmd;
o SqlDataReader dr;

Disconnected Architecture

1. Disconnected is the main feature of the .NET framework. ADO.NET contains various classes
that support this architecture. The .NET application does not always stay connected with
the database. The classes are designed in a way that they automatically open and close the
connection. The data is stored client-side and is updated in the database whenever
required.
2. The ADO.NET Disconnected architecture considers primarily the following types of objects:

o DataSet ds;
o SqlDataAdapter da;
o SqlConnection con;
o SqlCommandBuilder bldr;
1. Connection Object and Connection string
Connection Object

1. One of the first ADO.NET objects is the connection object, that allows you to establish a
connection to a data source.
2. The connection objects have the methods for opening and closing connections, for
beginning a transaction of data.
3. The .Net Framework provides two types of connection classes:
The sqlconnection object, that is designed specially to connect to Microsoft SQL Server
and the OleDbConnection object, that is designed to provide connection to a wide range
of databases, such as Microsoft Access and Oracle.
4. A connection is required to interact with the database. A Connection object helps to
identify the database server name, user name and password to connect to the database.
The Connection object is used by commands on the database.
5. A Connection object has the responsibility of establishing a connection with the data store.
6. How to use the Sqlconnection object:
o Instantiate the SqlConnection class.
o Open connection.
o Pass the connection to ADO.NET objects.
o Perform the database operations with ADO.NET object.
o Close the connection.

Connection String
Connection String
No Description
Parameter Name
.
Identify the server. Could be a local machine, machine domain
1 Data Source
name, or IP Address.
2 Initial Catalog Data base name.

3 Integrated Security Set to SSIP to make a connection with the user's window log in.
4 User ID Name of user configured in SQL Server.

5 Password Password matching SQL Server User ID

The connection string is different for each of the various data providers available in .NET 2.0.
There are different connection strings for the various types of data sources. You can find a list of all
the available providers for creating a connection in a table:

No Provider Description

1 System.Data.SqlClient Provides data for Microsoft SQL Server

2 System.Data.OleDb Provides data access for data sources exposed using OLE DB
3 System.Data.Odbc Provides data access for data source exposed using ODBC.

4 System.Data.OracleClient Provides data access for Oracle.

Example

1. SqlConnection con;
2. con = new SqlConnection("Server=Krushna;Database=Anagha;Uid=sa;Pwd=sa"

2. Command Object
 A Command object executes SQL statements on the database. These SQL statements can
be SELECT, INSERT, UPDATE, or DELETE. It uses a connection object to perform these
actions on the database.
 A Connection object specifies the type of interaction to perform with the database, like
SELECT, INSERT, UPDATE, or DELETE.
 A Command object is used to perform various types of operations, like SELECT, INSERT,
UPDATE, or DELETE on the database.
 SELECT
1. cmd =new SqlCommand("select * from Employee", con);
 INSERT
1. cmd = new SqlCommand("INSERT INTO Employee(Emp_ID,
2. Emp_Name)VALUES ('" + aa + "','" + bb + "')", con);
 UPDATE
1. SqlCommand cmd =new SqlCommand("UPDATE Employee SET
2. Emp_ID ='" + aa + "', Emp_Name ='" + bb + "' WHERE
3. Emp_ID = '" + aa + "'", con);
 DELETE
1. cmd =new SqlCommand("DELETE FROM Employee where
2. Emp_ID='" + aa + "'", con);
 A Command object exposes several execute methods like:
1. ExecuteScaler()
Executes the query, and returns the first column of the first row in the result set
returned by the query. Extra columns or rows are ignored.
2. ExecuteReader()
Display all columns and all rows in the client-side
environment. In other words, we can say that they
display datatables client-side.
3. ExecuteNonQuery()
Something is done by the database but nothing is returned by the database.

3. Data Reader Object


A DataReader object is used to obtain the results of a SELECT statement from a command
object. For performance reasons, the data returned from a data reader is a forward-only stream
of data. This means that the data can be accessed from the stream in a sequential manner. This
is good for speed, but if data needs to be manipulated then a dataset is a better object to work
with.

Example

1. dr = cmd.ExecuteReader();
2. DataTable dt = new DataTable();
3. dt.Load(dr);
 It is used in Connected architecture.
 Provide better performance.
 DataReader Object has Read-only access.
 DataReader Object Supports a single table based on a single SQL query of one database.
 While DataReader Object is Bind to a single control.
 DataReader Object has Faster access to data.
 DataReader Object Must be manually coded.
 we can't create a relation in the data reader.
 whereas Data reader doesn't support.
 The data reader communicates with the command object.
 DataReader can not modify data.

4. Data Adapter Object

 A Data Adapter represents a set of data commands and a database connection to fill the
dataset and update a SQL Server database.
 A Data Adapter contains a set of data commands and a database connection to fill the
dataset and update a SQL Server database. Data Adapters form the bridge between a data
source and a dataset.
 Data Adapters are designed depending on the specific data source. The following table
shows the Data Adapter classes with their data source.

Provider-Specific Data Adapter classes Data Source


SqlDataAdapter SQL Server

OledbDataAdapter OLE DB provider

OdbcDataAdapter ODBC driver


OracleDataAdapter Oracle

Provider-Specific Data Adapter

classes Data Source

 A Data Adapter object accesses data in a disconnected mode. Its object contains a
reference to a connection object.
 It is designed in a way that implicitly opens and closes the connection whenever required.
 It maintains the data in a DataSet object. The user can read the data if required from the
dataset and write back the changes in a single batch to the database. Additionally, the Data
Adapter contains a command object reference for SELECT, INSERT, UPDATE, and DELETE
operations on the data objects and a data source.
 A Data Adapter supports mainly the following two methods:
o Fill ()
The Fill method populates a dataset or a data table object with data from the
database. It retrieves rows from the data source using the SELECT statement specified
by an associated select command property.
The Fill method leaves the connection in the same state as it encountered it before
populating the data. If subsequent calls to the method for refreshing the data are
required then the primary key information should be present.
o Update ()
The Update method commits the changes back to the database. It also analyzes the
RowState of each record in the DataSet and calls the appriopriate INSERT,
UPDATE, and DELETE statements.
A Data Adapter object is formed between a disconnected ADO.NET object and a data source.
Example

1. SqlDataAdapter da=new SqlDataAdapter("Select * from Employee", con);


2. da.Fill(ds,"Emp");
3. bldr =new SqlCommandBuilder(da);
4. dataGridView1.DataSource = ds.Tables["Emp"];
5. DataSet Object

 In the disconnected scenario, the data retrieved from the database is stored in a local buffer
called DataSet. It is explicitly designed to access data from any data source. This class is
defined in the System.Data namespace.
 A Data Set object is an in-memory representation of the data. It is specially designed to
manage data in memory and to support disconnected operations on data.
 A Data Set is a collection of DataTable and DataRelations. Each DataTable is a collection of
DataColumn, DataRows, and Constraints.
 A DataTable, DataColumn, and DataRows could be created as follows.

Example
1. DataTable dt = new DataTable();
2. DataColumn col =new DataColumn();
3. Dt.columns.Add(col2);
4. DataRow row = dt.newRow();

 It is used in a disconnected architecture.


 Provides lower performance.
 A DataSet object has read/write access.
 A DataSet object supports multiple tables from various databases.
 A DataSet object is bound to multiple controls.
 A DataSet object has slower access to data.
 A DataSet object is supported by Visual Studio tools.
 We can create relations in a dataset.
 A Dataset supports integration with XML.
 A DataSet communicates with the Data Adapter only.
 A DataSet can modify data.

6. Command Builder Object

 Automatically generates insert, update, delete queries using the SelectCommand


property of a DataAdapter.
 A Command Builder Object is used to build commands for data modification from objects
based on a single table query. CommandBuilders are designed depending on the specific
data source. The following table shows the CommandBuilder classes with their data
source.
Provider-Specific Data Adapter classes Data Source
SqlDataAdapter SQL Server

OledbDataAdapter OLE DB provider


OdbcDataAdapter ODBC driver

OracleDataAdapter Oracle

Example

1. da = new SqlDataAdapter("Select * from Employee", con);


2. ds = new DataSet();
3. da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
4. da.Fill(ds, "Emp");
5. bldr = new SqlCommandBuilder(da);
6. dataGridView1.DataSource = ds.Tables["Emp"];

Differences Between DataReader and DataSet

N Data Reader DataSet


o
1 Used in a connected architecture used in a disconnected architecture

2 Provides better performance Provides lower performance


3 DataReader object has read-only access A DataSet object has read/write access

DataReader object supports a single table A DataSet object supports multiple tables from
4
based on a single SQL query of one database various databases
5 A DataReader object is bound to a single A DataSet object is bound to multiple controls
control
6 A DataReader object has faster access to data A DataSet object has slower access to data

7 A DataReader object must be manually coded A DataSet object is supported by Visual Studio
tools
8 We can't create a relation in a data reader We can create relations in a dataset
Whereas a DataReader doesn't support data A Dataset supports integration with XML
9
reader communicates with the command Dataset communicates with the Data Adapter
object. only
1 DataReader cannot modify data A DataSet can modify data
0

4: DataView Object

 A DataView is the same as a read-only mini-dataset.


 You typically load only a subset into a DataView.
 A DataView provides a dynamic view of data. It provides a datarow using the DataView.
Example
Add two buttons and a DataGridView control. Change the text of the first button to sort by
city and that of button2 to only select records in Mexico and add the code in form.cs.
Form Design

Coding Part

1. SqlConnection con;
2. SqlCommand cmd;
3. SqlDataReader dr;
4. public DataTable GetTable()
5. {
6.con = new SqlConnection("Data Source=.\\sqlexpress;Initial Catalog=information;Integrated Security= True;Pooling=Fa

7. con.Open();
8. cmd = new SqlCommand("select * from Customers", con);
9. dr = cmd.ExecuteReader();
10.DataTable dt = new DataTable();
11.dt.Load(dr);
12.dataGridView1.DataSource = dt;
13.con.Close();
14.return dt;
15. }
Form1_Load

1. dataGridView1.DataSource = GetTable().DefaultView;

ShortByCity_Click
1. DataView dv = new DataView(GetTable());
2. dv.Sort = "City ASC";
3. dataGridView1.DataSource = dv;

OnlyInMexico_Click

1. DataView dv = new DataView(GetTable());


2. dv.RowFilter = "Country = 'Mexico'";
3. dataGridView1.DataSource = dv;

 At the click of the sort by city button, the data already in the DataGridView control is sotred dy city.
 On clicking the second button, only the records in Mexico are displayed in the
DataGridView control. The output after clicking the only in Mexico button is as the Mexico
button.

Working With System.Data.SqlClient and System.Data.Oledb

Program: Design a simple Winform for accepting the details of Employee. Using the connected
architecture of ADO.NET, perform the following operations:

 Insert record.
 Search record.
 Update record.
 Delete record.

1. Form
Design 2.

3. Coding Part

Step 1: add namespace using System.Data.SqlClient;for SQL dataBase.

Step 2: Create a connection object.


1. SqlConnection con;
2. SqlCommand cmd;
3. SqlDataReader dr;

Step3: Form1_Load

4. con =new SqlConnection("Data Source=.\\sqlexpress;Initial


Catalog=information;Integrat edecurity=True;Pooling=False");
5. private void Display()
6. {
7. con.Open();
8. cmd =new SqlCommand("select * from Employee", con);
9. dr = cmd.ExecuteReader();
10. DataTable dt = new DataTable();
11. dt.Load(dr);
12. dataGridView1.DataSource = dt;
13. con.Close();
14. }

Insertbtn_Click

15. con.Open();
16. int aa = Convert.ToInt32(textBox1.Text);
17. string bb = textBox2.Text;
18. int cc = Convert.ToInt32(textBox3.Text);
19. cmd =new SqlCommand("INSERT INTO Employee(Emp_ID, Emp_Name,Salary)VALU
ES ('" + aa +"','" + bb + "','" + cc + "')", con);
20. cmd.ExecuteNonQuery();
21. MessageBox.Show("one record inserted:");
22. con.Close();
23. Display();

Deletebtn_Click

24. con.Open();
25. int aa = Convert.ToInt32(textBox1.Text);
26. cmd =new SqlCommand("DELETE FROM Employee where Emp_ID='" + aa + "'", con);

27. cmd.ExecuteNonQuery();

28. MessageBox.Show("one record Delete:");


29. con.Close();
30. Display();

Updatebtn_Click

31. con.Open();
32. int aa = Convert.ToInt32(textBox1.Text);
33. string bb = textBox2.Text;
34. int cc = Convert.ToInt32(textBox3.Text);
35. string abc = "UPDATE Employee SET Emp_ID ='" + aa + "', Emp_Name ='" + bb + "',Sa
lary ='" + cc + "' WHERE Emp_ID = '" + aa +"'";
36. SqlCommand cmd =new SqlCommand(abc, con);
37. cmd.ExecuteNonQuery();
38. MessageBox.Show("one record updated:");
39. con.Close();
40. Display();

Displaybtn_Click

41. Display();

Searchbtn_Click
42. con.Open();
43. int aa = Convert.ToInt32(textBox1.Text);
44. string abc = "SELECT Emp_ID,Emp_Name,Salary FROM Employee where Emp_ID='"
+ aa +"'";
45. cmd =new SqlCommand(abc, con);
46. MessageBox.Show("one record search:");
47. dr = cmd.ExecuteReader();
48. DataTable dt =new DataTable();
49. dt.Load(dr);
50. dataGridView1.DataSource = dt;
51. con.Close();

Totalrecordbtn_Click

52. con.Open();
53. cmd = new SqlCommand("select Count(*) from Employee", con);
54. int a = (int)cmd.ExecuteScalar();
55. label4.Text = "Total Record:--> " + a.ToString();
56. con.Close();

Exit_Click

57. Application.Exit();

Program: Design a Simple Winform for accepting the details of an Employee. Using the connected
architecture of ADO.NET, perform the following operations:

 Insert record.
 Search record.
 Update record.
 Delete record.

Form Design
Coding Part
Step 1: add namespace using System.Data.Oledb; for access Database.
Step 2: Create connection object.

1. OleDbConnection con;
2. OleDbCommand cmd;
3. OleDbDataReader dr;

Step 3: Form1_Load

1. con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\


Documents and Settings\\Admin\\Desktop\\Ado Connected Demo\\db1.mdb");
2. private void display()
3. con.Open();
4. cmd = new OleDbCommand("select * from Employee",con);
5. dr = cmd.ExecuteReader();
6. DataTable dt = new DataTable();
7. dt.Load(dr);
8. dataGridView1.DataSource = dt;
9. con.Close();

Display_Click

1. display();

Insert_Click

1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. string bb = textBox2.Text;
4. int cc = Convert.ToInt32(textBox3.Text);
5. cmd = new OleDbCommand("INSERT INTO Employee(Emp_ID, Emp_Name,Salary) VALUES
('" + aa + "','" + bb + "','" + cc + "')", con);
6. cmd.ExecuteNonQuery();
7. MessageBox.Show("one record inserted:");
8. con.Close();
9. display();

Delete_Click

1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. cmd = new OleDbCommand("DELETE FROM Employee where Emp_ID='" + aa + "'", con);
4. cmd.ExecuteNonQuery();
5. MessageBox.Show("one record Delete:");
6. con.Close();
7. display();

update_Click

1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. string bb = textBox2.Text;
4. int cc = Convert.ToInt32(textBox3.Text);
5. string abc = "UPDATE Employee SET Emp_ID ='" + aa + "', Emp_Name ='" + bb + "', Salary ='
" + cc + "' WHERE Emp_ID = '" + aa + "'";
6. OleDbCommand cmd = new OleDbCommand(abc, con);
7. cmd.ExecuteNonQuery();
8. MessageBox.Show("one record updated:");
9. con.Close();
10. display();

Find_Click

1. con.Open();
2. int aa = Convert.ToInt32(textBox1.Text);
3. string abc = "SELECT Emp_ID,Emp_Name,Salary FROM Employee where Emp_ID='" + aa + "'
";
4. cmd = new OleDbCommand(abc, con);
5. MessageBox.Show("one record search:");
6. dr = cmd.ExecuteReader();
7. DataTable dt = new DataTable();
8. dt.Load(dr);
9. dataGridView1.DataSource = dt;
10. con.Close();

Exit_Click

Application.Exit();

Program: Design a simple Winform for accepting the details of an Employee. Using the
disconnected architecture of ADO.NET, perform the following operations.

 Insert record.
 Display record.
 Update record.
 Delete record
Form Design
Coding Part

Step 1: add namespace using System.Data.SqlClient;for SQL dataBase.

Step 2: Create connection object.

1. DataSet ds;
2. SqlDataAdapter da;
3. SqlConnection con;
4. SqlCommandBuilder bldr;

Step 3: Form1_Load

1. con = new SqlConnection("Data Source=.\\sqlexpress;Initial


Catalog=information;IntegratedSecu rity=True;Pooling=False");
2. private void display()
3. da = new SqlDataAdapter("Select * from Employee", con);
4. ds = new DataSet();
5. da.MissingSchemaAction = MissingSchemaAction.AddWithKey;
6. da.Fill(ds, "Emp");
7. bldr = new SqlCommandBuilder(da);
8. dataGridView1.DataSource = ds.Tables["Emp"];

Display_Click

1. display();

Insert_Click

1. DataRow drnew = ds.Tables["Emp"].NewRow();


2. drnew[0] = textBox1.Text;
3. drnew[1] = textBox2.Text;
4. drnew[2] = textBox3.Text;
5. ds.Tables["Emp"].Rows.Add(drnew);
6. da.Update(ds, "Emp");
7. MessageBox.Show("Record added");
8. dataGridView1.DataSource = ds.Tables["Emp"];

Delete_Click

1. DataRow row = ds.Tables["Emp"].Rows.Find(Convert.ToInt32(textBox1.Text));


2. row.Delete();
3. da.Update(ds, "Emp");
4. MessageBox.Show("Record Deleted");
5. dataGridView1.DataSource = ds.Tables["Emp"];

Update_Click

1. DataRow dr = ds.Tables[0].Rows.Find(textBox1.Text);
2. dr["Emp_Name"] = textBox2.Text;
3. dr["Salary"] = textBox3.Text;
4. da.Update(ds, "Emp");
5. MessageBox.Show("updated..");
6. dataGridView1.DataSource = ds.Tables[0];

FirstRcd_Click

1. this.BindingContext[ds.Tables[0]].Position = 0;

LastRcd_Click

1. this.BindingContext[ds.Tables[0]].Position = ds.Tables[0].Rows.Count - 1;

NextRcd_Click

1. if (this.BindingContext[ds.Tables[0]].Position > 0)
2. {
3. this.BindingContext[ds.Tables[0]].Position -= 1;
4. }

PreviousRcd_Click

1. if (this.BindingContext[ds.Tables[0]].Position < ds.Tables[0].Rows.Count -


1)
2. {
3. this.BindingContext[ds.Tables[0]].Position += 1;
4. }

Data Binding in ADO.NET


The user can bind values to the respective controls in ADO.NET. Depending on the type of binding
offered, they are distinguished as follows:

1. Simple Data Binding


2. Complex Data Binding

1. Simple Data Binding


The Simple Data Binding is the process of binding the control with the single value in the dataset.
The controls like text box, label can be bound to the control through the control properties.

Consider an example to display the result of the students in an examination. The details are added
in the following format.
1. Create a Windows Form Application in Visual Studio .NET. The following customized
format is created for user.

2. Once the design of the form is created, select the View option from the menu bar. Click
on the Properties window.
3. Select the first text box and the properties for it appear in the window.
4. Expand the DataBindings property
5. Select the Text property for enabling the drop down list.
6. Click the Add Project Data Source from the drop down list
7. Make a connection with the CurrentInfo database and select the Student table
8. Select the Other Data Sources, Project Data Sources, CurrentInfoDataSet, Student table.
9. Select the Name column and bind it with the textbox.
10. Bind all the other text boxes with the database values.
11. Press F5 and execute the Windows Form.
12. The following output is displayed to the user.
2. Complex Data Binding
The Complex Data Binding is the process of binding the component with the Database. The
controls can be GridView, Dropdown list, or combo box. Multiple values can be displayed from the
dataset through the binding.

The controls that can be used for binding the multiple values from the database to the Windows
Form are listed below.

1. DataGridView: It is used to display the multiple records and columns. The DataSource
property of the DataGridView control is used for binding the specific data element.
2. ComboBox: The control contains a text box for entering the data and drop down list for
displaying the values. The DataSource property is useful for binding the control. The element
specific information can be bind through the DisplayMember property
3. ListBox: It is used for displaying the data for the column from several records of
datasets. The DataSource property is used for binding the control to the data source.
4. The DisplayMember property is used for binding the control to the specific data element.

Navigating Records in ADO.NET

A BindingNavigator control is used for handling the binding to the data source through the pointer
to the current item in the list of records.

The navigator control is used with the BindingSource control for enabling the users to navigate
the data records on a form. It provides a layer between the controls and windows form of the
data source. Users can navigate and modify the records in the Windows form.

The following figure displays the BindingNavigator control and the BindingSource control in the
Windows Form.

The Binding Navigator control has many controls for modifying the data source. The list of
controls and their functions are mentioned below:

1. bindingNavigatorAddNewItem Button: The + sign indicates that the new row can be added
to the data source.
2. bindingNavigatorDeleteItem Button: The X sign indicates that the current row can be
deleted from the data source.
3. bindingNavigatorMoveFirstItem Button: The button indicates that the user can move to
the first item in the data source.
4. bindingNavigatorMoveLastItem Button: The button indicates that the user can move to
the last item in the data source
5. bindingNavigatorMoveNextItem Button: The button indicates that the user can move to
the next item in the data source
6. bindingNavigatorMovePreviousItem Button: The button indicates that the user can move
to the previous item in the data source
7. bindingNavigatorPositionItem textbox: The returns current position in the data source
8. bindingNavigatorCountItemText box: The is used to return the total number of items in the data
source.
Consider the Order details table containing the data about the orders to be added. The data is
organized into a format as shown below:

1. Open Visual studio application and add Windows Forms Application from the template pane.
2. Add the labels and a binding Navigator control, and textbox controls to the form
3. Click OK button
4. Click View, Properties Window, and open the Properties Window.
5. Add the appropriate names to the controls present in the web form.

6. Open the Data Source Configuration Wizard. The Database icon must be selected. Click
Next Button
7. Click New Connection Button. Add Connection dialog box is shown.
8. Add the Server Name, select Use SQL Server Authentication option from the Log on the
server section
9. Add the User name as sa and password as abcd1234
10. Select the Order Details database and click Test Connection button
11. Click OK and close the Add Connection dialog box
12. Click Next button. In the Choose Your Database Objects dialog box, expand Tables node.
13. Select the Orderdata table and click Finish button.
For binding the data to the control in the Windows Form, the following steps are executed.
1. Select the textbox1, and expand the DataBindings property.
2. Select the Text property and click on the drop down list.
3. Expand the Other Data Sources, Project Data, Sources, Orderdataset, Orderdata nodes.
4. Select the OrderID column and bind it with textbox1.
5. Perform the similar operations for all the textboxes.
Press F5 or click Debug -> Start Debugging option from the menu. The Order Details form is
displayed as shown below:

User can navigate through the other records using the navigator button of the
control. Close the form and exit the Visual Studio application.

Filtering Data
There are requirements when user wants to display only limited data to the client. The filtering of
data is possible for displaying the desired results. The data can be sorted in ascending or
descending order.

There are two ways by which the data can be filtered. They are as mentioned below:
1. Parameterized Queries
2. Filtering data using controls in Windows Form.
1. Parameterized Queries

The stored procedures are always useful for accessing data from the database. By using the stored
procedures users can precompiled execution, use of code, less network traffic, and security is high
for the data stored in the system.

The parameterized queries are useful for filtering the data based on the conditions defined by the
user at runtime. They are useful when user wants to execute the data based on the situation.

The following query is useful for selecting the student with the ID specified.

SELECT StudName FROM


Student WHERE StudID =
@StudID

In the above code, the @StudID is the parameter in the query. The value is passed at the runtime
by the user.

In ADO.NET, for populating the @StudID parameter, the SqlParameter object in the SqlParameter class
for the command. The SqlParameter object is used for assigning the parameterized values to the queries.

Consider the example for extracting the details of the student. The following code shows the
execution parameterized query.

SqlConnection con = new SqlConnection();


con.ConnectionString = “DataSource = SQLSERVER02; Initial Catalog=StudData; User ID = sa;
Password=abcd1234”; con.Open();
string studid;
studid = textbox1.Text;
String query = “ SELECT * from StudData where StudID =
@StudID”; SqlCommand cmd = new SqlCommand( query,
con); cmd.Parameters.Add( new SqlParameter
( “@StudID”, StudID ) ); SqlDataReader dr =
cmd.ExecuteReader();

2. Filtering data using controls in Windows Form

Once the data is retrieved from the data source by binding the data to the control of the Windows
form, the data filter is used for displaying the selective records.

Consider the example of a company where user wants to view the information about the
employee data. The information is displayed in the form of a grid view. The connection is
established with the database and the data binding through the DataGridView control.

If user wants the data only of the specific employees in the organization, they can be filtered using
the following steps.

1. Select the DataGridView control in the form and open the DataGridViewTasks window.
2. Click on the Add Query option. The SearchCriteria Builder dialog box will open.
3. Add the following query in the query text box.
SELECT EmpID, EmpName, EmpRole FROM Employee WHERE ( EmpID = 101 )
4. Click on the Query Builder button
5. Click on the Execute Query button. The output generated by the query can be checked
6. Click OK button and close the Search Criteria Builder dialog box
7. Press F5 and execute the Windows Form.
In the above example, TableAdapter queries are the SQL statements or procedures that are
executed. The FillBy method is useful for executing the TableAdapter queries.

The following code can be added to the Click event of the FillByToolStrip control.

private void fillByToolStripButton_Click( object sender, EventArgs e )


{
tr
y
{ this.internalCandidateTableAdapter.FillBy( this.EmpDataSet.Employee);

}
catch( System.Exception ex )
{
System.Windows.Forms.MessageBox.Show( ex.Message );
}
}
In the above code, the FillBy method is used for adding data from the Employee table of the EmpDataSet.
Databinding with DataGridView in ADO.NET
DataGridView is very powerful and flexible control for displaying records in a tabular (row-
column) form. Here I am describing a different way of databinding with a DataGridView
control.

Take a windows Form Application -> take a DataGridView control.

Follow the given steps.

Step 1 : Select DataGridView control and click at smart property. Look at the following figure.

Step 2 : After clicking, a pop-up window will be open.


Step 3 : Click ComboBox.

Step 4 : Click at Add Project Data Source (Look at above figure). A new window will be opened to choose
Data Source Type.

Step 5 : Choose Database (By default it is selected) and click the next button. A new window will be open to
Database Model.
Step 6 : Select DataSet (By default it is selected) and click the next button. A new window will be open.

Step 7 : Click at New Connection button.


Step 8 : Write Server name, User name and Password of your SQL server and select Database
name. Look at the following figure.
Step 9 : Click "ok" button. After clicking ok button, you will reach the Data Source Configuration Wizard.

Step 10 : Click the next button.


Step 12 : Click on Table to explore all tables of your Database.

Step 13 : Click on the selected Database table to explore all columns.


Step 14 : Check the CheckBox to select columns.

Step 15 : Click the Finish button. You will note that the DataGridView will show all columns of the
table (Here, "Student_detail").

Run the application.

Output
Now we bind the DataGridView with database by code. Take another DataGridView control and
write the following code on the form load event.
using System;
using
System.Collections.Generic
; using
System.ComponentModel;
using System.Data;
using
System.Drawing;
using
System.Linq;
using
System.Text;
using
System.Windows.Forms
; using
System.Data.SqlClient;

namespace DatabindingWithdataGridView
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
SqlDataAdapter
dadapter; DataSet
dset;
string connstring =
"server=.;database=student;user=sa;password=wintellect";
private void Form1_Load(object sender, EventArgs e)
{
dadapter = new SqlDataAdapter("select * from
student_detail", connstring); dset = new
System.Data.DataSet();
dadapter.Fill(dset);
dataGridView1.DataSource = dset.Tables[0].DefaultView;
}
}
}

Run the application. Output will be same as above.

XML and ADO


Working with XML Data
Organizations store data in different formats. This makes the process of data interchange complex
and time consuming. To overcome this problem, organizations need a standard, simple way of
storing data in a format that can be exchanged across multiple platforms. XML is a language that
can display data in a standard and self describing format.
Data stored in XML format can be transferred to databases such as SQL Server with the help of
ADO.NET. These objects help in exchanging data between the databases and XML documents, and
enable to read and write the data stored in a dataset object as XML documents.
XML Data can be processed in .NET applications by using the System.Xml namespace, that contains
many classes to write and read XML documents.
Writing XML Data
The XmlWriter class in the System.Xml namespace provides non-cached forward only and write
only access to XML data. This class can be used to write either a stream of data or a text data.
XmlWriter provides full support for XML namespace.Isolation levels
XmlWriter objects are created by using the Create () method. The Create () method is a static
method. We can pass an object of XmlWriterSettings class to the Create () method in order to
specify the settings
or properties, which are to be enabled on the XmlWriter object. If no parameters are passed, the
default settings are applied.
Properties of XmlWriterSettings class

XmlWriterSettings property Description

CheckCharacters Gets or Sets a value indicating whether to do character checking or not.

CloseOutput Gets or Sets a value indicating whether the System.Xml.XmlWriter should clos
underlying stream or System.IO.TextWriter when the
System.Xml.XmlWriter.C method is called.

ConformanceLevel Gets or Sets the level of compliance with which the System.Xml.XmlWriter
co with

Encoding Gets or Sets the text encoding to use.

Indent Gets or Sets a value indicating whether to indent elements or not.

IndentChars Gets or Sets the character string to use while indenting

NewLineChars Gets or Sets a character string for line breaks.

NewLineHandling Gets or Sets a value indicating whether to normalize line breaks in the output
or

NewLineAttributes Gets or Sets a value indicating whether to write attributes on a new line or not.
Creating elements in an XML file
OmitXmlDeclaration Gets or Sets a value indicating whether to write an XML declaration or not.
Elements can be created in two ways:
By calling the WriteElementString() Method:
WriteElementString() method takes two parameters, the name of the element and the value of the
element. Like:
writer.WriteElementString(“Student”,”Robin”
); Here student is the element name and Robin is the
value By calling the WriteStartElement() Method:
WriteStartElement() method takes the name of the element as a parameter. After calling it,
WriteString() method is called to specify a value for this element. Then WriteEndElement()
method is called to end the element tag. Like:
writer.WriteStartElement(“Student”);
writer.WriteString(“Robin”);

writer.WriteEndElement();

Creating Attributes in XML file:


Attributes can be created in two ways:
· By calling the WriteAttributeString() method:
This method takes two parameters the name of the attribute and value of attribute.
writer.WriteAttributeString("StudentID”,”S-109”);
In this code snippet StudentID is attribute and S-109 is value.
· By calling the WriteStartAttribute() method:
This method takes the name of attribute as a parameter. After calling it, WriteString() method is
called to specify a value for this attribute, then WriteEndAttribute() method is called to end the
attribute.Like:
write.WriteStartAttribute(“Stu
dentID”);
writer.WriteString(“S-109”);
writer.WriteEndAttribute();writer.WriteStartElement(“Student”);
writer.WriteString(“Robin”);
writer.WriteEndElement();

Writing comments in XML file

Comments can be write using the WriteComment() method. This method takes a string as a
parameter. This string is written as a comment in the XML file.
writer.WriteComment(“This XML file is created for students details”);
Creating an XML file

XML file can be created in following ways:

By using XmlWriter

using System;

using

System.Collections.Generic

; using System.Text;
using System.Xml;

using

System.Data.SqlClient;

namespace xmlWrite

class Program

static void Main()

{
XmlWriterSettings settings=new

XmlWriterSettings();

settings=.Indent=true;

settings.IndentChars=” ”;

settings.NewLineOnAttribut

es=true;

using(XmlWriter writer=XmlWriter.Create(“D:\\productdetails.xml”,settings));

writer.WriteComment(“Product details”);

writer.WriteStartElement(“Product_detail

s”); writer.WriteStartElement(“Product”);

writer.WriteAttributeString(“Product_ID”

,”P-0001”);

writer.WriteElementString(“ProductNam

e”,”Toys”);

writer.WriteElementString(“Price”,”200”)

; writer.WriteEndElement();

writer.WriteStartElement(“Product”);
writer.WriteAttributeString(“Product_ID”

,”P-0213”);

writer.WriteElementString(“ProductName”,

”Mouse”);

writer.WriteElementString(“Price”,”500”)

; writer.WriteEndElement();

writer.WriteEndElement();

writer.Flush();

By using XmlTextWriter

Methods of XmlTextWriter

Methods Description

writeStartDocument() Writes the XML declaration in the beginning of XML document: <? xml
version=”1.0”

writeStartElement() Writes the start tag for a specified element


writeElementString() Writes an element that contains a string value

writeStartAttribute() Writes the start of attribute

writeAttributeString( Writes the value of given attribute


)

writeEndAttribute() Writes the end of attribute

writeEndElement() Writes the end tag of element

By saving a DataSet as XML data


DataSet can be saved in XML format by using the GetXml() method. It returns the XML
representation of a dataset.
String
xmlString=daProduct.GetXml();
Dataset object methods

Method Description

WriteXml() Enables to write the data of the datset into an XML file

WriteXmlSchema() Enables to write the data in the dataset as on XML Schema

Following code can be used to write the details stored in the Product table to an XML file:

using System;

using

System.Collections.Generic

; using System.Text;

using System.Xml;

using System.Data.SqlClient;

namespace xmlWrite

class Program
{

static void Main(string[ ] args)


{

SqlConnection con=new SqlConnection();

Con.ConnectionString=”DataSource=SQLSERVER01;Intial Catalog=HR;User
ID=sa;Password=password#1234”;

// Create a data adapter

SqlDataAdapter da=new SqlDataAdapter(“Select * from

Product”,con); DataSet ds=new DataSet();

da.Fill(ds,”Product”);

// Write dataset contents to an xml file by calling WriteXml() method

ds.WriteXml(“D:\\ProductDetails.xml”);

WriteXml( ) takes two parameters first the destination file where the output of XML file will be stored
and second but optional parameter is XmlWriteMode option that specifies how the XML output is to be
written.

XmlWriteMode option Description

IgnoreSchema Used to write the contents of dataset as XML data without an XML Schema. It is
defa

WriteSchema Used to write the contents of dataset as XML data with the dataset structure as an inli
schema

DiffGram Used to write the contents of dataset as a DiffGram

Reading XML Data


The XmlReader class in the System.Xml namespace provides non-cached, forward only and read
only access to XML data.
The objects of XmlReader can be created by using the Create( ) method. The XmlReaderSettings
class is used to specify the settings or properties.
Properties of XmlReaderSettings class
XmlReaderSettings Description

CheckCharacters Indicates whether to do character check or not

ConformanceLevel Gets or Sets the level of compliance

IgnoreComments Gets or Sets whether to ignore comments or not

IgnoreProcessingInstruction Gets or Sets whether to ignore processing instructions or not

ValidationType Gets or Sets a value indicating whether the reader should perform validation
or

Schemas Gets or Sets the XmlSchemaSet object to use while performing schema
validat

XmlReaderSettings settings=new XmlReaderSettings( );

XmlReader reader=null;

Reader=XmlReader.Create(“D:\\

Products.xml”,settings);write.WriteStartAttribute(“StudentID”); writer.WriteString(“S-

109”); writer.WriteEndAttribute();writer.WriteStartElement(“Student”);

writer.WriteString(“Robin”);

writer.WriteEndElement();

XmlTextReader
XmlTextReader class is derived class of XmlReader class. The XmlTextReader class reads the XML
document but does not allow to access or validate the schema information.

Method Description

IsStartElement() Verifies the element is the start element

MoveToElement() Moves to the element that contains of the current attribute node

MoveToFirstAttribute() Moves to the first attribute

MoveToNextAttribute() Moves to the next attribute


Read() Reads the very next node from the stream

ReadAttributeValue() Reads the value of the attribute and parses it into one or more nodes.

ReadString() Reads the content of an element or text node in a string

ReadStartElement() Verifies if the current node is an element and moves the reader to the next
node.

ReadEndElement() Verifies if the current node is an end tag and moves the reader to the next
node

Skip() Skips the child nodes of the current node

Validating XML Data


A Schema is used to define the structure of an XML document. An XML document is considered to
be well formed if it conforms to all the syntactical requirements, as defined by the W3C XML 1.0
recommendation.
XML document can validate in the following ways:
· XmlReader
· XmlValidatingReader

Validating XML document using XmlReader


The XmlReader class can impose validation by using a XSD Schema. The ValidationType property
on the XmlReaderSettings class determines whether the XmlReader instance imposes validation or
not.

Validating XML document using XmlValidatingReader


An XML document can be validated by using the XmlValidatingReader as well. The
XmlValidatingReader class uses the ValidationEventHandler() callback method that is called when
a validation error occurs.
The following code explains validation of XML document using XmlValidatingReader class.
XmlTextReader textReader=new XmlTextReader(“Product.xml”);

XmlValidatingReader validatingReader=new

XmlValidatingReader(“textReader”);

To validate an XML document, first load XmlValidatingReader for an XML document by


using the Load() method.
To validate an XML document, first load XmlValidatingReader for an XML document by using

the Load() method. XmlDocument xdoc=new XmlDocument();

XmlTextReader textReader=new
XmlTextReader(“Product.xml”); XmlValidatingReader

validatingReader=new XmlValidatingReader(textReader);

xdoc.Load(validatingReader);

After loading the XmlValidaingReader for an XML document, the ValidationType property is
used to specify the type of validation that we have to perform on that document.
DiffGrams

When we create an XML representation of a dataset, ADO.NET enables to present the data in a
DiffGram format. The DiffGram format preserves information about changes to the data in the
dataset so that we can choose whether to accept or reject the changes when we read the XML data
back to the dataset.
A DiffGram is an XML format that identifies current and original versions of data elements.Elements of
DiffGram

Block Description

<DataInstance> It contains the name of the dataset or the data table. It contains the current data.

<diffgr:before> It contains the original row version

<diffgr:errors> It contains the error information for a particular row

Attributes of DiffGram

Attribute Description

Id Used to pair the elements in the <diffgr:before> and <diff:errors> blocks to elements in the
<DataInstance> block

parented It identifies which element from the <DataInstance> block is the parent element of the current
ele

hasChanges It identifies a row in the <DataInstance> block as modified. It has three values:
inserted
modified
descent
Following code explains it:
hasErrors It identifies a row in the<DataInstance> block with a RowError. The error is placed in the
using System;
<diffgr block

using
Error It contains the text of the RowError for an element in the <diff:errors> block
System.Collections.Generic

; using System.Text;
using System.Xml;

using

System.Data.SqlClien

t; namespace

xmlWrite

class Program
{

static void Main(string[] args)

SqlConnection con=new SqlConnection();

con.ConnectionString=”Data Source=SQLSERVER01; Initial Catalog=HR;User

ID=sa;Password=password#1234”; con.Open();

SqlDataAdapter da=new SqlDataAdapter(“Select * from

Product”,con); DataSet ds=new DataSet();

da.Fill(ds,”Product”);

//write dataset contents to an XML file by calling WriteXml() method in a diffgram mode

ds.WriteXml(“D:\\ProductDetails.xml”, XmlWriteMode.DiffGram);

con.Close();

}
UNIT IV

WEB SERVICES:

A Web Service is can be defined by following ways:


o It is a client-server application or application component for communication.
o The method of communication between two devices over the network.
o It is a software system for the interoperable machine to machine communication.
o It is a collection of standards or protocols for exchanging information between two devices
or application.
Let's understand it by the figure given below:

As you can see in the figure, Java, .net, and PHP applications can communicate with other
applications through web service over the network. For example, the Java application can interact
with Java, .Net, and PHP applications. So web service is a language independent way of
communication.

Web Service Features


1) XML-Based
Web services use XML at data description and data transportation layers. Using XML exclude any
networking, operating system, or platform binding. Web services-based operation is extremely
interoperable at their core level.
2) Loosely Coupled
A client of a web service is not fixed to the web service directly. The web service interface can
support innovation over time without negotiating the client's ability to communicate with the
service. A tightly coupled system means that the client and server logic are closely tied to one
another.
3) Coarse-Grained
Object-oriented technologies such as Java expose their functions through individual methods. A
specific process is too fine an operation to provide any suitable capability at a corporate level.
4) Ability to be Synchronous or Asynchronous
Synchronicity specifies the binding of the client to the execution of the function. In synchronous
invocations, the client blocks and delays in completing its service before continuing. Asynchronous
operations grant a client to invoke a task and then execute other functions.
5) Supports Remote Procedure Calls (RPCs)
Web services allow consumers to invoke procedures, functions, and methods on remote objects
using an XML-based protocol. Remote systems expose input and output framework that a web
service must support.
6) Supports Document Exchange
One of the essential benefits of XML is its generic way of representing not only data but also
complex documents.
7) Web Service Components

There are three major web service components.


1. SOAP
2. WSDL
3. UDDI
SOAP
 SOAP is an acronym for Simple Object Access Protocol.
 SOAP is a XML-based protocol for accessing web services.
 SOAP is a W3C recommendation for communication between applications.
 SOAP is XML based, so it is platform independent and language independent. In other words,
it can be used with Java, .Net or PHP language on any platform.
WSDL
 WSDL is an acronym for Web Services Description Language.
 WSDL is a xml document containing information about web services such as method name,
method parameter and how to access it.
 WSDL is a part of UDDI. It acts as a interface between web service applications.
 WSDL is pronounced as wiz-dull.
UDDI
 UDDI is an acronym for Universal Description, Discovery and Integration.
 UDDI is a XML based framework for describing, discovering and integrating web services.
 UDDI is a directory of web service interfaces described by WSDL, containing information
about web services.

The Architecture Of A Web Service


The architecture of a Web Service can be depicted in the following diagram.

As we already know, a typical Web Services architecture comprises three entities i.e. a
Client, a Web Server, and an Internet to carry out the operation. The operation is nothing but the
request and response in a client-server architecture.
A Client is typically a set of all the applications or software systems that requests a Web
Service thereby making it a Service Consumer.
A Web Server is a set of all applications or software systems that provide Web Service. Every
Web Service requires a network to perform and this results in the third entity called the Internet.
The working diagram of a Web Service is defined by the three components shown below.
 Service Requestor
(Find()) Service Provider
(Publish())
 Service Registry or Repository (Bind())

Types Of Web Services


Two types of Web Services are explained below in detail.
1) SOAP Service
SOAP Service stands for Simple Object Access Protocol. SOAP services are stateful services
that use XML language to form an envelope. A SOAP envelope can be described in two portions i.e.
one is a SOAP header and body, the other one is the protocol used to send SOAP messages.
This SOAP header consists of Authentication and Authorization which grants access. The
body comes under the payload section of the request which uses WSDL to describe the Web Service
and the protocol is mainly HTTP (HyperText Transmission Protocol).

Web Services Security


SOAP services have an SSL layer (Secure Socket Layer) which is responsible for avoiding any
data leakage during transmission, and thus provides encryption and decryption.
Meanwhile, the SOAP services are more secure as it also has WSS (Web Services Security) which
guarantees no divulge during communication between the service and the application.
Web Services has three important entities to cover the security factor during message transfer.
 Authentication and Authorization (Already explained above).
 Confidentiality: This is entirely dependent on the SSL which provides encryption and
decryption of the SOAP envelope.
 Network Security: This means to extract all the SOAP and XML – RPC responses that you
get from the server. For Example, If you take any Web Service tool like POSTMAN or
PARASOFT, you will find that under the HTTP header manager, there is an option to set the
value of the Content- Type. The value can be set to the Application/JSON so that it will
extract all REST (Since SOAP services do not support HTTP Header manager options). Thus,
you can pass the content-type: Application/XML in a payload itself in the form of XML. This
would also extract SOAP and XML- RPC.
These three factors constitute Web Services Security to cope up with the external attacks.

Architecture Of SOAP Service


Every SOAP service depends on three entities which ultimately form the architecture of SOAP Service.
 Service Provider: All software systems or application which is a part or provides Web Service.
 Service Requester: All software systems or applications which is a part of requests Web
Service from Service Provider.
 Service Registry: A registry or repository where all the information about Web Service is
provided by the Service Provider. (Already discussed in UDDI)

These three entities interact with each other to carry out a successful Web Service
Implementation. This is done in three phases. The first phase is the Publish() phase where a
Service Provider feeds all the details about a Web Service in a Service Registry or Repository.

The second phase is Find() where a Service Request mainly the client application finds the
details about Web Service from a repository (also has WSDL XML file). The last phase is Binding()
where the
client application or the Service Requester synchronizes with the Service Provider for the final
implementation of the Web Service.
2) RESTful Service
REST stands for Representational State Transfer which is a Stateless Service. It is called
Stateless as the Web Server does not store any information about the client session (time duration
till the client application is connected and in execution) which means each request type is treated
and performed easily with the help of REST inbuilt methods like GET, POST, CUSTOM (PUT),
DELETE, HEAD and so on. Indeed, these methods are not present in SOAP.
Each method in REST has its significance. Given Below is the briefing about each of them.
 GET: This method is used to retrieve the information that is sent to the server using any of
the methods like PUT or POST. This does not have a request body. Successful execution will
give you 200 response objects.
 POST: This method is used to create a document or record using a request body, specified
URL, document key, context key, etc. The same can be retrieved using the GET method.
Successful execution will give you a 201 response.
 PUT: This is under the CUSTOM option that is available in POSTMAN or PARASOFT. This
method is used to update any document or record that is already present. Successful
execution will give you a 201 or 200 response.
 DELETE: This method is used to delete any record. Successful execution will give you a 204
response (no content).

The Architecture Of REST Service


The architecture of REST service depends on two entities i.e. Service Consumer or
Requestor and Service Provider. The Service Consumer is the one who avails the Web Service and
Service Provider is the collection of software or system which provides the Web Service.
The client application which is typically a Service Consumer uses inbuilt methods of REST, a URL or
URI, an HTTP version and a payload (if supported by method).

SOAP vs REST

Their differences are listed down for your reference.


 SOAP envelope can be used in the REST but not vice versa. E.g. A user token which is created
in SOAP can be passed in the REST request under the HTTP header manager ->
Authorization.
 SOAP is typically more secure than REST services as SOAP services provide WSS apart from
SSL. This SSL is present both in SOAP and REST.
 SOAP is slower than REST as the request processing takes more time in SOAP due to the
XML data format. REST uses JSON which is very light-weighted and thus makes it faster.
 SOAP does not have any inbuilt method but REST does have GET, PUT, POST, etc.
 SOAP is stateful whereas REST is stateless.
 The request and response bodies in SOAP support only the XML data format. In REST, the
request and response bodies support many data formats like JSON, XML, Plain Text, etc.
What is SOAP?
 SOAP is an XML-based protocol for accessing web services over HTTP. It has some
specification which could be used across all applications.
 SOAP is known as the Simple Object Access Protocol, but in later times was just shortened to
SOAP v1.2. SOAP is a protocol or in other words is a definition of how web services talk to
each other or talk to client applications that invoke them.
 SOAP was developed as an intermediate language so that applications built on various
programming languages could talk easily to each other and avoid the extreme development
effort.
SOAP Introduction
 In today’s world, there is huge number of applications which are built on different
programming languages. For example, there could be a web application designed in Java,
another in .Net and another in PHP.
 Exchanging data between applications is crucial in today’s networked world. But data
exchange between these heterogeneous applications would be complex. So will be the
complexity of the code to accomplish this data exchange.
One of the methods used to combat this complexity is to use XML (Extensible Markup
Language) as the intermediate language for exchanging data between applications. Every
programming language can understand the XML markup language. Hence, XML was used as the
underlying medium for data exchange.
But there are no standard specifications on use of XML across all programming languages for
data exchange. That is where SOAP software comes in. SOAP was designed to work with XML over
HTTP and have some sort of specification which could be used across all applications. We will look
into further details on the SOAP protocol in the subsequent chapters.
Advantages of SOAP
SOAP is the protocol used for data interchange between applications.
 When developing SOAP based Web services, you need to have some of language which can
be used for web services to talk with client applications. SOAP is the perfect medium which
was developed in order to achieve this purpose. This protocol is also recommended by the
W3C consortium which is the governing body for all web standards.
 SOAP is a light-weight protocol that is used for data interchange between applications. Note
the keyword ‘light.’ Since SOAP programming is based on the XML language, which itself is a
light weight data interchange language, hence SOAP as a protocol that also falls in the same
category.
 SOAP is designed to be platform independent and is also designed to be operating system
independent. So the SOAP protocol can work any programming language based applications
on both Windows and Linux platform.
 It works on the HTTP protocol –SOAP works on the HTTP protocol, which is the default
protocol used by all web applications. Hence, there is no sort of customization which is
required to run the web services built on the SOAP protocol to work on the World Wide
Web.
SOAP Building Blocks
The SOAP specification defines something known as a “SOAP message” which is what is sent to the
web service and the client application.
The below diagram of SOAP architecture shows the various building blocks of a SOAP Message.
SOAP Message Building Blocks
The SOAP message is nothing but a mere XML document which has the below components.
 An Envelope element that identifies the XML document as a SOAP message – This is the
containing part of the SOAP message and is used to encapsulate all the details in the SOAP
message.This is the root element in the SOAP message.
 A Header element that contains header information – The header element can contain
information such as authentication credentials which can be used by the calling application.
It can also contain the definition of complex types which could be used in the SOAP message.
By default, the SOAP message can contain parameters which could be of simple types such
as strings and numbers, but can also be a complex object type.
A simple SOAP service example of a complex type is shown below.
Suppose we wanted to send a structured data type which had a combination of a “Tutorial Name”
and a “Tutorial Description,” then we would define the complex type as shown below.
The complex type is defined by the element tag <xsd:complexType>. All of the required elements
of the structure along with their respective data types are then defined in the complex type
collection.
<xsd:complexType>
<xsd:sequence>
<xsd:element name="Tutorial Name" type="string"/>
<xsd:element name="Tutorial Description" type="string"/>
</xsd:sequence>
</xsd:complexType>
 A Body element that contains call and response information – This element is what contains
the actual data which needs to be sent between the web service and the calling application.
Below is an SOAP web service example of the SOAP body which actually works on the
complex type defined in the header section. Here is the response of the Tutorial Name and
Tutorial Description that is sent to the calling application which calls this web service.
<soap:Body>
<GetTutorialInfo>
<TutorialName>Web Services</TutorialName>
<TutorialDescription>All about web services</TutorialDescription>
</GetTutorialInfo>
</soap:Body>
SOAP Message Structure
One thing to note is that SOAP messages are normally auto-generated by the web service when it is
called. Whenever a client application calls a method in the web service, the web service will
automatically generate a SOAP message which will have the necessary details of the data which will
be sent from the web service to the client application.
As discussed in the previous topic of this SOAP tutorial, a simple SOAP Message has the following
elements –
 The Envelope element
 The header element and
 The body element
 The Fault element (Optional)
Let’s look at an example below of a simple SOAP message and see what element actually does.
SOAP Message Structure
1. As seen from the above SOAP message, the first part of the SOAP message is the envelope
element which is used to encapsulate the entire SOAP message.
2. The next element is the SOAP body which contains the details of the actual message.
3. Our message contains a web service which has the name of “Guru99WebService”.
4. The “Guru99Webservice” accepts a parameter of the type ‘int’ and has the name of
TutorialID. Now, the above SOAP message will be passed between the web service and the client
application.

SOAP Envelope Element


The first bit of the building block is the SOAP Envelope. The SOAP Envelope is used to
encapsulate all of the necessary details of the SOAP messages, which are exchanged between the
web service and the client application.
The SOAP envelope element is used to indicate the beginning and end of a SOAP message.
This enables the client application which calls the web service to know when the SOAP message
ends.
The following points can be noted on the SOAP envelope element.
 Every SOAP message needs to have a root Envelope element. It is absolutely mandatory for
SOAP message to have an envelope element.
 Every Envelope element needs to have at least one soap body element.
 If an Envelope element contains a header element, it must contain no more than one, and it
must appear as the first child of the Envelope, before the body element.
 The envelope changes when SOAP versions change.
 A v1.1-compliant SOAP processor generates a fault upon receiving a message containing the
v1.2 envelope namespace.
 A v1.2-compliant SOAP processor generates a Version Mismatch fault if it receives a
message that does not include the v1.2 envelope namespace.
Below is an SOAP API example of version 1.2 of the SOAP envelope element.
<?xml version="1.0"?>
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://www.w3.org/2001/12/soap-envelope"
SOAP- ENV:encodingStyle=" http://www.w3.org/2001/12/soap-
encoding">
<soap:Body>
<Guru99WebService xmlns="http://tempuri.org/">
<TutorialID>int</TutorialID>
</Guru99WebService>
</soap:Body>
</SOAP-ENV:Envelope>
The Fault message
When a request is made to a SOAP web service, the response returned can be of either 2 forms
which are a successful response or an error response. When a success is generated, the response
from the server will always be a SOAP message. But if SOAP faults are generated, they are returned
as “HTTP 500” errors.
The SOAP Fault message consists of the following elements.
1. <faultCode>– This is the code that designates the code of the error. The fault code can be
either of any below values
1. SOAP-ENV:VersionMismatch – This is when an invalid namespace for the SOAP
Envelope element is encountered.
2. SOAP-ENV:MustUnderstand – An immediate child element of the Header element,
with the mustUnderstand attribute set to “1”, was not understood.
3. SOAP-ENV:Client – The message was incorrectly formed or contained incorrect
information.
4. SOAP-ENV:Server – There was a problem with the server, so the message could not proceed.
2. <faultString> – This is the text message which gives a detailed description of the error.
3. <faultActor> (Optional)– This is a text string which indicates who caused the fault.
4. <detail>(Optional) – This is the element for application-specific error messages. So the
application could have a specific error message for different business logic scenarios.
Example for Fault Message
An example of a fault message is given below. The error is generated if the scenario wherein the
client tries to use a method called TutorialID in the class GetTutorial.
The below fault message gets generated in the event that the method does not exist in the defined class.
<?xml version='1.0' encoding='UTF-8'?>
<SOAP-ENV:Envelope xmlns:SOAP-
ENV="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/1999/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/1999/XMLSchema">
<SOAP-ENV:Body>
<SOAP-ENV:Fault>
<faultcode xsi:type="xsd:string">SOAP-ENV:Client</faultcode>
<faultstring xsi:type="xsd:string">
Failed to locate method (GetTutorialID) in class (GetTutorial)
</faultstring>
</SOAP-ENV:Fault>
</SOAP-ENV:Body>
</SOAP-ENV:Envelope>

SOAP Communication Model


All communication by SOAP is done via the HTTP protocol. Prior to SOAP, a lot of web services used
the standard RPC (Remote Procedure Call) style for communication. This was the simplest type of
communication, but it had a lot of limitations.
Now in this SOAP API tutorial, let’s consider the below diagram to see how this communication
works. In this example, let’s assume the server hosts a web service which provided 2 methods as
 GetEmployee – This would get all Employee details
 SetEmployee – This would set the value of the details like employees dept, salary, etc.
accordingly. In the normal RPC style communication, the client would just call the methods in its
request and send the required parameters to the server, and the server would then send the

desired response.
The above communication model has the below serious limitations
1. Not Language Independent – The server hosting the methods would be in a particular
programming language and normally the calls to the server would be in that programming
language only.
2. Not the standard protocol – When a call is made to the remote procedure, the call is not
carried out via the standard protocol. This was an issue since mostly all communication over
the web had to be done via the HTTP protocol.
3. Firewalls – Since RPC calls do not go via the normal protocol, separate ports need to be
open on the server to allow the client to communicate with the server. Normally all firewalls
would block this sort of traffic, and a lot of configuration was generally required to ensure
that this sort of communication between the client and the server would work.
To overcome all of the limitations cited above, SOAP would then use the below communication model

1. The client would format the information regarding the procedure call and any arguments
into a SOAP message and sends it to the server as part of an HTTP request. This process of
encapsulating the data into a SOAP message was known as Marshalling.
2. The server would then unwrap the message sent by the client, see what the client requested
for and then send the appropriate response back to the client as a SOAP message. The
practice of unwrapping a request sent by the client is known as Demarshalling.

Practical SOAP Example


This topic will look at using the Microsoft.Net framework to build an ASMX web service. This
type of web service supports both SOAP version 1.1 and version 1.2. ASMX web services
automatically generate the Web Service Definition Language (WSDL) document. This WSDL
document is required by the calling client application so that the application knows what the web
service is capable of doing.
In our example, we are going to create a simple web service, which will be used to return a
string to the application which calls the web service. This web service will be hosted in an Asp.Net
web application. We will then invoke the web service and see the result that is returned by the web
service.
Visual Studio will also show us what the SOAP message being passed between the web
service and the calling application. The first pre-requisite to setup our Web service application
which can be done by following the below steps.

Step 1) The first step is to create an empty ASP.Net Web application. From Visual Studio 2013, click
on the menu option File->New project.
Once you click on the New Project option, Visual Studio will then give you another dialog
box for choosing the type of project and to give the necessary details of the project. This is
explained in the next step.
Step 2) In this step,
1. Ensure to first choose the C# web template of ASP.NET Web application. The project has to
be of this type in order to create SOAP services project. By choosing this option, Visual
Studio will then carry out the necessary steps to add required files which are required by
any web-based application.
2. Give a name for your project which in our case has been given as webservice.asmx. Then
ensure to give a location where the project files will be stored.

Once done you will see the project file created in your solution explorer in Visual Studio 2013.

Step 3) In this step,


We are going to add a Web service file to our project
1. First Right-click on the project file as shown below
2. Once you right-click on the project file, you have the chance to choose the option “Add->Web
Service(ASMX) to add a web service file. Just provide a name of Tutorial Service for the web
service name file.

Step 4) Add the following code to your Tutorial Service asmx file.

Code Explanation:
1. This line of code provides a name for your web service file. This is an important step
because it gives way for the client application to call the web service via the name of the web
service.
2. Normally a class file is used to encapsulate the functionality of a web service. So the class file
will have the definition of all the web methods which will provide some functionality to the
client application.
3. Here [WebMethod] is known as an attribute which describes a function. The subsequent
step creates a function called “Guru99WebService”, but with the inclusion of this step of
adding a [WebMethod] attribute makes sure that this method can be invoked by a client
application. If this attribute is not in place, then the method can never be called by a client
application.
4. Here we are defining a function called ‘Guru99WebService’ which will be used to return a
string to the calling client application. This function is a web service which can be called by
any client application.
5. We are using the return statement to return the string “This is a Guru99 Web service” to the
client application.
If the code is executed successfully, the following Output will be shown when you run your code in
the browser.
Output:

 The output clearly shows that the name of our web service is “Guru99 Web Service” which
is the result of giving a name for our web service.
 We can also see that we can to invoke the web service. If we click the Invoke button, we will
get the below response in the web browser.

The above output,


 It clearly shows that by invoking the web method, the string “This is a Guru99 Web service”
is returned.
 Visual Studio also allows you to view the SOAP message request and response which is
generated when the above web service is called.
The SOAP request which is generated when the web service is called is shown below.
Code Explanation:
1. The first part of the SOAP message is the envelope element which is what was discussed in
the prior chapters. This is the encapsulating element which is present in every SOAP
message.
2. The SOAP Body is the next element and contains the actual details of the SOAP message.
3. The third part is the element which specifies that we want to call the service which is called
‘Guru99WebService.’

<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-
instance">
<soap:Body>
<Guru99WebServiceResponse xmlns="http://tempuri.org/">
<Guru99WebServiceResult>string</Guru99WebServiceResult>
</Guru99WebServiceResponse>
</soap:Body>
</soap:Envelope>
Code Explanation:
1. The first part of the SOAP message is the envelope element which is what was discussed in
the prior chapters. This is the encapsulating element which is present in every SOAP
message.
2. The SOAP Body is the next element and contains the actual details of the SOAP message.
3. The interesting part you will see now is the ‘string’ attribute. This tells the client application
that the web service being called returns an object of the type string. This is very useful
because if the client application which otherwise would not know what the web service
returns.

WSDL (Web services description language)


Web Services Description Language (WSDL) is an XML-based file that basically tells the client
application what the web service does. The WSDL file is used to describe in a nutshell what the web
service does and gives the client all the information required to connect to the web service and use
all the functionality provided by the web service.
Web Service Example
A Web services example of a WSDL file is given below.
<definitions>
<message name="TutorialRequest">
<part name="TutorialID" type="xsd:string"/>
</message>

<message name="TutorialResponse">
<part name="TutorialName" type="xsd:string"/>
</message>

<portType name="Tutorial_PortType">
<operation name="Tutorial">
<input message="tns:TutorialRequest"/>
<output message="tns:TutorialResponse"/>
</operation>
</portType>

<binding name="Tutorial_Binding" type="tns:Tutorial_PortType">


<soap:binding style="rpc"
transport="http://schemas.xmlsoap.org/soap/h
ttp"/>
<operation name="Tutorial">
<soap:operation soapAction="Tutorial"/>
<input>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/enco
ding/" namespace="urn:examples:Tutorialservice"
use="encoded"/>
</input>

<output>
<soap:body
encodingStyle="http://schemas.xmlsoap.org/soap/
encoding/" namespace="urn:examples:Tutorialservice"
use="encoded"/>
</output>
</operation>
</binding>
</definitions>
The important aspects to note about the above WSDL declaration examples of web services are as
follows:
1. <message> – The message parameter in the WSDL definition is used to define the different
data elements for each operation performed by the web service. So in the web services
examples above, we have 2 messages which can be exchanged between the web service and
the client application, one is the “TutorialRequest”, and the other is the “TutorialResponse”
operation. The TutorialRequest contains an element called “TutorialID” which is of the type
string. Similarly, the TutorialResponse operation contains an element called “TutorialName”
which is also a type string.
2. <portType> – This actually describes the operation which can be performed by the web
service, which in our case is called Tutorial. This operation can take 2 messages; one is an
input message, and the other is the output message.
3. <binding> – This element contains the protocol which is used. So in our case, we are
defining it to use http (http://schemas.xmlsoap.org/soap/http). We also specify other
details for the body of the operation, like the namespace and whether the message should
be encoded.

Structure of a WSDL Document


A WSDL document is used to describe a web service. This description is required, so that client
applications are able to understand what the web service actually does.
 The WSDL file contains the location of the web service and
 The methods which are exposed by the web service.
The WSDL file itself can look very complex to any user, but it contains all the necessary
information that any client application would require to use the relevant web service.
Below is the general structure of a WSDL file
 Definition
 TargetNamespace
 DataTypes
 Messages
 Porttype
 Bindings
 service
One key thing to note here is that definition of messages, which is what is passed by the SOAP
protocol is actually defined in the WSDL document. The WSDL document actually tells a client
application what are the types of SOAP messages which are sent and accepted by the Web service.
In other words, the WSDL is just like a postcard which has the address of a particular location.
The address provides the details of the person who delivered the postcard. Hence, in the same way,
the WSDL
file is the postcard, which has the address of the web service which can deliver all the functionality
that the client wants.
<!-- WSDL definition structure -->
<definitions
name="Guru99Service"
targetNamespace=http://example.org/math/
xmlns=http://schemas.xmlsoap.org/wsdl/>
<!-- abstract definitions -->
<types> ...
<message> ...
<portType> ...

<!-- concrete definitions -->


<binding> ...
<service> ...
</definition>
Below is a diagram of the structure of a WSDL file

Structure of a WSDL
WSDL Elements
The WSDL file contains the following main parts
1. The <types> tag is used to define all the complex datatypes, which will be used in the
message exchanged between the client application and the web service. This is an important
aspect of the client application, because if the web service works with a complex data type,
then the client application should know how to process the complex data type. Data types
such as float, numbers, and strings are all simple data types, but there could be structured
data types which may be provided by the web service.
For example, there could be a data type called EmployeeDataType which could have 2
elements called “EmployeeName” of type string and “EmployeeID” of type number or
integer. Together they form a data structure which then becomes a complex data type.
2. The <messages> tag is used to define the message which is exchanged between the client
application and the web server. These messages will explain the input and output
operations which can be performed by the web service. An example of a message can be a
message which accepts the EmployeeID of an employee, and the output message can be the
name of the employee based on the EmpoyeeID provided.
3. The <portType> tag is used to encapsulate every input and output message into one logical
operation. So there could be an operation called “GetEmployee” which combines the input
message of accepting the EmployeeID from a client application and then sending the
EmployeeName as the output message.
4. The <binding> tag is used to bind the operation to the particular port type. This is so that
when the client application calls the relevant port type, it will then be able to access the
operations which are bound to this port type. Port types are just like interfaces. So if a client
application needs to use a web service they need to use the binding information to ensure
that they can connect to the interface provided by that web service.
5. The <service> tag is a name given to the web service itself. Initially, when a client
application makes a call to the web service, it will do by calling the name of the web service.
For example, a web service can be located at an address such as
http://localhost/Guru99/Tutorial.asmx . The service tag will actually have the URL
defined as http://localhost/Guru99/Tutorial.asmx, which will actually tell the client
application that there is a web service available at this location.
Why WSDL
A web service is an important component in building modern day web applications. Their main
purpose is to allow multiple applications built on various programming languages to talk to each
other. For instance, we can have a .Net web application talks to a Java application via a Web service.
A web service has the following key features
 It is built using the XML programming language. Almost all modern day technologies such as
.Net and Java have corresponding commands that have the ability to work with XML. Hence,
XML was taken as the most appropriate language for building web services.
 Web services communicate over HTTP. HTTP is a protocol used by all web-based
applications. Hence, it just made sense to ensure that Web services also had the ability to
work over the HTTP protocol.
 Web services conform to a particular language specification. This specification is set by the
W3C, which is the governing body for all web standards.
 Web services have a description language known as WSDL, which is used to describe the
web service.
The WSDL file is written in plain old XML. The reason that it is in XML is so that the file can be read
by any programming language.
So if the client application was written in .Net, it would understand the XML file. Similarly, if the
client application was written in the Java programming language then also it would be able to
interpret the WSDL file.

The WSDL file is what binds everything together. From the above diagram, you can see that
you can create a web service in the .Net language.

WSDL Message Part


The WSDL consists of a section called “messages” which is denoted by the <message>
element. This element is basically used to describe the data that gets exchanged between the web
service and the client application.
Each web service will always have 2 types of messages,
 One is for the input of the web service, and the other is for the output of the web service.
 The input is used to describe the parameters which are accepted by the web service. This is
an important aspect of the client application so that it knows the values to be sent as
parameters to the web service.
 The other type of message is the output message which tells what results are provided by
the web service.
Each message, in turn, will have a <part> element which is used to describe the parameter
used by the input and output message. Below is a simple example, of what a message for a web
service looks like. The functionality of the web service is to provide the name of a “Tutorial” once a
“Tutorial ID” is submitted as a parameter to the web service.
1. As we can see the web service has 2 messages, one for the input and the other for the output.
2. The input message is known as TutorialNameRequest which has one parameter called
TutorialID. This parameter is of the type number which is specified by the xsd:number type
3. The output message is known as TutorialNameResponse which has one parameter called
TutorialName. This parameter is of the type string which is specified by the xsd:string type
Port Type Binding
Ports are used in WSDL to define one complete operation which is offered by the web service.
In the previous topic, we saw that our web service provided 2 messages, one for the input called
“TutorialNameRequest” and the other for the output called “TutorialNameResponse.” Together the
input and output message form is known as one complete operation.
WSDL provides an element called <portType> which is used to define the operations provided by
the Web service.

So in our above example we can note the following:


1. The name of the port Type which encapsulates the operation is given as “Tutorial_PortType.”
2. The operation itself is given a name of “Tutorial”. So our operation basically
provides a TutorialName if the TutorialID is given as an input parameter.
3. Next is our 2 messages, one for the input and the other for the output which forms our
operation In addition to the <portType> element, there is also the <binding> element which is
used to define how the messages will be transferred.
1. The above example shows that the binding consists of a binding name which in our case is
given as “TutorialSoapBinding”. Binding in simple terms is the information which the client
application uses to actually bind itself to the web service. Once it is actually bound to the
web service, it then has the ability to call the various operations that are exposed by the web
service.
2. The transport layer is given as http:// which means that the messages which will transfer
over the HTTP protocol.
Creating WSDL File
The WSDL file gets created whenever a web service is built in any programming language.
Since the WSDL file is pretty complicated to be generated from plain scratch, all editors such as
Visual Studio for .Net and Eclipse for Java automatically create the WSDL file.
Below is an example of a WSDL file created in Visual Studio.

<?xml version="1.0"?>
<definitions name="Tutorial"
targetNamespace=http://Guru99.com/
Tutorial.wsdl xmlns:tns=http://Guru99.com/Tutorial.wsdl
xmlns:xsd1=http://Guru99.com/Tutorial.xsd
xmlns:soap=http://schemas.xmlsoap.org/wsdl/soap/
xmlns="http://schemas.xmlsoap.org/wsdl/">
<types>
<schema targetNamespace=http://Guru99.com/Tutorial.xsd
xmlns="http://www.w3.org/2000/10/XMLSchema">

<element name="TutorialNameRequest">
<complexType>
<all>
<element name="TutorialName" type="string"/>
</all>
</complexType>
</element>
<element name="TutorialIDRequest">
<complexType>
<all>
<element name="TutorialID" type="number"/>
</
all>
</complexType>
</element>
</schema>
</types>
<message name="GetTutorialNameInput">
<part name="body" element="xsd1:TutorialIDRequest"/>
</message>
<message name="GetTutorialNameOutput">
<part name="body" element="xsd1:TutorialNameRequest"/>
</message>
<portType name="TutorialPortType">
<operation name="GetTutorialName">
<input message="tns:GetTutorialNameInput"/>
<output message="tns:GetTutorialNameOutput"/>
</operation>
</portType>
<binding name="TutorialSoapBinding" type="tns:TutorialPortType">
<soap:binding style="document" transport="http://schemas.xmlsoap.org/soap/http"/>
<operation name="GetTutorialName">
<soap:operation soapAction="http://Guru99.com/GetTutorialName"/>
<input>
<soap:body use="literal"/>
</input>
<output>
<soap:body use="literal"/>
</output>
</operation>
</binding>

<service name="TutorialService">
<documentation>TutorialService</documentation>
<port name="TutorialPort" binding="tns:TutorialSoapBinding">
<soap:address location="http://Guru99.com/Tutorial"/>
</port>
</service>
</definitions>
Publishing the Web Service Example
In this example, we will create a web service with one WebMethod. This method will accept
an Integer parameter called “TutorialID.” The Web method will then return a string called “Web
Services.”
We will then create a console based application, which will consume this web service and
call our web method accordingly.
Let’s look at the steps required to carry out this example.
Step 1) The first step is to create your web service. The detailed steps of how the Asp.Net web
project and a web service is created has been explained here; Please follow the same steps to create
the project and web service accordingly. The key part is to enter the below code in the Web services
file.
namespace webservic asmx
{
[WebService(Name = "Guru99 Web service")]
public class TutorialService : System.Web.Services.WebService
{
[WebMethod]
public string GetTutorialService(int TutoriallD)
{
string TutorialName = "Web Services";
return TutorialName;
}
}
}
Code Explanation:
1. Here we are creating a WebMethod called “Guru99WebService.” In this web method, we are
including an integer parameter which needs to be passed whenever this web method is
called.
2. Next we are defining a variable called “TutorialName” which will hold the string value of
“Web Services.” This is the value which will be returned when the web service is called.
Step 2) Once we have defined the web services file, the next step is to create a client project which
will consume this web service.
Follow the below steps to create a console application. Right-click the Visual Studio solution
file and choose the option Add->New project
Step3) In this step,
1. Ensure to first choose the Visual C# Windows option. Then choose the option of creating a
console application.
2. Give a name for your project which in our case has been given as “DemoApplication.”
After you click the OK button in the above screen, you will be able to see the project in the Solution
explorer in Visual Studio.

Step 4) In this step, you be setting the DemoApplication Console application as the startup project.
This is done to ensure that this application launches first when the entire Visual Studio project is
run. This Console application will, in turn, call the web service which will be automatically launched
by Visual Studio.
To complete this step, right-click the DemoApplication project and choose the option “Set as
StartUp Project.”
Step 5) The next step is to add the service reference of our “Guru99Webservice” to our console
application. This is done so that the DemoApplication can reference the web service and all of the
web methods in the web service.
To do this, right-click the DemoApplication project file and choose the menu option Add->Service
Reference.

Step 6) In this step, we will provide the different values which are required to add our service reference
1. Firstly we need to choose our discover option. This option will automatically pick up the
WSDL file for our TutorialService web service.
2. Next, we should give a name for our service reference. In our case, we are giving it a name of
Guru99Webservice.
3. Then we need to expand on the TutorialService.asmx option so that we can have the ability
to see the ‘GetTutorialService’ method on the right-hand side. Here TutorialService.asmx is
the name of our Visual Studio .Net file which contains the code for our web service.
4. We will then see our Web method which we had in our web service known as “GetTutorialService”
When we click on the ‘OK’ button, all of the required code to access this web service will be
added to our DemoApplication Console application as shown below.
The screenshot shows that the “Guru99Webservice” was successfully added to our console application.

Step 7) The next step is to add the code to our console application to access the web method in our
web service. Open the Program.cs code file which comes automatically with the console application
and add the below code

namespace DemoApplication
{
class Program
{
static void Main(string[ ] args)
{
var client = new
Guru99Webservice.Guru99WebserviceSoapClient();
Console.WriteLine(client.GetTutorialService(l));
Console.ReadKey();
}
}
}
Code Explanation:-
1. The first part is to choose the Program.cs file. This is the main file which is created by Visual
Studio when a console application is created. This file is what gets executed when the
console application (in our case demo application) is executed.
2. We then create a variable called “client” which will be set to an instance of our Service
reference which was created in an earlier step. In our case, the service reference is
‘Guru99Webservice.Guru99WebserviveSoapClient()’
3. We are then calling our Webmethod ‘GetTutorialService’ in the TutorialService web service
Remember that our GetTutorialService’ method accepts an integer parameter, so we are just
passing an integer parameter to the web method.
4. This final line is just to ensure the console log screen remains active so that we can view the
output. This command will just wait for some input from the user.
Output
When all of the above steps are followed, and the DemoApplication is run the below output will be
displayed.

From the output, we can clearly see that the DemoApplication calls our Web service and that the
string returned by the Web service is displayed in our Console log.
UDDI is an XML-based standard for describing, publishing, and finding web services.
 UDDI stands for Universal Description, Discovery, and Integration.
 UDDI is a specification for a distributed registry of web services.
 UDDI is a platform-independent, open framework.
 UDDI can communicate via SOAP, CORBA, Java RMI Protocol.
 UDDI uses Web Service Definition Language(WSDL) to describe interfaces to web services.
 UDDI is seen with SOAP and WSDL as one of the three foundation standards of web services.
 UDDI is an open industry initiative, enabling businesses to discover each other and define
how they interact over the Internet.
UDDI has two sections −
 A registry of all web service's metadata, including a pointer to the WSDL description of a service.
 A set of WSDL port type definitions for manipulating and searching that registry.

UDDI - Elements
A business or a company can register three types of information into a UDDI registry. This
information is contained in three elements of UDDI.
These three elements are −
 White Pages,
 Yellow Pages, and
 Green Pages.
White Pages
 Contains Basic information about the company and its business.
 Basic contact information including business name, address, contact phone number, etc.
 A Unique identifiers for the company tax IDs. This information allows others to discover
your web service based upon your business identification.
Yellow Pages
 Yellow pages contain more details about the company. They include descriptions of the kind
of electronic capabilities the company can offer to anyone who wants to do business with it.
 Yellow pages uses commonly accepted industrial categorization schemes, industry codes,
product codes, business identification codes and the like to make it easier for companies to
search through the listings and find exactly what they want.
Green Pages
Green pages contains technical information about a web service. A green page allows someone
to bind to a Web service after it's been found. It includes −
 The various interfaces
 The URL locations
 Discovery information and similar data required to find and run the Web service.

UDDI - Technical

Architecture UDDI Data

Model
UDDI Data Model is an XML Schema for describing businesses and web services. The data model is
described in detail in the "UDDI Data Model" chapter.
UDDI API Specification
It is a specification of API for searching and publishing UDDI
data. UDDI Cloud Services
These are operator sites that provide implementations of the UDDI specification and synchronize
all data on a scheduled basis.

The UDDI Business Registry (UBR), also known as the Public Cloud, is a conceptually single
system built from multiple nodes having their data synchronized through replication. The current
cloud services provide a logically centralized, but physically distributed, directory. It means the
data submitted to one root node will automatically be replicated across all the other root nodes.
Currently, data replication occurs every 24 hours.
UDDI cloud services are currently provided by Microsoft and IBM. Ariba had originally
planned to offer an operator as well, but has since backed away from the commitment. Additional
operators from other companies, including Hewlett-Packard, are planned for the near future.
It is also possible to set up private UDDI registries. For example, a large company may set
up its own private UDDI registry for registering all internal web services. As these registries are
not automatically synchronized with the root UDDI nodes, they are not considered as a part of the
UDDI cloud.

UDDI - Data Model

UDDI includes an XML Schema that describes the following data structures −
 businessEntity
 businessService
 bindingTemplate
 tModel
 publisherAssertion
businessEntity Data
Structure
The business entity structure represents the provider of web services. Within the UDDI registry,
this structure contains information about the company itself, including contact information,
industry categories, business identifiers, and a list of services provided.
Here is an example of a fictitious business's UDDI registry entry −
<businessEntity businessKey = "uuid:C0E6D5A8-C446-4f01-99DA-
70E212685A40" operator = "http://www.ibm.com" authorizedName = "John
Doe">
<name>Acme Company</name>
<description>
We create cool Web services
</description>

<contacts>
<contact useType = "general info">
<description>General Information</description>
<personName>John Doe</personName>
<phone>(123) 123-1234</phone>
<email>[email protected]</email>
</contact>
</contacts>

<businessServices>
...
</businessServices>
<identifierBag>
<keyedReference tModelKey = "UUID:8609C81E-EE1F-4D5A-B202-3EB13AD01823"
name = "D-U-N-S" value = "123456789" />
</identifierBag>

<categoryBag>
<keyedReference tModelKey = "UUID:C0B9FE13-179F-413D-8A5B-5004DB8E5BB2"
name = "NAICS" value = "111336" />
</categoryBag>
</businessEntity>
businessService Data
Structure
The business service structure represents an individual web service provided by the business
entity. Its description includes information on how to bind to the web service, what type of web
service it is, and what taxonomical categories it belongs to.
Here is an example of a business service structure for the Hello World web service.
<businessService serviceKey = "uuid:D6F1B765-BDB3-4837-828D-
8284301E5A2A" businessKey = "uuid:C0E6D5A8-C446-4f01-99DA-
70E212685A40">
<name>Hello World Web Service</name>
<description>A friendly Web service</description>
<bindingTemplates>
...
</bindingTemplates>
<categoryBag />
</businessService>
Notice the use of the Universally Unique Identifiers (UUIDs) in the
businessKey and serviceKey attributes. Every business entity and business service is uniquely
identified in all the UDDI registries through the UUID assigned by the registry when the
information is first entered. bindingTemplate Data Structure
Binding templates are the technical descriptions of the web services represented by the business
service structure. A single business service may have multiple binding templates. The binding
template represents the actual implementation of the web service.
Here is an example of a binding template for Hello World.
<bindingTemplate serviceKey = "uuid:D6F1B765-BDB3-4837-828D-
8284301E5A2A" bindingKey = "uuid:C0E6D5A8-C446-4f01-99DA-
70E212685A40">
<description>Hello World SOAP Binding</description>
<accessPoint URLType = "http">http://localhost:8080</accessPoint>

<tModelInstanceDetails>
<tModelInstanceInfo tModelKey = "uuid:EB1B645F-CF2F-491f-811A-4868705F5904">
<instanceDetails>
<overviewDoc>
<description>
references the description of the WSDL service definition
</description>

<overviewURL>
http://localhost/helloworld.wsdl
</overviewURL>
</overviewDoc>
</instanceDetails>
</tModelInstanceInfo>
</tModelInstanceDetails>
</bindingTemplate>

Creating a Web Service


Launch Visual Studio 2015, go to file -> new project, in the New Project dialog box, select Visual C#
and under web tab, select ASP.Net Web Application, I named my application as “TestableAPI”.
Once you are done Click OK. Visual Studio will ask you the template you want to start with. Since I
am trying to demonstrate the documentation & testing capabilities, I just want an empty project
with Web API references added. I have chosen Empty as my project template, selected Web API
check box for references and change the authentication to “No Authentication”.

The created Web API looks as follows in the solution explorer.

In real life, you may add your models to the project then add the corresponding API controllers.
Since we are discussing about the documentation/testability, let us add an empty API Controller for
the project.
Right click the Controller folder, select Add -> Controller, select the template “Web API 2 Controller
– Empty” and then click on the Add button

For the purpose of this walkthrough I am going to add a Greeting Control that have some
methods/actions to greet a particular user.

The Web API controller is created. I am going to add two actions, the first one that accepts a user
and return the greeting based on the system time. The second action will accept a name, the hour of
day and return the greeting message based on the hour. The completed Controller code is given
below

The purpose of this article is not to evaluate whether the GreetMessage logic is ideal or not, instead
let us look into the Web API artifacts. One thing you will notice is that I am defining routes for both
actions. Though this works, in real life scenarios, it is better to define the route in the
WebApiConfig.cs file. By defining routes in one place increases the maintainability of the project.
Now Let us focus on the problem we are trying to solve. Basically we need to address the below two
issues that every developer needs to address
 Documentation
 Test Client
Documentation
The first step in generating the documentation is adding XML Comments to your controllers and
actions. XML Comments are out there for years to support the documentation.
Once you enabled the documentation, you need to ensure to select the XML documentation file
generation from the build properties of your project. From solution explorer, right click your
project and select properties. Now in the Build menu, make sure you have selected the checkbox
associated with XML documentation file.
You can use GhostDoc or any other Visual Studio extension to generate XML comments. Basically
you can do this without using any tool too, but the tools will dramatically reduce your efforts. I have
added the comments with the help of GhostDoc. Now the controller looks as below.

The next thing we need to do is to generate Help documentation from these XML comments.
Luckily Microsoft has released a Nuget package for this purpose. You can refer the package from
the link https://www.nuget.org/packages/Microsoft.AspNet.WebApi.HelpPage/
I have installed the HelpPage package from the package manager console. In Visual Studio you can
open the package manager console from Tools -> Package Manger

Once the package is successfully installed, you can see the Areas Folder, where the HelpPage
components are added.
You are not done yet! We need the help pages to read the documentation from your comments,
right. In order to do this, you need to ensure Visual Studio generates the XML file while building
your application. Right click the project in solution explorer click on properties, go to the Build tab,
you can see “XML documentation file” check box, make sure you select this.

Now you need to configure the help page to read from the generated XML file. Open the
HelpPageConfig.cs find under Areas -> App_Start -> HelpPageConfig.cs, by default the
HelpPageConfig.cs looks as below.

Just uncomment the config.SetDocumentationProvider method and update the path to your XML as
per the build configuration. The modified method is given below.

We are almost there! Let us enable the users to browse the documentation. Basically we need to
register the Help page. Open WebApiConfig.cs file from the App_Start folder, In the register method,
call RegisterAllAreas() method. See the modified webapiconfig.cs file

Now build & run the application and browse to “/help”, you will see the documentation in the
browser.Cool!
Test Client
Now we have the documentation, what is next? I need to test my APIs. In our case the service
methods are all HttpGet and is easy to test in the browser by entering the url. But what if the
methods are with HttpPost or other verbs, Definitely we need an effective way to test. There are
couple of Nuget packages available for this, you can find one from the link
https://www.nuget.org/packages/WebApiTestClient/
The Nuget packages are maintained with high level of documentation. The author of the package
already wrote a good blog in MSDN. You can read it from the below Uri.
https://blogs.msdn.microsoft.com/yaohuang1/2012/12/02/adding-a-simple-test-client-to-asp-
net-web-api- help-page/
Ok. Let me install it from the package manager console. The
command is Install-Package WebApiTestClient

Note:- There are some other packages available in Nuget that serves the same purpose. To be
honest with you I didn’t test them all, but you can try them.
Now once the WebApiTestClient package is installed, you will have the following files created in
the solution.
 Scripts\WebApiTestClient.js
 Areas\HelpPage\TestClient.css
 Areas\HelpPage\Views\Help\DisplayTemplates\TestClientDialogs.cshtml
 Areas\HelpPage\Views\Help\DisplayTemplates\
TestClientReferences.cshtml Now the only thing left is to call the API
methods from the Help pages. Open the file Api.cshtml from Areas ->
HelpPage -> Views-> Help

By default the API.cshtml have the below code.


To the end of this file, Add the following
@Html.DisplayForModel("TestClientDialogs")
@Html.DisplayForModel("TestClientReferences")
The blog post from the author recommends to add the second (TestclientReferences) in a script
section, but its worked for me without that. The modified api.cshtml is given below

Now let us browse the help page, and when I select any method/action details, there is a button for
testing the API, great!

Click on the TestAPI button, you will be allowed to pass the parameters and test the service method.

Once you enter the parameter values, click Send and the Web API method will be called and you
can see the response. This work for all HTTP methods such as HttpPost, HttpGet and so on.
I entered some sample values and clicked on Send, and immediately I am able to view the response.
It is good that you can achieve the documentation and test without doing much work. That’s cool
and during the development process, the moment you add a service, other team members can view
the service documentation and test them.
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 Stock Service 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.
UNIT – V
Advanced ASP.NET
Component-Based Programming

Component-based programming is a simple, elegant idea. When used properly, it allows your code to be
more organized, consistent, and reusable. It's also incredibly easy to implement in a .NET application,
because you never need to use the Windows registry or perform any
special configuration.

A component, at its simplest, is one or more classes that are compiled into a separate DLL assembly file.
These classes provide some unit of logically related functionality. You can access a component in a single
application, or you can share the component between multiple applications. Your web pages (or any
other .NET application) can use the classes in your components in the same way they use any other .NET
class. Best of all, your component is encapsulated, which means it provides exactly the features your code
requires and hides all the other messy details.

When combined with careful organization, component-based programming is the basis of


good ASP.NET application design. In this chapter, you'll examine how you can create components (and why
you should) and consider examples that show you how to
encapsulate database functionality with a well-written business object. You'll also learn how to bind
your database component to the web controls on a page using the ObjectDataSource.

Using Component (Creating Basic Component) in ASP.Net:

As we know components enable us to reuse application logic across multiple pages or even say across
multiple applications. We can write a method named GetConnection() once and use this method in all the
pages consist in website. By taking advantage of components, we can make our applications very easier to
maintain, execute, reuse and even extend the use in multiple aspects. But if we are working on simple website
project, there is no reason to take advantage of components.

In this article series we will discuss how to build simple and advanced components. I am writing this series
in multiple parts. If we are working on Components then we also have to discuss on its methods, properties,
constructors, inheritance and interfaces.

Basic Component

In this basic component we will create simple welcome application suing components. Here is the example given
below.
Class1.vb File Code

Imports Microsoft.VisualBasic Public

Class Class1
Public Function Welcome() As String Return
"Welcome to MINDCRACKER"
End Function End
Class

Default.aspx File Code

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_De fault" %>

<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:Label ID="Label1" runat="server" Text=""></asp:Label>

</div>
</form>
</body>
</html>

Default.aspx.vb File Code

Partial Class _Default


Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me


.Load
Dim showMessage As New Class1() Label1.Text
= showMessage.Welcome()
End Sub End
Class

In the Page_Load() event handler, an instance of the Class1() component is created. Next, the result returned
by a call to the Welcome() method is assigned to a Label control. When we open the page in your browser,
we'll see the message "Welcome to MINDCRACKER" from the Class.vb File.
ASP.NET State Management

State management is very important and useful in ASP.NET. It is also asked in many interviews to fresher and
experienced developers.

ASP.NET State management is a preserve state control and object in an application because ASP.NET
web applications are stateless. A new instance of the Web page class is created each time the page is
posted to the server. If a user enters information into a web application, that information would be lost
in the round trip from the browser (MSDN).

In a single line, State management maintains and stores the information of any user till the end of the user
session.

Two types of State Management techniques are available in ASP.NET as in the following figure,
Figure 1: State Management Part
Server side
Session

Session is a very important technique to maintain state. Normally session is used to store information
and identity. The server stores information using Sessionid.

Set User Session

1. protected void btnSubmit_Click(object sender, EventArgs e)


2. {
3.Session["UserName"] = txtName.Text;
4.
5.Response.Redirect("Home.aspx");
6. }

Session Event

Session event can be seen in project Global.asax file. Two

types of Session Events

Session_Start

The Session_start event is raised every time a new user requests without a session ID.

1. void Session_Start(object sender, EventArgs e)


2. {
3.Session["master"] = "~/Master.master";
4. }

Session_End

The Session_End event is raised when session is ended by a user or a time out using Session end
method.

1. void Session_End(object sender, EventArgs e)


2. {
3.Response.Write("Session_End");
4. }

The session is stored in the following for ways in ASP.NET.

 InProcMode
It is a default session mode and a value store in web server memory (IIS). In this the session value stored
with server start and it ends when the server is restarted.

 State Server Mode


In this mode session data is stored in separate server.

 SQL Server Mode


In this session is stored in the database. It is a secure mode.

 Custom Mode
Generally under session data is stored in InProc, Sql Server, State server, etc. If you store session data
with other new techniques then provide ASP.NET.

Application

Application State is a server side management state. It is also called application level state management. In this
mainly store user activity in server memory and application event shown in Global.asax file.

Their are three types of applications in ASP.NET.

Application_Start

This event begins with domain start.

1. Void Application_Start(object sender, EventArgs e)


2. {
3.Application["AppstartMessage"] = "Welcome to CSharp Corner Developer Communtiy";
4. }

Application_Error

In this section manage unhandled exception error.

1. void Application_Error(object sender, EventArgs e)


2. {
3.// Write an unhandled error code exception
4. }

Application_ End

This ends with domain or restarts IIS.

1. Void Application_End(object sender, EventArgs e)


2. {
3.Application["AppEndMessage"] = "Application Closed";
4. }

Cache

Cache is stored on server side. It implements Page Caching and data caching. Cache is use to set expiration
polices

Response.Cache.SetExpiresTime(DateTime.Now.AddDays(1));

Client Side

Now here I am explaining client side state management one by one:


Also state management has the following four important parts available on the client side,
Cookie

Cookie is a small and an important part of ASP.NET. In this store user information, session and application. It
can be created constant and temporary and they work with browser request. Cookies are store on client side.
The server can read cookies and abstract data.

Two types of cookies are available,

Persistence

This type of cookie works with Date and time.

1. Response.Cookies["CookieName"].Value = "Test Cookies";


2. //set expire time
3. Response.Cookies["CookieName"].Expires = DateTime.Today.AddHours(1);

Non-Persistence

This is a temporary cookie. It is created with access application and discards the close application.

1. Response.Cookies["CookieName"].Value = "Test Cookies";


Control state

Control state technique is developed to maintain data work properly in order. We can use view state but
suppose view state is disabled by the user, the control will not work as expected. For expected results of
the control we have to use Control State. In application, the Viewstate is by default true. Sometimes we
need to use custom control to manage application properly.

1. if (!IsPostBack)
3.lblmsg1.Text
2. { = "Welcome to C# corner"; 5. }

4.lblmsg2.Text = "Welcome to C# corner community";

When two messages are displayed on a Postback event, then control which one is displayed by using
customized control state.
Hidden Field

Hidden fields are used to store value to client side. Hidden field is not displayed on the browser, but it
works on a request.

1. if (HiddenField1.Value != null)
2. {
3. int val = Convert.ToInt32(HiddenField1.Value) + 1;
4. HiddenField1.Value = val.ToString();
5. Label1.Text = val.ToString();
6. }

Viewstate is a very useful client side property. It is used for page level state management. Viewstate
stores any type of data and used for sending and receiving information,

Example 1 - Count.

1. ViewState Demo Count: <asp:Label runat="server" id="lblcount" />


2.
3. <asp:Button runat="server" id="Submit" onclick="Submit_Click" text="show" />
4.
5. protected void Page_Load(object sender, EventArgs e)
6. {
7. if (IsPostBack)
8. {
9. if (ViewState["count"] != null)
10. {
11. int ViewstateVal = Convert.ToInt32(ViewState["count"]) + 1;
12. lblcount.Text = ViewstateVal.ToString();
13. ViewState["count"] = ViewstateVal.ToString();
14. }
15. else
16. {
17. ViewState["count"] = "1";
18. }
19.}
20. }
21. protected void Submit_Click(object sender, EventArgs e)
22. {
23.lblcount.Text = ViewState["count"].ToString();

Example 2 - Set/Get user.

1. if (ViewState["UserName"] != null)
2. lblName.Text = ViewState["UserName"].ToString();

OR,

1. ViewState["UserName"] = txtUserName.Text;

Viewstate is easy to apply and does not need access to any server resources. In a Viewstate, do not store big
data, only store small values. Viewstate enables and disables on page level control. It also supports
Encryption and Decryption and data/value is stored in hashed format. So we are not storing important data
such as password, account information, etc. When more data is stored in this, then the page becomes heavy.

Query String

Query string stores the value in URL.

Response.Redirect("ShowStringValue.aspx?Username=" +

txtUsername.Text); It is visible to all the users in url as in the following

link,

Components of .NET and ASP.NET


The .NET platform supports all major computer operating systems, and it contains editors and tools that
developers can use to build a plethora of applications. The ASP.NET framework has extra characteristics,
like an authentication system and editor extensions.
Main .NET components
These are the main components of the .NET platform:
Languages: These include C#, VB.NET and J#, as well as compilers. The C# programming language is
commonly used by developers.
The dot net framework has a set of standard class libraries. Developers commonly use the web library for web
applications. All .NET programs run on the Common Language Infrastructure, which is also a platform. All .NET
programs use CLR for performing key activities, like Exception handling and Garbage collection.

Extra ASP.NET components


These are components of the ASP.NET framework:
An authentication
This includes libraries, a database and template pages for user logins. There are also tools
for multilayer authentication and external authentication for social media websites and other websites that
allow users to log in externally.
A base framework for processing web
As part of the ASP.NET framework, servers evaluate the code that web developers write with
C# and send HTML to the user. Client-side code is written in JavaScript.
Code behind
Visual Studio separates the design of a web page from the coding by creating separate files
for each. A general file type for a ASP.NET file is .aspx, and the file type that contains the coding for the
web page is .aspx.cs.
Editor
These include syntax highlighting, code completion and other features to assist web page
developers.
Libraries for common web
One of the common libraries is Model View Controller.
Razor:
This is the webpage templating syntax web developers will use for building dynamic web
pages with C Sharp.
State
State management is the concept of remembering the state of an application at the current
point in time. Since HTTP is a stateless protocol, extra coding is necessary to carry a transaction a user
initiates from one web page to the next. ASP.NET has this capability.
Caching
Pages are stored in a temporary location on a user's computer to improve the performance of
an application by quickly retrieving a page a user requests and giving that user a better response.

Working With COM/COM+ in ASP.NET


Microsoft introduced a new concept called managed code. Code that runs within the CLR environment is
called managed code. Code that runs outside the boundaries of CLR environment is called unmanaged code.
Some of the example of unmanaged code are COM, ActiveX components.
.NET provides a mechanism which makes it possible to use the existing unmanaged components with
ASP.NET application. This mechanism is called interoperability.
Introduction to COM/COM+
COM is a binary standard. It is acronym for the Component Object Model. COM is a specification and the
components built in any language according to this specification (COM) can be integrated with any client
application written in any language. The Client doesn't has to know the location of the components. When
working with COM, the objects are compiled into DLLs i.e. the binary executable files. A DLL can contain
more than one class.
COM+ is nothing but an extension of COM. COM+ is a combination of operating system services and an object
oriented programming architecture. By extension to COM, I meant of adding a few services, like event
registry, the queues of asynchronously received requests for a service (transaction management), ensuring
security against the system requests (authentication), object pooling.

Invoking COM/COM+ components


In .NET, all codes are executed within the Common Language Runtime (CLR) environment. CLR runs your
code and specifies services required for the development process. ASP.NET application cannot directly
interact with COM components.
When an ASP.NET application calls a method defined in the COM component, CLR creates a wrapper called
Runtime Callable Wrapper (RCW). RCW is a .NET object and is executed in CLR. The primary task of RCW is
to marshal calls between the >NET application and the COM components. The CLR only creates one RCW
object for a COM component even if it is referred more than one time in an application. RCW stores the
number of references attached to it in an internal cache. RCW is created on the heap and so is subjected to
garbage collection. When reference count to a particular RCW becomes zero, the garbage collection module
will delete it and the memory allocated to the RCW object will be released.
When an ASP.NET application calls a method defined within the COM component, RCW performs the
following tasks:
 Creates an instance of the COM object and bind it to the application
 Manages data conversion between managed and unmanaged data type.
 Manages the life time of the COM component for which it is acting as a wrapper.
 Handles exception during the data conversion process.
The following figure displays the process of invoking a COM component from .NET application:

In this section you will add a COM component to an ASP.NET application.


For example to add a COM component, perform the following steps:
1. Open new project and select Visual C# projects from the Project types pane and ASP.NET Web Service
from the templates pane.
2. Select Project->Add References. The following dialog box appears:

4. Click the COM tab in the Add Reference dialog box. A list of COM components is displayed.
5. Select the COM component that you want to use within your ASP.NET application. For example, select
the Microsoft ActiveX Data Objects 2.7 library option form the list and double click the Select button. The
component is added to the Selected Components pane, as displayed in the following figure:
6. Click the OK button. The component that you have added to the project is displayed in the
Reference node in Solution Explorer.
7. You can use the COM component in the application by specifying its library class, as follows:
ADODB.RecordsetClass rs=new ADODB.RecordsetClass();
You can use this COM object rs, in your application to call its method.

Create your own COM/COM+


In this section, we will laern about creating your own class that can be used as a COM/COM+. Perform
the following steps for the same:
1. Create a new project and from the templates pane select, Class Library.
2. Next step is to create a n interface. But it is essentila here to include the GUID and the ComVisible
interface. All you need to do for this give the value true to ComVisible and for GUID, go to tools in menu bar
and select "create GUID". The following window will appear, now select the Registry format option and click
copy. Now go to your code and click paste. Remember to remove the braces {}. Thus add the following lines
of code:
[Guid("6B8551ED-6468-48c9-BE12-5766DDA8B20D")]
[ComVisible(true)]
public interface myinterface
{
mymethod();
//Methods
}
3. Now declare your class. Your class should inherit from ServicedComponent and your interface. For this
you must include System.EnterpriseServices. Thus the declaration should be like:
public class myclass : ServicedComponent, myinterface
{
public mymethod
{
//method implementation
}
//methods
}
But its essential to register your component before using it as COM/COM+. To do this use RegAsm
utility
ASP.NET - Custom Controls
ASP.NET allows the users to create controls. These user defined controls are categorized into:

 User controls
 Custom controls
User Controls
User controls behaves like miniature ASP.NET pages or web forms, which could be used by many other
pages. These are derived from the System.Web.UI.UserControl class. These controls have the following
characteristics:

 They have an .ascx extension.


 They may not contain any <html>, <body>, or <form> tags.
 They have a Control directive instead of a Page directive.
To understand the concept, let us create a simple user control, which will work as footer for the web
pages. To create and use the user control, take the following steps:

 Create a new web application.


 Right click on the project folder on the Solution Explorer and choose Add New Item.

 Select Web User Control from the Add New Item dialog box and name it footer.ascx. Initially, the
footer.ascx contains only a Control directive.
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="footer.ascx.cs"

Inherits="customcontroldemo.footer" %>

 Add the following code to the file:


 <table>
 <tr>
 <td align="center"> Copyright ©2010 TutorialPoints Ltd.</td>
 </tr>


<tr>


<td align="center"> Location: Hyderabad, A.P </td>
</tr>
</table>

To add the user control to your web page, you must add the Register directive and an instance of the
user control to the page. The following code shows the content file:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs"
Inherits="customcontroldemo._Default" %>

<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

<!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>

<asp:Label ID="Label1" runat="server" Text="Welcome to ASP.Net


Tutorials "></asp:Label>
<br /> <br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Copyright Info" />

</div>
<Tfooter:footer ID="footer1" runat="server" />
</form>

</body>
</html>
When executed, the page shows the footer and this control could be used in all the pages of your
website.

Observe the following:


(1) The Register directive specifies a tag name as well as tag prefix for the control.
<%@ Register Src="~/footer.ascx" TagName="footer" TagPrefix="Tfooter" %>

(2) The following tag name and prefix should be used while adding the user control on the page:
<Tfooter:footer ID="footer1" runat="server" />

Custom Controls
Custom controls are deployed as individual assemblies. They are compiled into a Dynamic Link Library
(DLL) and used as any other ASP.NET server control. They could be created in either of the following way:

 By deriving a custom control from an existing control


 By composing a new custom control combing two or more existing controls.
 By deriving from the base control class.
To understand the concept, let us create a custom control, which will simply render a text message on the
browser. To create this control, take the following steps:
Create a new website. Right click the solution (not the project) at the top of the tree in the Solution Explorer.
In the New Project dialog box, select ASP.NET Server Control from the project templates.

The above step adds a new project and creates a complete custom control to the solution, called
ServerControl1. In this example, let us name the project CustomControls. To use this control, this must be
added as a reference to the web site before registering it on a page. To add a reference to the existing
project, right click on the project (not the solution), and click Add Reference.
Select the CustomControls project from the Projects tab of the Add Reference dialog box. The Solution
Explorer should show the reference.

To use the control on a page, add the Register directive just below the @Page directive:

<%@ Register Assembly="CustomControls" Namespace="CustomControls" TagPrefix="ccs"


%>

Further, you can use the control, similar to any other controls.
<form id="form1" runat="server">
<div>
<ccs:ServerControl1 runat="server" Text = "I am a Custom Server Control" />
</div>
</form>
When executed, the Text property of the control is rendered on the browser as shown:

Working with Custom Controls


In the previous example, the value for the Text property of the custom control was set. ASP.NET added this
property by default, when the control was created. The following code behind file of the control reveals
this.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

using System.Web; using


System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]

public class ServerControl1 : WebControl


{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]

public string Text


{
get
{
String s = (String)ViewState["Text"]; return ((s
== null) ? "[" + this.ID + "]" : s);
}

set
{
ViewState["Text"] = value;
}
}

protected override void RenderContents(HtmlTextWriter output)


{
output.Write(Text);
}
}
}
The above code is automatically generated for a custom control. Events and methods could be added to
the custom control class.
Example
Let us expand the previous custom control named SeverControl1. Let us give it a method named
checkpalindrome, which gives it a power to check for palindromes.
Palindromes are words/literals that spell the same when reversed. For example, Malayalam, madam,
saras, etc.
Extend the code for the custom control, which should look as:

using System;
using
System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace CustomControls
{
[DefaultProperty("Text")]
[ToolboxData("<{0}:ServerControl1 runat=server></{0}:ServerControl1 >")]

public class ServerControl1 : WebControl


{
[Bindable(true)]
[Category("Appearance")]
[DefaultValue("")]
[Localizable(true)]
{
get
{
String s = (String)ViewState["Text"]; return ((s
== null) ? "[" + this.ID + "]" : s);
}

set
{
ViewState["Text"] = value;
}
}

protected override void RenderContents(HtmlTextWriter output)


{
if (this.checkpanlindrome())
{
output.Write("This is a palindrome: <br />");
output.Write("<FONT size=5 color=Blue>");
output.Write("<B>");
output.Write(Text);
output.Write("</B>");
output.Write("</FONT>");
}
else
{
output.Write("This is not a palindrome: <br />");
output.Write("<FONT size=5 color=red>"); output.Write("<B>");
output.Write(Text);
output.Write("</B>");
output.Write("</FONT>");
}
}

protected bool checkpanlindrome()


{
if (this.Text != null)
{
String str = this.Text;
String strtoupper = Text.ToUpper(); char[]
rev = strtoupper.ToCharArray();
Array.Reverse(rev);
String strrev = new String(rev);
if (strtoupper == strrev)
{
return true;
}
else
{
return false;
}
}
else
{
return false;
}
}
}
}
When you change the code for the control, you must build the solution by clicking Build --> Build Solution,
so that the changes are reflected in your project. Add a text box and a button control to the page, so that the
user can provide a text, it is checked for palindrome, when the button is clicked.

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


<div>
Enter a word:
<br />
<asp:TextBox ID="TextBox1" runat="server" style="width:198px"> </asp:TextBox>

<br /> <br />

<asp:Button ID="Button1" runat="server onclick="Button1_Click" Text="Check Palindrome"


style="width:132px" />

<br /> <br />

<ccs:ServerControl1 ID="ServerControl11" runat="server" Text = "" />


</div>
</form>

The Click event handler for the button simply copies the text from the text box to the text property of the
custom control.

protected void Button1_Click(object sender, EventArgs e)


{
this.ServerControl11.Text = this.TextBox1.Text;
}
When executed, the control successfully checks palindromes.

Observe the following:


(1) When you add a reference to the custom control, it is added to the toolbox and you can directly use it
from the toolbox similar to any other control.

(2) The RenderContents method of the custom control class is overridden here, as you can add your
own methods and events.
(3) The RenderContents method takes a parameter of HtmlTextWriter type, which is responsible for
rendering on the browser.

Performance Tuning in ASP.Net Web Applications

In this article, we will walk through some performance improvement techniques in ASP.NET Web Applications.

As you know, good performance of a web application is what a customer expects. The web application
performance issue arises when the number of users increases in the application or it can also occur after a
few days in production or during load testing in UAT. At this point, it's a tedious task to fix the performance
issues since efforts are more toward making code changes and henceforth everyone blames developers for
this issue. The main point is more if it's an application like Online Banking in which more customers are
engaged at a time.

Now, if we came to understand that our web application has performance issues then we can fix it easily.
First, we will something that could be potentially the cause of performance issue. It is the time to learn which
one is the culprit for a performance issue and fix it soon. The major tasks I
categorize as being performance tuning issues are Collect Data, Analyze Results, Fine-tune the code and
again test it for performance measure in an iterative fashion.

CPU and memory are the two places where most of the performance issues occur. The following are the
points which one needs to check before collecting data as a .Net developer.

Set debug=false in web.config

When you create the ASP.Net web application, by default this attribute is set to "true" in the web.config file
that is very useful when developing. However, when you are deploying your application, always set it to
"false". Setting it to "true" requires the pdb information to be inserted into the file and that results in a
comparatively larger file and hence processing will be
slow. So always set debug="false" before deployment.

Turn off Tracing unless until required


Tracing enables us to track the applications trace and the sequences that the developer needs to
monitor the trace. When trace is enabled it tries to add extra information to the page. Always set this to
"false" unless you require monitoring the trace logging in the production web.config.

1. <trace enabled="false" requestLimit=”10” pageoutput=”false” traceMode=”SortByTime”


localOnly=”true”>

Choose Session State management carefully

One extremely powerful feature of ASP.NET is its ability to store session state for users for any web
applications. Since ASP.NET manages session state by default, we pay the cost in memory even if you don't
use it. In other words, whether you store your data in in-process or on a state server or in a SQL Database,
session state requires memory and it's also time consuming when you store or retrieve data from it. You may
not require session state when your pages are static or when you do not need to store information captured
in the page. In such cases where you need not use session state, disable it on your web form using the
directive:
1. <@%Page EnableSessionState="false"%>

In case you use the session state only to retrieve data from it and not to update it, make the session state
read-only using the following directive.

1. <@%Page EnableSessionState ="ReadOnly"%>

If the application needing session mode state is out of process then consider carefully whether there is a
need of the state server or SQL Server session mode. SQL Server session mode provides lower performance
than session state server mode.

Don't store Session Sate to store objects of any type (including objects you create) since they are stored by
serializing and then de-serializing them and that results in a big performance penalty.

Use the client-side session state management technique to transfer data from one page to other page like query
string and clientsidestorage if possible.

Deploy with Release Build

Be sure you use Release Build mode and not Debug Build when you deploy your site to production. If
you think this doesn't matter, think again. By running in debug mode, you are creating PDBs and
cranking up the timeout. Deploy Release mode and you will see the speed improvements.

Disable View State of a Page if possible

View state is a technique in ASP.NET for storing some state data in a hidden input field inside the generated
page. When the page is posted back to the server, the server can parse, validate and apply this view state data
back to the page's tree of controls.

View state is a very powerful capability since it allows state to be persisted with the client and it requires no
cookies or server memory to save this state. Many ASP.NET server controls use view state to persist settings
made during interactions with elements on the page; for example, saving the current page that is being
displayed when paging through data.

There are a number of drawbacks to the use of view state, however it increases the total payload of the page,
both when served and when requested. There is also an additional overhead incurred when serializing or
deserializing view state data that is posted back to the server. View state increases the memory allocations
on the server. Several server controls, the most well known of which is the DataGrid, tend to make excessive
use of view state, even in cases where it is not needed. Pages that do not have any server postback events
can have the view state turned off.

The default behaviour of the View State property is enabled, but if you don't need it, you can turn it off at the
control or page level. Within a control, simply set the EnableViewState property to false, or set it globally
within the page using this setting.
<%@ Page EnableViewState="false" %>

Avoid Response.Redirect

To do client-side redirection in ASP.NET, users can call Response.Redirect and pass the URL. When
Response.Redirect is called, the server sends a command back to the browser telling it to request the page
redirected to it. An extra roundtrip happens that affects the performance. We can send information from the
source page using a query string. There is a limitation on the length of a query string, it cannot be used to
pass large amounts of data over the wire.
To do server-side redirection, users can use Server.Transfer. Since the execution is transferred on the server,
Server.Transfer does not require the client to request another page. In Server.Transfer, by using HttpContext
we can access the source page's items collection in the target page. The drawback of using this method is that
the browser does not know that a different page was returned to it. It displays the first page's URL in the
browser's address bar. This can confuse the user and cause problems if the user tries to bookmark the page.
Transfer is not recommended since the operations typically flow through several pages.

Use StringBuilder to concatenate strings

All the manipulations you do to the string are stored in memory as separate references and it must be
avoided as much as possible. In other words, when a string is modified, the runtime will create a new string
and return it, leaving the original to be garbage collected. Most of the time this is a fast and simple way to do
it, but when a string is being modified repeatedly it begins to be a burden on performance, all of those
allocations eventually get expensive. Use StringBuilder whenever a string concatenation is needed so that it
only stores the value in the original string and no additional reference is created.

Don't throwing exceptions

Exceptions cause slowdowns you will never see in web applications, as well as Windows applications. You
can use as many try/catch blocks as you want. Using exceptions gratuitously is where you lose performance.
For example, you should stay away from things like using exceptions to control flow.

Use Finally Method to kill resources

The finally method gets executed independent of the outcome of the block. Always use a finally block to kill
resources like closing database connections, closing files and other resources such that they are executed
independent of whether the code in the try worked or went to the catch.

Use Client-side Scripts for validations

User Input is evil and it must be thoroughly validated before processing to avoid overhead and possible
injections to your applications. Client-side validation can help reduce round trips required to process a user's
request. In ASP.NET you can also use client-side controls to validate user input. However, do a check at the
server side too to avoid the infamous JavaScript disabled scenarios.
Avoid unnecessary round trips to the server

Round trips significantly affect performance. They are subject to network latency and to downstream
server latency. Many data-driven Web sites heavily access the database for every user request. Whereas
connection pooling helps, the increased network traffic and processing load on the database server can
adversely affect performance. Keep round trips to an absolute minimum.
Implement Ajax UI whenever possible. The idea is to avoid full page refresh and only update the portion of
the page that needs to be changed.

Use Page.ISPostBack

Be sure you don't execute code needlessly. Use the Page.ISPostBack property to ensure that you only
perform page initialization logic when a page is first time loaded and not in response to client postbacks.

Include Return Statements within the Function/Method

Explicitly using a return allows the JIT to perform slightly more optimizations. Without a return statement,
each function/method is given several local variables on the stack to transparently support returning values
without the keyword. Keeping these around makes it harder for the JIT to optimize and can impact the
performance of your code. Look through your functions/methods and insert a return as needed. It doesn't
change the semantics of the code at all and it can help you get more speed from your application.

Use Foreach loop instead of For loop for String Iteration

A foreach statement is far more readable and in the future it will become as fast as a for loop for special cases
like strings. Unless string manipulation is a real performance hog for you, the slightly messier code may not
be worth it. Use a LINQ query expression when needed.

Avoid Unnecessary Indirection

When you use byRef, you pass pointers instead of the actual object. Many times this makes sense (side-
effecting functions, for example), but you don't always need it. Passing pointers results in more indirection
and that is slower than accessing a value that is on the stack. When you don't need to go through the heap, it
is best to avoid it, thereby avoiding indirection.

Choose correct collections object

Choose the right collection object that does better over another. For example, an ArrayList is better than an
array because an ArrayList has everything that is good about an array plus automatic sizing, Add, Insert,
Remove, Sort, Binary Search. All these great helper methods are added when implementing the IList
interface and the downside of an ArrayList is the need to cast objects upon retrieval. Carefully choosing a
collection over another gives better performance.
Here is the list of collection performance issues that helps us deciding which one gives better performance.

Always check Page.IsValid when using Validation Controls

Always be sure you check Page.IsValid before processing your forms when using Validation Controls.

Use Paging: The Grid Choice

Most web applications need the data to be shown in tabular format. For that we need a Grid view, DataGrid,
JQgrid, Telerik grid, Kendo Grid UI and so on. When doing a selection we should use a thin grid that gives
better performance. ASP.NET grid view uses server-side code and makes the
page heavy, whereas JQGRID is faster since it does everything at the client side. Use paging to display data on
a user demand basis instead of pulling a huge amount of data and showing it in a grid. Use a Repeater control
instead of a DataGrid or DataList because it is efficient, customizable and programmable and faster in
performance than that of a GridView, DataGrid and DataList.

Do Ajax calls instead of ASP.NET code behind code

Call a web service from JavaScript or jQuery instead of server-side. Use asynchronous calls to call a web
method from a web service.

Store your content by using caching

ASP.NET allows you to cache entire pages, fragments of pages or controls. You can cache also variable data by
specifying the parameters that the data depends on. By using caching you help the ASP.NET engine to return
data for repeated request for the same page much faster.

The proper use and fine tuning of the caching approach of caching will result in better performance and
scalability of your site. However improper use of caching will actually slow down and consume lots of server
memory and memory usage. A good candidate to use caching is if you have infrequent chance of data or
static content of a web page.

Use low cost authentication

Authentication can also have an impact on the performance of your application. For example, Passport
authentication is slower than form-based authentication and that in turn is slower than Windows
authentication.

Minimize the number of web server controls

The use of web server controls increases the response time of your application because they need time to
be processed on the server side before they are rendered on the client side. One way to minimize the
number of web server controls is to take into consideration the use of HTML elements where they are
suited, for example if you want to display static text.

Avoid using unmanaged code

Calls to unmanaged code is a costly marshalling operation. Try to reduce the number of calls between
the managed and unmanaged code. Consider doing more work in each call rather than making frequent
calls to do small tasks. Use a using block.

Avoid making frequent calls across processes

If you are working with distributed applications then this involves additional overhead negotiating network
and application level protocols. In this case network speed can also be a bottleneck. Try to do as much work
as possible in fewer calls over the network.
Design with Value Types
Use simple structs when you can and when you don't do much boxing and unboxing.
ValueTypes are far less flexible than Objects and end up degrading performance if used incorrectly. You
need to be very careful about when you treat them like objects. This adds extra boxing and unboxing
overhead to your program and can end up costing you more than it would if you had stuck with objects.

Remove the unused HTTPMODULES

There are several ASP.NET default Http Modules that sit in the request pipeline and intercept each and every
request. For example, SessionStateModule intercepts each request, parses the session cookie and then loads
the proper session in the HttpContext. Not all of these modules are always necessary for processing in the
page execution life cycle.

For example, if you aren't using Membership and Profile provider, you don't need FormsAuthentication
module remove this from web application web.config file.

Minimize assemblies

Minimize the number of assemblies you use to keep your working set small. If you load an entire assembly
just to use one method, you're paying a tremendous cost for very little benefit. See if you can duplicate that
method's functionality using code that you already have loaded.

Use Reflection wisely if needed

Avoid using reflection if there is no functional need. Especially Activator.CreateInstance() in refelection


takes more time to execute. I noticed many times in the Ant profiler that dynamically creating an instance
using Activator.CreateInstance (with two constructor parameters) is taking a decent amount of time. If you
use reflection at the core module then test it in the profiler and see the performance hit before using it any
UI application.

Encode Using ASCII When You Don't Need UTF

By default, ASP.NET comes configured to encode requests and responses as UTF-8. If ASCII is all your
application needs, eliminating the UTF overhead can return a few cycles. Note that this can only be done on a
per-application basis.

Avoid Recursive Functions / Nested Loops

These are general things to adopt in any programming language that consumes much memory. Always
avoid nested loops and recursive functions, to improve performance.

Minimize the Use of Format ()

When you can, use toString() instead of Format(). In most cases, it will provide you with the functionality you
need, with much less overhead.
Make JavaScript and CSS External
Using external files generally produces faster pages because the JavaScript and CSS files are cached
by the browser. Inline JavaScript and CSS increases the HTML document size but reduces the number of
HTTP requests. With cached external files, the size of the HTML is kept small without increasing the number
of HTTP requests, thus improving the performance.

Use multiple threads when calling multiple operations

The problem arises when single-threaded code gets stuck on a long-running process. So when we call
multiple services in a single method we should call two methods in two different threads. Use of multiple
threads makes the application more responsive.

Profiling ASP.NET Applications - Overview


ASP.NET applications can be seen as Internet Information Services (IIS) applications that are built with .NET
compilers and that use functionality provided by the .NET Framework and .NET assemblies. Despite the fact
that ASP.NET applications are similar to IIS applications, they are profiled in a different manner. This topic
provides a brief overview of profiling ASP.NET applications and services with AQTime. For information on
how to profile ordinary (unmanaged) IIS applications, see Profiling IIS Applications.
Profiling ASP.NET applications requires 32- or 64-bit editions of Windows XP, Windows Server 2003 or later
with Internet Information Services ver. 4.0 - 7.5.

The manner in which you profile your application depends on the development tool that you use to create
the ASP.NET application. Any ASP.NET application created in any development tool can be profiled using IIS.
Additionally, Visual Studio versions 2005 - 2012 have their own server
- ASP.NET Development Server - that is generally used instead of IIS to develop and debug ASP.NET
applications. However, it is still possible to use IIS to profile your application outside of Visual Studio. The
following topics provide instructions on different ways to profile ASP.NET applications.
Profiling ASP.NET Applications via ASP.NET Development Server
Describes how to profile ASP.NET applications or services using the ASP.NET Development Server.
Profiling ASP.NET Applications via Internet Information Services
Describes how to profile ASP.NET applications or services using the Internet Information Services (IIS).
What is Caching?
Caching is a technique of storing frequently used data/information in memory, so that, when the same
data/information is needed next time, it could be directly retrieved from the memory instead of being
generated by the application.
Caching is extremely important for performance boosting in ASP.NET, as the pages and controls are
dynamically generated here. It is especially important for data related transactions, as these are expensive in
terms of response time.
Caching places frequently used data in quickly accessed media such as the random access memory of the
computer. The ASP.NET runtime includes a key-value map of CLR objects called cache. This resides with the
application and is available via the HttpContext and System.Web.UI.Page.
In some respect, caching is similar to storing the state objects. However, the storing information in state objects
is deterministic, i.e., you can count on the data being stored there, and caching of data is nondeterministic.
The data will not be available in the following cases:

 If its lifetime expires,


 If the application releases its memory,
 If caching does not take place for some reason.
You can access items in the cache using an indexer and may control the lifetime of objects in the cache and
set up links between the cached objects and their physical sources.

Caching in ASP.Net

ASP.NET provides the following different types of caching:


 Output Caching : Output cache stores a copy of the finally rendered HTML pages or part of pages
sent to the client. When the next client requests for this page, instead of regenerating the page, a
cached copy of the page is sent, thus saving time.
 Data Caching : Data caching means caching data from a data source. As long as the cache is not
expired, a request for the data will be fulfilled from the cache. When the cache is expired, fresh
data is obtained by the data source and the cache is refilled.
 Object Caching : Object caching is caching the objects on a page, such as data-bound controls. The
cached data is stored in server memory.
 Class Caching : Web pages or web services are compiled into a page class in the assembly, when
run for the first time. Then the assembly is cached in the server. Next time when a request is made
for the page or service, the cached assembly is referred to. When the source code is changed, the
CLR recompiles the assembly.
 Configuration Caching : Application wide configuration information is stored in a configuration
file. Configuration caching stores the configuration information in the server memory.
In this tutorial, we will consider output caching, data caching, and object caching.
Output Caching
Rendering a page may involve some complex processes such as, database access, rendering complex
controls etc. Output caching allows bypassing the round trips to server by caching data in memory. Even the
whole page could be cached.
The OutputCache directive is responsible of output caching. It enables output caching and provides
certain control over its behaviour.
Syntax for OutputCache directive:
<%@ OutputCache Duration="15" VaryByParam="None" %>

Put this directive under the page directive. This tells the environment to cache the page for 15 seconds. The
following event handler for page load would help in testing that the page was really cached.
protected void Page_Load(object sender, EventArgs e)
{
Thread.Sleep(10000);
Response.Write("This page was generated and cache at:" +
DateTime.Now.ToString());
}
The Thread.Sleep() method stops the process thread for the specified time. In this example, the thread is
stopped for 10 seconds, so when the page is loaded for first time, it takes 10 seconds. However, next time
you refresh the page it does not take any time, as the page is retrieved from the cache without being
loaded.
The OutputCache directive has the following attributes, which helps in controlling the behaviour of the
output cache:

Attribute Values Description

DiskCacheable true/false Specifies that output could be written to a


disk based cache.

NoStore true/false Specifies that the "no store" cache


control header is sent or not.

CacheProfile String name Name of a cache profile as to be stored in


web.config.

VaryByParam Semicolon delimited list of string


None specifies query string values in a GET
* request or variable in a POST request.
Param- name
VaryByHeader Semicolon delimited list of strings specifies
* headers that might be submitted by a client.
Header names

VaryByCustom Tells ASP.NET to vary the output cache


Browser by browser name and version or by a
Custom string custom string.

Location
Any Any: page may be cached anywhere.
Client Client: cached content remains at
browser.
Downstream
Downstream: cached content stored in
Server
downstream and server both.
None Server: cached content saved only on
server.
None: disables caching.
Duration Number Number of seconds the page or control
is cached.
Let us add a text box and a button to the previous example and add this event handler for the button.
protected void btnmagic_Click(object sender, EventArgs e)
{
Response.Write("<br><br>");
Response.Write("<h2> Hello, " + this.txtname.Text + "</h2>");
}

Change the OutputCache directive:


<%@ OutputCache Duration="60" VaryByParam="txtname" %>

When the program is executed, ASP.NET caches the page on the basis of the name in the text box.

Data Caching
The main aspect of data caching is caching the data source controls. We have already discussed that the
data source controls represent data in a data source, like a database or an XML file. These controls derive
from the abstract class DataSourceControl and have the following inherited properties for implementing
caching:
 CacheDuration - It sets the number of seconds for which the data source will cache data.
 CacheExpirationPolicy - It defines the cache behavior when the data in cache has expired.
 CacheKeyDependency - It identifies a key for the controls that auto-expires the content of its
cache when removed.
 EnableCaching - It specifies whether or not to cache the data.
Example
To demonstrate data caching, create a new website and add a new web form on it. Add a SqlDataSource control
with the database connection already used in the data access tutorials.
For this example, add a label to the page, which would show the response time for the page.

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

Apart from the label, the content page is same as in the data access tutorial. Add an event handler for the
page load event:

protected void Page_Load(object sender, EventArgs e)


{
lbltime.Text = String.Format("Page posted at: {0}", DateTime.Now.ToLongTimeString());
}

The designed page should look as shown:


When you execute the page for the first time, nothing different happens, the label shows that, each time you
refresh the page, the page is reloaded and the time shown on the label changes.
Next, set the EnableCaching attribute of the data source control to be 'true' and set the Cacheduration
attribute to '60'. It will implement caching and the cache will expire every 60 seconds.
The timestamp changes with every refresh, but if you change the data in the table within these 60 seconds, it is
not shown before the cache expires.

<asp:SqlDataSource ID = "SqlDataSource1" runat = "server"


ConnectionString = "<%$ ConnectionStrings: ASPDotNetStepByStepConnectionString %>"
ProviderName = "<%$ ConnectionStrings:
ASPDotNetStepByStepConnectionString.ProviderName %>"
SelectCommand = "SELECT * FROM [DotNetReferences]"
EnableCaching = "true" CacheDuration = "60">
</asp:SqlDataSource>

Object Caching
Object caching provides more flexibility than other cache techniques. You can use object caching to place
any object in the cache. The object can be of any type - a data type, a web control, a class, a dataset object,
etc. The item is added to the cache simply by assigning a new key name, shown as follows Like:

Cache["key"] = item;

ASP.NET also provides the Insert() method for inserting an object to the cache. This method has four
overloaded versions. Let us see them:

Overload Description

Cache.Insert((key, value); Inserts an item into


the cache with the
key name
and value with
default priority
and expiration.

Cache.Insert(key, value, dependencies); Inserts an item into


the cache with key,
value, default
priority, expiration
and a
CacheDependency
name that links to
other files or
items so that when
these change the
cache item remains
no longer valid.

Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration); This indicates an


expiration policy
along with the
above issues.

Cache.Insert(key, value, dependencies, absoluteExpiration, slidingExpiration, This along with the


priority, onRemoveCallback); parameters also
allows you to set a
priority for the
cache item and a
delegate that, points
to a method to be
invoked when the
item is removed.

Sliding expiration is used to remove an item from the cache when it is not used for the specified time span.
The following code snippet stores an item with a sliding expiration of 10 minutes with no dependencies.

Cache.Insert("my_item", obj, null, DateTime.MaxValue, TimeSpan.FromMinutes(10));

Example
Create a page with just a button and a label. Write the following code in the page load event:
protected void Page_Load(object sender, EventArgs e)
{
if (this.IsPostBack)
{
lblinfo.Text += "Page Posted Back.<br/>";
}
else
{
lblinfo.Text += "page Created.<br/>";
}

if (Cache["testitem"] == null)
{
lblinfo.Text += "Creating test item.<br/>";
DateTime testItem = DateTime.Now; lblinfo.Text
+= "Storing test item in cache "; lblinfo.Text +=
"for 30 seconds.<br/>"; Cache.Insert("testitem",
testItem, null,
DateTime.Now.AddSeconds(30), TimeSpan.Zero);
}
else
{
lblinfo.Text += "Retrieving test item.<br/>"; DateTime
testItem = (DateTime)Cache["testitem"]; lblinfo.Text +=
"Test item is: " + testItem.ToString(); lblinfo.Text +=
"<br/>";
}

lblinfo.Text += "<br/>";
}
When the page is loaded for the first time, it says:
Page Created.
Creating test item.
Storing test item in cache for 30 seconds.
If you click on the button again within 30 seconds, the page is posted back but the label control gets its
information from the cache as shown:
Page Posted Back.
Retrieving test item.
Test item is: 14-07-2010 01:25:04
ASP.NET - Security
Implementing security in a site has the following aspects:
 Authentication : It is the process of ensuring the user's identity and authenticity. ASP.NET allows
four types of authentications:
o Windows Authentication
o Forms Authentication
o Passport Authentication
o Custom Authentication
 Authorization : It is the process of defining and allotting specific roles to specific users.
 Confidentiality : It involves encrypting the channel between the client browser and the web server.
 Integrity : It involves maintaining the integrity of data. For example, implementing digital
signature.
Forms-Based Authentication
Traditionally, forms-based authentication involves editing the web.config file and adding a login page with
appropriate authentication code.
The web.config file could be edited and the following codes written on it:

<configuration>

<system.web>
<authentication mode="Forms">
<forms loginUrl ="login.aspx"/>
</authentication>

<authorization>
<deny users="?"/>
</authorization>
</system.web>
...
...
</configuration>

The login.aspx page mentioned in the above code snippet could have the following code behind file with
the usernames and passwords for authentication hard coded into it.

protected bool authenticate(String uname, String pass)


{
if(uname == "Tom")
{
if(pass == "tom123")
return true;
}

if(uname == "Dick")
{
if(pass == "dick123")
return true;
}

if(uname == "Harry")
{
if(pass == "har123")
return true;
}

return false;
}

public void OnLogin(Object src, EventArgs e)


{
if (authenticate(txtuser.Text, txtpwd.Text))
{
FormsAuthentication.RedirectFromLoginPage(txtuser.Text, chkrem.Checked);
}
else
{
Response.Write("Invalid user name or password");
}
}
Observe that the FormsAuthentication class is responsible for the process of authentication.
However, Visual Studio allows you to implement user creation, authentication, and authorization with
seamless ease without writing any code, through the Web Site Administration tool. This tool allows
creating users and roles.
Apart from this, ASP.NET comes with readymade login controls set, which has controls
performing all the jobs for you.
Implementing Forms-Based Security
To set up forms-based authentication, you need the following:

 A database of users to support the authentication process


 A website that uses the database
 User accounts
 Roles
 Restriction of users and group activities
 A default page, to display the login status of the users and other information.
 A login page, to allow users to log in, retrieve password, or change password To
create users, take the following steps:
Step (1) : Choose Website -> ASP.NET Configuration to open the Web Application Administration Tool.
Step (2) : Click on the Security tab.

Step (3) : Select the authentication type to 'Forms based authentication' by selecting the 'From the Internet'
radio button.

Step (4) : Click on 'Create Users' link to create some users. If you already had created roles, you could assign
roles to the user, right at this stage.
Step (5) : Create a web site and add the following pages:

 Welcome.aspx
 Login.aspx
 CreateAccount.aspx
 PasswordRecovery.aspx
 ChangePassword.aspx
Step (6) : Place a LoginStatus control on the Welcome.aspx from the login section of the toolbox. It has two
templates: LoggedIn and LoggedOut.
In LoggedOut template, there is a login link and in the LoggedIn template, there is a logout link on the
control. You can change the login and logout text properties of the control from the Properties window.

Step (7) : Place a LoginView control from the toolbox below the LoginStatus control. Here, you can put
texts and other controls (hyperlinks, buttons etc.), which are displayed based on whether the user is
logged in or not.
This control has two view templates: Anonymous template and LoggedIn template. Select each view and
write some text for the users to be displayed for each template. The text should be placed on the area
marked red.
Step (8) : The users for the application are created by the developer. You might want to allow a visitor to
create a user account. For this, add a link beneath the LoginView control, which should link to the
CreateAccount.aspx page.
Step (9) : Place a CreateUserWizard control on the create account page. Set the ContinueDestinationPageUrl
property of this control to Welcome.aspx.

Step (10) : Create the Login page. Place a Login control on the page. The LoginStatus control automatically links
to the Login.aspx. To change this default, make the following changes in the web.config file.
For example, if you want to name your log in page as signup.aspx, add the following lines to the
<authentication> section of the web.config:

<configuration>
<system.web>
<authentication mode="Forms">
<forms loginUrl ="signup.aspx" defaultUrl = “Welcome.aspx― />
</authentication>
</system.web>
</configuration>

Step (11) : Users often forget passwords. The PasswordRecovery control helps the user gain access to the
account. Select the Login control. Open its smart tag and click 'Convert to Template'.
Customize the UI of the control to place a hyperlink control under the login button, which should link to the
PassWordRecovery.aspx.
Step (12) : Place a PasswordRecovery control on the password recovery page. This control needs an email
server to send the passwords to the users.

Step (13) : Create a link to the ChangePassword.aspx page in the LoggedIn template of the LoginView
control in Welcome.aspx.

Step (14) : Place a ChangePassword control on the change password page. This control also has two views.

Now run the application and observe different security operations.


To create roles, go back to the Web Application Administration Tools and click on the Security tab. Click on
'Create Roles' and create some roles for the application.
Click on the 'Manage Users' link and assign roles to the users.

-------------------------------------------------------------------------------------------------------------

You might also like