Sie sind auf Seite 1von 49

.

NET

ASP.NET 2.0 using C#

Contents of ASP.NET:

Introduction to ASP.NET technology


Web application development using server controls
Style sheets
Skins and Themes
Master pages
ADO.NET 2.0
Security
Forms Authentication
Windows Authentication
Passport Authentication
Caching
Page output cache
Page fragmentation cache
Data cache
State management
Page level state management
Application level state management
Session level state management
Profiles
Globalization and localization of webforms
Tracing
Page level tracing
Application level tracing
Customizing errors
Sending emails using ASP.NET
File uploading using ASP.NET
Intranet search development using index server
Introduction to XML
XML webservices
Introduction to mobile.net
Web parts
ASP.NET AJAX (ATLAS)
Setup and Deployment
Project implementation with coding
2

Requirement: A technology to contact the external resources and to provide the response
back to the client.
Solution: Serverside technology
Advantage: Performance will be very fast.
Drawbacks: Resources of webserver will be blocked.
Resources of webserver will not be utilized efficiently

Requirement: A technology to contact an external resources and to provide the response


to the clients without providing burden to the webserver.
Solution: Servelets technology
Advantage: Resources of webserver will not be blocked.
Drawbacks: Performance will be very slow.

Requirement: A technology to contact the external resources and to provide the response
to the clients without providing any burden to the clients and webserver.
Solution: Server pages technology

Sunmicrosystems  Java Server Pages (JSP)


Oracle Corporation  PL/SQL Server Pages (PSP)
Microsoft Corporation  Active Server Pages (ASP)

Drawbacks of ASP.3.0:

ASP = HTML (for user interface(these are browser dependent i.e. tags are different for different browses))
+
Java Script (for client side validations)
+
VB Script (for server side control)
+
ASP built in objects
+
COM (for interacting with external resources)

1) Huge complex coding is required


2) Code readability
3) Performance
4) Security
5) Caching
6) Sessions
7) Setup and deployment
8) All the limitations of COM is also applicable
3

ASP.NET: It is a specification which is used for designing:

i) Webforms: It is used for designing the web applications where a web


application is an application is an application which uses HTTP or HTTPS
protocols for sending the request and for receiving the response using the
browser.
ii) Webservcies: It is a specification to achieve the cross language, cross
platform and cross device integration i.e. a webservice can be considered as a
class definition which will be maintained on the webserver as a service such
that the definitions can be used from any application developed using any
language for any platform or for any device.
iii) Mobileforms: It is used for designing device independent applications.
Note: ASP.Net specification can be implemented using either C#, VB.NET or
VJScript.NET or J#

Architecture of ASP.NET:

Webserver is used to receive


ASP.NET runtime is used for processing

where
IIS means Internet Information Services
aspnet_isapi.dll means ASP.NET Internet Server Application Programming Interface
wp means worker process
inet info.exe identifies aspx or asp
Requested page is processed is a 10 stage i.e. ASP.NET page life cycle
4

For the first time when webpage is accessed:

If second time same then compiler and .aspx change colour.

If same code i.e. code not modified:

Whenever a client sends a request to the ASPX page to the webserver then “inetinfo.exe”
is a process which identifies the request type and incase if it identified the request is
called ASPX page then it sends a request for ASP.NET script engine (aspnet_isapi.dll).

Once a request is accepted by the script engine it will further send a request to the
ASP.NET runtime environment (“aspnet_wp.exe”) where the configuration files are
verified and the requested page is processed and the result will be provided as HTTP
response to the client.

Machine.config: It is a configuration file which provides the configuration details for all
the ASP.NET web applications registered within the server.

web.config: It is a configuration file which provides the configuration details for the
requested web application.
where configuration details specifies the language to be used for implementing ASP.NET
specification, state management information, connection strings to be used for interacting
with the database, tracing and debuggings, profiles management, used to provide the
security details such as authentication and authorization, globalization and localization
settings etc.
5

Features of ASP.NET 2.0:

1) Side by side execution: ASP and ASP.NET pages can be executed simultaneously
and can exist within a single application.
2) Server side controls: ASP.NET technology has introduced rich powerful
webserver controls which are capable to identify the clients browser and can
render the HTML tags accordingly.
Note: Web server controls are state managed controls.
3) Performance: Architecture of ASP.NET is designed in order to increase the
performance of the application.
Note: ASP.NET application are 28 times faster than JSP application.
4) Session: It is used to maintain the state of the user i.e. the user information across
the webforms present within the application.

Enhancements:
 Sessions in ASP.NET can be either a cookie based or it can be
cookieless.
 Sessions in ASP.NET can be enabled or it can be disabled in any
webform present within the application as per the requirement.
 Session information of ASP.NET can be maintained at the webserver
or at the state server or at sqlserver database.

5) Caching: It is used to maintain the result or output of the webform temporarily.


Note: ASP 3.0 supports only client side caching.
Enhancements:
ASP.NET supports client side caching and server side caching such as:
i) Page output cache
ii) Page fragmentation cache
iii) Data cache
6) Security:
Enhancements:
ASP.NET supports:
i) Forms authentication
ii) Windows authentication
iii) Passport authentication

7) Powerful database support: ASP.NET uses ADO.NET specification to interact


with any database or XML document.
8) Webservices: It is a specification to achieve cross language, cross platform and
cross device integration.
9) Setup and deployment: ASP.NET support web setup project which helps the
application to be deployed easily.
6

New features introduced in ASP.NET 2.0

1) 54 new web controls are introduced in ASP.NET 2.0.


2) Skins and Themes: It is used to build the styles for the webserver controls.
Note: This feature can be considered as an enhancement for the style sheets.
ASP.NET 2.0 supports the usage of style sheets, skins and themes within a single
webform.
3) Master pages: It is used to design a template for the application such that the
webforms can use the maser pages for receiving the contents.
4) Profiles: It is used to maintain the user information permanently at the webserver
by storing the user information permanently at the webserver by storing the user
details along with the computer details within a sql server database table.
5) Site navigation: ASP.NET technology introduced sitemaps and sitemap path
controls to achieve site navigation.
6) Webparts: It is used to design the webform to support adding the controls,
moving the controls, removing the controls and editing the controls present within
the webform dynamically at the runtime.

Software requirements:
Operating System Service Pack (is software) .NET framework
SDK 2.0
Win NT 4.0 6 Yes
Win 2000 4 Yes
Win XP 2 Yes
Win 2003 1 Yes

Internet Explorer 6.0 version and > 6.0 version


Optional: IIS (webserver)

Design tools:
Microsoft Visual Studio.Net 2005 professional [1.6 GB + Hard Disk]
Microsoft Visual Web Developer 2005 [800 MB]
(only ASP.NET application runs and free download from internet)
Macromedia Dream Weaver Mx [300 MB + Hard Disk]
7

Webserver Controls

It is used to provide the user interface for the webform.


Advantages: These controls are WYSWYG (What You See What You Get) controls.
These controls are state managed controls.
Note: ASP.Net webform can be designed using 2 methods:
a) In-Page techinique: Whenever the presentation logic and the business logic are
written within the same file then it is said to be in -page.
Advantage: Easy deployment of web application.
b) Code – behind page technique: Whenever the presentation logic inherits the
code behind page then it is said to be code behind page technique.
Advantage: Reusability of the business logic by multiple web forms.

ASP.Net programming model:


1) Auto Post Back
To collect the data: Control Name.Property
2) To collect the data:
GET: Request . QueryString [“_____”]
POST: Request . Form [“_____”]

Table: It is used to divide the webform into logic blocks such that the controls can be
grouped together and backgrounds can be set for individual blocks and also used
to design a webform to provide an effective look and feel.

STANDARD CONTROLS:

Label Control: It is used to provide any static information on the webform.

Common properties for all the webserver controls:

id: It is used to specify an unique identifier for the control placed on the webform.

Text: It is used to set or get the value from any webserver control.

Common syntax for all the webserver controls:


Syntax:
<asp: controlType id = “…”
runat = “server” …> Data
</asp: controlType>
_______________________________________________

Button Control: It is used to submit the data to the server.


_______________________________________________
8

Textbox Control: It is used to accept a single line, multi line or password characters as
the input.

Properties:
Textmode: Used to specify the mode to accept the input from the user.
(Default mode is single line).

Max Length: It is used to specify the maximum characters that can be accepted as the
input.
Read only: It is used to define a control as a non-editable control.
_______________________________________________

RadioButton Control: It is used to select a single option from a collection of radio


button controls.

Properties:

Checked: Returns true if the radio button is selected else returns false.

GroupName: Specify a name to logically group all the related radio button controls.
_______________________________________________

RadioButtonList Control: It is used to select a single item from a collection of radio


button list items.

Common properties for the list controls which supports single item selection:

Items: It is used to maintain the collection of list items.

RepeatDirection: Used to specify the direction in which the list item has to be displayed.
(Default direction is vertical).

Code part:

SelectedItem.Text: Returns the text of the selected list item.

SelectedItem.Value or SelectedValue: Returns the value of the selected list item.

SelectedIndex: Returns the index number of the selected list item.


_______________________________________________
9

DropDownList Control: It is used to select a single item from a collection of list items.

Note: The properties used for RadioButtonList are applicable for DropDownList control
control.
_______________________________________________

ArrayList: It is a collection which is used to maintain a list of values that can be


considered as a data source for any standard control.

Syntax:
ArrayList alObject = new ArrayList();

To add the values for the arraylist object syntax:


alObject.Add (stringvalue);

Inorder to provide the source for the standard control syntax:


ControlName.DataSource = objectName;

Note: Whenever an object has been assigned as a data source for any standard controls
then schema information will be binded but not the data.

Inorder to bind the data to the control syntax:


ControlName.DataBind();

Note: Whenever the data bind method is used within the page load event then the method
should be used carefully else the control will not maintain its state.
_______________________________________________

CheckBox Control: It is used for selecting a boolean value i.e. true or false.

Property:
Checked: Returns true if the check box is selected else returns false.
_______________________________________________

CheckBoxList Control: It is used to select multiple items from a collection of checkbox


list items.

Common properties for the list control that supports multiple item selection:

Items.Count: Returns the number of list items present within the list control.

Items [index].Selected: Returns true if the specified list item is selected else returns false.

Items [index].Text: Returns the text of the specified list item.

Items [index].Value: Returns the value of the specified list item.


10

_______________________________________________

ListBox Control: It is used to select a single item or multiple items from a collection of
list items.

Property:
Selection Mode: It is used to specify the mode of selecting the values from the list
control.
(Default selection mode is single).
Note: If selection mode is single then the properties used for radio button list control can
be used and if selection mode is multiple then the properties used for check box list
control can be used.

Common methods for all the list controls:

Items.Add (string or list item): It is used to add a list item to the items collection of the
list control.
Note: If the string is passed as the argument value then the text and the value for the list
item will remain the same.
Inorder to provide different value for the text and values for list item, then list item
object should be passed as the argument value.

To do:
ListItem liobject = new ListItem();
Liobject.Text = value 1;
Liobject.Value = value 2;
listControl.Items.Add(liobject);

Items.RemoveAt(listIndex): It is used to remoce an item from the items collection of the


list control based on the list value.

Items.Clear(): It is used to clear all the items present within the items collection of the list
control.

Note: Inorder to bind a java script function to the webserver control.

ControlName.Attributes.Add(“eventName”, “[return] functionName ([arg Value(s)])”);

Ex: To get a message box:


btnClick.Attributes.Add(“onClick”, “alert (‘Welcome to .Net’)”);

To rise a confirmation box:

btnClick.Attributes.Add(“onClick”,”return Confirm(‘Prompt message’)”);


_______________________________________________
11

AdRotator File: It is used to place the advertisements on the webform.

Property:
Advertisement File: Specify the name of the XML file which provided the details about
the advertisements to be placed on the webform.

Target: Specify the name of the frame in which the advertisement has to be opened.
(Default target is _top)

Structure of Advertisement file:

<Advertisements>
<Ad>
<ImageUrl>…</ImageUrl>
<NavigateUrl>…</NavigateUrl>
<AlternateText>…</AlternateText>
<Impressions>…</Impressions>
</Ad>

<Ad>
….
….
</Ad>

</Advertisements>
_______________________________________________

Calendar Control: It is used to project the calendar on the webform.

Property:
SelectedDate: Returns the date selected within the calendar control.

SelectedDates: Returns the list of dates selected within the calendar control.

Note: In order to select more than a single date then the selection mode property of the
calendar control should be set.

Customizing Calendar Control:


Note: A calendar control can be considered as a collection of table cells where the table
cells will provide the information about the calendar days.
12

In order to customize the table cells present within the calendar control then DayRender
event should be used DayRender event will be executed for each and every Calendar day
present within the calendar control.

In order to extract the current table cell information:

(TableCell)e.cell

In order to extract current calendar day: (CalendarDay)e.day


where ‘e’ in the above syntax is a DayRender event args variable.
_______________________________________________

Literal Control: It is used to add a string as a control to any other standard controls.

Syntax:

LiteralControl lcobject = new LiteralControl(string value);

In order to add a control to any other control:

ControlName.Controls.Add(Control or object);

In order to clear the controls present within other controls:

ControlName.Controls.Clear();
_______________________________________________

File upload Control: It is used to read a file present at the clients system and used to
upload the file to the webserver.

1) Create a folder for maintaining the uploaded files at the web server.
2) Set the permission for reading and writing the contents on the folder (Right click
properties, security, full control tick, OK).
_______________________________________________

Panel Control: It is a container control which is used to logically group the controls
together.

Note: Whenever any control has to be added dynamically at the runtime to the webform
or if a group of controls has to be set with common property such as visible property then
panel control should be used.
_______________________________________________

Wizard Control: It is used to design a web application or a web form using various steps
where every single step can maintain a collection of controls.
13

VALIDATION CONTROLS:
These controls are used to validate the user input.

Required Field Validator: It is used to verify whether the user has provided a value for
a control or not.

Common properties for the validation controls:

ControlToValidate: Specify the name of the control to be validated.

ErrorMessage: Specify the error description to be displayed if the user provides an


invalid input.

Note: A single validation control can be used to validate a single webserver control.
A single webserver control can be binded with any number of validation controls.

Note: Whenever validation controls are used then the validations are performed at client
system only.
_______________________________________________

Compare Validator: It is used to validate the input of one control by comparing the
value present at other control.

Properties:

ControlToCompare: Specify the name of the control which acts like a source.

Operator: Specify the operator to be used for comparing the values.


(Default operator is equal).

Type: Specify the data type to be used for comparing the values.
(Default type is string).
Note: Other than Required Field Validator all the remaining validation controls will not
validate the control if the value of the control is empty.
_______________________________________________

Range Validator Control: It is used to validate the user input whether the given value is
existing within the specific property.
Property:
Minimum Value: Specify the lower range.
Maximum Value: Specify the upper range.
Type: Specify the data type to be used for validating the user input.
14

_______________________________________________

Custom Validator: It is used to validate the user input based on the user defined
functionality.

Note: It is the only validation control which can validate the user input at client side and
also at the server side.

Property:
Client Validation Function: Specify the client side java script function name which is
used to validate the user input at the client system.

Events:

Server Validate: The code written within this event will be executed implicitly to validate
the user input at the server side.
_______________________________________________

RegularExpressionValidator Control: It is used to validate the user input based on a


expression.

Property:
ValidationExpression: Specify the expression to e used for validating the user input.

Characters used to define an expression:

\d: Accepts a single numerical value.


\D: Accepts a single character value.
\w: Accepts a string or a word without a white space.
[a-zA-Z0-9]: Accepts alpha numerical value
^[a-zA-Z0-9]: Accepts any special characters or symbol characters
[0-4a-d]: Accepts 0 to 4 and a to d characters.
[a,e,i,o,u]: Accepts only the characters present in the []

Occurrences: It is used to specify the occurrence of the character within the expression.

{number}: Accepts the input if the length of the expression is equal to the specified
number. Ex. \d{6}

{minNumber, }: Accepts the input if the length of the expression is greater than or equal
to the specified minimum number.

{minNumber, maxNumber}: Accepts the input if the length of the expression is between
a specific range.
15

Mode: It is used to specify the occurrence of the characters specified within the
expression.

Mode MinOccur. MaxOccur.


? 0 1
+ 1 Any
. 0 Any

[ma+m] = madam, malayalam


_______________________________________________

ValidationSummary Control: It is used to validate other validation controls.

Note: Error messages of other validation controls will be considered as a input for the
validation summary control.
Note: Whenever validation summary control is used within the form then it is mandatory
that for other validation controls text property has to be set.
Note: Validation summary is the only control which is capable to project a message box.
_______________________________________________
16

ADO.NET
(Active X Data Objects for .Net)

It is a specification which is used to interact with any database or XML documents.

ADO.Net supports two types of connectivity to the database


1) Disconnected Model
2) Connection Oriented Model

1) Disconnected Model: If used to interact with the database then the connectivity
between the application and the database is not required while performing
navigations or manipulations on the data.

2) Connection Oriented Model: If used for interacting with the database then the
connectivity between the application and the database has to be maintained till the
application interacts with the database.

Connection: It is used to establish physical relationship between the application and the
database.

Data Adapter: It is a collection of commands which acts like an interface or bridge


between the database and the dataset for transferring the data.
Note: If the Data Adapter can be binded to the single table.

Methods of Data Adapter:


Fill (DataSetName, Data Table): It is used to read the data from the database based on the
select statement of select command of the data adapter and fills the data within the
dataset.

Update (DataSetName, Data Table): It is used to read the data from the data members of
the dataset and used to update the database with that data.

Dataset: It is an in-memory representation of the data at the client system in the format of
XML.

Note:
1) Dataset can maintain the information about any number of tables irrespective of
their native database.
2) Dataset supports establishing relationship between the data members of the
dataset.
3) Dataset will not be aware of the information about the data tables from which
database they belong to.
4) Any manipulations performed o the dataset will not be reflected on the database.
17

Dataset is of two types:


1) Typed Dataset
2) Untyped Dataset

1) Typed Dataset: Whenever a dataset is defined using the XML schema definition
then it is said to be typed dataset.
Note: The data members of the typed dataset will be binded to the dataset at the
design time itself.

To refer the data members of Typed Dataset: DataSetName . DataMemberName


Ex: DS . Emp

2) Untyped Dataset: Whenever a dataset is defined without the XML schema


definition then it is said to be untyped dataset.
Note: The datamembers of the untyped dataset will be binded to the dataset at the
runtime.

To refer the data members of Untyped Dataset: DataSetName . Tables(tableIndex)


Ex: DS.Tables(0)

DataView: It is logically representation of the data present within the datamembers of


the dataset.

Note: Dataview should be used if the data has to be sorted or if the data has to be
filtered or if the data has to be projected in pagewise.

Command: It is used to provide the source for the connection object.

DataReader: It is a read only and forward only recordset which maintains the data
retrieved by the command object using connection oriented object method.

SqlServerDB:
(System.Data.Sqlclient) is Namespace
SqlConnection
SqlCommand
SqlDataReader
SqlDataAdapter are classes.

OracleDB: (ODB.Net (Oracle Dataproviders for .Net)


(System.Data.Oracleclient)
OracleConnection
OracleCommand
OracleDataReader
18

OracleDataAdapter

Oledb Providers: (Object linking embedded database providers)


(System.Data.Oledb)
OledbConnection
OledbCommand
OledbDataReader
OledbDataAdapter

ODBC Drivers: (Open Database Connectivity)[DSN (Data Source Name) Based Model]
(System.Data.Odbc)
OdbcConnection
OdbcCommand
OdbcDataReader
OdbcDataAdapter

DataSet System.Data (Namespace)


DataView

Syntax:

Connection:
In VB.Net: modifier objectName as new xxxConnection(connectionString)

In C#: xxxConnection objectName = new xxxConnection(connectionString);

Where xxx in above syntax can be either Sql, Oracle, Oledb or ODBC.

Connection string to connect to Sql server database:


provider = sqloledb.1; user id = sa; password = ; datasouce = server; database = DBName

Connection string to connect to Oracle database:


provider = oraoledb.oracle; user id = scott; password = tiger[; datasouce = server]
(Underlined is optional. If client and server same no need optional).
If Oracle 8i then provider = msdaora.1; …
Note: Whenever Sqlconnection class is used to connect Sqlserver and Oracle connection
class is used to connect Oracle database then provider = providername should not be
mentioned within the connection string.

DataAdapter:

In VB.Net: modifier objectName as new xxxDataAdapter(select statement, <connectionString or connectionObject>)


In C#: xxxDataAdapter objectName = new xxxDataAdapter (select statement, <connectionString or connectionObject>);

Note: Whenever a DataAdapter is defined using the above syntax then select command of
data adapter will be generated (other commands will not be generated).
19

DataSet:

In VB.Net: modifier objectName as new Dataset()


In C#: Dataset objectName = new Dataset();

Note: Whenever a dataset is defined using the above syntax then it is said to be untyped
dataset.

DataView:

In VB.Net: modifier objectName as new Dataview(DatasetName.DataTable)


In C#: Dataview objectName = new Dataview(DatasetName.DataTable);

Command:
In VB.Net: modifier objectName as new xxxCommand([Sql Statement, ConnectionObject or ConnectionString])
In C#: xxxCommand objectName = new xxxCommand ([Sql statement, ConnectionObject or ConnectionString]);

DataReader:
In VB.Net: modifier objectName as xxxDataReader
In C#: xxxDataReader objectName;

CommandBuilder: It is a class which is used to generate the commands for the


DataAdapter based on the table definition that is if the table is defined with primary key
then all the commands will be generated else the commands relevant for the Update
command and Delete command will not be generated.
Syntax:
In VB.Net: modifier objectName as new xxxCommandBuilder(DataAdapterObject)
In C#: xxxCommandBuilder objectName = new xxxCommandBuilder(DataAdapterObject);
20

ADO.Net 2.0

ObjectDataSource
SqlDataSource
XMLDataSource
AccessDataSource

ObjectDataSource: Whenever a data access layer has to be used as a data source for the
application then object data source should be used.

Steps to project the data using disconnected model:


Define a connection object
Define a data adapter object
Define a dataset
Fill the data set
[optional] Assign the data set as a data source
[optional] Bind the data to the control

Steps to insert a record using disconnected model:


Step 1: Define a data row
Syntax: DataRow rowVariable;

Step 2: Assign the data row of the data member of the data set to the data row variable
Syntax: rowVariable = DataSetName. DataTable.NewRow ();

Step 3: Assign the values to the data columns of the data row variable
Syntax: rowVariable[columnIndex or columnName] = value;

Step 4: Add the data row variable to the data rows collection of the data member of the
data set
Syntax: Datasetname. Datatable. Rows. Add (rowVariable);

Step 5: Update the data adapter with the data present at the datamember of the dataset
Syntax: DataAdapterName. Update(DatasetName, DataTable);

Steps for updating the data using disconnected model:


Step 1: Define a Datarow variable
Step 2: Assign the Datarow of the data member which has to be modified to the datarow
variable
Syntax:
1st method: rowVariable = DataSetName. DataTableName.Rows[rowIndex];
2nd method: rowVariable= DataSetName.DataTable.Rows.Find(primarykeycolumnname)
21

Note: To add a constraint to the datamember of the dataset:


DatasetName.DataTableName.Constraints .Add(“constraintName”, DataColumn,booleanValue);
(if true is passed then it defines a primary key constraint and
if false is passed then it defines an unique constraint)

Step 3: Start the edit mode


Syntax: rowVariable.BeginEdit();

Step 4: Assign the values to the Datacolumns of the datarow variable


Step 5: End the Edit mode
Syntax: rowVariable.EndEdit();
Step 6: Update the DataAdapter with the data present at the datamembers of Dataset

Steps to delete the data using disconnected model:


Step 1: Delete the datarow from the datarows collection of the datamember of dataset
Syntax:
1st method: DataSetName.DataTable.Rows[rowIndex].Delete( );
2nd method: DataSetName.DataTable.Rows.Find(primarykey column value).Delete( );

Step 2: Update the dataadapter with the data present at the datamembers of dataset

Common steps for data manipulations:


Define a connection object
Define a DataAdapter object
Define a CommandBuilder object
Define a DataSet
Fill the Dataset
Add a constraint to the datamember of dataset (Required if update or delete task has to be
performed)

Example:

public class DataAccessLayer


{
public DataSet ShowRs()
{
SqlConnection cn = new SqlConnection ("user id=sa;password=;database=pubs;data source=net");
SqlDataAdapter da = new SqlDataAdapter("select * from ft222batch",cn);
DataSet ds = new DataSet();
da.Fill(ds,"ft222batch");
return ds;
}

}
22

Inserting:

public bool RegisterUser (string usr, string pwd)


{
try
{
SqlConnection cn = new SqlConnection("user id=sa;password=;database=pubs;data source=net");
SqlDataAdapter da = new SqlDataAdapter("select * from ft222batch",cn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds,"ft222batch");
ds.Tables[0].Constraints.Add("usr_pk",ds.Tables[0].Columns["usr"],true);

DataRow row;
row = ds.Tables[0].NewRow();
row[0]=usr;
row[1]=pwd;
ds.Tables[0].Rows.Add(row);
da.Update(ds.Tables[0]);
return true;
}

catch(Exception ex)
{
return false:
}
}

Updating for password:

public bool ChangePassword (string usr, string npwd)


{
try
{
SqlConnection cn = new SqlConnection("user id=sa;password=;database=pubs;data source=net");
SqlDataAdapter da = new SqlDataAdapter("select * from ft222batch",cn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds,"ft222batch");
ds.Tables[0].Constraints.Add("usr_pk",ds.Tables[0].Columns["usr"],true);

DataRow row;
row=ds.Tables[0].Rows.Find(usr);
row.BeginEdit();
row["pwd"]=npwd;
23

row.EndEdit();
da.Update(ds.Tables[0]);
return true;
}

catch (Exception ex)


{
return false;
}
}

Deleting the user:

public bool DeleteUsr (string usr)


{
try
{
SqlConnection cn = new SqlConnection("user id=sa;password=;database=pubs;data source=net");
SqlDataAdapter da = new SqlDataAdapter("select * from ft222batch",cn);
SqlCommandBuilder cmd = new SqlCommandBuilder(da);
DataSet ds = new DataSet();
da.Fill(ds,"ft222batch");
ds.Tables[0].Constraints.Add("usr_pk",ds.Tables[0].Columns["usr"],true);

ds.Tables[0].Rows.Find(usr).Delete();
da.Update(ds.Tables[0]);
return true;
}

catch (Exception ex)


{
return false;
}
24

SqlDataSource: It is used to interact with any database for performing manipulation or


projection on the data without writing any code.

Using SqlDataSource for projecting the data


Customizing GridView to project selected columns
Using SqlDataSource for projecting the data in pagewise
Customizing SqlDataSource for filtering the data based on a condition
Configuring SqlDataSource for manipulations

Details view control

Customize GridViewControl
Customizing GridViewControl to project scroll bar
Customizing GridViewControl to add controls dynamically at the runtime and to read the
value from the gridview:

Gridview is a collection of templates where template is a collection of table cells. The


data present within the gridviewcontrol can exist either within a table cell directly or the
data can exist within any control present at the table cell.

The collection of all the related table cells is called as a row.

The collection of all the row present within the gridviewcontrol is called as rows
collection.

Whenever the user selects any specific row within the gridviewcontrol then it is said to be
selected row.

Inorder to refer to selectedrow from any events other than the gridview events then
GridViewName. SelectedRow should be used.
The above syntax should be used if gridview selectedindex changed event is used.

Inorder to refer a selected row from the grid view events then: e.Row should be used
where ‘e’ is an gridview row event args variable.

To read the value present within the table cell of GridViewControl:

(TableCell)GridViewName.SelectedRow.Cells[cellIndex]

Ex:
TableCell ename;
For outside of gridviewcontrol:
ename= (TableCell) GridViewName.SelectedRow.Cells[1];
For within the gridviewcontrol:
ename= (TableCell) e.Row.Cells[1];
25

In order to read the value from the control present at the table cell of grid view control:

(ControlType) GridViewSelectedRow.Cells[cellIndex].Controls[controlIndex]

Ex:
CheckBox chkempno;
chkempno = (CheckBox)GridViewName.SelectedRow.Cells[0].Controls[0];

DropDownList ddljob;
Ddljob = (DropDownList)e.Row.Cells[2].Controls[0];

In order to add any controls dynamically at the runtime then row created event should be
used.

If the controls are added without the code (i.e. without programming) then index of
control will start with 1.

Customizing Grid control for adding the controls dynamically using the tools.
26

Globalization and Localization:

It is used for designing an application to support multiple languages and cultures.

In ASP.Net globalization can be achieved at 2 levels:


i) Application Level Globalization
ii) Page Level Globalization

i) Application Level Globalization: If used then all the webforms present within the
application uses the same culture.

To set: [In web.config]

<globalization culture = “xx-XX”/>

where xx represents the language


XX represents the country or culture

For eg: Telugu (India) : te – IN

ii) Page Level Globalization: It is used to globalize any specific webform present within
the application.

Pagelevel globalization is of 2 types:

1) Globalizing the webform based on browser settings:


To set:
<%@ page language = “C#” culture = “auto:en-US” … %>

2) Globalizing the webform based an user specifications:


To do:
Step 1: import the System.Threading and the System.Globalization namespace
Step 2: Define an object for the cultureinfo class
Syntax:
CultureInfo objectName = new CultureInfo(culture); where culture is a string which will
be in the format of xx-XX
Step 3: Assign the cultureinfo object to the CurrentCulture and CultureUICulture
properties of current processing thread

Note:
CultureInfo: It is a class which acts like a repository for maintaining all the cultures
supported by the technology and also it is used to define a culture specific object.
CurrentCulture: It is a property which is used to set the current processing thread culture
to any specific CultureInfo object.
27

CurrentUICulture: It is a property which is used to project the information on the user


interface based on the culture binded to the current processing thread.
_______________________________________________

Localization: It is used to localize the form based on the information present within the
satellite resource assembly files.

Satellite assembly resource file: It is used for maintaining the resource information of the
.Net form.

Note: Satellite assembly resource file contents and the filename are case sensitive.
Note: If an application supports n cultures then n+1 satellite assembly resource files
should be created.
Note: The filename for satellite assembly resource for any specific culture should be in
following format:

For ex:
Main Resource File: myResource.resx
Resource File Telugu (India) : myResource . te-IN.resx
_______________________________________________

Style Sheets:
It is used to build the styles for the html contents present within the webform.
The extension for the cascading style sheet file should be ‘.css’.

To build styles for the html tags:


tag
{
property: value;

}

Syntax to define StyleSheetClass:


.ClassName
{
property:value;

}

Note: A single class can be used to provide styles for any number of webserver controls.
28

Syntax to define a style based on Control ID:


#idName
{
property:value;
…}
Style sheets should be used if the styles has to be applied for any HTML tags and it is not
advisable to use style sheets to provide styles for the webserver controls.
_______________________________________________

Skins and Themes:


(Used for only web server controls)

Skin file: It is used to provide the styles for the webserver controls.
The extension for a skin file should be ‘.skin’.

Theme:
The collection of style sheets and the skin files is called as a theme.

Note: A single web application can have any number of themes.

_______________________________________________
29

Security in ASP.NET:

ASP.NET technology supports the following security features:


i) Forms authentication
ii) Windows authentication (Default)
iii) Passport authentication

i) Forms authentication: It is used to provide security for the intranet or internet based
application.

First decide on number of users:

If two users 1) Registered users


2) Unregistered users
If three users 1) Anonymous users(i.e. all users)
2) Registered users
3) Administrator
If four users 1) Anonymous users (can view)
2) Registered users (can access)
3) Administrator (can do anything)
4) Moderator (can upload information)

Roles and Management:

To do:
Set the configuration file to use Forms authentication.

In web.config:
<authentication mode = “Forms”/>

Create the folders as per the requirement.


Set the permissions for accessing the folders by providing authorization for the user.

(Authentication: It is used to specify the authentication mode to be used by the ASP.NET


web application.

To set to Forms Authentication:


<authentication mode = “Forms”/>

Authorization: It is used to allow or deny the users from accessing the webforms present
within the application.

Syntax:

<authorization>
<allow users = “user1, user2, … or * ”/>
30

<allow roles = “roleName, … or * ”/>


<deny users = “?” or * or user or role ”/>
</authorization>) ( )  Notes within this is generated automatically

Note: Within a single webapplication there can be any number of web.config files.

The users information of the forms authentication will be maintained within


“aspnetdb.mdf” database within the tables called as “aspnet_users” and the
“aspnet_memberships”.

Controls to support Forms Authentication:

LOGIN CONTROLS:

Login: It is used to project the login form on the webform.

LoginView: It is used to provide a different views based on the user login details.
Note: LoginView supports two types of templates:
1) Anonymous template
2) Logged in template

PasswordRecovery: This control accepts the user name and provides the security
question and if the question has been answered with the correct security answer then this
control will update the password of the user and mails the new password to the email id
provided at the user registration.

LoginStatus: It is used to provide the status of the user and also it is used to provide
functionality to login or to log off based on the user login status.
Note: If login.aspx is not present within the main application folder then this control will
raise an error at the runtime.

LoginName: Returns the name of the user logged within the application.

CreateUserWizard: It is a wizard control which is used to register a new user for the
ASP.NET web application.

ChangePassword: It is used to update the old password with a new password if the user
provides a valid user credentials.

Customizing Create User wizard control for accepting additional information


31

ii) Windows Authentication: It is used to provide the security for the intranet based
applications based on the users registered within the network.

Windows Authentication is the default authentication used by the ASP.NET web


application. Windows Authentication is performed by IIS webserver and hence it is
essential that the application has to be configured within the IIS web server.

To set the Windows Authentication as the security:

In web.config file:
<authentication mode = “windows”;
<authorization>
<allow users = “domain / username, … or *”/>
<deny users = “domain / username, … or *”/>
</authorization>

 Whenever the user who sends the request is one among the users present within the
allow users list, then the requested page by the user will be provided as the response.
 Trusting the user credentials and providing the response is said to be impersonation.
 If the user who sends a request is logged one among the users present within the allow
users list, then the web server will project network login window as the response.

 Windows authentication mode supports three types of authentication:


a) Basic Authentiction: If used then the user credentials will be passed as the clear text
across the network.
b) Digest Authentication: It is a special authentication type used by the windows
authentication mode to authenticate the user credential of the domain server.
 This option will be disabled if network is a work group model.
c) Integrated Windows Authentication: (NTLM—New Technology LAN Manager
Authentication):It is the default authentication type used by the windows authentication
mode to validate the user credentials. If used then the user information will be passed as a
stream within the network.
 More than one authentication type can be used by the windows authentication mode.

iii) Passport Authentication: It is used to maintain the same user credentials across the
multiple applications which are partners of Microsoft.
To set passport authentication:
Steps:
 Install Microsoft passport SDK
 Configure web.config file to use passport authentication

In web.config file:
Syntax:
<authentication mode = “passport”>
<passport redirecturl = “internal/url”/>
</authentication>
32

State Management (SM):


It is used for maintaining the state of the user. State Management can be achieved at three
levels:
1) Session level
2) Application Level
3) Page Level

1) Session Level State Management: it is used to maintain the state of the user across
multiple webforms present within the web application.
 To achieve session level state management, sessions and cookies are used.

Sessions: It is used to maintain the user information across the web forms present within
the application by maintaining the data at the server side.

Enhancements of Sessions in ASP.NET:


 Session information can be enabled or can be disabled as per the requirement in any
web form within the application.
 Sessions in ASP.NET can be either cookies based or cookieless.
 Session information can be stored within the web server as a Inprocess and also the
session information can be maintained within the state server and also sql server database
as a Outprocess.

To set:
 session [session Variable] = value;

The value that can be assigned to a session variable can be either a string or an object.
 If string is passed as a value then the session information will be maintained within the
contents collection and if any object is assigned as a value then the information will be
maintained within the state objects collection.
 The default expiration time for the session information will be 20 mintues.

To read string information:


variable = Session [ sessionVariable].ToString();

To read object information:


objectname = (objecttype)Session [sessionVariable];

String database object information in the sessions

To disable the sessions for any specific webform:

In source of .aspx file:


%@page language = “C#” EnableSessionState = “false” ... %
33

 Whenever ‘enableSessionState’ attribute has been set to false then the session object
cannot be used within that web form and the resources required for maintaining the
sessions will not be allocated for that page.
 If ‘enableSessionState’ is set to false and if the session object is used within the form
then the asp.net runtime environment will raise an error.

By default the sessions are always cookie based sessions.

 Browsers are having a capability to disable the cookies and if the browsers has been
diabled with the cookies then the web application which uses cookie based sessions will
not function properly.
 Inorder to identify the session id of the client session.SessionID should be used.

Cookieless Sessions: If used for maintaining the session information then the session id
of the client will be appended for all the navigate url accessed within the web application.
Where navigateurl is the url to which the user sending a requesting.

To set:
In web.config file:
<sessionState mode = “InProc” cookieless=”true”/>

 Whenever cookieless sessions are used then as the session id of the client will be
appended on all the urls the application will function properly irrespective to cookies are
enabled or disabled at the client system.

Client system maintains session id.


Server system maintains session info.

Cookieless sessions can be used if and if the web application does not use any
confidential data.
By default the session information is maintained within the webserver as a InProcess.
Whenever the session information is stored as a InProcess within the webserver. If the
webserver crashes then the total session information maintained within the webserver
will be lost and hence if the same application is existing within other webserver, the data
cannot be accessed.

Maintaining session information as a out process: (i.e. Sql server database, State server)

Maintaining session information within state server:


State server: It is a window service which is used to refer the address of a memory block
at the webserver.

To store session information within state server

Performance: (Maintaining session information)


Webserver > State Server > Sql server DB
34

Faster Slow

Consistency: (of data)


Webserver < State Server < Sql server DB
Less secure More secure

Inorder to kill the session of the user explicitly:


Session. Abandon();

Cookies: It is used to maintain the server side information at client system.


Cookies is of 2 types:
1) In memory cookies or temporary cookies or non-persistant cookies
2) Permanent cookies or persistant cookies

1) In memory cookies: If used for maintaining the user information then the cookie
details will be stored within the memory allocated by the web browser.
2) Permanent cookies: If persistant cookies are used for maintaining the user information
then the cookie details will be maintained within the file at the client system.

To set the cookie:


1st method:
Response.Cookies[cookieName].Value = value;

2nd method:
HttpCookie cookieObject = new HttpCookie (“name”, “value”);
Response.Appendcookies(cookieObject);

Only string information can be maintained within the cookies.


The default expiration time for the cookie information will be 30 minutes.

To set the expiration time for the cookie information:


1st method:
Response.Cookies[cookieName].Expires = DataTime;

2nd method:
cookieObject.Expires = DateTime;

If a cookie has been defined without an expiration time then it is said to be an in memory
cookie and if the cookie information has been defined with the expiration time then it is
said to be persistant cookies.

To read the value from the cookie:


variable = Request .Cookies [cookieName].Value;

Cookies can store only string information and the information will always be maintained
at the client system only.
35

Web browsers are having a capability to disable the cookies and if the browser disables
the cookie then the web application which uses cookies will not function properly.

The information maintained within the cookie are not secure.

Sessions should be used whenever the data has to be maintained confidential and if any
objects has to be passed across multiple webform and the data will be accessed by less
users.
Cookies should be used if only string information has to be passed across multiple pages
and if the data is not confident and if more number of users access the web application.

Application level state management: Whenever the information of all the users accessing
the web application has to be maintained then application level state management should
be used.
Assume that we have a web server within webserver we have web application and within
application has ‘n’ number of webforms.

To set:
Application[“variable”] = value; where the value can be either string or an object

If string information has been assigned to the application variable then the information
will be maintained within the contents collection and if any objects are assigned to the
application variable then the information will be maintained within the static objects
collection.

Application variable will not have any expiration period but if the server has been
restarted then the contents present within the application variable will be lost.
The information maintained within the application object will be shared for all the users
accessing the web application.

To read the value from the application collection:


To read string information:
variable = Application[“variable”].ToString();

To read object information:


objectName = (objectType)Application[“variable”];

Application.Lock(): It is used to lock the application contents collection from accessing


by other users variable, the application contents collection is used by one user.

Whenever an application has been locked then once a complete page has been processed
then the application collection will be unlocked implicitly.

Application.Unlock(): It is used to release the lock defined on the application using the
Application.Lock method.
36

Working with Global.asax file:

Global.asax: (Global ASP.Net Application file)


It is a collection of events which will be raised implicitly based on the actions performed
by the user within the web application.

Events present within the Global.asax file:


1) Application_Start: The code written within this event will be executed only once
whenever the web application is requested for the first time.
2) Application_BeginRequest: The code written within this event will be executed for all
the web forms present within the web application before processing the code written
within the page load event.
3) Application_EndRequest: The code written within this event will be executed for all
the webforms present within the web application before the user navigates from one web
form to the other.
4) Application_Authenticate: The code written within this event will be executed before
the user credentials has been authenticated by the ASP.Net runtime.
5) Application_Error: The code written within this event will be executed implicitly
whenever any exception is raised within any webform present within the application and
if the exception is not handled within the form.
6) Application_End: The code written within this event will be executed only once
whenever the website has been shutdown.
7) Session_Start: The code written within this event will be executed every time a new
session has been created for a web application within the server.
8) Session_End: The code written within this event will be executed whenever the session
of the user has been expired.

If the session information is maintained within the SQL server database or the state server
and if the session of the user has been expired this event will not be raised.

3) Page level state management: It is used for maintaining the state of the controls after
submitting the data to the server.

By default for all the web server controls page level state management will be enabled.
Inorder to achieve page level state management, view state will be used.

Viewstate is a class which maintains the state of the control by maintaining the
information in a name value pair within the view state bag collection.

To set the view state explicitly:


ViewState[“control”] = value;

To read the value from the view state:


variable = ViewState[“control”];
37

whenever view state has been enabled for the control then the ASP.Net runtime
environment will define a HTML hidden field with a name _ _ ViewState and the value
will be encrypted.

HTML Screen Scraping:


It is used to read the result of the webform and use the output of the web form as the
contents within other webforms.

In order to support HTML screen scraping System.Net namespace should be used.

Sending Emails using ASP.Net 2.0:


In order to send mails using ASP.Net 2.0 then System.Net.Mail namespace should be
used.

SmtpClient: It is a class which is used to specify the smtp server name and port number
to be used for sending the email and also it provides the method called sending the email.

Properties:
Host: It is used to specify the Smtpserver name or its IPaddress.

MailMessage Class: It is used to compose the mail.


Properties: From
To
Subject
CC
Bcc
IsBodyHTML
Priority
Body

MailAddress: It is used to specify the sender and the recipient mail address.

Inorder to send mails the system should be installed with Internet Information Services
i.e. webserver and smtp virtual server software.

Intranet search using index server with ASP.Net 2.0 application:

Indexserver: It is used to maintain the index of the files present within the local drivers
of the system and also maintains the index of the web documents present within the web
server.

To start the index server:

By default the index server provides 2 catalogs:


1) System catalog
38

2) Web catalog
1) System Catalog maintains the index of all the files present within the local drives of
the system.
2) Web Catalog maintains the index of all the web documents present within the web
server.

Connection string to connect index server database:


provider = msidxs; data source = catalogName

Select statement for retrieving the data from the index server:
select filename, vpath from scope() where freetext(contents, ‘searchText’)

Caching: It is used for maintaining the result or the output of the webform temporarily.
Advantage: If used in a efficient manner the performance of the application will be
improved from 12 to 15%

Caching should be used if and if the following two features are supported:
1) The contents of the webform should be static.
2) The number of requests for the webpages should be more.

ASP.Net technology supports the following caching:


1) Page output cache
2) Page fragmentation cache or Partial page cache
3) Data Cache

1) Page output cache: It is used to maintain the total output of the webform as a cache
information.
To set:
<%@ outputcache duration= “seconds” varybyparam = “controlName or arrayVariable or none”%>

VaryByParam: If assigned with any control or array variable then for every unique value
assigned for the VaryByParam attribute at distinct cache page will be created at the server
and will be maintained by the web server.

2) Page fragmentation cache or Partial page cache:


a) Whenever any specific path of the web form has to be maintained as a cache
information then page fragmentation cache should be used.
Web user control: It is used to create a reusable web control such that the control can be
used within any web form present within the same application.
b) Substitution Caching: Whenever any specific contents has to dynamic and if entire
webform output has to be maintained within the cache then substitution caching should
be used.

Inorder to support substitution caching ASP.Net 2.0 has introduced substitution control.
Inorder to project the dynamic information the substitution controls, method name
property should be assigned with the method that returns the dynamic information.
39

The method which projects the dynamic information should be defined as a static method
and it is mandatory that the method should accept http context argument.

3) Data Cache: It is used for maintaining the memory variables or objects as the cache
information.
To set:
1st method:
Cache[“key”] = value;
If the cache has been set using the above syntax then it is said to be low level caching.

2nd method:
Cache.Insert(“key”,value);
If the cache has been set using the above syntax then it is said to be high level caching.

Cache can maintain any string information or any object as a value:

To get or read:
To read string information:
variable = Cache [“key”].ToString();

To read object information:


objectName = (objectType) Cache [“key”];

Cache dependency: It is used to kill the cache if the contents present at the file binded to
the cache dependency object is modified.

Syntax: CacheDependency cdObject = new CacheDependency (filename);

Syntax to set the cache based on cache dependency object:


Cache.Insert(key, value, CDObject);

Inorder to set the cache with the expiration time:


Cache.Insert(key, value, CDObject, ExpirationDateTime, SlidingTimeSpan);

Tracing: It is used to trace the flow of the application. It is of two types


1) Application level tracing
2) Page level tracing

1) Application level tracing: If set then the trace information will be displayed for all
the webforms present within the web application.
To set: [In web.config] file
<trace enabled = “true” requestLimit = “10” pageOutput = “true”/>

2) Page level tracing: It is used to enable or disable the trace information for any web
form present with the web application.
40

To enable or disable:
<%@ page language = “C#” trace = “true or false”… %>

Methods to support tracing:


Trace.Write: It is used for writing the page information within the tracing details of the
webform.
Trace.Warn: It is same as Trace.Write but the fore color of the text will be in red.

Crystal Reports usage in .Net:


Crystal Report: It is a tool for presenting the information in an efficient manner such that
the data will be displayed with a effective look and feel so that the end users can analyze
the data easily.

Creating a basic crystal report


The name of the crystal report file will be considered as a class name for which an object
has to be created in order to use the crystal reports programmatically.

To use crystal report

Creating crystal report for accepting the parameters

Master Pages: It is used to design a template for the ASP.Net web application such that
based on that template information any number of content pages can be designed.
The extension for the master page should be .master.

A single web application can have any number of master pages. Master pages can be
nested. Master pages can be used as templates and cannot be executed.

Steps to design a master page.


To add a content page

Sitemap file:
It is an XML document which is used to maintain the path of the web forms used within
the web application in a hierarchy.

The extension of the sitemap file will be .sitemap.


Whenever the sitemap file has to be used within the web form then sitemap data source
file should be used.

To use a sitemap file

Structure of web.sitemap file:


<?xml version = “1.0” encoding = “utf-8”?>
<siteMap xmlns = “http:// schemas.microsoft.com/AspNet/SiteMap.File.1.0”>
<siteMapNode url = “” title = “” description = “”>
41

</siteMapNode>
</sitemap>

To apply the master page for the existing web form


%@Page Language = “C#” MasterPageFile = “~/MasterPage.master” ....

Profiles:
It is used to maintain the user information along with the system details permanently at
the SQL server database present at the server. Also called personalization of web form.

To set:
Variable = Profiles . ProfileName;

In order to access the profile information it is mandatory to set the profiles at the web
configuration file.

Whenever the profile information has been set explicitly then the information will be
maintained within aspnet_Profile table present the ASPnetDB.MDF database.

eXtensible Markup Language (XML):


It is a platform or device independent language or a tool for transferring the data between
the discrete systems.

XML language is not developed for replacing HTML.


HTML is used to present the data.
XML is used to represent the data.

XML document is of two types:


i) Well formed XML
ii) Valid XML

i) Well formed XML: Whenever the XML document represents only the data then it is
said to be well formed XML document.
Rules for creating a well formed XML document:
 The extension for the XML document should be .xml.
 XML document is a case sensitive file and the document does not have any predefined
tags like HTML.
 The user is free to use any tag as per the requirement where a tag can be considered as
a string enclosed between angular braces i.e. <tag>
 It is mandatory that the tag which has been opened has to be closed.
 If the tags are nested then it is mandatory that the tags has to closed using a proper
hierarchy.

XML document supports the following named entities:


&lt; (lesser than)
&gt; (greater than)
42

&ge; (greater than equal to)


&le; (lesser than equal to)
&ne; (not equal to)
&apos; (apostrophe)
&quot; (single quotes)

Structure of an XML document:

<RootElement>
<ParentElement>
<childElement> … </childElement>

</ParentElement>


</RootElement>

 It is mandatory that a XML document should be defined using only one root element.
 The above XML document gives an illusion that the data belongs to some employees
but the fact is for the system the above file is just a normal 7 bit ASCII text file which is
supported by all the platforms and the devices.
 XML document cannot project or present the data on its own. Always the XML
document will depend upon some application to present the data.
 A HTML page to project the XML document’s data.

ii) Valid XML document: Whenever a XML document is used to represent the data along
with the definitions then it is said to be a valid XML document where the definitions for
the document can be provided using XML schema definition file.

XML definition file:


It is used to specify the elements that can be used within the XML document their data
types and the attributes that can be used with the elements. The constraints to be used to
specify for the elements and also used to specify the occurrences of elements within the
XML document.
The extension for the XML schema definition file should be .xsd.

Using .Net technology for generating valid XML document:


Inorder to interact with XML documents System.Data.DataSetClass should be used.

Methods to support XML document:


WriteXml: It is used to read the data from the datamembers of the dataset and used to
write that information to an XML document.

WriteXmlSchema: It is used to write the XML schema definition for the data present at
the data members of the dataset.
43

ReadXml: It is used to read the data from the Xml document and used to write that
information within the dataset as a datamembers.
ReadXmlSchema: It is used to read the Xml schema definition from the XSD file.

XML parser is of two types:


i) DOM Parser
ii) SAX Parser

i) DOM Parser: (Document Object Model Parser) It is used to read the entire XML
document and parses the data and the result will be maintained within the cache.
DOM is of two types: 1) Non Validating DOM parser
2) Validating Parser

1) Non Validating DOM parser: It is used to parse a well formed XML document.
If a non validating DOM parser is used to validate a valid XML document then the parser
will verify only the rules of the XML specifications and if the document violates the
definition file then the parser will ignore and projects the data. (Example: Browsers)

2) Validating Parser: It is used to parse a valid XML document and if the document
violates the definition file then the system will raise an exception.(Example: VS.Net)

ii) SAX Parser: (Simple API for XML parser): It is used to parse only the requested
information and the result will not be maintained at the cache.
SAX parser is also called as event based parser.

To transfer data from Windows to Linux we use XML.

All devices can understand XML.

App_data is used for maintaining database.


App_Code is used for class files.
App_Themes is used for themes.
44

ASP.NET AJAX

Evolution of Web applications:

HTML: It is used to designing a web page where the page will be parsed by the web
browser.
Drawbacks:
HTML is a browser dependent language.
HTML cannot interact with the external resources like database.
HTML cannot be used for performing validations.

Java script: It is a scripting language which is used to perform client side validations.
Drawbacks:
In order to use Java script to interact with external resources like Livewire Software
should be installed within the server.

Serverside Technology: (CGI, Serve lets, ASP, JSP, …) It is a technology to interact with
the external resources like flat files database or network and used to provide the result as
a response to the clients.
Drawback:
The code has to processed at the server side and result has to be provided as a response
and hence for every request a new page will be generated and will be provided as the
response and hence the performance will be very slow.

Applets: It is a set of java code which will be loaded on client machine and will be
processed at the browser.
Advantage: As the code will be processed at the client system performance will be very
fast.
Drawback: Applets cannot interact with the client system resources. Web browsers should
be installed with Java Virtual Machine in order to support applets.

Drawbacks of all te above web development methods:

Whenever synchronous methodology of web application is developed then web server


will return a new page for every client request and performance will be slow.

If synchronous method is used for web application development then till the server
provides the response to the clients the user cannot interact with the webform.

Solution is AJAX (Asynchronous Java Script and XML)


AJAX: It is used to send a request to the web server using Java script with the support of
XmlHttpRequest object without submitting the entire data to the server.
AJAX is a specification for developing asynchronous web application with the support
of Java script and xml.
AJAX is a browser independent and device independent specification.
AJAX is used for achieving rich web surfing experience.
45

AJAX specification has been implemented by Microsoft and it is said to be ASP.Net


AJAX and formerly it was to be called as ATLAS.

Pre requisites to work with ASP.Net AJAX:


Download ASPAJAXExtSetup.msi and install ASP.Net AJAX server extension SDK.

In order to support asynchronous web application development it is essential to create an


object for the XmlHttpRequest based on the browser specification.

To support:
Mozilla Firefox, Opera, Neo Planet, Netscape, …
Create an object for XmlHttpRequest
Ex: variable=new XmlHttpRequest();
To support:
Internet Explorer 5.5
Ex: variable=new ActiveXObject (“Msxml2.XMLHTTP”);
Internet Explorer 6.0 or above
Ex: variable=new ActiveXObject (“Microsoft.XMLHTTP”);

Properties of XmlHttpRequest:

Onreadystatechange: It is a property which is used to identify if an event has been raised


at the client system.
readyState: It is a property which is used to identify the status at the server for the client
request.
readyState returns an integer which is used to identify the status of the server.

Value Status
0 Server not at accepted the request
1 Server accepted the request
2 Server initialized the process
3 Server is processing the request
4 Server has completed its processing

responseText: It is a property which is used to collect the response from the server if any
string information is passed as the response.
responseXmlText: It is a property which is used to collect the response as a XML
information.

Methods of XmlHttpRequest:
function(): It is used to submit the request to the server.
open(“GET or POST”, URL, boolean): It is used to send a request to the specified url
using get or post method.
If true is passed as a boolean value then asynchronous request will be sent and
46

If false is passed as a boolean value then synchronous method will be used for sending
the request.
send(object): It is used to submit the request to the server.

AJAXControlToolkit
 Download ASP.Net AjaxControlToolkit.
 Extract the AjaxControlToolkit to the following path
C:\Pgm files\Microsoft Ajax Control Toolkit
 Open in Internet Explorer this i.e. above path.
Then open new website, in that select Ajax Enabled Website. By (Ctrl+Alt+x), right click
on ToolBox, Click on Add tab, specify(type) Ajax Client Side Controls.

Drag and drop Ajax Control Toolkit.dll file present at the following directory
C:\Pgm files\Microsoft Ajax Control Toolkit\Sample Website\Bin and drop on the tab
created on the tool box.

XML Web Services

Requirement: A technology such that the code present in one system should be accessed
from the applications present in other systems connected within the network.
Solution: Distributed Network

Distributed Server Client Platform Protocol Internet


Technology Support
DCOM VB / VC++ VB / VC++ Windows RPC No
.Net Any .Net Any .Net Windows TCP / HTTP Yes
remoting language language
RMI Java Java Any RMI No
EJB Java Java Any JNDI Yes
CORBA Any Any Unix IIOP No

Platform  Application to be executed in


Protocol  To communicate between client and server

Limitations of above distributed technologies:


All the previous distributed technology target their native platform and hence whenever
there is a requirement for designing business to business (B2B) applications, the above
technologies fails.

Requirement: A technology such that the code or the definitions should be accessed from
the applications developed using any language for any platform or any device.
Solution: Web services
47

Web services: It is a specification to achieve cross language, cross platform and cross
device integration.
Web service specification has been provided by W3C consortium and implemented by the
following organizations:

IBM Corporation  Web services


Oracle Corporation  PL / SQL web services
Microsoft Corporation  ASP.Net Web services (or XML web services)
Sun Micro Systems  Java Web services

XML Web services: It is a specification to achieve cross language, cross platform and
cross device integration or it can be considered as a class definition where the definition
is maintained within the webserver as a service such that the definitions can be accessed
from any application developed using any language for any platform or any device.

XML web service architecture:

UDDI: It is a guidelines for publishing the web service.


Directory: It acts like a repository for maintaining the information about the web service.
Discovery: It is used for maintaining the presence of the web service within the web
server
 A discovery document can also be a web service which is used to search other web
service programmatically.
 A discovery document is of two types .disco file and .vsdisco file.

Descriptions: It provides information about the members of the web service such as the
attributes, the properties and the methods present within the web service.
Wire Formats: There are the protocols which are used by the web service inorder to
communicate between the systems which uses web service descriptions.

The protocols which are supported by the web service are: HTTP, SOAP

HTTP: It is a standard web protocol which is used to send a request and receive the
response from the server.
HTTP supports two methods for submitting the data: HTTP-GET, HTTP-POST.

Steps for URL encoding:


1) Combines all the name and value as a pair equal to.
2) Combines all the name and value pair using ampersand.
3) Replaces all the non alpha numerical values with its relevant hexa decimal value
prefixed with percentile.
4) Replaces all the blank spaces present in the above expression with plus.

The expression is the data which will be submitted from the client system to the server.
48

If HTTP-GET method is used for submitting the data, the above string will be appended
as a search to the navigate url.
HTTP-GET HTTP-POST
Appends the data as a search. Passes the data as streams.
Only limited data can be transferred. No limitation for the data transfer.
Only character data can be transferred. Any type of data can be transferred.
If the webform uses HTTP-GET then the If HTTP-POST method is used for
performance will be very fast. transferring the data, performance will be
comparatively slow.

SOAP: (Simple Object Access Protocol)


It is a formatting protocol which is used to format the request of the client and the
response from the server as a SOAP message such that cross language, cross platform and
cross integration can be achieved.

SOAP protocol is divided into 4 parts:


1) SOAP Address or SOAP Envelope: It is used to maintain the information of the web
service or any SOAP request that has to be processed by the SOAP protocol.
2) SOAP Request and SOAP Response: It is used to specify the method to be used for
accessing the service and the method to be used for providing the response.
3) SOAP Message: It is the information which has been accepted as the request or it can
be a message which has to be provided as the response.
4) Data bindings between the SOAP protocol and HTTP protocol: It is used to specify the
binding rules to be followed for binding SOAP messages with the HTTP protocol.

Steps to design a web service:


Write the code as per the requirement.
In order to specify a class definition as a web service then it is mandatory that the class
has to inherit System.Web.Services.WebService class.
In order to expose a method definition on the web then it is mandatory that the method
should be prefixed with web method attribute.

Attributes of web methods:


BufferResponse: It is equal to setting response.Buffer = booleanValue; that is if the
BufferResponse is set true then the contents will be displayed after the complete page has
been processed and if false is set then the contents will be displayed once the statements
has been passed.
The default value for response.Buffer = true

CacheDuration: If set then the result or output will be maintained for the specified period
of time as a cache.

Description: It is used to specify the description of the web method.

EnableSession: If set to true then the result will be maintained at the session.
MessageName: It is used to provide an alias name for the web method.
49

Web parts
Whenever the contents present at the web form has to be moved or removed or has to be
modified or if any new information has to be added dynamically to the web form by the
client then web parts should be used.

WebPartManager: It is a class which is used to manage all the web parts present within
the web form.
Whenever web parts are used in the web form then it is mandatory that the
webpartmanager control should be placed as the first control on the web form.
WebPartZone: It is used to define a single web part within the web form.
In order to design ‘n’ number of web parts then ‘n’ number of webpartzones should be
created.
The contents present in one webpartzone can be moved to other webpartzone directly at
the runtime.
CatalogZone: It acts like a container for maintaining the catalogs to be added
dynamically at the runtime to the webpartzone.
DeclarativeCatalogZone: It is used to maintain the contents or the control to be added on
the webpartzone.
Any number of DecrativeCatalogZones may be places within the catalogzone.
EditorZone: It acts like a container for maintaining the information that can be used for
modifying the webpartzone contents.
ApperanceEditorZone: It is a collection of properties which is used to set the appearance
of the webpartzone.
LayoutEditorPart: It is a collection of properties which is used to modify the layout of the
webpartzone.
PropertyGridEditorPart: It is a collection of properties which is used to set or get the
values from the user defined controls.

 Whenever the display mode is browsed then the user can view the webparts.
 If the display mode is design then the user can move the contents present within one
webpartzone to the other zone and also contents can be deleted.
 If the display mode is catalog then the user can add the contents present within the
DeclarativeCatalogZone to any webpartzone.
 If the display mode is edit then the client can modify the appearance, layout, property
and the behavior of the webpartzone.

Creating custom control for ASP.Net web application:


Web Custom Control: It is used to design reusable web component such that the control
can be used from any Asp.Net web sites.