0% found this document useful (0 votes)
3 views93 pages

ASP Net Notes

ASP.NET is a web development platform that enables the creation of robust web applications using various programming languages like C# and Visual Basic.Net. It operates on the HTTP protocol and includes features like state management, a component model for building user interfaces, and a comprehensive .NET framework. The document also covers the ASP.NET application and page life cycles, environment setup, and the Visual Studio IDE for developing ASP.NET applications.
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)
3 views93 pages

ASP Net Notes

ASP.NET is a web development platform that enables the creation of robust web applications using various programming languages like C# and Visual Basic.Net. It operates on the HTTP protocol and includes features like state management, a component model for building user interfaces, and a comprehensive .NET framework. The document also covers the ASP.NET application and page life cycles, environment setup, and the Visual Studio IDE for developing ASP.NET applications.
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

UNIT-I

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

[Link] Web Forms Model


[Link] web forms extend the event-driven model of interaction to the web applications. The
browser submits a web form to the web server and the server returns a full markup page or HTML
page in response.
All client side user activities are forwarded to the server for stateful processing. The server
processes the output of the client actions and triggers the reactions.
Now, HTTP is a stateless protocol. [Link] framework helps in storing the information
regarding the state of the application, which consists of:
• Page state
• Session state
The page state is the state of the client, i.e., the content of various input fields in the web form.
The session state is the collective information obtained from various pages the user visited and
worked with, i.e., the overall session state. To clear the concept, let us take an example of a
shopping cart.
User adds items to a shopping cart. Items are selected from a page, say the items page, and the
total collected items and price are shown on a different page, say the cart page. Only HTTP cannot
keep track of all the information coming from various pages. [Link] session state and server
side infrastructure keeps track of the information collected globally over a session.
The [Link] runtime carries the page state to and from the server across page requests while
generating [Link] runtime codes, and incorporates the state of the server side components in
hidden fields.
This way, the server becomes aware of the overall application state and operates in a two-tiered
connected way.

The [Link] Component Model


The [Link] component model provides various building blocks of [Link] pages. Basically
it is an object model, which describes:
• Server side counterparts of almost all HTML elements or tags, such as <form> and
<input>.
• Server controls, which help in developing complex user-interface. For example, the
Calendar control or the Gridview control.
[Link] is a technology, which works on the .Net framework that contains all web-related
functionalities. The .Net framework is made of an object-oriented hierarchy. An [Link] web
application is made of pages. When a user requests an [Link] page, the IIS delegates the
processing of the page to the [Link] runtime system.
The [Link] runtime transforms the .aspx page into an instance of a class, which inherits from
the base class page of the .Net framework. Therefore, each [Link] page is an object and all its
components i.e., the server-side controls are also objects.

Components of .Net Framework 3.5


Before going to the next session on Visual [Link], let us go through at the various components
of the .Net framework 3.5. The following table describes the components of the .Net framework
3.5 and the job they perform:
The .Net Programming Framework

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

XML File I/O (and so on)

Core system classes (threading, serialization, reflection,


collections, and so on)

The .Net Class Library

Compiler and Loader

Code verification and optimization

Memory Management and Garbage Collection

Code access security

(Other Managed code services)

The Common Language Runtime

Components and their Description


• Common Language Runtime or CLR: It performs memory management, exception
handling, debugging, security checking, thread execution, code execution, code safety,
verification, and compilation. The code that is directly managed by the CLR is called the
managed code. When the managed code is compiled, the compiler converts the source
code into a CPU independent intermediate language (IL) code. A Just In Time(JIT)
compiler compiles the IL code into native code, which is CPU specific.
• .Net Framework Class Library: It contains a huge library of reusable types. classes,
interfaces, structures, and enumerated values, which are collectively called types.
• Common Language Specification: It contains the specifications for the .Net supported
languages and implementation of language integration.
• Common Type System: It provides guidelines for declaring, using, and managing types
at runtime, and cross-language communication.
• Metadata and Assemblies: Metadata is the binary information describing the program,
which is either stored in a portable executable file (PE) or in the memory. Assembly is a
logical unit consisting of the assembly manifest, type metadata, IL code, and a set of
resources like image files.
• Windows Forms: Windows Forms contain the graphical representation of any window
displayed in the application.
• [Link] and [Link] AJAX: [Link] is the web development model and AJAX is
an extension of [Link] for developing and implementing AJAX functionality.
[Link] AJAX contains the components that allow the developer to update data on a
website without a complete reload of the page.
• [Link]: It is the technology used for working with data and databases. It provides
access to data sources like SQL server, OLE DB, XML etc. The [Link] allows
connection to data sources for retrieving, manipulating, and updating data.
• Windows Workflow Foundation (WF): It helps in building workflow-based applications
in Windows. It contains activities, workflow runtime, workflow designer, and a rules
engine.
• Windows Presentation Foundation: It provides a separation between the user interface
and the business logic. It helps in developing visually stunning interfaces using documents,
media, two and three dimensional graphics, animations, and more.
• Windows Communication Foundation (WCF): It is the technology used for building
and executing connected systems.
• Windows CardSpace: It provides safety for accessing resources and sharing personal
information on the internet.
• LINQ: It imparts data querying capabilities to .Net languages using a syntax which is
similar to the tradition query language SQL.

[Link] Environment Setup


[Link] provides an abstraction layer on top of HTTP on which the web applications are built.
It provides high-level entities such as classes and components within an object-oriented paradigm.
The key development tool for building [Link] applications and front ends is Visual Studio. In
this tutorial, we work with Visual Studio 2008.
Visual Studio is an integrated development environment for writing, compiling, and debugging
the code. It provides a complete set of development tools for building [Link] web applications,
web services, desktop applications, and mobile applications.
Installation
Microsoft provides a free version of visual studio which also contains SQL Server and it can be
downloaded from [Link].
Step 1 − Once downloading is complete, run the installer. The following dialog will be displayed.
Step 2 − Click on the Install button and it will start the installation process.

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.

Working with Views and Windows


You can work with windows in the following ways:
• To change the Web Forms Designer from one view to another, click on the Design or
source button.
• To close a window, click on the close button on the upper right corner and to redisplay,
select it from the View menu.
• To hide a window, click on its Auto Hide button. The window then changes into a tab. To
display again, click the Auto Hide button again.
• To change the size of a window, just drag it.

Adding Folders and Files to your Website


When a new web form is created, Visual Studio automatically generates the starting HTML for
the form and displays it in Source view of the web forms designer. The Solution Explorer is used
to add any other files, folders or any existing item on the web site.
• To add a standard folder, right-click on the project or folder under which you are going to
add the folder in the Solution Explorer and choose New Folder.
• To add an [Link] folder, right-click on the project in the Solution Explorer and select
the folder from the list.
• To add an existing item to the site, right-click on the project or folder under which you are
going to add the item in the Solution Explorer and select from the dialog box.
Projects and Solutions
A typical [Link] application consists of many items: the web content files (.aspx), source files
(.cs files), assemblies (.dll and .exe files), data source files (.mdb files), references, icons, user
controls and miscellaneous other files and folders. All these files that make up the website are
contained in a Solution.
When a new website is created. VB2008 automatically creates the solution and displays it in the
solution explorer.
Solutions may contain one or more projects. A project contains content files, source files, and
other files like data sources and image files. Generally, the contents of a project are compiled into
an assembly as an executable file (.exe) or a dynamic link library (.dll) file.
Typically a project contains the following content files:
• Page file (.aspx)
• User control (.ascx)
• Web service (.asmx)
• Master page (.master)
• Site map (.sitemap)
• Website configuration file (.config)
Building and Running a Project
You can execute an application by:
• Selecting Start
• Selecting Start Without Debugging from the Debug menu,
• pressing F5
• Ctrl-F5
The program is built meaning, the .exe or the .dll files are generated by selecting a command from
the Build menu.

[Link] life cycle


[Link] life cycle specifies, how:
• [Link] processes pages to produce dynamic output
• The application and its pages are instantiated and processed
• [Link] compiles the pages dynamically
The [Link] life cycle could be divided into two groups:
• Application Life Cycle
• Page Life Cycle

[Link] Application Life Cycle


The application life cycle has the following stages:
• User makes a request for accessing application resource, a page. Browser sends this
request to the web server.
• A unified pipeline receives the first request and the following events take place:
o An object of the class ApplicationManager is created.
o An object of the class HostingEnvironment is created to provide information
regarding the resources.
o Top level items in the application are compiled.
• Response objects are created. The application objects such as HttpContext, HttpRequest
and HttpResponse are created and initialized.
• An instance of the HttpApplication object is created and assigned to the request.
• The request is processed by the HttpApplication class. Different events are raised by this
class for processing the request.
[Link] Page Life Cycle
When a page is requested, it is loaded into the server memory, processed, and sent to the browser.
Then it is unloaded from the memory. At each of these steps, methods and events are available,
which could be overridden according to the need of the application. In other words, you can write
your own code to override the default code.
The Page class creates a hierarchical tree of all the controls on the page. All the components on
the page, except the directives, are part of this control tree. You can see the control tree by adding
trace= "true" to the page directive. We will cover page directives and tracing under 'directives'
and 'event handling'.
The page life cycle phases are:
• Initialization
• Instantiation of the controls on the page
• Restoration and maintenance of the state
• Execution of the event handler codes
• Page rendering
Understanding the page cycle helps in writing codes for making some specific thing happen at
any stage of the page life cycle. It also helps in writing custom controls and initializing them at
right time, populate their properties with view-state data and run control behavior code.
Following are the different stages of an [Link] page:
• Page request - When [Link] gets a page request, it decides whether to parse and
compile the page, or there would be a cached version of the page; accordingly the response
is sent.
• Starting of page life cycle - At this stage, the Request and Response objects are set. If the
request is an old request or post back, the IsPostBack property of the page is set to true.
The UICulture property of the page is also set.
• Page initialization - At this stage, the controls on the page are assigned unique ID by
setting the UniqueID property and the themes are applied. For a new request, postback
data is loaded and the control properties are restored to the view-state values.
• Page load - At this stage, control properties are set using the view state and control state
values.
• Validation - Validate method of the validation control is called and on its successful
execution, the IsValid property of the page is set to true.
• Postback event handling - If the request is a postback (old request), the related event
handler is invoked.
• Page rendering - At this stage, view state for the page and all controls are saved. The page
calls the Render method for each control and the output of rendering is written to the
OutputStream class of the Response property of page.
• Unload - The rendered page is sent to the client and page properties, such as Response
and Request, are unloaded and all cleanup done.

[Link] Page Life Cycle Events


At each stage of the page life cycle, the page raises some events, which could be coded. An event
handler is basically a function or subroutine, bound to the event, using declarative attributes such
as Onclick or handle.
Following are the page life cycle events:
• PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and
determines whether the page is a postback. It sets the themes and master pages, creates
dynamic controls, and gets and sets profile property values. This event can be handled by
overloading the OnPreInit method or creating a Page_PreInit handler.
• Init - Init event initializes the control property and the control tree is built. This event can
be handled by overloading the OnInit method or creating a Page_Init handler.
• InitComplete - InitComplete event allows tracking of view state. All the controls turn on
view-state tracking.
• LoadViewState - LoadViewState event allows loading view state information into the
controls.
• LoadPostData - During this phase, the contents of all the input fields are defined with the
<form> tag are processed.
• PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event
can be handled by overloading the OnPreLoad method or creating a Page_PreLoad
handler.
• Load - The Load event is raised for the page first and then recursively for all child controls.
The controls in the control tree are created. This event can be handled by overloading the
OnLoad method or creating a Page_Load handler.
• LoadComplete - The loading process is completed, control event handlers are run, and
page validation takes place. This event can be handled by overloading the
OnLoadComplete method or creating a Page_LoadComplete handler
• PreRender - The PreRender event occurs just before the output is rendered. By handling
this event, pages and controls can perform any updates before the output is rendered.
• PreRenderComplete - As the PreRender event is recursively fired for all child controls,
this event ensures the completion of the pre-rendering phase.
• SaveStateComplete - State of control on the page is saved. Personalization, control state
and view state information is saved. The HTML markup is generated. This stage can be
handled by overriding the Render method or creating a Page_Render handler.
• UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad
event for all controls recursively and lastly for the page itself. Final cleanup is done and
all resources and references, such as database connections, are freed. This event can be
handled by modifying the OnUnLoad method or creating a Page_UnLoad handler.

Language compilation in .Net

Code in any Language ([Link], C#)

Compiler converts code into


Intermediate Language (IL) Code

Common Language Runtime


executes IL

Common Language Runtime

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.

Microsoft Intermediate Language (MSIL / IL)


A .net programming language does not compile into executable code, instead it compiles into an
intermediate code called MSIL. The MSIL code then sends to CLR that converts to code to
machine language.

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.

Meta data and JIT Compilation

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:

const int interestRate = 10;

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:

Reserved .NET Size


Word Type Type (bits) Range (values)
byte Byte Unsigned integer 8 0 to 255
sbyte SByte Signed integer 8 -128 to 127
short Int16 Signed integer 16 -32,768 to 32,767
ushort UInt16 Unsigned integer 16 0 to 65,535
int Int32 Signed integer 32 -2,147,483,648 to 2,147,483,647
uint UInt32 Unsigned integer 32 0 to 4294967295
long Int64 Signed integer 64 -9,223,372,036,854,775,808 to
9,223,372,036,854,775,807
ulong UInt64Unsigned integer 64 0 to 18,446,744,073,709,551,615
float SingleSingle-precision floating point 32 -3.402823e38 to 3.402823e38
type
double Double Double-precision floating point 64 -1.79769313486232e308 to
type 1.79769313486232e308
decimal Decimal Precise fractional or integral 128 (+ or -)1.0 x 10e-28 to 7.9 x 10e28
type that can represent decimal
numbers with 29 significant
digits
char Char A single Unicode character 16 Unicode symbols used in text
bool Boolean Logical Boolean type 8 True or False
object Object Base type of all other types
string String A sequence of characters
DateTime DateTime Represents date and time 0:00:00am 1/1/01 to 11:59:59pm
12/31/9999
As you can see in the above table that each data types (except string and object) includes value
range. Compiler will give an error if value goes out of datatype's permitted range. For example,
int data type's range is -2,147,483,648 to 2,147,483,647. So if you assign value which is not in this
range then compiler would give error.
Reference data Type
The reference types do not contain the actual data stored in a variable, but they contain a reference
to the variables.
In other words, they refer to a memory location. Using multiple variables, the reference types can
refer to a memory location. If the data in the memory location is changed by one of the variables,
the other variable automatically reflects this change in value. Example of built-in reference types
are: object, dynamic, and string.
Object Type
The Object Type is the ultimate base class for all data types in C# Common Type System (CTS).
Object is an alias for [Link] class. The object types can be assigned values of any other
types, value types, reference types, predefined or user-defined types. However, before assigning
values, it needs type conversion.
When a value type is converted to object type, it is called boxing and on the other hand, when an
object type is converted to a value type, it is called unboxing.
object obj; obj = 100; // this is boxing

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 −

Operator Description Example

+ Adds two operands A + B = 30

- Subtracts second operand from the first A - B = -10

* Multiplies both operands A * B = 200

/ Divides numerator by de-numerator B/A=2


% Modulus Operator and remainder of after an integer division B%A=0

++ Increment operator increases integer value by one A++ = 11

-- Decrement operator decreases integer value by one A-- = 9

Relational Operators
Following table shows all the relational operators supported by C#. Assume variable A holds 10
and variable B holds 20, then −

Operator Description Example

== 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 −

Operator Description Example

&& Called Logical AND operator. If both the operands are non zero (A &&
then condition becomes true. B) is
false.

|| Called Logical OR Operator. If any of the two operands is non zero (A || B) is


then condition becomes true. true.
! Called Logical NOT Operator. Use to reverses the logical state of !(A &&
its operand. If a condition is true then Logical NOT operator will B) is
make false. true.

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 −

Operator Description Example

& Binary AND Operator copies a bit to the result if it exists in both (A & B) =
operands. 12, which is
0000 1100

| Binary OR Operator copies a bit if it exists in either operand. (A | B) = 61,


which is
0011 1101

^ Binary XOR Operator copies the bit if it is set in one operand (A ^ B) =


but not both. 49, which is
0011 0001

~ 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

= Simple assignment operator, Assigns values from right side C=A+B


operands to left side operand assigns
value of A
+ B into C

+= Add AND assignment operator, It adds right operand to the left C += A is


operand and assign the result to left operand equivalent
to C = C +
A

-= Subtract AND assignment operator, It subtracts right operand from C -= A is


the left operand and assign the result to left operand equivalent
to C = C -
A

*= Multiply AND assignment operator, It multiplies right operand C *= A is


with the left operand and assign the result to left operand equivalent
to C = C *
A

/= Divide AND assignment operator, It divides left operand with the C /= A is


right operand and assign the result to left operand equivalent
to C = C /
A

%= Modulus AND assignment operator, It takes modulus using two C %= A is


operands and assign the result to left operand equivalent
to C = C
%A

<<= Left shift AND assignment operator C <<= 2 is


same as C
= C << 2

>>= Right shift AND assignment operator C >>= 2 is


same as C
= C >> 2

&= Bitwise AND assignment operator C &= 2 is


same as C
=C&2

^= bitwise exclusive OR and assignment operator C ^= 2 is


same as C
=C^2

|= bitwise inclusive OR and assignment operator C |= 2 is


same as C
=C|2

Miscellaneous Operators
There are few other important operators including sizeof, typeof and ? :supported by C#.

Operator Description Example

sizeof() Returns the size of a data type. sizeof(int), returns 4.

typeof() Returns the type of a class. typeof(StreamReader);

& &a; returns actual address


Returns the address of an variable.
of the variable.

* *a; creates pointer named


Pointer to a variable.
'a' to a variable.

?: If Condition is true ? Then


Conditional Expression value X : Otherwise value
Y

is If( Ford is Car) // checks


Determines whether an object is of a certain type. if Ford is an object of the
Car class.

as Object obj = new


Cast without raising an exception if the cast fails.
StringReader("Hello");
StringReader r = obj as
StringReader;

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.

Category Operator Associativity

Postfix () [] -> . ++ - - Left to right

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

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right


Decision Statements
Decision making structures requires the programmer to specify one or more conditions to be
evaluated or tested by the program, along with a statement or statements to be executed if the
condition is determined to be true, and optionally, other statements to be executed if the condition
is determined to be false.
Following is the general form of a typical decision-making structure found in most of the
programming languages

C# provides following types of decision-making statements.

[Link]. Statement & Description

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.

5 nested switch statements


You can use one switch statement inside another switchstatement(s).
If Statements
An if statement consists of a boolean expression followed by one or more statements.
Syntax
The syntax of an if statement in C# is:
if(boolean_expression)
{
/* statement(s) will execute if the boolean expression is true */
}
If the boolean expression evaluates to true, then the block of code inside the if statement is
executed. If boolean expression evaluates to false, then the first set of code after the end of the if
statement(after the closing curly brace) is executed.
Flow Diagram

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:

Exp1 ? Exp2 : Exp3;

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); }

Here is the flow of control in a for loop −


• The init step is executed first, and only once. This step allows you to declare and initialize
any loop control variables. You are not required to put a statement here, as long as a
semicolon appears.
• Next, the condition is evaluated. If it is true, the body of the loop is executed. If it is false,
the body of the loop does not execute and flow of control jumps to the next statement just
after the for loop.
• After the body of the for loop executes, the flow of control jumps back up to
the increment statement. This statement allows you to update any loop control variables.
This statement can be left blank, as long as a semicolon appears after the condition.
• The condition is now evaluated again. If it is true, the loop executes and the process repeats
itself (body of loop, then increment step, and then again testing for a condition). After the
condition becomes false, the for loop terminates.
Flow Diagram

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.

Class versus Structure


Classes and Structures have the following basic differences −
• Classes are reference types and structs are value types
• Structures do not support inheritance
• Structures cannot have default constructor
Enumerations
An enumeration is a set of named integer constants. An enumerated type is declared using
the enum keyword. C# enumerations are value data type. In other words, enumeration contains its
own values and cannot inherit or cannot pass inheritance.

Declaring enum Variable


The general syntax for declaring an enumeration is:

enum <enum_name> { enumeration list };

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];

Assigning Values to an Array


• You can assign values to individual array elements, by using the index number, like
double[] balance = new double[10]; balance[0] = 4500.0;
• You can assign values to the array at the time of declaration, as shown:
double[] balance = { 2340.0, 4523.69, 3421.0};
• You can also create and initialize an array, as shown –
int [] marks = new int[5] { 99, 98, 92, 97, 95};
• You may also omit the size of the array, as shown:
int [] marks = new int[] { 99, 98, 92, 97, 95};
• You can copy an array variable into another target array variable. In such case, both the target
and source point to the same memory location:
int [] marks = new int[] { 99, 98, 92, 97, 95}; int[] score = marks;
When you create an array, C# compiler implicitly initializes each array element to a default value
depending on the array type. For example, for an int array all elements are initialized to 0.

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];
}

You can initialize a jagged array as –

int[][] scores = new int[2][]{new int[]{92,93,94},new int[]{85,66,87,88}};

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.

The array class


The Array class is the base class for all the arrays in C#. It is defined in the System namespace.
The Array class provides various properties and methods to work with arrays.
Properties of the Array Class
• IsFixedSize: Gets a value indicating whether the Array has a fixed size.
• IsReadOnly: Gets a value indicating whether the Array is read-only.
• Length: Gets a 32-bit integer that represents the total number of elements in all the
dimensions of the Array.
• LongLength: Gets a 64-bit integer that represents the total number of elements in all the
dimensions of the Array.
• Rank: Gets the rank (number of dimensions) of the Array.
Methods of the Array Class
• Clear: Sets a range of elements in the Array to zero, to false, or to null, depending on the
element type.
• Copy(Array, Array, Int32): Copies a range of elements from an Array starting at the first
element and pastes them into another Array starting at the first element. The length is
specified as a 32-bit integer.
• CopyTo(Array, Int32): Copies all the elements of the current one-dimensional Array to
the specified one-dimensional Array starting at the specified destination Array index. The
index is specified as a 32-bit integer.
• GetLength: Gets a 32-bit integer that represents the number of elements in the specified
dimension of the Array.
• GetLongLength: Gets a 64-bit integer that represents the number of elements in the
specified dimension of the Array.
• GetLowerBound: Gets the lower bound of the specified dimension in the Array.
• GetType: Gets the Type of the current instance. (Inherited from Object.)
• GetUpperBound: Gets the upper bound of the specified dimension in the Array.
• GetValue(Int32): Gets the value at the specified position in the one-dimensional Array.
The index is specified as a 32-bit integer.
• IndexOf(Array, Object): Searches for the specified object and returns the index of the first
occurrence within the entire one-dimensional Array.
• Reverse(Array): Reverses the sequence of the elements in the entire one-dimensional
Array.
• SetValue(Object, Int32): Sets a value to the element at the specified position in the one-
dimensional Array. The index is specified as a 32-bit integer.
• Sort(Array): Sorts the elements in an entire one-dimensional Array using the IComparable
implementation of each element of the Array.
• ToString: Returns a string that represents the current object. (Inherited from Object.)

Button Controls
[Link] provides three types of button control:

• Button : It displays text within a rectangular area.

• Link Button : It displays text that looks like a hyperlink.

• Image Button : It displays an image.

When a user clicks a button, two events are raised: Click and Command.

Basic syntax of button control:

<asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Click" / >


Common properties of the button control:
• Text: The text displayed on the button. This is for button and link button controls only.
• ImageUrl: For image button control only. The image to be displayed for the button.
• AlternateText: For image button control only. The text to be displayed if the browser
cannot display the image.
• CausesValidation: Determines whether page validation occurs when a user clicks the
button. The default is true.
• CommandName: A string value that is passed to the command event when a user clicks
the button.
• CommandArgument:A string value that is passed to the command event when a user
clicks the button.
• PostBackUrl:The URL of the page that is requested when the user clicks the button.

Text Boxes and Labels


Text box controls are typically used to accept input from the user. A text box control can accept
one or more lines of text depending upon the settings of the TextMode attribute.

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.

Basic syntax of text control:

<asp:TextBox ID="txtstate" runat="server" ></asp:TextBox>

Common Properties of the Text Box and Labels:

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

Check Boxes and Radio Buttons


A check box displays a single option that the user can either check or uncheck and radio buttons
present a group of options from which the user can select just one option.

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.

Basic syntax of check box:

<asp:CheckBox ID= "chkoption" runat= "Server"> </asp:CheckBox>

Basic syntax of radio button:

<asp:RadioButton ID= "rdboption" runat= "Server"> </asp: RadioButton>

Common properties of check boxes and radio buttons:

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

Basic syntax of list box control:

<asp:ListBox ID="ListBox1" runat="server" AutoPostBack="True"


OnSelectedIndexChanged="ListBox1_SelectedIndexChanged"> </asp:ListBox>
Basic syntax of drop-down list control:

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True"


OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">
</asp:DropDownList>

Common properties of list box and drop-down Lists:


• Items: The collection of ListItem objects that represents the items in the control. This
property returns an object of type ListItemCollection.
• Rows: Specifies the number of items displayed in the box. If actual list contains more
rows than displayed then a scroll bar is added.
• SelectedIndex: The index of the currently selected item. If more than one item is selected,
then the index of the first selected item. If no item is selected, the value of this property is
-1.
• SelectedValue : The value of the currently selected item. If more than one item is selected,
then the value of the first selected item. If no item is selected, the value of this property is
an empty string ("").
• SelectionMode: Indicates whether a list box allows single selections or multiple
selections.
Common properties of each list item objects:

• Text: The text displayed for the item.


• Selected: Indicates whether the item is selected.
• Value: A string value associated with the item.
It is important to notes that:
• To work with the items in a drop-down list or list box, you use the Items property of the
control. This property returns a ListItemCollection object which contains all the items of
the list.
• The SelectedIndexChanged event is raised when the user selects a different item from a
drop-down list or list box.

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.

Common properties of ListItemCollection:


• Item(integer): A ListItem object that represents the item at the specified index.
• Count: The number of items in the collection.

Common methods of ListItemCollection:

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

Radio Button list and Check Box list


A radio button list presents a list of mutually exclusive options. A check box list presents a list of
independent options. These controls contain a collection of ListItem objects that could be referred
to through the Items property of the control.

Basic syntax of radio button list:

<asp:RadioButtonList ID="RadioButtonList1" runat="server" AutoPostBack="True"


OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">
</asp:RadioButtonList>

Basic syntax of check box list:

<asp:CheckBoxList ID="CheckBoxList1" runat="server" AutoPostBack="True"


OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">
</asp:CheckBoxList>
Common properties of check box and radio button lists:
• RepeatLayout: This attribute specifies whether the table tags or the normal html flow to
use while formatting the list when it is rendered. The default is Table.
• 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.

Bulleted lists and Numbered lists


The bulleted list control creates bulleted lists or numbered lists. These controls contain a
collection of ListItem objects that could be referred to through the Items property of the control.

Basic syntax of a bulleted list:

<asp:BulletedList ID="BulletedList1" runat="server"> </asp:BulletedList>

Common properties of the bulleted list:

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

Basic syntax for a hyperlink control:

<asp:HyperLink ID="HyperLink1" runat="server"> HyperLink </asp:HyperLink>

It has the following important properties:

• ImageUrl: Path of the image to be displayed by the control.


• NavigateUrl: Target link URL.
• Text: The text to be displayed as the link.
• Target: The window or frame which loads the linked page.

Image Control
The image control is used for displaying images on the web page, or some alternative text, if the
image is not available.

Basic syntax for an image control:

<asp:Image ID="Image1" runat="server">


It has the following important properties:

• AlternateText: Alternate text to be displayed in absence of the image.


• ImageAlign: Alignment options for the control.
• ImageUrl: Path of the image to be displayed by the control.

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 −

• Abort: returns [Link] value, when user clicks an Abort button.

• Cancel: returns [Link], when user clicks a Cancel button.

• Ignore: returns [Link], when user clicks an Ignore button.

• No: returns [Link], when user clicks a No button.

• None: returns nothing and the dialog box continues running.

• OK: returns [Link], when user clicks an OK button

• Retry: returns [Link] , when user clicks an Retry button

• Yes: returns [Link], when user clicks an Yes button

The following diagram shows the common dialog class inheritance –


All these above-mentioned classes have corresponding controls that could be added from the
Toolbox during design time. You can include relevant functionality of these classes to your
application, either by instantiating the class programmatically or by using relevant controls.

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.

The following are the commonly used dialog box controls:


• ColorDialog: It represents a common dialog box that displays available colors along with
controls that enable the user to define custom colors.
• FontDialog: It prompts the user to choose a font from among those installed on the local
computer and lets the user select the font, font size, and color.
• OpenFileDialog: It prompts the user to open a file and allows the user to select a file to
open.
• SaveFileDialog: It prompts the user to select a location for saving a file and allows the
user to specify the name of the file to save data.
• PrintDialog: It lets the user to print documents by selecting a printer and choosing which
sections of the document to print from a Windows Forms application.

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.

The following figure shows the [Link] 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.

Some important properties of the DataSet class:

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

Important methods of the DataSet class:


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

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:
• 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.

Some important methods of the DataTable class:


• 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:

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

Important methods of the DataRow class:

• 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="[Link]"
Inherits="createdatabase._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"[Link]
<html xmlns="[Link] >
<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>
</html>
The code behind file is as given:
namespace createdatabase
{
public partial class _Default : [Link]
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
DataSet ds = CreateDataSet();
[Link] = [Link]["Student"];
[Link]();
}
}
private DataSet CreateDataSet()
{
//creating a DataSet object for tables
DataSet dataset = new DataSet();
// creating the student table
DataTable Students = CreateStudentTable(); [Link](Students);
return dataset;
}
private DataTable CreateStudentTable()
{
DataTable Students = new DataTable("Student");

// 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));
}

//adding data into the table


private void AddNewRow(DataTable table, int id, string name, string city)
{
DataRow newrow = [Link]();
newrow["StudentID"] = id;
newrow["StudentName"] = name;
newrow["StudentCity"] = city;
[Link](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:

Difference between ADO and [Link]


1. Fundamentally we can say that ADO works in Connected environment whereas [Link]
works in Disconnected environment.
2. In ADO, the in memory representation of data is “Recordset“, whereas in [Link] the in
memory representation of data is “DataSet“.
3. Recordset contains only one table, but to get the data from multiple tables JOINS must be
used.
4. DataSet contains one or more than one Table. The tables between Dataset are Known as
“DataTable“.
5. In ADO, data can be accessed sequencialy with the help of RecordSet Object by using
“MoveNext” method.
6. In [Link], the records are present in table and therefore it can be accessed like any other
collection by iterating over it or by using Primary key index.
7. In [Link] you open connections only long enough to perform a database operation,
such as a Select or Update. You can read rows into a dataset and then work with them
without staying connected to the data source. In ADO the recordset can provide
disconnected access, but ADO is designed primarily for connected access.
8. There is one significant difference between disconnected processing in ADO and
[Link]. In ADO you communicate with the database by making calls to an OLE DB
provider. In [Link] you communicate with the database through a data adapter
(anOleDbDataAdapter, SqlDataAdapter, OdbcDataAdapter, or
OracleDataAdapter object), which makes calls to an OLE DB provider or the APIs
provided by the underlying data source.
9. Transmitting an [Link] dataset between applications is much easier than transmitting
an ADO disconnected recordset. To transmit an ADO disconnected recordset from one
component to another, you use COM marshalling. To transmit data in [Link], you use
a dataset, which can transmit an XML stream.

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.

[Link] supports three modes of persistence for server-side session variables:

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

[Link] State Management

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.

[Link] manages four types of states:

• 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 view state could be enabled or disabled for:

• 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" %>

• A control by setting the [Link] property.


It is implemented using a view state object defined by the StateBag class which defines a
collection of view state items. The state bag is a data structure containing attribute value pairs,
stored as strings associated with objects.

The StateBag class has the following properties:


• Item(name): The value of the view state item with the specified name. This is the default
property of the StateBag class.
• Count: The number of items in the view state collection.
• Keys: Collection of keys for all the items in the collection.
• Values: Collection of values for all the items in the collection.

The StateBag class has the following methods:


• Add(name, value): Adds an item to the view state collection and existing item is updated.
• Clear: Removes all the items from the collection.
• Equals(Object): Determines whether the specified object is equal to the current object.
• Finalize: Allows it to free resources and perform other cleanup operations.
• GetEnumerator: Returns an enumerator that iterates over all the key/value pairs of the
StateItem objects stored in the StateBag object.
• GetType: Gets the type of the current instance.
• IsItemDirty: Checks a StateItem object stored in the StateBag object to evaluate whether
it has been modified.
• Remove(name): Removes the specified item.
• SetDirty: Sets the state of the StateBag object as well as the Dirty property of each of the
StateItem objects contained by it.
• SetItemDirty: Sets the Dirty property for the specified StateItem object in the StateBag
object.
• ToString: Returns a string representing the state bag object.
Control State
Control state cannot be modified, accessed directly, or disabled.

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.

The HttpSessionState class has the following properties:


• SessionID: The unique session identifier.
• Item(name): The value of the session state item with the specified name. This is the default
property of the HttpSessionState class.
• Count: The number of items in the session state collection.
• TimeOut: Gets and sets the amount of time, in minutes, allowed between requests before
the session-state provider terminates the session.
The HttpSessionState class has the following methods:
• Add(name, value): Adds an item to the session state collection.
• Clear: Removes all the items from session state collection.
• Remove(name): Removes the specified item from the session state collection.
• RemoveAll: Removes all keys and values from the session-state collection.
• RemoveAt: Deletes an item at a specified index from the session-state collection.

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.

The HttpApplicationState class has the following properties:


• Item(name): The value of the application state item with the specified name. This is the
default property of the HttpApplicationState class.
• Count: The number of items in the application state collection.
The HttpApplicationState class has the following methods:
• Add(name, value): Adds an item to the application state collection.
• Clear: Removes all the items from the application state collection.
• Remove(name): Removes the specified item from the application state collection.
• RemoveAll: Removes all objects from an HttpApplicationState collection.
• RemoveAt: Removes an HttpApplicationState object from a collection by index.
• Lock(): Locks the application state collection so only the current user can access it.
• Unlock(): Unlocks the application state collection so all the users can access it.
Application state data is generally maintained by writing handlers for the events:
• Application_Start
• Application_End
• Application_Error
• Session_Start
• Session_End

Change Home Directory in IIS

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.

Set a default document for IIS


To configure default document settings in IIS:
1. Start Internet Services Manager, or start the Microsoft Management Console (MMC) that
contains the IIS snap-in.
2. Right-click the Web site, virtual folder, or folder whose default document settings you want
to configure, and then click Properties.
3. Click the Documents tab.
4. Click to select the Enable Default Document check box. This turns on default document
handling for the Web site, virtual folder, or folder that you selected.
5. To add a new default document:
1. Click Add.
2. In the Default Document Name box, type the name of the default document that you
want to add (for example, type [Link]), and then click OK.
NOTE: Make sure that the name of the new default document that you add matches the name
of the actual default document file. Also, make sure that the file exists in the appropriate
content folder on the Web site.
6. To change the search order priority, click the document that you want to move, and then click
the Up or Down button to move the document to the position in the list that you want.
7. To remove a default document, click the document that you want to remove, and then
click Remove.
8. Click OK, and then quit Internet Services Manager, or the IIS snap-in.

Add a virtual Directory in IIS

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.

How to create a new Virtual Directory

1. Open Internet Information Services (IIS) Manager:


• If you are using Windows Server 2012 or Windows Server 2012 R2:
o On the taskbar, click Server Manager, click Tools, and then click Internet
Information Services (IIS) Manager.
• If you are using Windows 8 or Windows 8.1:
o Hold down the Windows key, press the letter X, and then click Control Panel.
o Click Administrative Tools, and then double-click Internet Information
Services (IIS) Manager.
• If you are using Windows Server 2008 or Windows Server 2008 R2:
o On the taskbar, click Start, point to Administrative Tools, and then click Internet
Information Services (IIS) Manager.
• If you are using Windows Vista or Windows 7:
o On the taskbar, click Start, and then click Control Panel.
o Double-click Administrative Tools, and then double-click Internet Information
Services (IIS) Manager.
2. In the Connections pane, expand the server name, expand Sites, expand the Web site to
which you want to add the virtual directory, and then click the application to which you
want to add the virtual directory.

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.

[Link] provides the following validation controls:


• RequiredFieldValidator
• RangeValidator
• CompareValidator
• RegularExpressionValidator
• CustomValidator
• ValidationSummary

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:

• ControlToValidate: Indicates the input control to validate.


• Display: Indicates how the error message is shown.
• EnableClientScript: Indicates whether client side validation will take.
• Enabled: Enables or disables the validator.
• ErrorMessage: Indicates error string.
• Text: Error text to be shown if validation fails.
• IsValid: Indicates whether the value of the control is valid.
• SetFocusOnError: It indicates whether in case of an invalid control, the focus should
switch to the related input control.
• ValidationGroup: The logical group of multiple validators, where this control belongs.
• Validate(): This method revalidates the control and updates the IsValid property.
RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not empty. It is generally
tied to a text box to force input into the text box.
RangeValidator Control
The RangeValidator control verifies that the input value falls within a predetermined range.
It has three specific properties:
• Type: It defines the type of the data. The available values are: Currency, Date, Double,
Integer, and String.
• MinimumValue: It specifies the minimum value of the range.
• MaximumValue: It specifies the maximum value of the range.
CompareValidator Control
The CompareValidator control compares a value in one control with a fixed value or a value in
another control.
It has the following specific properties:
• Type: It specifies the data type.
• ControlToCompare: It specifies the value of the input control to compare with.
• ValueToCompare: It specifies the constant value to compare with.
• Operator:It specifies the comparison operator, the available values are: Equal, NotEqual,
GreaterThan, GreaterThanEqual, LessThan, LessThanEqual, and DataTypeCheck.
RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching against a pattern of
a regular expression. The regular expression is set in the ValidationExpression property.
The following are the commonly used syntax constructs for regular expressions:
• \b :Matches a backspace.
• \t :Matches a tab.
• \r :Matches a carriage return.
• \v :Matches a vertical tab.
• \f :Matches a form feed.
• \n :Matches a new line.
• \ :Escape character.
Apart from single character match, a class of characters could be specified that can be matched,
called the metacharacters.

Metacharacters Description

. Matches any character except \n.


[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

[2-7a-mA-M] Matches any character specified in the range.

\w Matches any alphanumeric character and underscore.

\W Matches any non-word character.

\s Matches whitespace characters like, space, tab, new line etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

Quantifiers could be added to specify number of times a character could appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.

{N} N matches.

{N,} N or more matches.

{N,M} Between N and M 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:

• ShowSummary : shows the error messages in specified format.

• ShowMessageBox : shows the error messages in a separate window.

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.

Server Side Controls

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.

[Link] uses five types of web controls, which are:

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

Control Name Applicable Events Description

Label None It is used to display text on the HTML page.

TextBox TextChanged It is used to create a text input in the form.

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

LinkButton Click, Command It is used to create a button that looks similar


to the hyperlink.

ImageButton Click It is used to create an imagesButton. Here, an


image works as a Button.

Hyperlink None It is used to create a hyperlink control that


responds to a click event.

DropDownList SelectedIndexChanged It is used to create a dropdown list control.

ListBox SelectedIndexCnhaged It is used to create a ListBox control like the


HTML control.

DataGrid CancelCommand, It used to create a frid that is used to show


EditCommand, data. We can also perform paging, sorting,
DeleteCommand, and formatting very easily with this control.
ItemCommand,
SelectedIndexChanged,
PageIndexChanged,
SortCommand,
UpdateCommand,
ItemCreated,
ItemDataBound

DataList CancelCommand, It is used to create datalist that is non-tabular


EditCommand, and used to show data.
DeleteCommand,
ItemCommand,
SelectedIndexChanged,
UpdateCommand,
ItemCreated,
ItemDataBound

Repeater ItemCommand, It allows us to create a non-tabular type of


ItemCreated, format for data. You can bind the data to
ItemDataBound 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


VisibleMonthChanged, default date, move forward and backward etc.
DayRender

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.
The syntax for using server controls is:

<asp:controlType ID ="ControlID" runat="server" Property1=value1 [Property2=value2] />

Properties of the Server Controls


[Link] server controls with a visual aspect are derived from the WebControl class and inherit
all the properties, events, and methods of this class.
The WebControl class itself and some other server controls that are not visually rendered are
derived from the [Link] class. For example, PlaceHolder control or XML
control.
[Link] server controls inherit all properties, events, and methods of the WebControl and
[Link] class.
The following table shows the inherited properties, common to all server controls:
Property Description

AccessKey Pressing this key with the Alt key moves focus to the control.

Attributes It is the collection of arbitrary attributes (for rendering only) that


do not correspond to properties on the control.

BackColor Background color.

BindingContainer The control that contains this control's data binding.

BorderColor Border color.

BorderStyle Border style.

BorderWidth Border width.

CausesValidation Indicates if it causes validation.

ChildControlCreated It indicates whether the server control's child controls have been
created.

ClientID Control ID for HTML markup.

Context The HttpContext object associated with the server control.

Controls Collection of all controls contained within the control.

ControlStyle The style of the Web server control.

CssClass CSS class

DataItemContainer Gets a reference to the naming container if the naming container


implements IDataItemContainer.
DataKeysContainer Gets a reference to the naming container if the naming container
implements IDataKeysControl.

DesignMode It indicates whether the control is being used on a design surface.

DisabledCssClass Gets or sets the CSS class to apply to the rendered HTML
element when the control is disabled.

Enabled Indicates whether the control is grayed out.

EnableTheming Indicates whether theming applies to the control.

EnableViewState Indicates whether the view state of the control is maintained.

Events Gets a list of event handler delegates for the control.

Font Font.

Forecolor Foreground color.

HasAttributes Indicates whether the control has attributes set.

HasChildViewState Indicates whether the current server control's child controls have
any saved view-state settings.

Height Height in pixels or %.

ID Identifier for the control.

IsChildControlStateCleared Indicates whether controls contained within this control have


control state.

IsEnabled Gets a value indicating whether the control is enabled.

IsTrackingViewState It indicates whether the server control is saving changes to its


view state.

IsViewStateEnabled It indicates whether view state is enabled for this control.

LoadViewStateById It indicates whether the control participates in loading its view


state by ID instead of index.

Page Page containing the control.

Parent Parent control.

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.

Style Gets a collection of text attributes that will be rendered as a style


attribute on the outer tag of the Web server control.

TabIndex Gets or sets the tab index of the Web server control.

TagKey Gets the HtmlTextWriterTag value that corresponds to this Web


server control.

TagName Gets the name of the control tag.

TemplateControl The template that contains this 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.

UniqueID Unique identifier.

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.

ViewStateIgnoreCase It indicates whether the StateBag object is case-insensitive.

ViewStateMode Gets or sets the view-state mode of this control.

Visible It indicates whether a server control is visible.

Width Gets or sets the width of the Web server control.

Methods of the Server Controls


The following table provides the methods of the server controls:

Method Description

AddAttributesToRender Adds HTML attributes and styles that need to be rendered to


the specified HtmlTextWriterTag.

AddedControl Called after a child control is added to the Controls


collection of the control object.

AddParsedSubObject Notifies the server control that an element, either XML or


HTML, was parsed, and adds the element to the server
control's control collection.
ApplyStyleSheetSkin Applies the style properties defined in the page style sheet to
the control.

ClearCachedClientID Infrastructure. Sets the cached ClientID value to null.

ClearChildControlState Deletes the control-state information for the server control's


child controls.

ClearChildState Deletes the view-state and control-state information for all


the server control's child controls.

ClearChildViewState Deletes the view-state information for all the server control's
child controls.

CreateChildControls Used in creating child controls.

CreateControlCollection Creates a new ControlCollection object to hold the 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.

DataBindChildren Binds a data source to the server control's child controls.

Dispose Enables a server control to perform final clean up before it is


released from memory.

EnsureChildControls Determines whether the server control contains child


controls. If it does not, it creates child controls.

EnsureID Creates an identifier for controls that do not have an


identifier.

Equals(Object) Determines whether the specified object is equal to the


current object.

Finalize Allows an object to attempt to free resources and perform


other cleanup operations before the object is reclaimed by
garbage collection.

FindControl(String) Searches the current naming container for a server control


with the specified id parameter.
FindControl(String, Int32) Searches the current naming container for a server control
with the specified id and an integer.

Focus Sets input focus to a control.

GetDesignModeState Gets design-time data for a control.

GetType Gets the type of the current instance.

GetUniqueIDRelativeTo Returns the prefixed portion of the UniqueID property of the


specified control.

HasControls Determines if the server control contains any child controls.

HasEvents Indicates whether events are registered for the control or any
child controls.

IsLiteralContent Determines if the server control holds only literal content.

LoadControlState Restores control-state information.

LoadViewState Restores view-state information.

MapPathSecure Retrieves the physical path that a virtual path, either


absolute or relative, maps to.

MemberwiseClone Creates a shallow copy of the current object.

MergeStyle Copies any nonblank elements of the specified style to the


web control, but does not overwrite any existing style
elements of the control.

OnBubbleEvent Determines whether the event for the server control is


passed up the page's UI server control hierarchy.

OnDataBinding Raises the data binding event.

OnInit Raises the Init event.

OnLoad Raises the Load event.

OnPreRender Raises the PreRender event.

OnUnload Raises the Unload event.

OpenFile Gets a Stream used to read a file.

RemovedControl Called after a child control is removed from the controls


collection of the control object.

Render Renders the control to the specified HTML writer.


RenderBeginTag Renders the HTML opening tag of the control to the
specified writer.

RenderChildren Outputs the contents of a server control's children to a


provided HtmlTextWriter object, which writes the contents
to be rendered on the client.

RenderContents Renders the contents of the control to the specified writer.

RenderControl(HtmlTextWriter) Outputs server control content to a provided HtmlTextWriter


object and stores tracing information about the control if
tracing is enabled.

RenderEndTag Renders the HTML closing tag of the control into the
specified writer.

ResolveAdapter Gets the control adapter responsible for rendering the


specified control.

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.

SetDesignModeState Sets design-time data for a control.

ToString Returns a string that represents the current object.

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

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
Button Action attribute in the FORM tag

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


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

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

Password An input area on an HTML form, although any characters 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

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

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.

The basic syntax of adding an AdRotator is as follows:


<asp:AdRotator runat = "server" AdvertisementFile = "[Link]" Target = "_blank" />
Before starting details of the AdRotator control and its properties, first understand about
construction of the advertisement file.

The Advertisement File


The advertisement file is an XML file, which contains the information about the advertisements
to be displayed.

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.

Following is an example of XML file:


<BOOK>
<NAME> Learn XML </NAME>
<AUTHOR> Samuel Peterson </AUTHOR>
<PUBLISHER> NSS Publications </PUBLISHER>
<PRICE> $30.00</PRICE>
</BOOK>
Like all XML files, the advertisement file needs to be a structured text file with well-defined tags
delineating the data. There are the following standard XML elements that are commonly used in
the advertisement file:

Element Description

Advertisements Encloses the advertisement file.

Ad Delineates separate ad.

ImageUrl The path of image that will be displayed.

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.

Keyword Keyword identifying a group of advertisements. This is used for


filtering.

Impressions The number indicating how often an advertisement will appear.

Height Height of the image to be displayed.


Width Width of the image to 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

AdvertisementFile The path to the advertisement file.

AlternateTextFeild The element name of the field where alternate text is provided.
The default value is AlternateText.

DataMember The name of the specific list of data to be bound when


advertisement file is not used.
DataSource Control from where it would retrieve data.

DataSourceID Id of the control from where it would retrieve data.

Font Specifies the font properties associated with the advertisement


banner control.

ImageUrlField The element name of the field where the URL for the image is
provided. The default value is ImageUrl.

KeywordFilter For displaying the keyword based ads only.

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.

UniqueID Obtains the unique, hierarchically qualified identifier for the


AdRotator control.

Following are the important events of the AdRotator class:

Events Description

AdCreated It is raised once per round trip to the server after creation of the
control, but before the page is rendered

DataBinding Occurs when the server control binds to a data source.

DataBound Occurs after the server control binds to a data source.

Disposed Occurs when a server control is released from memory, which is


the last stage of the server control lifecycle when an [Link]
page is requested

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.

Unload Occurs when the server control is unloaded from memory.


Working with AdRotator Control
Create a new web page and place an AdRotator control on it.
<form id="form1" runat="server">
<div>
<asp:AdRotator ID="AdRotator1" runat="server" AdvertisementFile
="~/[Link]" onadcreated="AdRotator1_AdCreated" />
</div>
</form>
The [Link] file and the image files should be located in the root directory of the web site.

The Calendar control

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

The basic syntax of a calendar control is:

<asp:Calender ID = "Calendar1" runat = "server"> </asp:Calender>

Properties and Events of the Calendar Control


The calendar control has many properties and events, using which you can customize the actions
and display of the control. The following table provides some important properties of the Calendar
control:

Properties Description

Caption Gets or sets the caption for the calendar control.

CaptionAlign Gets or sets the alignment for the caption.

CellPadding Gets or sets the number of spaces between the data and the cell
border.

CellSpacing Gets or sets the space between cells.

DayHeaderStyle Gets the style properties for the section that displays the day of
the week.

DayNameFormat Gets or sets format of days 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 <.

SelectedDate Gets or sets the selected date.

SelectedDates Gets a collection of DateTime objects representing the selected


dates.

SelectedDayStyle Gets the style properties for the selected dates.

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.

ShowNextPrevMonth Gets or sets a value indicating whether next and previous


month navigation elements are shown in the title section.

ShowTitle Gets or sets a value indicating whether the title section is


displayed.

TitleFormat Gets or sets the format for the title section.

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.

TodaysDate Gets or sets the value for today's date.

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

SelectionChanged It is raised when a day, a week or an entire month is selected.

DayRender It is raised when each data cell of the calendar control is


rendered.

VisibleMonthChanged It is raised when user changes a month.

Working with the Calendar Control


Putting a bare-bone calendar control without any code behind file provides a workable calendar
to a site, which shows the months and days of the year. It also allows navigation to next and
previous months.

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

Day To select a single day.

DayWeek To select a single day or an entire week.

DayWeekMonth To select a single day, a week, or an entire month.

None Nothing can be selected.


The syntax for selecting days:

<asp:Calender ID = "Calendar1" runat = "server" SelectionMode="DayWeekMonth">


</asp:Calender>

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.

The Data Source Control

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:

Data source controls Description

SqlDataSource It represents a connection to an [Link] data provider that


returns SQL data, including data sources accessible via
OLEDB and ODBC.

ObjectDataSource It allows binding to a custom .Net business object that returns


data.

LinqdataSource It allows binding to the results of a Linq-to-SQL query


(supported by [Link] 3.5 only).

AccessDataSource It represents connection to a Microsoft Access database.


Data Source Views
Data source views are objects of the DataSourceView class. Which represent a customized view
of data for different data operations such as sorting, filtering, etc.
The DataSourceView class serves as the base class for all data source view classes, which define
the capabilities of data source controls.
The following table provides the properties of the DataSourceView class:

Properties Description

CanDelete Indicates whether deletion is allowed on the underlying


data source.

CanInsert Indicates whether insertion is allowed on the underlying


data source.

CanPage Indicates whether paging is allowed on the underlying data


source.

CanRetrieveTotalRowCount Indicates whether total row count information is available.

CanSort Indicates whether the data could be sorted.

CanUpdate Indicates whether updates are allowed on the underlying


data source.

Events Gets a list of event-handler delegates for the data source


view.

Name Name of the view.

The following table provides the methods of the DataSourceView class:

Methods Description

CanExecute Determines whether the specified command can be


executed.

ExecuteCommand Executes the specific command.

ExecuteDelete Performs a delete operation on the list of data that


the DataSourceView object represents.

ExecuteInsert Performs an insert operation on the list of data that


the DataSourceView object represents.

ExecuteSelect Gets a list of data from the underlying data


storage.
ExecuteUpdate Performs an update operation on the list of data
that the DataSourceView object represents.

Delete Performs a delete operation on the data associated


with the view.

Insert Performs an insert operation on the data associated


with the view.

Select Returns the queried data.

Update Performs an update operation on the data


associated with the view.

The SqlDataSource Control


The SqlDataSource control represents a connection to a relational database such as SQL Server
or Oracle database, or data accessible through OLEDB or Open Database Connectivity (ODBC).
Connection to data is made through two important properties ConnectionString and
ProviderName.

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:

Property Group Description

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

SortParameterName Gets or sets the name of an input parameter that the


command's stored procedure will use to sort data.

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 ObjectDataSource Control


The ObjectDataSource Control enables user-defined classes to associate the output of their
methods to data bound controls. The programming interface of this class is almost same as the
SqlDataSource control.

Following are two important aspects of binding business objects:

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

The student class:


public class Student
{
public int StudentID
{
get; set;
}
public string Name
{
get; set;
}
public string City
{
get; set;
}
public Student()
{
}
public DataSet GetStudents()
{
DataSet ds = new DataSet();
DataTable dt = new DataTable("Students");
[Link]("StudentID", typeof(System.Int32));

[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:

<asp:AccessDataSource ID="AccessDataSource1 runat="server"


DataFile="~/App_Data/[Link]" SelectCommand="SELECT *
FROM [DotNetReferences]">
</asp:AccessDataSource>
The AccessDataSource control opens the database in read-only mode. However, it can also be
used for performing insert, update, or delete operations. This is done using the [Link]
commands and parameter collection.

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.

Declarative Data Binding

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

However, the data binding involves the following objects:

• A dataset that stores the data retrieved from the database.

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

Relation between the data binding objects:


Web Services

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.

Key Web Service Technologies

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

Web Services Limitations

• SOAP, WSDL, UDDI- require further development.


• Interoperability.
• Royalty fees.
• Too slow for use in high-performance situations.
• Increase traffic on networks.
• The lack of security standards for Web services.
• The standard procedure for describing the quality (i.e. levels of performance, reliability,
security etc.) of particular Web services – management of Web services.
• The standards that drive Web services are still in draft form (always will be in
refinement).
• Some vendors want to retain their intellectual property rights to certain Web services
standards.

There are three aspects of web service development:

• Creating the web service


• Creating a proxy
• Consuming the web service

Creating a Web Service


A web service is a web application which is basically a class consisting of methods that could be
used by other applications. It also follows a code-behind architecture such as the [Link] web
pages, although it does not have a user interface.

To understand the concept let us create a web service to provide stock price information. The
clients can query about the name and price of a stock based on the stock symbol. To keep this
example simple, the values are hardcoded in a two-dimensional array. This web service has three
methods:

• A default HelloWorld method


• A GetName Method
• A GetPrice Method

Take the following steps to create the web service:

Step (1) : Select File -> New -> Web Site in Visual Studio, and then select [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)]

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


// using [Link] AJAX, uncomment the following line.
// [[Link]]

public class Service1 : [Link]


{
[WebMethod]

public string HelloWorld()


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

using [Link];
using [Link];
using [Link];

using [Link];

[WebService(Namespace = "[Link]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]

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


// using [Link] AJAX, uncomment the following line.
// [[Link]]

public class StockService : [Link]


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

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

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

[WebMethod]
public double GetPrice(string symbol)
{
//it takes the symbol as parameter and returns price
for (int i = 0; i < [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];
}

return "Stock Not Found";


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

Step (8) : Click on a method name, and check whether it runs properly.
Step (9) : For testing the GetName method, provide one of the stock symbols, which are hard
coded, it returns the name of the stock

Consuming the Web Service


For using the web service, create a web site under the same solution. This could be done by right
clicking on the Solution name in the Solution Explorer. The web page calling the web service
should have a label control to display the returned results and two button controls one for post
back and another for calling the service.

The content file for the web application is as follows:


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="[Link]"
Inherits="wsclient._Default" %>

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


"[Link]

<html xmlns="[Link] >

<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 [Link];
using [Link];
using [Link];
using [Link];

using [Link];
using [Link];
using [Link];
using [Link];
using [Link];
using [Link];

using [Link];

//this is the proxy


using localhost;

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]();
}
}

protected void btnservice_Click(object sender, EventArgs e)


{
StockService proxy = new StockService();
[Link] = [Link]("Current SATYAM Price:{0}",
[Link]("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();
[Link] = [Link]("Current SATYAM Price: {0}",
[Link]("SATYAM").ToString());
}

Take the following steps for creating the proxy:

Step (1) : Right click on the web application entry in the Solution Explorer and click on 'Add
Web Reference'.
Step (2) : Select 'Web Services in this solution'. It returns the StockService reference.

Step (3) : Clicking on the service opens the test web page. By default the proxy created is called
'localhost', you can rename it. Click on 'Add Reference' to add the proxy to the client application.

Include the proxy in the code behind file by adding:

using localhost;

You might also like