ASP Net Notes
ASP Net Notes
[Link] Introduction
[Link] 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.
[Link] works on top of the HTTP protocol, and uses the HTTP commands and policies to set
a browser-to-server bilateral communication and cooperation.
[Link] is a part of Microsoft .Net platform. [Link] 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 [Link] application codes can be written in any of the following languages:
• C#
• Visual [Link]
• Jscript
• J#
[Link] is used to produce interactive, data-driven web applications over the internet. It consists
of a large number of controls such as text boxes, buttons, and labels for assembling, configuring,
and manipulating code to create HTML pages.
The starting point of any analysis of the .net framework is the understanding that .net is really a
cluster of different technologies. It includes:
• The .Net languages, which includes C# and visual basic .net, the object oriented and
modernized successor to Visual Basic 6.
• The Common Language Runtime (CLR), the .Net Runtime engine that executes all .Net
programs, and provides modern services such as automatic memory management,
security, optimization and garbage collection.
• The .Net Class Library, which collects the thousands of pieces of prebuilt functionality
that you can snap in to your applications. These are sometime organized into technology
sets, such as [Link], and windows forms
• [Link], the platform services that allow you to program web applications and web
services in any .Net language, with almost any feature from the .Net class Library.
• Visual Studio .Net, an optional development tool that contains a rich set of productivity
and debugging features.
The Common Language Runtime
[Link] Windows
Web Forms
Data access Forms
Step 3 − Once the installation process is completed successfully, you will see the following
dialog. Close this dialog and restart your computer if required.
Step 4 − Open Visual Studio from start Menu which will open the following dialog. It will be a
while for the first time for preparation.
Step 5 − Once all is done you will see the main window of Visual studio.
Let’s create a new project from File → New → Project
The Visual Studio IDE
The new project window allows choosing an application template from the available templates.
When you start a new web site, [Link] provides the starting folders and files for the site,
including two files for the first web form of the site.
The file named [Link] contains the HTML and asp code that defines the form, and the file
named [Link] (for C# coding) or the file named [Link] (for VB coding)
contains the code in the language you have chosen and this code is responsible for the actions
performed on a form.
The primary window in the Visual Studio IDE is the Web Forms Designer window. Other
supporting windows are the Toolbox, the Solution Explorer, and the Properties window. You use
the designer to design a web form, to add code to the control on the form so that the form works
according to your need, you use the code editor.
CLR is the engine that supports all the .net languages. It is the runtime that converts a MSIL
(Microsoft Intermediate language) code into the host machine language code.
The CLR also provides the whole set of related services:
• Code verification & optimization
• Memory management & garbage collection
• Code access security
• Compiler & Loader
The implications of CLR
1. Deep language Integration: the CLR makes no distinction between different languages-
In fact, it has no way of knowing what language was used to create an executable
2. No More DLL hell: IL program store extra information about their classes and the
components they required (Called meta data). The CLR examines this information and
automatically prevents an application from using a wrong version of a component.
3. Side by Side Execution: The CLR also has ability to load more than one version of a
component at a time.
4. Fewer errors: Whole categories of errors are impossible with the CLR.
The .net class Library: the .net class library is the giant repository of classes that provide pre
fabricated functionality for everything from reading an XML to sending an e-mail message.
Managed Code
Managed Code in Microsoft .Net Framework, is the code that has executed by the Common
Language Runtime (CLR) environment. On the other hand Unmanaged Code is directly executed
by the computer's CPU. Data types, error-handling mechanisms, creation and destruction rules,
and design guidelines vary between managed and unmanaged object models.
The benefits of Managed Code include programmers convenience and enhanced security .
Managed code is designed to be more reliable and robust than unmanaged code , examples
are Garbage Collection , Type Safety etc. The Managed Code running in a Common Language
Runtime (CLR) cannot be accessed outside the runtime environment as well as cannot call directly
from outside the runtime environment. This makes the programs more isolated and at the same
time computers are more secure . Unmanaged Code can bypass the .NET Framework and make
direct calls to the Operating System. Calling unmanaged code presents a major security risk.
Metadata in .Net is binary information which describes the characteristics of a resource . This
information include Description of the Assembly , Data Types and members with their declarations
and implementations, references to other types and members , Security permissions etc. A
module's metadata contains everything that needed to interact with another module.
During the compile time Metadata created with Microsoft Intermediate Language (MSIL) and
stored in a file called a Manifest . Both Metadata and Microsoft Intermediate Language (MSIL)
together wrapped in a Portable Executable (PE) file. During the runtime of a program Just In Time
(JIT) compiler of the Common Language Runtime (CLR) uses the Metadata and converts
Microsoft Intermediate Language (MSIL) into native code. When code is executed, the runtime
loads metadata into memory and references it to discover information about your code's classes,
members, inheritance, and so on. Moreover Metadata eliminating the need for Interface Definition
Language (IDL) files, header files, or any external method of component reference.
Variables
Variables are essentially locations in computer memory that are reserved for storing the data used
by an application. Each variable is given a name by the programmer and assigned a value. The
name assigned to the variable may then be used in the C# code to access the value assigned to the
variable. This access can involve either reading the value of the variable, or changing the value. It
is, of course, the ability to change the value of variables which gives them the name variable.
A variable must be declared as a particular type such as an integer, a character or a string. C# is
what is known as a strongly typed language in that once a variable has been declared as a particular
type it cannot subsequently be changed to a different type. While this may come as a shock to
those familiar with loosely typed languages such as Ruby it will be familiar to Java, C and C++
programmers. Whilst it is not possible to change the type of a variable it is possible to disguise the
variable as another type under certain circumstances.
Variable declarations require a type, a name and, optionally a value assignment.
int interestRate;
Constant
A constant is similar to a variable in that it provides a named location in memory to store a data
value. Constants differ in one significant way in that once a value has been assigned to a constant
it cannot subsequently be changed.
Constants are particularly useful if there is a value which is used repeatedly throughout the
application code. Rather than use the value each time, it makes the code easier to read if the value
is first assigned to a constant which is then referenced in the code. For example, it might not be
clear to someone reading your C# code why you used the value 5 in an expression. If, instead of
the value 5, you use a constant named interestRate the purpose of the value becomes much clearer.
Constants also have the advantage that the if the programmer needs to change a widely used value
it only needs to be changed once in the constant declaration and not each time it is referenced.
As with variables, constants have a type, a name and a value. Unlike variables, constants must be
initialized at the same time that they are declared and must be prefixed with the const keyword:
Data Types
The data type tells the compiler what kind of value a variable can hold. C# includes many in-built
data types for different kinds of data, e.g. String, number, float, decimal, etc.
Each data types includes specific range of values. For example, a variable of int data type can have
any value between -2,147,483,648 to 2,147,483,647. The same way, bool data type can have only
two value - true or false. The following table lists the data types available in C# along with the
range of values possible for each data type:
Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical
manipulations. C# has rich set of built-in operators and provides the following type of operators
−
• Arithmetic Operators
• Relational Operators
• Logical Operators
• Bitwise Operators
• Assignment Operators
• Misc Operators
Arithmetic Operators
Following table shows all the arithmetic operators supported by C#. Assume variable A holds 10
and variable B holds 20 then −
Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then −
== Checks if the values of two operands are equal or not, if yes then (A == B)
condition becomes true. is not
true.
!= Checks if the values of two operands are equal or not, if values are (A != B)
not equal then condition becomes true. is true.
> Checks if the value of left operand is greater than the value of right (A > B)
operand, if yes then condition becomes true. is not
true.
< Checks if the value of left operand is less than the value of right (A < B)
operand, if yes then condition becomes true. is true.
>= Checks if the value of left operand is greater than or equal to the (A >= B)
value of right operand, if yes then condition becomes true. is not
true.
<= Checks if the value of left operand is less than or equal to the value (A <= B)
of right operand, if yes then condition becomes true. is true.
Logical Operators
Following table shows all the logical operators supported by C#. Assume variable A holds
Boolean value true and variable B holds Boolean value false, then −
&& Called Logical AND operator. If both the operands are non zero (A &&
then condition becomes true. B) is
false.
Bitwise Operators
Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |, and ^
are as follows −
p q p&q p|q p^q
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
Assume if A = 60; and B = 13; then in the binary format they are as follows −
A = 0011 1100
B = 0000 1101
-------------------
A&B = 0000 1100
A|B = 0011 1101
A^B = 0011 0001
~A = 1100 0011
The Bitwise operators supported by C# are listed in the following table. Assume variable A holds
60 and variable B holds 13, then −
& Binary AND Operator copies a bit to the result if it exists in both (A & B) =
operands. 12, which is
0000 1100
~ Binary Ones Complement Operator is unary and has the effect (~A ) = -61,
of 'flipping' bits. which is
1100 0011
in 2's
complement
due to a
signed
binary
number.
<< Binary Left Shift Operator. The left operands value is moved left A << 2 =
by the number of bits specified by the right operand. 240, which
is 1111
0000
>> Binary Right Shift Operator. The left operands value is moved A >> 2 = 15,
right by the number of bits specified by the right operand. which is
0000 1111
Assignment Operators
There are following assignment operators supported by C# −
Operator Description Example
Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? :supported by C#.
Operator Precedence in C#
Operator precedence determines the grouping of terms in an expression. This affects evaluation
of an expression. Certain operators have higher precedence than others; for example, the
multiplication operator has higher precedence than the addition operator.
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence
than +, so the first evaluation takes place for 3*2 and then 7 is added into it.
Here, operators with the highest precedence appear at the top of the table, those with the lowest
appear at the bottom. Within an expression, higher precedence operators are evaluated first.
1 if statement
An if statement consists of a boolean expression followed by one or more
statements.
2 if...else statement
An if statement can be followed by an optional else statement, which executes
when the boolean expression is false.
3 nested if statements
You can use one if or else if statement inside another if or else ifstatement(s).
4 switch statement
A switch statement allows a variable to be tested for equality against a list of
values.
if..else statements
An if statement can be followed by an optional else statement, which executes when the boolean
expression is false.
Syntax
The syntax of an if...else statement in C# is :
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
else
{
/* statement(s) will execute if the boolean expression is false */
}
If the boolean expression evaluates to true, then the if block of code is executed, otherwise else
block of code is executed.
Switch Statements
A switch statement allows a variable to be tested for equality against a list of values. Each value
is called a case, and the variable being switched on is checked for each switch case.
Syntax
The syntax for a switch statement in C# is as follows:
switch(expression)
{
case constant-expression1 : statement(s);
break;
case constant-expression2 :
case constant-expression3 : statement(s);
break;
/* you can have any number of case statements */
default : /* Optional */
statement(s);
}
The following rules apply to a switch statement −
• The expression used in a switch statement must have an integral or enumerated type, or
be of a class type in which the class has a single conversion function to an integral or
enumerated type.
• You can have any number of case statements within a switch. Each case is followed by the
value to be compared to and a colon.
• The constant-expression for a case must be the same data type as the variable in the
switch, and it must be a constant or a literal.
• When the variable being switched on is equal to a case, the statements following that case
will execute until a break statement is reached.
• When a break statement is reached, the switch terminates, and the flow of control jumps
to the next line following the switch statement.
• Not every case needs to contain a break. If no break appears, then it will raise a compile
time error.
• A switch statement can have an optional default case, which must appear at the end of the
switch. The default case can be used for performing a task when none of the cases is true.
Flow Diagram
The ? : Operator
We have covered conditional operator ? : in previous chapter which can be used to
replace if...else statements. It has the following general form:
Where Exp1, Exp2, and Exp3 are expressions. Notice the use and placement of the colon.
The value of a ? expression is determined as follows: Exp1 is evaluated. If it is true, then Exp2 is
evaluated and becomes the value of the entire ? expression. If Exp1 is false, then Exp3 is evaluated
and its value becomes the value of the expression.
Looping structures
There may be a situation, when you need to execute a block of code several number of times. In
general, the statements are executed sequentially: The first statement in a function is executed
first, followed by the second, and so on.
Programming languages provide various control structures that allow for more complicated
execution paths.
A loop statement allows us to execute a statement or a group of statements multiple times and
following is the general from of a loop statement in most of the programming languages −
C# provides following types of loop to handle looping requirements.
• while loop: It repeats a statement or a group of statements while a given condition is true. It tests the
condition before executing the loop body.
• for loop: It executes a sequence of statements multiple times and abbreviates the code that manages the
loop variable.
• do...while loop: It is similar to a while statement, except that it tests the condition at the end of the loop
body
• nested loops: You can use one or more loop inside any another while, for or do..while loop.
while Loop
A while loop statement in C# repeatedly executes a target statement as long as a given condition
is true.
Syntax
The syntax of a while loop in C# is –
while(condition)
{
statement(s);
}
Here, statement(s) may be a single statement or a block of statements. The condition may be
any expression, and true is any non-zero value. The loop iterates while the condition is true.
When the condition becomes false, program control passes to the line immediately following the
loop.
Flow Diagram
Here, key point of the while loop is that the loop might not ever run. When the condition is tested
and the result is false, the loop body is skipped and the first statement after the while loop is
executed.
for loop
A for loop is a repetition control structure that allows you to efficiently write a loop that needs to
execute a specific number of times.
Syntax
The syntax of a for loop in C# is:
for ( init; condition; increment ) { statement(s); }
do….while loop
Unlike for and while loops, which test the loop condition at the start of the loop,
the do...while loop checks its condition at the end of the loop.
A do...while loop is similar to a while loop, except that a do...while loop is guaranteed to execute
at least one time.
Syntax
The syntax of a do...while loop in C# is:
do
{
statement(s);
} while( condition );
Notice that the conditional expression appears at the end of the loop, so the statement(s) in the
loop execute once before the condition is tested.
If the condition is true, the flow of control jumps back up to do, and the statement(s) in the loop
execute again. This process repeats until the given condition becomes false.
Flow Diagram
Loop Control Statements
Loop control statements change execution from its normal sequence. When execution leaves a
scope, all automatic objects that were created in that scope are destroyed.
C# provides the following control statements. Click the following links to check their details.
• break statement: Terminates the loop or switch statement and transfers execution to the
statement immediately following the loop or switch.
• continue statement: Causes the loop to skip the remainder of its body and immediately
retest its condition prior to reiterating.
break statement
The break statement in C# has following two usage −
• When the break statement is encountered inside a loop, the loop is immediately
terminated and program control resumes at the next statement following the loop.
• It can be used to terminate a case in the switch statement.
If you are using nested loops (i.e., one loop inside another loop), the break statement will stop the
execution of the innermost loop and start executing the next line of code after the block.
Syntax
The syntax for a break statement in C# is as follows –
break;
Flow Diagram
continue statement
The continue statement in C# works somewhat like the break statement. Instead of forcing
termination, however, continue forces the next iteration of the loop to take place, skipping any
code in between.
For the for loop, continue statement causes the conditional test and increment portions of the
loop to execute. For the while and do...while loops, continue statement causes the program
control passes to the conditional tests.
Syntax
The syntax for a continue statement in C# is as follows −
continue;
Flow Diagram
UNIT-II
Structure
In C#, a structure is a value type data type. It helps you to make a single variable hold related data
of various data types. The struct keyword is used for creating a structure. Structures are used to
represent a record. Suppose you want to keep track of your books in a library. You might want to
track the following attributes about each book −
• Title
• Author
• Subject
• Book ID
Defining a Structure
To define a structure, you must use the struct statement. The struct statement defines a new data
type, with more than one member for your program.
For example, here is the way you can declare the Book structure –
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};
Features of C# Structures
Structures in C# are quite different from that in traditional C or C++. The C# structures have the
following features:
• Structures can have methods, fields, indexers, properties, operator methods, and events.
• Structures can have defined constructors, but not destructors. However, you cannot define
a default constructor for a structure. The default constructor is automatically defined and
cannot be changed.
• Unlike classes, structures cannot inherit other structures or classes.
• Structures cannot be used as a base for other structures or classes.
• A structure can implement one or more interfaces.
• Structure members cannot be specified as abstract, virtual, or protected.
• When you create a struct object using the New operator, it gets created and the appropriate
constructor is called. Unlike classes, structs can be instantiated without using the New
operator.
• If the New operator is not used, the fields remain unassigned and the object cannot be used
until all the fields are initialized.
Where,
The enum_name specifies the enumeration type name.
The enumeration list is a comma-separated list of identifiers.
Each of the symbols in the enumeration list stands for an integer value, one greater than
the symbol that precedes it. By default, the value of the first enumeration symbol is 0.
For example −
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
Example:
using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };
static void Main(string[] args)
{
int WeekdayStart = (int)[Link];
int WeekdayEnd = (int)[Link];
[Link]("Monday: {0}", WeekdayStart);
[Link]("Friday: {0}", WeekdayEnd);
[Link]();
}
}
}
Arrays
An array stores a fixed-size sequential collection of elements of the same type. An array is used to
store a collection of data, but it is often more useful to think of an array as a collection of variables of
the same type stored at contiguous memory locations.
Instead of declaring individual variables, such as number0, number1, ..., and number99, you declare
one array variable such as numbers and use numbers[0], numbers[1], and ..., numbers[99] to represent
individual variables. A specific element in an array is accessed by an index.
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element
and the highest address to the last element.
Declaring Arrays
To declare an array in C#, you can use the following syntax:
datatype[] arrayName;
where,
datatype is used to specify the type of elements in the array.
[ ] specifies the rank of the array. The rank specifies the size of the array.
arrayName specifies the name of the array.
For example
double[] balance;
Initializing an Array
Declaring an array does not initialize the array in the memory. When the array variable is initialized,
you can assign values to the array.
Array is a reference type, so you need to use the new keyword to create an instance of the array. For
example,
double[] balance = new double[10];
Element[0] = 100 Element[1] = 101 Element[2] = 102 Element[3] = 103 Element[4] = 104
Element[5] = 105 Element[6] = 106 Element[7] = 107 Element[8] = 108 Element[9] = 109
There are following few important concepts related to array which should be clear to a C# programmer
• Multi-dimensional arrays: C# supports multidimensional arrays. The simplest form of the
multidimensional array is the two-dimensional array.
• Jagged arrays: C# supports multidimensional arrays, which are arrays of arrays.
• Passing arrays to functions: You can pass to the function a pointer to an array by specifying
the array's name without an index.
• Param arrays: This is used for passing unknown number of parameters to a function.
• The Array Class: Defined in System namespace, it is the base class to all arrays, and provides
various properties and methods for working with arrays.
Multi-dimensional arrays
C# allows multidimensional arrays. Multi-dimensional arrays are also called rectangular array.
You can declare a 2-dimensional array of strings as:
string [,] names;
or, a 3-dimensional array of int variables as:
int [ , , ] m;
Two-Dimensional Arrays
The simplest form of the multidimensional array is the 2-dimensional array. A 2-dimensional
array is a list of one-dimensional arrays.
A 2-dimensional array can be thought of as a table, which has x number of rows and y number of
columns. Following is a 2-dimensional array, which contains 3 rows and 4 columns –
Thus, every element in the array a is identified by an element name of the form a[ i , j ], where a
is the name of the array, and i and j are the subscripts that uniquely identify each element in array
a.
Initializing Two-Dimensional Arrays
Multidimensional arrays may be initialized by specifying bracketed values for each row. The
Following array is with 3 rows and each row has 4 columns.
int [,] a = new int [3,4]
{
{0, 1, 2, 3} , /* initializers for row indexed by 0 */
{4, 5, 6, 7} , /* initializers for row indexed by 1 */
{8, 9, 10, 11} /* initializers for row indexed by 2 */
};
Jagged arrays
A Jagged array is an array of arrays. You can declare a jagged array named scores of type int as
int [][] scores;
Declaring an array, does not create the array in memory. To create the above array:
int[][] scores = new int[5][];
for (int i = 0; i < [Link]; i++)
{
scores[i] = new int[4];
}
Where, scores is an array of two arrays of integers - scores[0] is an array of 3 integers and
scores[1] is an array of 4 integers.
Button Controls
[Link] provides three types of button control:
When a user clicks a button, two events are raised: Click and Command.
Label controls provide an easy way to display text which can be changed from one execution of
a page to the next. If you want to display text that does not change, you use the literal text.
• TextMode: Specifies the type of text box. SingleLine creates a standard text box,
MultiLine creates a text box that accepts more than one line of text and the Password
causes the characters that are entered to be masked. The default is SingleLine.
• Text: The text content of the text box.
• MaxLength: The maximum number of characters that can be entered into the text box.
• Wrap: It determines whether or not text wraps automatically for multi-line text box;
default is true.
• ReadOnly: Determines whether the user can change the text in the box; default is false,
i.e., the user can not change the text.
• Columns: The width of the text box in characters. The actual width is determined based
on the font that is used for the text entry.
• Rows: The height of a multi-line text box in lines. The default value is 0, means a single
line text box.
The mostly used attribute for a label control is 'Text', which implies the text displayed on the
label.
To create a group of radio buttons, you specify the same name for the GroupName attribute of
each radio button in the group. If more than one group is required in a single form, then specify
a different group name for each group.
If you want check box or radio button to be selected when the form is initially displayed, set its
Checked attribute to true. If the Checked attribute is set to true for multiple radio buttons in a
group, then only the last one is considered as true.
• Text: The text displayed next to the check box or radio button.
• Checked: Specifies whether it is selected or not, default is false.
• GroupName: Name of the group the control belongs to.
List Controls
[Link] provides the following controls
• Drop-down list,
• List box,
• Radio button list,
• Check box list,
• Bulleted list.
These control let a user choose from one or more items from the list. List boxes and drop-down
lists contain one or more list items. These lists can be loaded either by code or by the
ListItemCollection editor.
The ListItemCollection
The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents
one item in the list. Items in a ListItemCollection are numbered from 0.
When the items into a list box are loaded using strings like: [Link]("Blue"), then both
the Text and Value properties of the list item are set to the string value you specify. To set it
differently you must create a list item object and then add that item to the collection.
The ListItemCollection Editor is used to add item to a drop-down list or list box. This is used to
create a static list of items. To display the collection editor, select edit item from the smart tag
menu, or select the control and then click the ellipsis button from the Item property in the
properties window.
• Add(string): Adds a new item at the end of the collection and assigns the string parameter
to the Text property of the item.
• Add(ListItem): Adds a new item at the end of the collection.
• Insert(integer, string): Inserts an item at the specified index location in the collection, and
assigns string parameter to the text property of the item.
• Insert(integer, ListItem): Inserts the item at the specified index location in the collection.
• Remove(string): Removes the item with the text value same as the string.
• Remove(ListItem): Removes the specified item.
• RemoveAt(integer): Removes the item at the specified index as the integer.
• Clear: Removes all the items of the collection.
• FindByValue(string): Returns the item whose value is same as the string.
• FindByValue(Text): Returns the item whose text is same as the string.
• BulletStyle:This property specifies the style and looks of the bullets, or numbers.
• RepeatDirection: It specifies the direction in which the controls to be repeated. The values
available are Horizontal and Vertical. Default is Vertical.
• RepeatColumns: It specifies the number of columns to use when repeating the controls;
default is 0.
HyperLink Control
The HyperLink control is like the HTML <a> element.
Image Control
The image control is used for displaying images on the web page, or some alternative text, if the
image is not available.
Dialog boxes
There are many built-in dialog boxes to be used in Windows forms for various tasks like opening
and saving files, printing a page, providing choices for colors, fonts, page setup, etc., to the user
of an application. These built-in dialog boxes reduce the developer's time and workload.
All of these dialog box control classes inherit from the CommonDialog class and override
the RunDialog() function of the base class to create the specific dialog box.
The RunDialog() function is automatically invoked when a user of a dialog box calls
its ShowDialog() function.
The ShowDialog method is used to display all the dialog box controls at run-time. It returns a
value of the type of DialogResult enumeration. The values of DialogResult enumeration are −
When you double click any of the dialog controls in the toolbox or drag the control onto the form,
it appears in the Component tray at the bottom of the Windows Forms Designer, they do not
directly show up on the form.
UNIT-III
[Link]
[Link] provides a bridge between the front end controls and the back end database. The
[Link] 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.
• 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.
• IsInitialized: Indicates whether the DataSet is initialized.
• Locale: Gets or sets the locale information used to compare strings within the table.
• Tables: Returns the collection of DataTable objects.
• 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 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.
// adding columns
AddNewColumn(Students, "System.Int32", "StudentID");
AddNewColumn(Students, "[Link]", "StudentName");
AddNewColumn(Students, "[Link]", "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 = [Link](columnName,
[Link](columnType));
}
• 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:
Features of [Link]
Pages
[Link] Web pages, known officially as Web Forms, are the main building block for application
development. Web forms are contained in files with an “.aspx” extension; these files typically
contain static (X)HTML markup, as well as markup defining server-side Web Controls and User
Controls where the developers place all the required static and dynamic content for the Web page.
Additionally, dynamic code which runs on the server can be placed in a page within a block <% -
- dynamic code -- %>, which is similar to other Web development technologies such as PHP, JSP,
and ASP. With [Link] Framework 2.0, Microsoft introduced a new code-behind model which
allows static text to remain on the .aspx page, while dynamic code remains in an .[Link] or
.[Link] or .[Link] file (depending on the programming language used).
Directives
A directive is special instructions on how [Link] should process the page. The most common
directive is <%@ Page %> which can specify many things, such as which programming language
is used for the server-side code.
User controls
User controls are encapsulations of sections of pages which are registered and used as controls
in [Link]. User controls are created as ASCX markup files. These files usually contain static
(X)HTML markup, as well as markup defining server-side Web controls. These are the locations
where the developer can place the required static and dynamic content. A user control is compiled
when its containing page is requested and is stored in memory for subsequent requests. User
controls have their own events which are handled during the life of [Link]. An event
bubbling mechanism provides the ability to pass an event fired by a user control up to its containing
page. Unlike an [Link] page, a user control cannot be requested independently; one of its
containing pages is requested instead.
Custom controls
Programmers can also build custom controls for [Link] applications. Unlike user controls,
these controls do not have an ASCX markup file, having all their code compiled into a dynamic
link library (DLL) file. Such custom controls can be used across multiple Web applications
and Visual Studio projects.
Rendering technique
[Link] uses a visited composites rendering technique. During compilation, the template (.aspx)
file is compiled into initialization code which builds a control tree (the composite) representing
the original template. Literal text goes into instances of the Literal control class, and server controls
are represented by instances of a specific control class. The initialization code is combined with
user-written code (usually by the assembly of multiple partial classes) and results in a class specific
for the page. The page doubles as the root of the control tree.
Actual requests for the page are processed through a number of steps. First, during the initialization
steps, an instance of the page class is created and the initialization code is executed. This produces
the initial control tree which is now typically manipulated by the methods of the page in the
following steps. As each node in the tree is a control represented as an instance of a class, the code
may change the tree structure as well as manipulate the properties/methods of the individual nodes.
Finally, during the rendering step a visitor is used to visit every node in the tree, asking each node
to render itself using the methods of the visitor. The resulting HTML output is sent to the client.
After the request has been processed, the instance of the page class is discarded and with it the
entire control tree. This is a source of confusion among novice [Link] programmers who rely
on class instance members that are lost with every page request/response cycle.
State management
[Link] applications are hosted by a Web server and are accessed using
the stateless HTTP protocol. As such, if an application uses stateful interaction, it has to
implement state management on its own. [Link] provides various functions for state
management. Conceptually, Microsoft treats “state” as GUI state. Problems may arise if an
application needs to keep track of “data state”; for example, afinite-state machine which may be
in a transient state between requests (lazy evaluation) or which takes a long time to initialize. State
management in [Link] pages with authentication can make Web scraping difficult or
impossible.
Application State
Application state is held by a collection of shared user-defined variables. These are set and
initialized when the Application_OnStartevent fires on the loading of the first instance of the
application and are available until the last instance exits. Application state variables are accessed
using the Applications collection, which provides a wrapper for the application state. Application
state variables are identified by name.
Session State
Server-side session state is held by a collection of user-defined session variables that are persistent
during a user session. These variables, accessed using the Session collection, are unique to each
session instance. The variables can be set to be automatically destroyed after a defined time of
inactivity even if the session does not end. Client-side user session is maintained by either
a cookie or by encoding the session ID in the URL itself.
• In-Process Mode: The session variables are maintained within the [Link] process. This
is the fastest way; however, in this mode the variables are destroyed when
the [Link] process is recycled or shut down.
• ASPState Mode: [Link] runs a separate Windows service that maintains the state
variables. Because state management happens outside the [Link] process, and because
the [Link] engine accesses data using .NET Remoting, ASPState is slower than In-
Process. This mode allows an [Link] to be load-balanced and scaled across
multiple servers. Because the state management service runs independently of [Link],
the session variables can persist across [Link] process shutdowns. However, since
session state server runs as one instance, it is still one point of failure for session state. The
session-state service cannot be load-balanced, and there are restrictions on types that can
be stored in a session variable.
• SqlServer Mode: State variables are stored in a database, allowing session variables to be
persisted across [Link] process shutdowns. The main advantage of this mode is that it
allows the application to balance load on a server cluster, sharing sessions between servers.
This is the slowest method of session state management in [Link].
View State
View state refers to the page-level state management mechanism, utilized by the HTML pages
emitted by [Link] applications to maintain the state of the Web form controls and widgets. The
state of the controls is encoded and sent to the server at every form submission in a hidden field
known as __VIEWSTATE. The server sends back the variable so that when the page is re-
rendered, the controls render at their last state. At the server side, the application may change the
viewstate, if the processing requires a change of state of any control. The states of individual
controls are decoded at the server, and are available for use in [Link] pages using
the ViewState collection.
The main use for this is to preserve form information across postbacks. View state is turned on by
default and normally serializes the data in every control on the page regardless of whether it is
actually used during a postback. This behavior can (and should) be modified, however, as View
state can be disabled on a per-control, per-page, or server-wide basis.
Developers need to be wary of storing sensitive or private information in the View state of a page
or control, as the base64 string containing the view state data can easily be de-serialized. By
default, View state does not encrypt the __VIEWSTATE value. Encryption can be enabled on a
server-wide (and server-specific) basis, allowing for a certain level of security to be maintained.
Server-Side Caching
[Link] offers a “Cache” object that is shared across the application and can also be used to
store various objects. The “Cache” object holds the data only for a specified amount of time and
is automatically cleaned after the session time-limit elapses.
Hyper Text Transfer Protocol (HTTP) is a stateless protocol. When the client disconnects from
the server, the [Link] engine discards the page objects. This way, each web application can
scale up to serve numerous requests simultaneously without running out of server memory.
However, there needs to be some technique to store the information between requests and to
retrieve it when required. This information i.e., the current value of all the controls and variables
for the current user in the current session is called the State.
• View State
• Control State
• Session State
• Application State
View State
The view state is the state of the page and all its controls. It is automatically maintained across
posts by the [Link] framework.
When a page is sent back to the client, the changes in the properties of the page and its controls
are determined, and stored in the value of a hidden input field named _VIEWSTATE. When the
page is again posted back, the _VIEWSTATE field is sent to the server with the HTTP request.
• The entire application by setting the EnableViewState property in the <pages> section
of [Link] file.
• A page by setting the EnableViewState attribute of the Page directive, as <%@ Page
Language="C#" EnableViewState="false" %>
Session State
When a user connects to an [Link] website, a new session object is created. When session
state is turned on, a new session state object is created for each new request. This session state
object becomes part of the context and it is available through the page.
Session state is generally used for storing application data such as inventory, supplier list,
customer record, or shopping cart. It can also keep information about the user and his preferences,
and keep the track of pending operations.
Sessions are identified and tracked with a 120-bit SessionID, which is passed from client to server
and back as cookie or a modified URL. The SessionID is globally unique and random.
The session state object is created from the HttpSessionState class, which defines a collection of
session state items.
Application State
The [Link] application is the collection of all web pages, code and other files within a single
virtual directory on a web server. When information is stored in application state, it is available
to all the users.
To provide for the use of application state, [Link] creates an application state object for each
application from the HTTPApplicationState class and stores this object in server memory. This
object is represented by class file [Link].
Application State is mostly used to store hit counters and other statistical data, global application
data like tax rate, discount rate etc. and to keep the track of users visiting the site.
1. In IIS Manager, expand the local computer, expand the Web Sites directory, right-click the
Web site you wish to change, and click Stop.
2. Use Windows Explorer, to rename the LocalDrive:\Inetpub\Wwwroot directory to the
name of your choice. Alternatively, you can copy the entire \Wwwroot directory tree to a
new location.
3. In IIS Manager, right-click your Web site, and click Properties.
4. Click the Home Directory tab, and under The content for this resource should come from,
click A directory located on this computer, A share located on another computer, or A
redirection to a URL, depending on where your home directory is located.
5. In the Local path box, type the path name, share name, or URL of your directory.
The <virtualDirectory> element is a child of the <application> element and controls the
configuration settings for a specific virtual directory. A virtual directory is a directory name (also
referred to as path) that you specify in Internet Information Services (IIS) and map to a physical
directory on a local or remote server. The virtual directory name becomes part of the application's
URL, and users can request the URL from a browser to access content in the physical directory,
such as a Web page or a list of additional directories and files. If you specify a different name than
the physical directory for the virtual directory, it is more difficult for users to discover the actual
physical file structure on your server because the URL does not map directly to the root of the site.
3. In the Actions pane, click View Virtual Directories, and then click Add Virtual
Directory...
4. In the Add Virtual Directory dialog box, at a minimum enter information in
the Alias:and Physical path: text boxes, and then click OK.
UNIT-IV
Validation Controls
[Link] validation controls validate the user input data to ensure that useless, unauthenticated,
or contradictory data don't get stored.
BaseValidator Class
The validation control classes are inherited from the BaseValidator class hence they inherit its
properties and methods. Therefore, it would help to take a look at the properties and the methods
of this base class, which are common for all the validation controls:
Metacharacters Description
Quantifier Description
{N} N matches.
CustomValidator
The CustomValidator control allows writing application specific custom validation routines for
both the client side and the server side validation.
The client side validation is accomplished through the ClientValidationFunction property. The
client side validation routine should be written in a scripting language, such as JavaScript or
VBScript, which the browser can understand.
The server side validation routine must be called from the control's ServerValidate event handler.
The server side validation routine should be written in any .Net language, like C# or [Link].
ValidationSummary
The ValidationSummary control does not perform any validation but shows a summary of all
errors in the page. The summary displays the values of the ErrorMessage property of all validation
controls that failed validation.
The following two mutually inclusive properties list out the error message:
Validation Groups
Complex pages have different groups of information provided in different panels. In such
situation, a need might arise for performing validation separately for separate group. This kind of
situation is handled using validation groups.
To create a validation group, you should put the input controls and the validation controls into
the same logical group by setting their ValidationGroupproperty.
Controls are small building blocks of the graphical user interface, which include text boxes,
buttons, check boxes, list boxes, labels, and numerous other tools. Using these tools, the users
can enter data, make selections and indicate their preferences.
Controls are also used for structural jobs, like validation, data access, security, creating master
pages, and data manipulation.
• HTML controls
• HTML Server controls
• [Link] Server controls
• [Link] Ajax Server controls
• User controls and custom controls
[Link] server controls are the primary controls used in [Link]. These controls can be
grouped into the following categories:
• Validation controls - These are used to validate user input and they work by running
client-side script.
• Data source controls - These controls provides data binding to different data sources.
• Data view controls - These are various lists and tables, which can bind to data from data
sources for displaying.
• Personalization controls - These are used for personalization of a page according to the
user preferences, based on user information.
• Login and security controls - These controls provide user authentication.
• Master pages - These controls provide consistent layout and interface throughout the
application.
• Navigation controls - These controls help in navigation. For example, menus, tree view
etc.
• Rich controls - These controls implement special features. For example, AdRotator,
FileUpload, and Calendar control.
The following table contains the server-side controls for the Web Forms.
AccessKey Pressing this key with the Alt key moves focus to the control.
ChildControlCreated It indicates whether the server control's child controls have been
created.
DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML
element when the control is disabled.
Font Font.
HasChildViewState Indicates whether the current server control's child controls have
any saved view-state settings.
RenderingCompatibility It specifies the [Link] version that the rendered HTML will be
compatible with.
Site The container that hosts the current control when rendered on a
design surface.
SkinID Gets or sets the skin to apply to the control.
TabIndex Gets or sets the tab index of the Web server control.
TemplateSourceDirectory Gets the virtual directory of the page or control containing this
control.
ToolTip Gets or sets the text displayed when the mouse pointer hovers
over the web server control.
ViewState Gets a dictionary of state information that saves and restores the
view state of a server control across multiple requests for the
same page.
Method Description
ClearChildViewState Deletes the view-state information for all the server control's
child controls.
CreateControlStyle Creates the style object that is used to implement all style
related properties.
DataBind Binds a data source to the server control and all its child
controls.
DataBind(Boolean) Binds a data source to the server control and all its child
controls with an option to raise the DataBinding event.
HasEvents Indicates whether events are registered for the control or any
child controls.
RenderEndTag Renders the HTML closing tag of the control into the
specified writer.
SaveControlState Saves any server control state changes that have occurred
since the time the page was posted back to the server.
SaveViewState Saves any state that was modified after the TrackViewState
method was invoked.
TrackViewState Causes the control to track changes to its view state so that
they can be stored in the object's view state property.
HTML Controls
These controls render by the browser. We can also make HTML controls as server control.
Controls Description
Name
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
Button Action attribute in the FORM tag
File Field Places a text field and a Browse button on a form and allows the user to
select a file name from their local machine when the Browse button is
clicked
Password An input area on an HTML form, although any characters typed into this
Field field are displayed as asterisks
CheckBox Gives the user a check box that they can select or clear
Radio Used two or more to a form, and allows the user to choose one of the
Button controls
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.
Ad-rotator
The AdRotator control randomly selects banner graphics from a list, which is specified in an
external XML schedule file. This external XML schedule file is called the advertisement file.
The AdRotator control allows you to specify the advertisement file and the type of window that
the link should follow in the AdvertisementFile and the Target property respectively.
Extensible Markup Language (XML) is a W3C standard for text document markup. It is a text-
based markup language that enables you to store data in a structured format by using meaningful
tags. The term 'extensible' implies that you can extend your ability to describe a document by
defining meaningful tags for the application.
XML is not a language in itself, like HTML, but a set of rules for creating new markup languages.
It is a meta-markup language. It allows developers to create custom tag sets for special uses. It
structures, stores, and transports the information.
Element Description
NavigateUrl The link that will be followed when the user clicks the ad.
AlternateText The text that will be displayed instead of the picture if it cannot be
displayed.
Apart from these tags, customs tags with custom attributes could also be included. The following
code illustrates an advertisement file [Link]:
<Advertisements>
<Ad>
<ImageUrl>[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText>Order flowers, roses, gifts and more </AlternateText>
<Impressions>20</Impressions>
<Keyword>flowers</Keyword>
</Ad>
<Ad>
<ImageUrl>[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText>Order roses and flowers</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
<Ad>
<ImageUrl>[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText>Send flowers to Russia</AlternateText>
<Impressions>20</Impressions> <Keyword>russia</Keyword> </Ad>
<Ad>
<ImageUrl>[Link]</ImageUrl>
<NavigateUrl>[Link]
<AlternateText>Edible Blooms</AlternateText>
<Impressions>20</Impressions>
<Keyword>gifts</Keyword>
</Ad>
</Advertisements>
Properties and Events of the AdRotator Class
The AdRotator class is derived from the WebControl class and inherits its properties. Apart from
those, the AdRotator class has the following properties:
Properties Description
AlternateTextFeild The element name of the field where alternate text is provided.
The default value is AlternateText.
ImageUrlField The element name of the field where the URL for the image is
provided. The default value is ImageUrl.
NavigateUrlField The element name of the field where the URL to navigate to is
provided. The default value is NavigateUrl.
Target The browser window or frame that displays the content of the
page linked.
Events Description
AdCreated It is raised once per round trip to the server after creation of the
control, but before the page is rendered
Init Occurs when the server control is initialized, which is the first
step in its lifecycle.
Load Occurs when the server control is loaded into the Page object.
PreRender Occurs after the Control object is loaded but prior to rendering.
The calendar control is a functionally rich web control, which provides the following capabilities:
• Displaying one month at a time
• Selecting a day, a week or a month
• Selecting a range of days
• Moving from month to month
• Controlling the display of the days programmatically
Properties Description
CellPadding Gets or sets the number of spaces between the data and the cell
border.
DayHeaderStyle Gets the style properties for the section that displays the day of
the week.
DayStyle Gets the style properties for the days in the displayed month.
FirstDayOfWeek Gets or sets the day of week to display in the first column.
NextMonthText Gets or sets the text for next month navigation control. The
default value is >.
NextPrevFormat Gets or sets the format of the next and previous month
navigation control.
OtherMonthDayStyle Gets the style properties for the days on the Calendar control
that are not in the displayed month.
PrevMonthText Gets or sets the text for previous month navigation control. The
default value is <.
SelectionMode Gets or sets the selection mode that specifies whether the user
can select a single day, a week or an entire month.
SelectMonthText Gets or sets the text for the month selection element in the
selector column.
SelectorStyle Gets the style properties for the week and month selector
column.
SelectWeekText Gets or sets the text displayed for the week selection element in
the selector column.
ShowDayHeader Gets or sets the value indicating whether the heading for the
days of the week is displayed.
ShowGridLines Gets or sets the value indicating whether the gridlines would be
shown.
Titlestyle Get the style properties of the title heading for the Calendar
control.
TodayDayStyle Gets the style properties for today's date on the Calendar
control.
UseAccessibleHeader Gets or sets a value that indicates whether to render the table
header <th> HTML element for the day headers instead of the
table data <td> HTML element.
VisibleDate Gets or sets the date that specifies the month to display.
WeekendDayStyle Gets the style properties for the weekend dates on the Calendar
control.
The Calendar control has the following three most important events that allow the developers to
program the calendar control. They are:
Events Description
Calendar controls allow the users to select a single day, a week, or an entire month. This is done
by using the SelectionMode property. This property has the following values:
Properties Description
When the selection mode is set to the value DayWeekMonth, an extra column with the > symbol
appears for selecting the week, and a >> symbol appears to the left of the days name for selecting
the month.
A data source control interacts with the data-bound controls and hides the complex data binding
processes. These are the tools that provide data to the data bound controls and support execution
of operations like insertions, deletions, sorting, and updates.
Each data source control wraps a particular data provider-relational databases, XML documents,
or custom classes and helps in:
• Managing connection
• Selecting data
• Managing presentation aspects like paging, caching, etc.
• Manipulating data
There are many data source controls available in [Link] for accessing data from SQL Server,
from ODBC or OLE DB servers, from XML files, and from business objects.
Based on type of data, these controls could be divided into two categories:
• Hierarchical data source controls
• Table-based data source controls
The data source controls used for hierarchical data are:
• XMLDataSource - It allows binding to XML files and strings with or without schema
information.
• SiteMapDataSource - It allows binding to a provider that supplies site map information.
The data source controls used for tabular data are:
Properties Description
Methods Description
The following code snippet provides the basic syntax of the control:
<asp:SqlDataSource runat="server" ID="MySqlSource"
ProviderName='<%$ConnectionStrings:[Link] %>'
ConnectionString='<%$ ConnectionStrings:LocalNWind %>'
SelectionCommand= "SELECT * FROM EMPLOYEES" />
<asp:GridView ID="GridView1" runat="server" DataSourceID="MySqlSource" />
Configuring various data operations on the underlying data depends upon the various properties
(property groups) of the data source control.
The following table provides the related sets of properties of the SqlDataSource control, which
provides the programming interface of the control:
DeleteCommand, Gets or sets the SQL statement, parameters, and type for
deleting rows in the underlying data.
DeleteParameters,
DeleteCommandType
InsertCommand, Gets or sets the SQL statement, parameters, and type for
inserting rows in the underlying database.
InsertParameters,
InsertCommandType
SelectCommand, Gets or sets the SQL statement, parameters, and type for
retrieving rows from the underlying database.
SelectParameters,
SelectCommandType
UpdateCommand, Gets or sets the SQL statement, parameters, and type for
updating rows in the underlying data store.
UpdateParameters,
UpdateCommandType
The following code snippet shows a data source control enabled for data manipulation:
<asp:SqlDataSource runat="server" ID= "MySqlSource"
ProviderName='<%$ConnectionStrings:[Link] %>'
ConnectionString=' <%$ ConnectionStrings:LocalNWind %>'
SelectCommand= "SELECT * FROM EMPLOYEES"
UpdateCommand= "UPDATE EMPLOYEES SET LASTNAME=@lame"
DeleteCommand= "DELETE FROM EMPLOYEES WHERE EMPLOYEEID=@eid"
FilterExpression= "EMPLOYEEID > 10">
</asp:SqlDataSource>
• The bindable class should have a default constructor, it should be stateless, and have
methods that can be mapped to select, update, insert, and delete semantics.
• The object must update one item at a time, batch operations are not supported.
Let us go directly to an example to work with this control. The student class is the class to be used
with an object data source. This class has three properties: a student id, name, and city. It has a
default constructor and a GetStudents method for retrieving data.
[Link]("StudentName", typeof([Link]));
[Link]("StudentCity", typeof([Link]));
[Link](new object[] { 1, "M. H. Kabir", "Calcutta" });
[Link](new object[] { 2, "Ayan J. Sarkar", "Calcutta" });
[Link](dt);
return ds;
}
}
Take the following steps to bind the object with an object data source and retrieve data:
• Create a new web site.
• Add a class ([Link]) to it by right clicking the project from the Solution Explorer,
adding a class template, and placing the above code in it.
• Build the solution so that the application can use the reference to the class.
• Place an object data source control in the web form.
• Configure the data source by selecting the object.
• Select a data method(s) for different operations on data. In this example, there is only one
method.
• Place a data bound control such as grid view on the page and select the object data source
as its underlying data source.
• At this stage, the design view should look like the following:
• Run the project, it retrieves the hard coded tuples from the students class.
The AccessDataSource Control
The AccessDataSource control represents a connection to an Access database. It is based on the
SqlDataSource control and provides simpler programming interface. The following code snippet
provides the basic syntax for the data source:
Updates are problematic for Access databases from within an [Link] application because an
Access database is a plain file and the default account of the [Link] application might not have
the permission to write to the database file.
Data Binding
Every [Link] web form control inherits the DataBind method from its parent Control class,
which gives it an inherent capability to bind data to at least one of its properties. This is known
as simple data binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which implements the
IEnumerable interface, or the DataSet and DataTable classes to the DataSource property of the
control.
On the other hand, some controls can bind records, lists, or columns of data into their structure
through a DataSource control. These controls derive from the BaseDataBoundControl class. This
is called declarative data binding.
The data source controls help the data-bound controls implement functionalities such as, sorting,
paging, and editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
• DataBoundControl
• HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
• ListControl
• CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and
these controls are:
• BulletedList
• CheckBoxList
• DropDownList
• ListBox
• RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from
the abstract class CompositeDataBoundControl. These controls are:
• DetailsView
• FormView
• GridView
• RecordList
Simple Data Binding
Simple data binding involves the read-only selection lists. These controls can bind to an array list
or fields from a database. Selection lists takes two values from the database or the data source;
one value is displayed by the list and the other is considered as the value corresponding to the
display.
Let us take up a small example to understand the concept. Create a web site with a bulleted list
and a SqlDataSource control on it. Configure the data source control to retrieve two values from
your database (we use the same DotNetReferences table as in the previous chapter).
Choosing a data source for the bulleted list control involves:
• Selecting the data source control
• Selecting a field to display, which is called the data field
• Selecting a field for the value
When the application is executed, check that the entire title column is bound to the bulleted list
and displayed.
We have already used declarative data binding in the previous tutorial using GridView control.
The other composite data bound controls capable of displaying and manipulating data in a tabular
manner are the DetailsView, FormView, and RecordList control.
In the next tutorial, we will look into the technology for handling database, i.e, [Link].
• The data provider, which retrieves data from the database by using a command over a
connection.
• The data adapter that issues the select statement stored in the command object; it is also
capable of update the data in a database by issuing Insert, Delete, and Update statements.
A web service is a web-based functionality accessed using the protocols of the web to be used by
the web applications.
A Web Service is a software program that uses XML to exchange information with other
software via common internet protocols. In a simple sense, Web Services are a way of
interacting with objects over the Internet.
A web service is
• Language Independent.
• Protocol Independent.
• Platform Independent.
• It assumes a stateless service architecture.
• Scalable (e.g. multiplying two numbers together to an entire customer-relationship
management system).
• Programmable (encapsulates a task).
• Based on XML (open, text-based standard).
• Self-describing (metadata for access and use).
• Discoverable (search and locate in registries)- ability of applications and developers to
search for and locate desired Web services through registries. This is based on UDDI.
• XML- Describes only data. So, any application that understands XML-regardless of the
application's programming language or platform has the ability to format XML in a
variety of ways (well-formed or valid).
• SOAP- Provides a communication mechanism between services and applications.
• WSDL- Offers a uniform method of describing web services to other programs.
• UDDI- Enables the creation of searchable Web services registries.
Web services advantages
• Use open, text-based standards, which enable components written in various languages
and for different platforms to communicate.
• Promote a modular approach to programming, so multiple organizations can
communicate with the same Web service.
• Comparatively easy and inexpensive to implement, because they employ an existing
infrastructure and because most applications can be repackaged as Web services.
• Significantly reduce the costs of enterprise application (EAI) integration and B2B
communications.
• Implemented incrementally, rather than all at once which lessens the cost and reduces the
organizational disruption from an abrupt switch in technologies.
• The Web Services Interoperability Organization (WS-I) consisting of over 100 vendors
promotes interoperability.
To understand the concept let us create a web service to provide stock price information. The
clients can query about the name and price of a stock based on the stock symbol. To keep this
example simple, the values are hardcoded in a two-dimensional array. This web service has three
methods:
Step (1) : Select File -> New -> Web Site in Visual Studio, and then select [Link] Web
Service.
Step (2) : A web service file called [Link] and its code behind file, [Link] is created in
the App_Code directory of the project.
Step (3) : Change the names of the files to [Link] and [Link].
Step (4) : The .asmx file has simply a WebService directive on it:
<%@ WebService Language="C#" CodeBehind="~/App_Code/[Link]"
Class="StockService" %>
Step (5) : Open the [Link] file, the code generated in it is the basic Hello World service.
The default web service code behind file looks like the following:
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace StockService
{
// <summary>
// Summary description for Service1
// <summary>
[WebService(Namespace = "[Link]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
using [Link];
using [Link];
using [Link];
using [Link];
[WebService(Namespace = "[Link]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
string[,] stocks =
{
{"RELIND", "Reliance Industries", "1060.15"},
{"ICICI", "ICICI Bank", "911.55"},
{"JSW", "JSW Steel", "1201.25"},
{"WIPRO", "Wipro Limited", "1194.65"},
{"SATYAM", "Satyam Computers", "91.10"}
};
[WebMethod]
public string HelloWorld() {
return "Hello World";
}
[WebMethod]
public double GetPrice(string symbol)
{
//it takes the symbol as parameter and returns price
for (int i = 0; i < [Link](0); i++)
{
if ([Link](symbol, stocks[i, 0], true) == 0)
return [Link](stocks[i, 2]);
}
return 0;
}
[WebMethod]
public string GetName(string symbol)
{
// It takes the symbol as parameter and
// returns name of the stock
for (int i = 0; i < [Link](0); i++)
{
if ([Link](symbol, stocks[i, 0], true) == 0)
return stocks[i, 1];
}
Step (8) : Click on a method name, and check whether it runs properly.
Step (9) : For testing the GetName method, provide one of the stock symbols, which are hard
coded, it returns the name of the stock
<head runat="server">
<title>
Untitled Page
</title>
</head>
<body>
</div>
</form>
</body>
</html>
The code behind file for the web application is as follows:
using System;
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
namespace wsclient
{
public partial class _Default : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
[Link] = "First Loading Time: " + [Link]
}
else
{
[Link] = "PostBack at: " + [Link]();
}
}
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.
Step (1) : Right click on the web application entry in the Solution Explorer and click on 'Add
Web Reference'.
Step (2) : Select 'Web Services in this solution'. It returns the StockService reference.
Step (3) : Clicking on the service opens the test web page. By default the proxy created is called
'localhost', you can rename it. Click on 'Add Reference' to add the proxy to the client application.
using localhost;