128
ASP.NET TYBSC(CS) SEM 5 COMPILED BY : SZ 302 PARANJPE UDYOG BHAVAN, NEAR KHANDELWAL SWEETS, NEAR THANE STATION , THANE (WEST) PHONE NO: 8097071144 / 8097071155

Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

Embed Size (px)

Citation preview

Page 1: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

ASP.NET

TYBSC(CS) SEM 5

COMPILED BY : SZ

302 PARANJPE UDYOG BHAVAN, NEAR KHANDELWAL SWEETS, NEAR THANE

STATION , THANE (WEST)

PHONE NO: 8097071144 / 8097071155

Page 2: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

UNIT TOPICS PAGENO

Unit I Overview of .NET Framework, Objectives, Main components of .NET Framework and their overview, Types of Applications .NET Framework Architecture– CLR(Goal of CLR, Services/Features, Benefits, Managed Execution Process, Automatic memory Management), CTS(CTS Overview, Type Definitions, Type members, Different types of data such as class, delegates, pointes, arrays, interfaces), Meta Data, Structure of Metadata & Self Describing Components, Cross Language Interoperability & CLS, Assemblies(Assembly overview, Benefits, Contents, Types) Creating Web Sites :- Working with Web Forms, Working with CSS in Visual Web Developer, ASP.NET Server Controls, Standard Controls, HTML Controls, Understanding ASP.NET State Engine.

1

Unit II Introduction to Programming:- Data Types and Variables, Statements, Methods: Functions and Subroutines. Consistent Page Layout with Master Pages, Using a Centralized Base Page. Structured Exception Handling : try, catch, finally blocks, throwing exceptions, Err object, Using masked Textboxes Navigation Controls- Architecture of the Navigation Controls, Menu Control, TreeView Control Validation Controls – Validations & Validator controls,

24

Unit III ADO.NET: Data Provider Model, Direct Data Access - Creating a Connection, Select Command, DataReader, Disconnected Data Access Data Binding: Introduction, Single-Value Data Binding, Repeated-Value Data Binding, Data Source Controls – SqlDataSource, Other Data Controls, Working Together with Data Source and Data-bound Controls User Controls-Creating User Controls, Adding User Controls to a Content Page or Master Page LINQ -LINQ to Objects, LINQ to ADO.NET Introducing Query Syntax, Standard Query Operators, Shaping Data with Anonymous Types, Using Server Controls with LINQ Queries.

64

Unit IV Caching : Introduction to Caching Data ,Different Ways to Cache Data in ASP.NET Web Applications Security-Identity, Authentication, Authorization, Using Login Controls , Configuring the Web Application AJAX in ASP.NET –Using ScriptManager, Partial refreshes, UpdatePanel, Triggers, Timed Refreshes Web Service – What is web service, ASP.NET Web services, Creating a simple web service, Consuming Web service

107

Page 3: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

1 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

UNIT 1 INTRODUCTION TO .NET FRAMEWORK

1.1 Overview of the .NET Framework

The .NET Framework is an integral Windows component that supports building and running the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the

following objectives:

Question : what are the objectives of .net framework?

To provide a consistent object-oriented programming environment whether object

code is stored and executed locally, executed locally but Internet-distributed, or executed

remotely.

To provide a code-execution environment that minimizes software deployment and

versioning conflicts.

To provide a code-execution environment that promotes safe execution of code,

including code created by an unknown or semi-trusted third party.

To provide a code-execution environment that eliminates the performance problems of

scripted or interpreted environments.

To make the developer experience consistent across widely varying types of

applications, such as Windows-based applications and Web-based applications.

To build all communication on industry standards to ensure that code based on the .NET

Framework can integrate with any other code.

Question : what are the main components of .net framework? The .NET Framework has two main components:

the common language runtime o It is an agent that manages code at execution time, providing core services such as

memory management, thread management, and remoting. o Also enforcing strict type safety and other forms of code accuracy that promote

security and robustness. o In fact, the concept of code management is a fundamental principle of the runtime. o Code that targets the runtime is known as managed code, while code that does not

target the runtime is known as unmanaged code. o Internet Explorer is an example of an unmanaged application that hosts the runtime (in

the form of a MIME type extension).

.NET Framework class library o The class library is a comprehensive, object-oriented collection of reusable types that

you can use to develop applications ranging from traditional command-line or graphical user interface (GUI) applications to applications based on the latest innovations provided by ASP.NET, such as Web Forms and XML Web services.

o third-party components can integrate seamlessly with classes in the .NET Framework.

Page 4: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

2 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

.NET Framework is used to develop the following types of applications and services:

Console applications.

Windows GUI applications (Windows Forms).

ASP.NET applications.

XML Web services.

Windows services.

1.2 .NET Framework Architecture

1.2.1 COMMON LANGUAGE RUNTIME (CLR)

Goals of CLR runs the code and provides services that make the development process easier.

Services/features cross-language integration, cross-language exception handling, enhanced security, versioning and deployment support, a simplified model for component interaction, and debugging and profiling services

Benefits Performance improvements.

The ability to easily use components developed in other languages.

Extensible types provided by a class library.

Language features such as inheritance, interfaces, and overloading for object-oriented

programming.

Support for explicit free threading that allows creation of multithreaded, scalable

applications.

Support for structured exception handling.

Support for custom attributes.

Garbage collection.

Page 5: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

3 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Use of delegates instead of function pointers for increased type safety and security

Managed execution process Describes the steps required to take advantage of the common language runtime.

Automatic memory management Describes how the garbage collector allocates and releases memory.

1.2.2 Common Type System The common type system defines how types are declared, used, and managed in the

runtime, and is also an important part of the runtime's support for cross-language integration.

The common type system performs the following functions:

Establishes a framework that helps enable cross-language integration, type safety, and

high performance code execution.

Provides an object-oriented model that supports the complete implementation of many

programming languages.

Defines rules that languages must follow, which helps ensure that objects written in

different languages can interact with each other.

Type Definitions

Describes user-defined types.

Type Members

Describes events, fields, nested types, methods, and properties, and concepts such

as member overloading, overriding, and inheritance.

Value Types

Describes built-in and user-defined value types.

Classes

Describes the characteristics of common language runtime classes.

Delegates

Describes the delegate object, which is the managed alternative to unmanaged

function pointers.

Arrays

Describes common language runtime array types.

Interfaces

Describes characteristics of interfaces and the restrictions on interfaces imposed

by the common language runtime.

Pointers

Describes managed pointers, unmanaged pointers, and unmanaged function

pointers.

Page 6: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

4 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

1.2.3 Metadata and Self-Describing Components

The .NET Framework makes component interoperation even easier by allowing

compilers to emit additional declarative information into all modules and assemblies. This information, called metadata, helps components to interact seamlessly.

Metadata is binary information describing your program that is stored either in a

common language runtime portable executable (PE) file or in memory When you compile your code into a PE file, metadata is inserted into one portion of the

file, and your code is converted to Microsoft intermediate language (MSIL) Every type and member that is defined and referenced in a module or assembly is

described within metadata. Metadata describes every type and member defined in your code in a language-neutral

manner Metadata stores the following information:

Description of the assembly.

o Identity (name, version, culture, public key).

o The types that are exported.

o Other assemblies that this assembly depends on.

o Security permissions needed to run.

Description of types.

o Name, visibility, base class, and interfaces implemented.

o Members (methods, fields, properties, events, nested types).

Attributes.

o Additional descriptive elements that modify types and members.

Benefits of Metadata

Self-describing files.

o Common language runtime modules and assemblies are self-describing. A

module's metadata contains everything needed to interact with another module

Language interoperability and easier component-based design.

o Metadata provides all the information required about compiled code for you to

inherit a class from a PE file written in a different language.

Attributes.

o The .NET Framework lets you declare specific kinds of metadata, called attributes

Page 7: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

5 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

1.2.4 Cross-Language Interoperability (CLI)

common language runtime's built-in support for language interoperability and explains

the role that the Common Language Specification (CLS) plays in enabling guaranteed cross-

language interoperability.

Language interoperability is the ability of code to interact with code that is written by using a

different programming language. Language interoperability can help maximize code reuse and

improve the efficiency of the development process.

1.2.5 Common Language Specification (CLS)

To fully interact with other objects regardless of the language they were implemented in, objects must expose to callers only those features that are common to all the languages they must interoperate with. For this reason, the Common Language Specification (CLS), which is a set of basic language features needed by many applications, has been defined. The CLS rules define a subset of the Common Type System

If your component uses only CLS features in the API that it exposes to other code (including derived classes), the component is guaranteed to be accessible from any programming language that supports the CLS.

1.2.5 Assemblies

Assemblies are the building blocks of .NET Framework applications; they form the fundamental unit of deployment, version control, reuse, activation scoping, and security permissions. An assembly is a collection of types and resources that are built to work together and form a logical unit of functionality

Assembly Benefits

Assemblies are designed to simplify application deployment and to solve versioning problems that can occur with component-based applications.

Versioning Problems

An End to DLL Conflicts

The Assembly Solution

Page 8: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

6 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Assembly Contents

The assembly manifest (assembly metadata), which contains assembly metadata.

Type metadata.

Microsoft intermediate language (MSIL) code that implements the types.

A set of resources.

WORKING WITH WEB FORMS

ASP.NET is a web development platform, which provides a programming model, a comprehensive software infrastructure and various services required to build up robust web applications for PC, as well as mobile devices. ASP.NET works on top of the HTTP protocol, and uses the HTTP commands and policies to set a browser-to-server bilateral communication and cooperation. ASP.NET is a part of Microsoft .Net platform. ASP.NET applications are compiled codes, written using the extensible and reusable components or objects present in .Net framework. These codes can use the entire hierarchy of classes in .Net framework. ASP.NET 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.

ASP.NET Web Forms Model

ASP.NET 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. ASP.NET framework helps in storing the information

regarding the state of the application, which consists of:

Page state

Session state

Page 9: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

7 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

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. ASP.NET

session state and server side infrastructure keeps track of the information collected globally

over a session.

The ASP.NET runtime carries the page state to and from the server across page requests

while generating ASP.NET 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 ASP.NET Component Model

The ASP.NET component model provides various building blocks of ASP.NET 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.

ASP.NET 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 ASP.NET

web application is made of pages. When a user requests an ASP.NET page, the IIS

delegates the processing of the page to the ASP.NET runtime system.

The ASP.NET runtime transforms the .aspx page into an instance of a class, which inherits

from the base class page of the .Net framework. Therefore, each ASP.NET page is an object

and all its components i.e., the server-side controls are also objects.

Introduction to Server Controls

It‘s important to understand how server controls operate and how they are

completely different from the way you define controls in other languages like classic ASP or

PHP — another popular programming language creating dynamic web sites.

Eg:

To create a text box with a message and the current time in it in classic ASP, you

can use the following code:

<input type=”text” value=”Hello World, the time is <%=Time()%>” />

Page 10: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

8 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

As you can see, this code contains plain HTML, mixed with a server-side block,

delimited by <% and %> that outputs the current time using the equals (=) symbol. This type

of coding has a major disadvantage: the HTML and server-side code is mixed, making it

difficult to write and manage your pages.

Server controls work differently. In ASP.NET, the controls ―live‖ on the server inside

an ASPX page. When the page is requested in the browser, the server-side controls are

processed by the ASP.NET runtime — the engine that is responsible for receiving and

processing requests for ASPX pages. The controls then emit client-side HTML code that is

appended to the final page output. It‘s this HTML code that eventually ends up in the

browser, where it‘s used to build up the page.

instead of defining HTML controls in your pages directly, you define an ASP.NET

Server Control with the following syntax

<asp:TextBox ID=”Message” Runat=”Server” />

Working with css with visual developer

Click style sheet

Page 11: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

9 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Right click on elements and click on Add style rule

Select element and click on > button and click ok

Page 12: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

10 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Right click on element from css outline and click build style

Now modify the category and set the properties it will create code behind

How to attach style sheet

Page 13: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

11 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Types of Controls

ASP.NET 4 comes with a large number of server controls, supporting most of your

web development needs. To make it easy for you to find the right controls, they have been

placed in separate control categories in the Visual Web Developer Toolbox

Common Properties for All Controls

Most of the server controls you find in the VWD Toolbox share some common

behavior. Part of this behavior includes the so-called properties that define the data a

control can contain and expose.

Page 14: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

12 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Each server control has an ID to uniquely identify it in the page, a Runat attribute

that is always set to Server to

indicate the control should be processed on the server, and a ClientID that contains

the client-side ID attribute that will be assigned to the element in the final HTML.

propertY desCription

AccessKey Enables you to set a key with which a control can be accessed at

the client by pressing the associated letter.

BackColor ForeColor Enables you to change the color of the background (BackColor)

and text (ForeColor) of the control.

BorderColor

BorderStyle

BorderWidth

Changes the border of the control in the browser. The similarities

with the CSS border properties you saw in the previous chapter

are no coincidence. Each of these three ASP.NET properties maps

directly to its CSS counterpart.

CssClass Lets you define the HTML class attribute for the control in the

browser. This class name then points to a CSS class you defined

in the page or an external CSS file.

Enabled Determines whether the user can interact with the control in the

browser. For

example, with a disabled text box (Enabled=‖False‖) you cannot

change its text.

Font Enables you to define different font-related settings, such as Font-

Size, Font-Names, and Font-Bold.

Height Width Determines the height and width of the control in the browser.

TabIndex Sets the client-side HTML tab index attribute that determines the

order in which users can move through the controls in the page

by pressing the Tab key.

ToolTip Enables you to set a tooltip for the control in the browser. This

tooltip, rendered as a title attribute in the HTML, is shown when

the user hovers the mouse over the relevant HTML element.

Visible Determines whether or not the control is sent to the browser. You

should really see this as a server-side visibility setting because an

invisible control is never sent to the browser at all. This means it‘s

quite different from the CSS display and visibility properties you

saw in the previous chapter that hide the element at the client.

Types of Controls

Standard Controls The Standard category contains many of the basic controls that almost any web page

needs. You‘ve already seen some of them, like the TextBox, Button, and Label controls

Page 15: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

13 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Simple Controls The Toolbox contains a number of simple and straightforward controls, including

TextBox, Button, Label, HyperLink, RadioButton, and CheckBox.

List Controls These controls include ListBox, DropDownList, CheckBoxList, RadioButtonList, and

BulletedList.

Container Controls Quite often it‘s desirable to have the ability to group related content and controls.

This grouping can be done by putting the controls (and other markup) in one of the

container controls, like the Panel, the PlaceHolder, the MultiView, or the Wizard.

LinkButton and ImageButton The LinkButton and the ImageButton controls operate similarly to an ordinary Button

control. Both of them cause a postback to the server when they are clicked. The LinkButton

presents itself as a simple <a> element but posts back (using JavaScript) instead of

requesting a new page. The ImageButton does the same, but displays an image that the

user can click to trigger the postback.

Image and ImageMap These controls are pretty similar in that they display an image in the browser. The

ImageMap enables you to define hotspots on the image that when clicked either cause a

postback to the server or navigate to a different page.

Calendar The Calendar control presents a rich interface that enables a user to select a date.

You see more of it toward the end of this chapter when the ASP.NET state engine is

discussed.

FileUpload The FileUpload control enables a user to upload files that can be stored on the

server.

AdRotator The AdRotator control enables you to display random advertisements on your web

site. The ads come from an XML file that you create on your server.

HiddenField The HiddenField control enables you to store data in the page that is submitted with

each request.This is useful if you want the page to remember specific data without the user

seeing it on the page.

XML The XML control enables you to transform data from an XML format to another

format

Table

Page 16: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

14 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

The <asp:Table> control is in many respects identical to its HTML <table>

counterpart.

HTML Controls The HTML category of the Toolbox contains a number of HTML controls that look

similar to the ones found in the Standard category.

For example, you find the Input (Button) that looks like the <asp:Button>. Similarly,

there is a Select control that has the <asp:DropDownList> and <asp:ListBox> as its

counterparts.

In contrast to the ASP.NET Server Controls, the HTML controls are client-side

controls and end up directly in the final HTML in the browser. You can expose them to

server-side code by adding a Runat=‖Server‖ attribute to them. This enables you to

program against them from the Code Behind of a Web Form, to influence things like their

visibility.

Data Controls offer an easy way to access various data sources like databases, XML files, and

objects. Instead of writing lots of code to access the data source as you had to do in earlier

versions of ASP.NET

Validation Controls Validation controls enable you to rapidly create Web Forms with validation rules that

prohibit users from entering invalid data.

Navigation Controls The controls you find under the Navigation category of the Toolbox are used to let

users find their way through your site.

The TreeView control presents a hierarchical display of data and can be used to show

the structure of your site, giving easy access to all the pages in the site.

The Menu control does a similar thing and provides options for horizontal and vertical

fold-out menus.

Login Controls Just like the Data and Navigation controls, the Login controls were introduced in

ASP.NET 2.0 and are still strongly present in ASP.NET 4. With very little effort, login controls

enable you to create secure web sites where users need to sign up and log in before they

can access specific parts of the web site (or even the entire web site). In addition, they

provide the tools for users to change their password, or request a new password if they

forget the old one, and enable you to display different data depending on the logged-in

status and role of the user.

Ajax Extensions These extensions enable you to create flicker-free web applications that are able to

retrieve data from the server from client-side JavaScript without a full postback.

WebParts ASP.NET WebParts are a set of controls that enables an end user of a web page to

change the appearance and behavior of a web site. With a few simple actions, users can

Page 17: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

15 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

change the entire appearance of a web site by rearranging content, hiding or showing parts

of the web page, and adding other content fragments to the page.

Dynamic Data The controls in this category are used in Dynamic Data Web Sites. Dynamic Data

sites enable you to quickly build a user interface to manage data in a database.

State Management The ASP .NET State Engine The text in the text box is maintained by the ASP.NET state engine, a feature that is deeply

integrated into the ASP.NET runtime. It enables controls to maintain their state across

postbacks, so their values and settings remain available after every postback of the page.

When a form is submitted in classic ASP, all form values are cleared. Suppose you have

submitted a form with a lot of information and the server comes back with an error. You will

have to go back to the form and correct the information. You click the back button, and

what happens.......ALL form values are CLEARED, and you will have to start all over again!

The site did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in the browser window together

with all form values. How come? This is because ASP .NET maintains your ViewState. The

ViewState indicates the status of the page when submitted to the server. The status is

defined through a hidden field placed on each page with a <form runat="server"> control.

The source could look something like this:

<form name="_ctl0" method="post" action="page.aspx" id="_ctl0">

<input type="hidden" name="__VIEWSTATE"

value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />

.....some code

</form>

__VIEWSTATE The hidden form field that is used to transfer the state from the

server to the client and back

View State The mechanism that enables the ASP.NET controls to store state at the client

View state concepts

View state is an ASP.NET feature that provides for retaining the values of page and

control properties that change from one execution of a page to another.

Before ASP.NET sends a page back to the client, it determines what changes the pro-

gram has made to the properties of the page and its controls. These changes are

encoded into a string that‘s assigned to the value of a hidden input field named

_VIEWSTATE.

Page 18: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

16 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

When the page is posted back to the server, the _VIEWSTATE field is sent back to

the server along with the HTTP request. Then, ASP.NET retrieves the property values

from the _VIEWSTATE field and uses them to restore the page and control

properties.

ASP.NET also uses view state to save the values of the page properties it uses, such

as IsPostBack.

View state is not used to restore data entered by a user into a text box or any other

input control unless the control responds to change events.

If view state is enabled for a data-bound control, the control will not be rebound

when the page is reposted. Instead, the control‘s values will be restored from view

state.

How to use view state for your own data

Although view state is designed to automatically save page and control property values

across round trips to the browser, you can also add your own data to view state. To do that,

you store the data in a view state object that‘s created from the StateBag class as shown in

figure

Indexer Description

[name] The value of the view slate item with the

specified name. If you set the value

of an item that doesn’t exist, that item is

created.

Property Description

Count The number of items in the view state

collection.

Keys A collection of keys for all of the items in the

view state collection.

Values A collection of values for all of the items in

the view state collection.

Method Description

Add(name,

value)

Adds an item to the view state collection. If

the item you name already exists,

its value is updated.

Clear() Removes all items from the view state

collection.

Remove(name) Removes the item with the specified name from

the view state collection.

A statement that adds or updates a view state item

ViewState.Add("TimeStamp", Now);

Page 19: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

17 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Another way to add or update a view state item

ViewState ["TimeStamp"] = DateTime.Now;

A statement that retrieves the value of a view state item

DateTime timeStamp = (DateTime) ViewState["TimeStamp"];

A statement that removes an item from view state

ViewState.Remove("TimeStamp");

Like the session state object, the view state object contains a collection of key/value pairs

that represent the items saved in view state. To access this object, you use the ViewStatc

property of the page. Then, you can use the methods listed in this figure to work with the

view state object.

To illustrate, the first two examples in this figure show how you can add or update a view

state item named TimeStamp. The third example shows how to retrieve that item. And the

last example shows how to remove it. Notice in the third example that because a view state

item is stored as an object type, the code must cast the object to the DateTime data type.

Keep in mind that you usually use session state, not view state, to save data across round

trips to the browser. Occasionally, though, it does make sense to use view state for passing

small amounts of data, especially when you want to associate the data with a specific page.

Session State

ASP.NET uses session state to track the state of each user of an application. To do that, it

creates a session stale object that contains a unique session ID for each user‘s session. This

ID is passed back to the browser as part of the response and then eturned to the server

with the next request. ASP.NET can then use the session ID to get the session state object

that‘s associated with the request.

To manage a user session, you can store data in the session state object as shown in figure

Indexer Description

[name] The value of the session state item with the

specified name. If you set the

value of an item that doesn’t exist, that item

is created.

Property Description

SessionID The unique II) of the session.

Count The number of items in die session state

collection.

Method Description

Add(name,

value)

Adds an item to the session state collection. If

the item you name already

Page 20: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

18 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

exists, its value is updated.

Clear() Removes all items from the session state

collection.

Remove(name) Removes the item with the specified name from

the session state collection.

A statement that adds or updates a session state item

Session["EMail"] = email;

A statement that retrieves the value of a session state item

string email = Session["EMail"].ToStringO;

A statement that removes an item from session state

Session.Remove("EMail");

A statement that retrieves a session state item from a non-page class

string email = HttpContext.Current.Session["EMail"].ToString();

Description ASP.NET uses session state to track the state of each user of an application. To do

that, it creates a session state object that contains a session ID. This ID is passed to

the browser and then back to the server with the next request so the server can

identify the session associated with that request.

Because session state sends only the session ID to the browser, it doesn‘t slow

response time. By default, though, session state objects are maintained in server

memory so they can slow performance on the server side.

To work with the data in session state, you use the HttpSessionState class, which

defines a collection of session state items.

To access the session state object from the code-behind file for a web form, use the

Session property of the page.

To access the session state object from a class other than a code-behind file, use the

Current property of the HttpContext class to get the HttpContext object for the

current

request. Then, use the Session property to get the session state object.

Four options for storing session state data

Page 21: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

19 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

In-process mode (the default) stores session state data in IIS server memory in the

same process as the ASP.NET application. This is the session state mode that‘s used

the most, hut it‘s suitable only when a single server is used for the application.

State Server mode stores session state data in server memory under the control of a

separate service called the ASP.NF.T state service. This service can be accessed by

other IIS servers, so it can be used when an application is hosted on a web farm that

consists of more than one IIS server. In that case, each request for the application

can be processed by a different server, so the session state information must be

available to all the servers.

SQL Server mode stores session state data in a SQL Server database. Like State

Server mode, SQL Server mode is used for applications that require more than one

IIS server. Although this mode is slower than In-process mode and State Server

mode, it‘s also the most reliable.

Custom mode lets you write your own session state store provider to read and write

session state data.

Two options for tracking session IDs

By default, ASP.NET uses cookie-based session tracking to keep track of user

sessions. However, if a browser doesn‘t support cookies, this doesn‘t work.

With cookieless session tracking, the session ID is encoded as part of the URL. As a

result, cookieless session state works whether or not the browser supports cookies.

Application State

In contrast to session state, which stores data for a single user session, application state

lets you store data that is shared by all users of an application.

To start, an application is made up of all the pages, code, and other files

that arc located under a single directory in an IIS web server. The first time a user requests

a page that resides in an application‘s directory, ASP.NET initializes the application. During

that process, ASP.NET creates an application object from the HttpApplication class. This

object is represented by a special class file named global.asax.

The application object can be accessed by any of the application‘s pages.

This object exists until the application ends, which normally doesn‘t happen until IIS shuts

down. However, the application is automatically restarted each

time you rebuild the application or edit the application‘s web.config file.

Each time ASP.NET starts an application and creates an application object,

it also creates an application state object from the HttpApplicationState class.

You can use this object to store data in server memory that can be accessed by

any page that‘s part of the application.

Page 22: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

20 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Common members of the HttpApplicationState class

Indexer Description

[name] The value of the application state item with the

specified name. If you set the

value of an item that doesn’t exist, that item is

created.

Property Description

Count The number of items in the application state

collection.

Method Description

Add(name,

value)

Clear()

Remove(name)

Lock()

Unlock()

Adds an item to the application state collection.

Removes all items from the application state

collection.

Removes the item with the specified name from the

application state collection.

Locks the application state collection so only

the current user can access it.

Unlocks the application state collection so other

users can access it.

A statement that retrieves an item from application state

int applicationCount = Convert.ToInt32(Application["ClickCount"]);

A statement that adds an item to application state

Application.Add("ClickCount", 0);

A statement that retrieves the application state from a non-page class

int applicationCount = Convert.ToInt32

(HttpContext.Current.Application["ClickCount"]);

Code that locks application state while retrieving and updating an item

Application.Lock();

int applicationCount = Convert.ToInt32(Application["ClickCount"]);

applicationCount++;

Application["ClickCount"] = applicationCount;

Application.UnLock();

How to use cookies and URL encoding To create a cookie, you instantiate an object from the HttpCookie class. Then, you include it

in the HTTP response that the server sends back to the browser, and the user‘s browser

stores the cookie either in its own memory or in a text file on the client machine‘s disk.

Page 23: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

21 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

A cookie that‘s stored in the browser‘s memory is called a session cookie because it exists

only for that session. When the browser session ends, the contents of any session cookies

are lost. Session cookies arc what ASP.NET uses to track session ID‘s. In contrast,

persistent cookies arc written to disk, so they are maintained after the browser session

ends. Whether session or persistent, though, once a cookie is sent to a browser, it‘s

automatically returned to the server with each HTTP request.

Besides using cookies for session IDs, you can use cookies to save information that

identifies each user so the users don‘t have to enter that information each time they visit

your web site. You can also use cookies to store information that lets you personalize the

web pages that are displayed for a user.

When you use cookies to store this type of information, you should keep in mind that some

users may have disabled cookies on their browsers. In that case, you won‘t be able to save

cookies on the user‘s computer. Unfortunately, ASP.NET doesn‘t provide a way for you to

determine whether a user has disabled cookies. As a result, if you use cookies in an

application, you may need to notify the user that cookies must be enabled to use it.

Two ways to create a cookie

New HttpCookie(name)

New HttpCookie(name, value)

Common properties of the HttpCookie class

Property Description

Expires A DateTime value that indicates when the cookie

should expire.

Name The cookie’s name.

Secure A Boolean value that indicates whether the cookie

should be sent only when a secure connection is used.

See chapter 18 for information on secure connections.

Value The string value assigned to the cookie.

Code that creates a session cookie

HttpCookie nameCookie = new HttpCookie("UserName", userName)

Code that creates a persistent cookie

HttpCookie nameCookie = new HttpCookie("UserName");

nameCookie.Value = userName;

nameCookie.Expires = DateTime.Now.AddYears(1);

Description

A cookie is a name/value pair that‘s stored in the user‘s browser or on the user‘s

disk.

Page 24: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

22 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

A web application sends a cookie to a browser via an HTTP response. Then, each

time the browser sends an HTTP request to the server, it attaches any cookies that

are associated with that server.

By default, ASP.NET uses a cookie to store the session ID for a session, but you can

also create and send your own cookies to a user‘s browser.

A session cookie is kept in the browser‘s memory and exists only for the duration of

the browser session. A persistent cookie is kept on the user‘s disk and is retained

until the cookie‘s expiration date.

To create a cookie, you specify its name or its name and value. To create a

persistent cookie, you must also set the Expires property to the time you want the

cookie to expire.

Common members of the HttpCookieCollection class

Indexer Description

[name] The cookie with the specified name.

Property Description

Count The number of cookies in the collection.

Method Description

Add(cookie) Adds a cookie to the collection.

Clear() Removes all cookies from the collection.

Remove(name) Removes the cookie with the specified name from the

collection.

A method that creates a new cookie and adds it to the HttpResponse object

private void AddCookie()

{

HttpCookie nameCookie = new HttpCookie("UserName",txtUserName.Text)

nameCookie.Expires = DateTime.Now.AddYears(1);

Response.Cookies.Add(nameCookie);

}

A method that retrieves the value of a cookie from the HttpRequest object

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

if (!(Request.Cookies["UserName"] == null))

lblUserName.Text = "Welcome back " + Request.Cookies["UserName"].value;

}

Page 25: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

23 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

}

A method that deletes a persistent cookie

private void DeleteCookie()

{

HttpCookie nameCookie = new HttpCookie("UserName");

nameCookie.Expires = DateTime.Now.AddSeconds(-1);

Response.Cookies.Add(nameCookie);

}

Page 26: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

24 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

UNIT 2

INTRODUCTION TO PROGRAMMING

Variables and Expressions

BASIC C# SYNTAX

The look and feel of C# code is similar to that of C++ and Java.

C# code is made up of a series of statements, each of which is terminated with a semicolon.

Because whitespace is ignored, multiple statements can appear on one line, although for

readability it is usual to add carriage returns after semicolons, to avoid multiple statements

on one line.

C# is a block-structured language, meaning statements are part of a block of code. These

blocks, which are delimited with curly brackets ({ and }), may contain any number of

statements, or none at all.

COMMENTS IN C#

/* This is a comment */

Multiline comment

/* And so...

... is this! *

Single line comment

// this is comment line

code outlining functionality

You can do this with the #region and #endregion

#region Using directives

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

#endregion

C# syntax for declaring variables

Page 27: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

25 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

<type> <name>;

String ename

number of different integer types can be used to store various ranges of numbers

u characters before some variable names are shorthand for unsigned

floating-point values

three other simple types

Declaring and assigning values to variables

class Program

{

static void Main(string[] args)

{

string strEname; //declaring variable

strEname = "We-It tutorials"; //initalizing value

Console.WriteLine(strEname); //printing value of variable

Page 28: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

26 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

}

}

Naming Conventions

naming convention is a set of rules for choosing the character sequence to be used for

identifiers which denote variables, types, functions, and other entities in source code and

documentation.

two naming conventions are used in the .NET Framework namespaces: PascalCase and

camelCase.

camelCase variable names:

Camel case is the practice of writing compound words or phrases such that each word or

abbreviation in the middle of the phrase begins with a capital letter, with no intervening

spaces or punctuation.

age

firstName

timeOfDeath

These are PascalCase:

PascalCase is the practice of writing compound words or phrases such that the first letter of

each concatenated word is capitalized. No other characters are used to separate the words,

like hyphens or underscores. This is different from camelCase in which the first letter can be

lowercase or capitalized and each subsequent concatenated word is capitalized.

Age

LastName

WinterOfDiscontent

Literal Values

Page 29: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

27 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

String Literals

Eg :

If we want to print

"sid"s place"

Solution use escape character

"sid\"s\ place"

EXPRESSIONS

By combining operators with variables and literal values (together referred to as operands

when used with operators), you can create expressions, which are the basic building blocks of

computation

Unary— Act on single operands

Binary—Act on two operands

Ternary—Act on three operands

Page 30: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

28 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Mathematical Operators

Assignment Operators

Page 31: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

29 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Operator Precedence

Namespaces

namespaces. These are the .NET way of providing containers for application code, such that

code and its contents may be uniquely identified. Namespaces are also used as a means of

categorizing items in the .NET Framework.

namespace outer

{

namespace inner

{

namespace moreinner

{

}

}

}

Using namespaces

using outer.inner.moreinner;

Flow Control

Boolean logic and how to use it

How to branch code

How to loop code

BOOLEAN LOGIC

Page 32: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

30 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

conditional Boolean operators

THE GOTO STATEMENT

C# enables you to label lines of code and then jump straight to them using the goto

statement

A goto statement provides an unconditional jump from the goto to a labeled statement in

the same function.

NOTE: Use of goto statement is highly discouraged because it makes difficult to trace the

control flow of a program, making the program hard to understand and hard to modify.

goto <labelName>;

Page 33: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

31 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

class Program

{

static void Main(string[] args)

{

string strEname; //declaring variable

goto jumpon;

strEname ="sid\"s place"; //initalizing value

Console.WriteLine(strEname); //printing value of variable

jumpon:

Console.ReadKey();

}

}

Goto jumpon; will directly jump on label jumpon: escaping between code.

The Ternary Operator

The ternary operator is an operator that takes three arguments. The first argument is a

comparison argument, the second is the result upon a true comparison, and the third is the

result upon a false comparison. If it helps you can think of the operator as shortened way of

writing an if-else statement.

<test> ? <resultIfTrue>: <resultIfFalse>

string a = (1 == 1) ? "its true" : "its false";

output:

value of a “its true”

The if Statement

An if statement is a programming conditional statement that, if proved true, performs a

function or displays information.

if (<test>)

<code executed if <test> is true>;

if (1 == 1)

{

Console.WriteLine(―condition true‖);

}

The If else

An if else statement in programming is a conditional statement that runs a different set of

statements depending on whether an expression is true or false

if (<test>) <code executed if <test> is true>;

else

Page 34: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

32 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

<code executed if <test> is false>;

if (1 == 1)

{

Console.WriteLine("condition true");// condition true

}

else

{

Console.WriteLine("condition false");

}

Checking More Conditions Using if Statements

if (1 == 2)

{

Console.WriteLine("condition true");

}

else

{

Console.WriteLine("condition false");

if (2 == 2)

{

Console.WriteLine("inside next condition check");

}

}

The switch Statement

A switch statement is a type of selection control mechanism used to allow the value

of a variable or expression to change the control flow of program execution via a multiway

branch.

switch (<testVar>)

{

case <comparisonVal1>:

<code to execute if <testVar> == <comparisonVal1> >

break;

case <comparisonVal2>:

<code to execute if <testVar> == <comparisonVal2> >

break;

default:

<code to execute if <testVar> != comparisonVals>

break;

}

int a = 2;

switch (a)

{

case 1:

Console.WriteLine("one");

break;

case 2:

Page 35: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

33 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Console.WriteLine("two");// executes

break;

default:

Console.WriteLine("default");

break;

}

Fall through in switch case

int a = 2;

switch (a)

{

case 1:

Console.WriteLine("one");

break;

case 2:

Console.WriteLine("two");// executes

Goto default:

default:

Console.WriteLine("default");//executes

break;

}

LOOPING

Looping refers to the repeated execution of statements. This technique comes

in very handy because it means that you can repeat operations as many times as you want

(thousands, even millions, of times) without having to write the same code each time.

do Loops

A do while loop is a control flow statement that executes a block of code at least once, and

then repeatedly executes the block, or not, depending on a given boolean condition at the

end of the block. The do while construct consists of a process symbol and a condition.

The structure of a do loop is as follows, where <Test> evaluates to a Boolean value:

do

{

<code to be looped>

} while (<Test>);

Do while loop is also called as exit condition checking loop, means it will check the

condition while exiting loop. Eg:

int i = 0;//initialization

do

{

System.Console.Write(" " + i.ToString());

i++; //increment

} while (i != 10); //condition

Page 36: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

34 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

while Loops

In most computer programming languages, a while loop is a control flow statement that

allows code to be executed repeatedly based on a given Boolean condition

The Boolean test in a while loop takes place at the start of the loop cycle, not at the

end ―entry level checking‖

while (<Test>)

{

<code to be looped>

} Eg:

int i = 1; //initialization while (i <= 10) // condition

{

Console.WriteLine(i);

i++; // increment

}

for Loops

A "For" Loop is used to repeat a specific block of code a known number of times. For

example, if we want to check the grade of every student in the class, we loop from 1 to that

number. When the number of times is not known before hand, we use a "While" loop.

This type of loop executes a set number of times and maintains its own counter.

for (<initialization>; <condition>; <operation>)

{

<code to loop>

} Eg:

for (int i = 0; i <= 10; i++)

{

Console.Write(" " + i.ToString());

}

Interrupting Loops

break—

o Causes the loop to end immediately.

o The break statement breaks the loop and continues executing the code after

the loop (if any).

continue—

Page 37: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

35 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

o Causes the current loop cycle to end immediately (execution continues with

the next loop cycle).

o The continue keyword can be used in any of the loop control structures. It

causes the loop to immediately jump to the next iteration of the loop

o In a for loop, the continue keyword causes control to immediately jump to the

update statement. In a while loop or do/while loop, control immediately

jumps to the Boolean expression.

goto—

o Allows jumping out of a loop to a labeled position

o The goto is C# unconditional jump statement. When encountered, program

flow jumps to the location specified by the goto.

o The goto requires a label of operation. A label is a valid C# identifier followed

by colon.

return— Jumps out of the loop and its containing function

o The return statement terminates execution of the method in which it appears

and returns control to the calling method. It can also return an optional value.

If the method is a void type, the return statement can be omitted.

About Variables

How to perform implicit and explicit conversions between types

How to create and use enum types

How to create and use struct types

How to create and use arrays

How to manipulate string values

Enumerations: Variable types that have a user-defined discrete set of possible

values that can be used in a human-readable way. (user defined integer datatype)

Structs: Composite variable types made up of a user-defined set of other variable

types. (userdefined datatype)

Arrays: Types that hold multiple variables of one type, allowing index access to the

individual value.

Declaring and initialization of variables

string s1, s2, s3; // declaration

int i1, i2, i3; // declaration

s1 = "hello"; // initialization

s2 = "world"; // initialization

i1 = 2; // initialization

i3 = 3; // initialization

Implicit conversion: Conversion from type A to type B is possible in all circumstances,

and the rules for performing the conversion are simple enough for you to trust in the

compiler.

Page 38: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

36 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Explicit conversion: Conversion from type A to type B is possible only in certain

circumstances or where the rules for conversion are complicated enough to merit

additional processing of some kind.

Implicit conversion chart

Explicit conversion

Converting string to integer

private void Form1_Load(object sender, EventArgs e)

{

int a = Convert.ToInt16("11");

}

Convert class for explicit conversions

Page 39: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

37 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Overflow checking

Two keywords exist for setting what is called the overflow checking context for an

expression: checked and unchecked. You use these in the following way:

checked(<expression>)

unchecked(<expression>)

Page 40: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

38 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

if you replace checked with unchecked in this code, you get the result shown

earlier, and no error occurs. That is identical to the default behavior

Enumerations

enum <typeName> : <underlyingType> {

<value1> = <actualVal1>, <value2>,

<value3> = <value1>,

<value4>,

...

<valueN> = <actualValN> }

Structs

struct employee

{

public int empno;

public string empname;

public string empsname;

}

private void button1_Click(object sender, EventArgs e)

{

string s; // this is how we declare

// variable of predefined datatype

Page 41: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

39 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

employee e; // this is how we declare

// variable of userdefined datatype

e.empno = 1; // initalization

e.empname = "max"; // initalization

e.empsname = "payne"; // initalization

MessageBox.Show(e.empno + " " + e.empname); // retrival

}

Output:

Arrays

All the types you‘ve seen so far have one thing in common: Each of them stores a

single value (or a single set of values in the case of structs). Sometimes, in situations where

you want to store a lot of data, this isn‘t very convenient. You may want to store several

values of the same type at the same time, without having to use a different variable for

each value.

The alternative is to use an array. Arrays are indexed lists of variables stored in a

single array type variable.

Declaring Arrays

<baseType>[ ] <name>;

This type declaration is also called as dynamic size array.

int[ ] myArray; //

use the new keyword to explicitly initialize the array, and a constant value to define

the size.

int[ ] myIntArray = new int[5]; // the depth of an array is to strore 5 values

Declaring and initializing array

int[ ] myArray = { 1, 2, 3, 4, 5 };

Page 42: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

40 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

int[ ] myArray = new int[5] { 1, 2, 3, 4, 5 };

myArray[0] = 1;

myArray[1] = 2;

myArray[2] = 3;

myArray[3] = 4;

myArray[4] = 5;

eg:

int[] myarray; // declaration

public void test()

{

int[] myarray = new int[2];

/* You can either specify the complete contents of the array in a literal form or specify the

size of the array and use the new keyword to initialize all array elements. */

myarray[0] = 1; // initialization

myarray[1] = 2; // initialization

for (int i = 0; i < myarray.Length; i++)

{

MessageBox.Show(myarray[i].ToString()); // retrival

}

}

Op: 1 2 in messagebox

Working with foreach Loops

Syntax:

foreach (<baseType> <name> in <array>)

{ // can use <name> for each element

}

Eg:

for (int i = 0; i < myarray.Length; i++)

{

MessageBox.Show(myarray[i].ToString()); // retrival

}

Same thing can be achived by foreach loop

foreach (int x in myarray)

{

MessageBox.Show(x.ToString());

}

Multidimensional Arrays

Page 43: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

41 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

A multidimensional array is simply one that uses multiple indices to access its

elements. You might specify a position using two coordinates, x and y. You want to use

these two coordinates as indices.

A two-dimensional array such as this is declared as follows:

<baseType>[ , ] <name>;

Arrays of more dimensions simply require more commas:

<baseType>[ , , , ] <name>;

Eg: int[,] myarray = new int[2,2]; // declaration

public void test()

{

myarray[0, 0] = 1; // initalization

myarray[0, 1] = 2;

myarray[1, 0] = 3;

myarray[1, 1] = 4; // initalization

foreach (int x in myarray)

{

MessageBox.Show(x.ToString());

}

}

Op: 1 2 3 4 in message box

Arrays of Arrays

Multidimensional arrays, as discussed in the last section, are said to be rectangular

because each ‗‗row‘‘ is the same size. Using the last example, you can have a y coordinate of

0 to 3 for any of the possible x coordinates.

It is also possible to have jagged arrays, whereby ‗‗rows‘‘ may be different sizes.

Eg:

public void test()

{

int[][] myarr = new int[2][]; // declaring arrays

myarr[0] = new int[2]; // initialize the array that contains other arrays

myarr[1] = new int[3]; // initialize the array that contains other arrays

/* 0 1 2

* 0 3 4

* 1 5 6 6

*

*/

myarr[0][0] = 3; // initialize value

Page 44: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

42 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

myarr[0][1] = 4; // initialize value

myarr[1][0] = 5; // initialize value

myarr[1][1] = 6; // initialize value

myarr[1][2] = 7; // initialize value

foreach (int[] x in myarr)

{

foreach (int a in x)

{

MessageBox.Show(a.ToString());

}

}

}

Another way of writing jagged array:

int[ ][ ] jaggedIntArray = { new int[ ] { 1, 2, 3 }, new int[ ] { 1 }, new int[ ] { 1, 2

} };

Collection

SYSTEM.COLLECTIONS

An ArrayList is a class that holds values like an array, but elements can be added or

removed at will (dynamic array).

They offer greater functionality over an array, but they also have a larger overhead.

ArrayLists are not type safe, meaning that each element of the ArrayList can be of a

different type.

Eg:

using System.Collections;

ArrayList myArrayList = new ArrayList(); //variable length

ArrayList myArrayList = new ArrayList(5) //fixed length

myArrayList.Add("Hello");

myArrayList.Add("World");

myArrayList.Add(10); Arraylist properties and methods

properties description

Capacity Contains the allocated length of the arraylist

Count Contains the number of items currently in the arraylist

methods description

Add() Adds an item to the arraylist and returns the newly added

index

Page 45: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

43 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

a.add(―abc‖) ;

Clear() Clears all items from the arraylist

a.Clear();

Contains() Returns True if the given object is in the current arraylist

a.Contains(―a‖);

CopyTo() Copies all or part of the current arraylist to another arraylist

that is passed in as an argument.

Eg a.copyto(onedimentionarray);

Insert() Inserts an item into the arraylist

a.Insert(index,object);

Remove() Removes an item from the arraylist

a.Remove(―a‖);

RemoveAt() Removes an item from the arraylist by index

a.RemoveAt(index);

RemoveRange() Removes a range of items from the arraylist

a.RemoveRange(index,range) ;

Sort() Sorts the items in the arraylist

a.sort();

STRING MANIPULATION

Your use of strings so far has consisted of writing strings to the console, reading

strings from the console, and concatenating strings using the + operator.

Eg:

string str1, str2;

string[] strArray = new string[3];

strArray[0] = "abc";

strArray[1] = "def";

strArray[2] = "jkl";

str1 = "we-it tutorials";

str2 = "hello world";

//public int IndexOf(char value);

MessageBox.Show(str1.IndexOf('-').ToString()); // op: 2

//public int IndexOf(string value);

MessageBox.Show(str1.IndexOf("ria").ToString()); // op: 10

//public int IndexOf(char value, int startIndex);

MessageBox.Show(str1.IndexOf('i',6).ToString()); // op: 11

//public int IndexOf(string value, int startIndex);

MessageBox.Show(str1.IndexOf("ria",4).ToString()); // op: 10

//public string Insert(int startIndex, string value);

MessageBox.Show(str1.Insert(15, " thane")); // op: we-it tutorials thane

//public static string Join(string separator, string[] value);

Page 46: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

44 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

MessageBox.Show(string.Join("*", strArray)); // op: abc*def*jkl

//public int LastIndexOf(string value);

MessageBox.Show(str1.LastIndexOf('t').ToString());// op: 8

//public string Remove(int startIndex);

MessageBox.Show(str2.Remove(4)); // op : hell

//public string Replace(string oldValue, string newValue);

MessageBox.Show(str2.Replace("world", "india")); // op: hello india

//public string[] Split(params char[] separator);

string[] xyz = str2.Split(' ');

foreach (string temp in xyz) { MessageBox.Show(temp); } // op: hello and

world

//public string Substring(int startIndex);

MessageBox.Show(str2.Substring(6)); // op: world

//public string Substring(int startIndex, int length);

MessageBox.Show(str2.Substring(6,3)); // op: wor

//public string ToLower();

MessageBox.Show(str1.ToLower()); // op: we-it tutorials

//public string ToUpper();

MessageBox.Show(str1.ToUpper()); // op: WE-IT TUTORIALS

//public string Trim();

MessageBox.Show(str1.Trim()); // we-it tutorials with out whitespace on both

side

Functions DEFINING AND USING FUNCTIONS static void Main(string[] args)

{

}

This is how we write Main method in c# also called entry method from which

the program starts execution

Syntax:

<Access specifier> <return type> <identifier> (parameters)

{

Return <datatype>;

}

Eg:

Page 47: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

45 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Public static int add()

{

Return 2+2;

}

Public : access specifier

Static : no class object needed to access function

Int : return type

Add : name of the method

Parameters

Syntax:

static <returnType> <FunctionName>(<paramType> <paramName>, ...)

{

... return <returnValue>;

}

Eg:

Public int add(int a, int b)

{

Return a + b;

}

Calling the function

Int sum = add(10,20);

Passing Array as parameter

Public int add(int[] x)

{

Return x.length;

}

Int[] x : is a array parameter

Parameter Arrays

A parameter declared with a params modifier is a parameter array.

Eg: class Test

{

static void F(params int[] args) {

Console.Write("Array contains {0} elements:", args.Length);

foreach (int i in args)

Console.Write(" {0}", i);

Console.WriteLine();

Page 48: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

46 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

}

static void Main() {

int[] arr = {1, 2, 3};

F(arr);

F(10, 20, 30, 40);

F();

}

}

Op:

Array contains 3 elements: 1 2 3

Array contains 4 elements: 10 20 30 40

Array contains 0 elements:

Parameters by ref and by val

Ref : shares same memory location of variable

Val : copies value from one variable to another (default)

Eg:

class Program

{

static void Main(string[] args)

{

int x = 10;

Program.swap(ref x);

Console.Write(x); // op : 20

Console.ReadLine();

}

public static void swap(ref int a)

{

a = 20;

}

}

Out Parameter

Out : used to take output back from parameter even we use void method.

Eg: class Program

{

static void Main(string[] args)

{

int x = 10;

int ret;

Program.test(x,out ret);

Console.Write(ret); // op : 20

Console.ReadLine();

}

Page 49: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

47 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

public static void test(int a, out int b)

{

b = 20;

}

}

Command line arguments

Eg:

class Program

{

static void Main(string[] args)

{

foreach (string x in args)

{

Console.WriteLine(x);

}

Console.ReadLine();

}

}

Op:

program.exe hello world

Hello

World

Overloading function

It allows the programmer to make one or several parameters optional, by giving

them a default value.

class Program

{

static void Main(string[] args)

{

Program pp = new Program();

Console.WriteLine(pp.add(10, 20).ToString);

Console.WriteLine(pp.add(10, 20, 30).ToString);

Console.ReadLine();

}

public int add(int a, int b)

{

return a + b;

}

public int add(int a, int b, int c)

{

return a + b + c;

}

Page 50: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

48 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

}

ERROR HANDLING

Error handling is the term for all techniques of this nature, and this section looks at

exceptions and how you can deal with them. An exception is an error generated either in

your code or in a function called by your code that occurs at runtime.

Object-Oriented Programming

WHAT IS OBJECT-ORIENTED PROGRAMMING?

Object-oriented programming is a relatively new approach to creating computer

applications that seeks to address many of the problems with traditional programming techniques. The type of programming you have seen so far is known as functional (or

procedural) programming, often resulting

in so-called monolithic applications, meaning all functionality is contained in a few

modules of code (often just one). With OOP techniques, you often use many more modules

of code, each offering specific functionality, and each module may be isolated or even

completely independent of the others. This

modular method of programming gives you much more versatility and provides more

opportunity for code reuse.

What Is an Object?

An object is a building block of an OOP application. This building block encapsulates

part of the application, which may be a process, a chunk of data, or a more abstract entity.

Eg:

class Program

{

#region fields

public string empname;

private string empid;

#endregion

#region properties

//properties are used to access private fields

public string accessempid

{get{return empid;} set { empid = value; }}

#endregion

#region constructor

//constructor is used to set values to private fields

//while initialization the object of the classs

public Program() // default constructor

{

Page 51: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

49 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

}

public Program(string a) // parametarized constructor

{

empid = a;

}

#endregion

#region destructor

~Program()

{

// destructor code

}

#endregion

#region methods and functions

static void Main(string[] args)

{

Program p = new Program(); // creating object of program class

Program p1 = new Program("testing"); // passing value to constructor

p.accessempid = "12"; // accessing property

}

#endregion

}

The Life Cycle of an Object

Construction: When an object is first instantiated it needs to be initialized. This initialization is known as construction and is carried out by a constructor function, often

referred to simply as a constructor for convenience.

Program p = new Program(); // creating object of program class

Destruction: When an object is destroyed, there are often some clean-up tasks to

perform, such as freeing memory. This is the job of a destructor function, also known as a destructor.

Program p1 = new Program("testing"); // passing value to constructor

Static and Instance Class Members

Static properties and fields enable you to access data that is independent of any

object instances, and static methods enable you to execute commands related to the class

type but not specific to object instances. When using static members, in fact, you don’t

even need to instantiate an object.

Page 52: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

50 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Static Constructors

A class can have a single static constructor, which must have no access modifiers

and cannot have any parameters. A static constructor can never be called directly; instead,

it is executed when one of the following occurs:

An instance of the class containing the static constructor is created.

A static member of the class containing the static constructor is accessed.

In both cases, the static constructor is called first, before the class is instantiated or

static members accessed.

Static Classes

Often, you will want to use classes that contain only static members and cannot be

used to instantiate objects (such as Console). A shorthand way to do this, rather than make the constructors of the class private, is to use a static class. A static class can contain only

static members and can‘t have instance constructors, since by implication it can never be

instantiated.

OOP TECHNIQUES

Interfaces

An interface is a collection of public instance (that is, nonstatic) methods and

properties that are grouped together to encapsulate specific functionality. After an interface

has been defined, you can implement it in a class. This means that the class will then

support all of the properties and members specified by the interface.

public interface int1 //interface

{

void display();// abstract method

}

public interface int2 //interface

{

void display();// abstract method

}

public class testing : int1, int2

// interface supports multiple inheritance

{

void int1.display()

{

Console.WriteLine("interface1 method");

}

void int2.display()

{

Console.WriteLine("interface2 method");

}

}

Page 53: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

51 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Inheritance

Inheritance is one of the most important features of OOP. Any class may inherit from

another, which means that it will have all the members of the class from which it inherits. In OOP terminology, the class being inherited from (derived from) is the parent class (also known

as the base class).

When using inheritance from a base class, the question of member accessibility

becomes an important one. Private members of the base class are not accessible from a

derived class, but public members are. However, public

members are accessible to both the derived class and external code.

To get around this, there is a third type of accessibility, protected, in which only

derived classes have access to a member.

public class parent

{

public void display()

{

Console.WriteLine("display method");

}

}

public class child : parent

{

// no methods or functions

}

class Program

{

static void Main(string[] args)

{

child c = new child(); // creating object of child class

c.display();// even though child class doesnt have methods display() method

is accessible because if inheritance

}

}

virtual, override , new

public class parent

{

public virtual void display() // virtual method

{

Console.WriteLine("display method");

}

}

public class child : parent

{

public override void display() // overridden method

{

Page 54: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

52 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Console.WriteLine("new display");

}

}

class Program

{

static void Main(string[] args)

{

child c = new child(); // creating object of child class

c.display(); // it will call display() of child class

}

}

Virtual method in base class can be overridden in derived class using override

keyword. when virtual keyword is not written in base class method we can not use override.

Override can be written only when virtual keyword is written.

This can be done by a new keyword

public class parent

{

public void display()

{

Console.WriteLine("display method");

}

}

public class child : parent

{

public new void display() // suppress base method

{

Console.WriteLine("new display");

}

}

class Program

{

static void Main(string[] args)

{

child c = new child(); // creating object of child class

c.display(); // it will call display() of child class

}

}

Sealed class and sealed method public sealed class parent

sealed class cannot be further inherited

public sealed void display()

sealed method cannot be overridden

Page 55: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

53 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Abstract class and abstract method

public abstract class parent // abstract class

{

public abstract void display();// abstract method

}

Abstract methods are like interface which has only declaration no body or execution

procedures

Abstract classes has abstract methods, it can not be used directly that‘s why it is

inhearited and method are overrided.

Polymorphism

C# gives us polymorphism through inheritance. Inheritance-based polymorphism

allows us to define methods in a base class and override them with derived class

implementations. Thus if you have a base class object that might be holding one of several

derived class objects, polymorphism when properly used allows you to call a method that

will work differently according to the type of derived class the object belongs to.

Master Pages

ASP.NET master pages allow you to create a consistent layout for the pages in your

application. A single master page defines the look and feel and standard behavior that you

want for all of the pages (or a group of pages) in your application. You can then create

individual content pages that contain the content you want to display. When users request

the content pages, they merge with the master page to produce output that combines the

layout of the master page with the content from the content page.

A master page is an ASP.NET file with the extension .master (for example, MySite.master)

with a predefined layout that can include static text, HTML elements, and server controls.

The master page is identified by a special @ Master directive that replaces the @ Page

directive that is used for ordinary .aspx pages. The directive looks like the following.

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

The @ Master directive can contain most of the same directives that a @ Control directive

can contain. For example, the following master-page directive includes the name of a code-

behind file, and assigns a class name to the master page.

<%@ Master Language="C#" CodeFile="MasterPage.master.cs" Inherits="MasterPage" %>

Replaceable Content Placeholders

Page 56: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

54 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

the master page also includes one or more ContentPlaceHolder controls. These placeholder

controls define regions where replaceable content will appear. In turn, the replaceable

content is defined in content pages.

Content Pages

You define the content for the master page's placeholder controls by creating individual

content pages, which are ASP.NET pages (.aspx files and, optionally, code-behind files) that

are bound to a specific master page. The binding is established in the content page's

@ Page directive by including a MasterPageFile attribute that points to the master page to

be used.

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copying

existing code, text, and control elements repeatedly; using framesets; using include files for

common elements; using ASP.NET user controls; and so on. Advantages of master pages

include the following:

They allow you to centralize the common functionality of your pages so that you can

make updates in just one place.

They make it easy to create one set of controls and code and apply the results to a

set of pages. For example, you can use controls on the master page to create a

menu that applies to all pages.

They give you fine-grained control over the layout of the final page by allowing you

to control how the placeholder controls are rendered.

They provide an object model that allows you to customize the master page from

individual content pages.

How to access a public property of the master page from a content page

Steps:

1.Add master page in project (MasterPage.master)

2.Add label on master page

<form id="form1" runat="server"> <div> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <asp:ContentPlaceHolder id="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form>

Page 57: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

55 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

3.Add public property in MasterPage.master.cs

public partial class MasterPage : System.Web.UI.MasterPage { public String AccessLabelText { set { Label1.Text = value; } get { return Label1.Text; } } }

4.Add webform(Default.aspx) with master page MasterPage.master

5.Add Directive and button in (Default.aspx)

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %> <%@ MasterType TypeName="MasterPage" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server"> </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server"> <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> </asp:Content>

6.Add code to button click

protected void Button1_Click(object sender, EventArgs e) { MasterPage mp = (MasterPage)this.Master; mp.AccessLabelText = "ACCESSED MASTER PAGE LABLE THROUGH CONTENT PAGE"; }

output:

Refer classroom notes for example

STRUCTURED EXCEPTIONAL HANDELING

Page 58: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

56 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

try . . . catch . . . finally

The C# language includes syntax for structured exception handling (SEH). Three keywords

mark code as being able to handle exceptions, along with instructions specifying what to do

when an exception occurs: try, catch, and finally. Each of these has an associated code block

and must be used in consecutive lines of code. The basic structure is as follows:

Syntax:

try

{

...

}

catch (<exceptionType> e)

{

...

}

finally

{

...

}

It is also possible, however, to have a try block and a finally block with no catch

block, or a try block with multiple catch blocks. If one or more catch blocks exist, then the

finally block is optional.

Without try catch program terminated unexceptionally

Page 59: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

57 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

With try catch program dint stopped working

Nested try

Try block inside try block is called nested try

The usage of try catch blocks

try— Contains code that might throw exceptions (‗‗throw‘‘ is the C# way of saying

‗‗generate‘‘ or ‗‗cause‘‘ when talking about exceptions)

catch—Contains code to execute when exceptions are thrown. catch blocks may be set

to respond only to specific exception types (such as System.IndexOutOfRangeException) using

<exceptionType>, hence the ability to provide multiple catch blocks. It is also possible to omit this

parameter entirely, to get a general catch block that responds to all exceptions.

finally— Contains code that is always executed, either after the try block if no

exception occurs, after a catch block if an exception is handled, or just before an unhandled

exception moves ‗‗up the call stack.‘‘ This phrase means that SEH allows you to nest

try...catch...finally blocks inside each other, either directly or because of a call to a function

within a try block.

Navigation

When you think about important parts of a navigation system, the first thing that you may

come up with is a menu. Menus come in all sorts and sizes, ranging from simple and static

HTML links to complex, fold-out menus driven by CSS or JavaScript. But there‘s more to

navigation than menus alone. ASP.NET comes with a number of useful navigation controls

that enable you to set up a navigation system in no time. These controls include the Menu,

TreeView, and SiteMapPath

Page 60: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

58 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Besides visual controls like Menu, navigation is also about structure. A well-organized site is

easy for your users to navigate. The Web.sitemap file that is used by the navigation

controls helps you define the logical structure of your site.

Different Ways to Move Around Your Site The most common way to let a user move from one page to another is by using the <a>

element.

<a href=‖Login.aspx‖>You can log in here</a>

The <a> element has a server-side counterpart called the HyperLink, which can be

created in the markup using <asp:HyperLink>.

It eventually ends up as an <a> element in the page.

The NavigateUrl property of this control maps directly to the href attribute of the

<a> element.

<asp:HyperLink runat=‖server‖ id=‖LoginLink‖ NavigateUrl=‖Login.aspx‖>You can log in

here</asp:HyperLink>

Understanding Absolute and Relative URLs

Key to working with links in your site is a good understanding of the different forms

a Uniform Resource Locator (URL) to a resource inside or outside your web site can

take.

A URL is used to uniquely identify a resource in your or another web site.

Absolute URL

In addition to several other meanings, the word absolute, in English, means "not dependent on

anything else". It also means "free from doubt".

An Absolute URL is, thus, something that is independent or free from any relationship.

When you use an absolute URL, you point directly to a file. Hence,

An absolute URL specifies the exact location of a file/directory on the internet.

For example: http://www.webdevelopersnotes.com/images/email.gif

<img src="http://www.webdevelopersnotes.com/images/email.gif"

width="..." height="..." />

Relative URL

Page 61: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

59 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

A relative URL points to a file/directory in relation to the present file/directory

<img src="../images/email.gif" width="..." height="..." />

Using the Navigation Controls ASP.NET 4 offers three useful navigation tools: SiteMapPath, TreeView, and Menu.

Architecture of the Navigation Controls To make it easy to show relevant pages in your site using a Menu, a TreeView, or a

SiteMapPath, ASP.NET uses an XML-based file that describes the logical structure of your

web site. By default, this file is called Web.sitemap. This file is then used by the navigation

controls in your site to present relevant links in an organized way. Simply by hooking up

one of the navigation controls to the Web.sitemap file you can create complex user interface

elements like fold-out menus or a tree view.

Web.sitemap File By default, you should call the site map file Web.sitemap. This enables the controls to find

the right file automatically.

A basic version of the site map file can look like this:

<?xml version=”1.0” encoding=”utf-8” ?>

<siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0”>

<siteMapNode url=”~/” title=”Home” description=”Go to the homepage”>

Page 62: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

60 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

<siteMapNode url=”~/Reviews” title=”Reviews” description=”Reviews published on this

site” />

<siteMapNode url=”~/About” title=”About” description=”About this site” />

</siteMapNode>

</siteMap>

Key Elements of the Web.sitemap File

Each siteMapNode can have many child nodes (but there can only be one siteMapNode

directly under the siteMap element), enabling you to create a site structure that can be both

wide and deep at the same time. The siteMapNode elements in this example

have three of their attributes set: url, title, and description.

The url attribute should point to a valid page in your web site.

The title attribute is used in the navigation controls to display the name of the page.

The description attribute is used as a tooltip for the navigation elements.

For code Refer classroom notes

programmatic redirection

Programmatic redirection is very useful and common in ASP.NET pages. For example,

imagine a page that enables a user to enter a review into the database. As soon as she

clicks the Save button, the review is saved and the user is taken to another page where she

can see the entire review.

ASP.NET supports three major ways to redirect users to a new page programmatically. The

first two, Response.Redirect and Response.RedirectPermanent (which is new in ASP.NET 4),

send an instruction to the browser to fetch a new page. The third option, Server.Transfer,

executes at the client. Because there‘s quite a difference in client- and server-side

redirection.

programmatically redirecting the Client to a Different page

Response.Redirect(newUrl)

Response.RedirectPermanent(newUrl)

The difference between Redirect and RedirectPermanent mainly has to do with search

engine optimization. Using Redirect tells the client that the page has moved temporarily.

RedirectPermanent tells the client the page has moved permanently. This is useful if you

want to tell a search engine to stop looking at an old page, and index the new one instead.

Page 63: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

61 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

server-side redirects

Server-side redirects are great if you want to send out a different page without modifying

the client‘s address bar. This enables you to hide details of page names and query strings,

which may lead to cleaner URLs from a user‘s point of view.

Server-side transfers are carried out with the Server object. Just like the Request and Response

objects you saw earlier give you information about the request and the response, so does

the Server object provide you with information about the server the page is running on. You

can use it to get information about the server name, its IP address, and so on. One of its

methods is Transfer, which performs a server-side transfer.

Server.Transfer can only be used to redirect to other pages within your site.

Server.Transfer(“Target.aspx?Test=SomeValue”)

Validating User Controls

Validating user input in Web forms People concerned with validating user input often use the mantra: Never trust user input.

Although this may seem like paranoia at first, it is really important in any open system.

Even if you think you know who your users are and even if you trust them completely, they

are often not the only users that can access your system.

A Warning on Client-Side Validation

Although client-side validation may seem enough to prevent users from sending invalid data

to your system, you should never rely on it as the only solution to validation. It‘s easy to

disable JavaScript in the browser, rendering the client-side validation routines useless. In

addition, a malicious user can easily bypass the entire page in the browser and send

information directly to the server, which will happily accept and process it if you don‘t take

countermeasures.

Introduction Validation Controls: This set of controls provide Rapid Application Development (RAD) features for automatically

checking the specified validity of user inputs. These controls are available in the

System.Web.UI.WebControls namespace.

One of the most tiresome tasks when building interactive web applications is the

requirement for validating values that the user enters into the input controls. This is

particularly the case if we need to perform client-side as well as server side validation.

Mostly, we use JavaScript for client side coding. Help is at hand with the range of validation

controls that are included in ASP.NET.

Page 64: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

62 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

The ASP.NET Validation Controls

One of the most tiresome tasks when building interactive web applications is the

requirement for validating values that the user enters into the input controls. This is

particularly the case if we need to perform client-side as well as server side validation.

Mostly, we use JavaScript for client side coding. Help is at hand with the range of validation

controls that are included in ASP.NET.

RequiredFieldValidator:: <asp:RequiredFieldValidator>

Checks that the validated control contains a value. It cannot be empty. Can be used in

conjunction with other validators on a control to trap empty values. Simply, we can use it to

check if the input control has any value. The most important property in the

RequiredFieldValidator is InitialValue.

<asp:RequiredFieldValidator id="validTxtName runat="server" controlToValidate="txtName"

errorMessage="Name must be entered" display="static">

</asp:RequiredFieldValidator>

RegularExpressionValidator:

<asp:RegularExpressionValidator>

Checks the value against a regular expression (pattern). Checks that the value in the

control matches a specified regular expression. If the validated control is empty, no

validation takes place. The most important property in the RegularExpressionValidator is

ValidationExpression.

<asp:RegularExpressionValidator id="regvH" runat="server" display="static"

controlToValidate="txtH" errorMessage="Hours must be 1-3 digits only"

validationExpression="\d{1,3}">

</asp:RegularExpressionValidator>

CompareValidator: <asp:CompareValidator>

Checks if the value is acceptable compared to a given value or compared to the content of

another control. In other words, it checks that the value in the validated control matches

the value in another control or a specific value. The data type and comparison operation can

be specified. If the validated control is empty, no validation takes place. The most important

properties in the CompareValidator are ValueToCompare, ControlToCompare, Operator, and

type.

Page 65: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

63 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

<asp:CompareValidator id="comvR" runat="server" display="static"

controlToValidate="txtR" errorMessage="Rate must be numeric" type="Double"

operator="DataTypeCheck"></asp:CompareValidator>

RangeValidator:

<asp:RangeValidator>

Checks if the input control‘s value is within a specified range. In other words, it checks that

the value in the validated control is within the specified text or numeric range. If the

validated control is empty, no validation takes place. The most important properties in the

RangeValidator are MaximumValue, MinimumValue, and type.

<asp:RangeValidator id="ranvDependents" runat="server" display="static"

controlToValidate="txtDependents" errorMessage="Must be from 0 to 10" type="Integer"

minimumValue=0 maximumValue=10></asp:RangeValidator>

CustomValidator:

<asp:CustomValidator>

Allows you to develop custom validation. Performs user-defined validation on an input

control using a specified function (client-side, server-side, or both). If the validated control

is empty, no validation takes place. The most important property in the CustomValidator is

ClientValidationFunction.

<asp:CustomValidator id="cusvDeptNum" runat="server" display="static"

controlToValidate="txtDeptNum" onServerValidate="validateDeptNum"

errorMessage="Must be in multiples of 10" > </asp:CustomValidator>

ValidationSummary:

<asp:ValidationSummary>

Displays a summary of all current validation errors. In other words, reports a summary of

all errors. The most important properties in the ValidationSummary are DisplayMode,

ShowHeaderText, ShowMessageBox, and ShowSummary.

<asp:ValidationSummary id="valSummary" runat="server" headerText="Please correct the

following errors" display="static" showSummary= "True" />

Page 66: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

64 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

UNIT 3

ADO.NET Fundamentals

Almost every piece of software ever written works with data.

In fact, a typical web application is often just a thin user interface shell on top of

sophisticated data-driven code that reads and writes information from a database.

Often, website users aren‘t aware (or don‘t care) that the displayed information originates

from a database.

The Role of the Database The most common way to manage data is to use a database. Database technology is

particularly useful for business software, which typically requires sets of related information.

the RDBMS takes the responsibility of providing data to multiple users simultaneously,

disallowing invalid data, and committing groups of actions at once using transactions.

Database Access in the Web World

Accessing a database in a web application is a completely different scenario than accessing

a database in a typical client-server desktop application.

Most developers hone their database skills in the desktop world and run into serious

problems when they try to apply what they have learned with stand-alone applications in

the world of the Web.

Problems of scale are the problems that can result from the massively multiuser nature of

the Web.

Problems of state are problems that can result from the disconnected nature of the Internet.

ADO.NET Basics ADO.NET relies on the functionality in a small set of core classes. You can divide these

classes into two groups: those that are used to contain and manage data (such as DataSet,

DataTable, DataRow, and DataRelation) and those that are used to connect to a specific

data source (such as Connection, Command, and DataReader).

Page 67: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

65 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

The second group of classes exists in several different flavors. Each set of data interaction

classes is called an ADO.NET data provider. Data providers are customized so that each one

uses the best-performing way of interacting with its data source.

It‘s important to understand that you can use any data provider in almost the same way,

with almost the same code.

.NET includes the following four providers:

• SQL Server provider: Provides optimized access to a SQL Server database (version 7.0 or

later)

• OLE DB provider: Provides access to any data source that has an OLE DB driver

• Oracle provider: Provides optimized access to an Oracle database (version 8i or later)

• ODBC provider: Provides access to any data source that has an ODBC (Open Database

Connectivity) driver

In addition, third-party developers and database vendors have released their own ADO.NET

providers, which follow the same conventions and can be used in the same way as those

that are included with the .NET Framework.

Different layers that come into play with ADO.NET

Page 68: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

66 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Data Namespaces The ADO.NET components live in several different namespaces in the .NET class library.

Together, these namespaces hold all the functionality of ADO.NET.

ADO.NET Namespaces

Namespace Purpose System.Data Contains fundamental classes with the core ADO.NET

functionality. This includes DataSet and DataRelation, which

allow you to manipulate structured relational data.

System.Data.Common Not used directly in your code. These classes are used by other

data provider classes that inherit from them and provide

versions customized for a specific data source.

System.Data.OleDb Contains the classes you use to connect to an OLE DB data

source and execute commands, including OleDbConnection and

OleDbCommand.

System.Data.SqlClient Contains the classes you use to connect to a Microsoft SQL

Server database (version 7.0 or later) and execute commands.

These classes, such as SqlCommand and SqlConnection, provide

all the same properties and methods as their counterparts in the

System.Data.OleDb namespace.

System.Data.SqlTypes Contains structures for SQL Server–specific data types such as

SqlMoney and SqlDateTime. You can use these types to work

with SQL Server data types without needing to convert them

into the standard .NET equivalents (such as System.Decimal and

System.DateTime).

System.Data.OracleClient Contains the classes you use to connect to an Oracle database

and execute commands, such as OracleConnection and

OracleCommand.

System.Data.Odbc Contains the classes you use to connect to a data source

through an ODBC driver and execute commands. These classes

include OdbcConnection and OdbcCommand.

The ADO.NET Data Provider Classes

SQL Server Data

Provider

OLE DB

Data Provider

Oracle

Data Provider

ODBC Data

Provider

Connection SqlConnection OleDbConnection OracleConnection OdbcConnection

Command SqlCommand OleDbCommand OracleCommand OdbcCommand

DataReader SqlDataReader OleDbDataReader OracleDataReader OdbcDataReader

DataAdapter SqlDataAdapter OleDbDataAdapter OracleDataAdapter OdbcDataAdapter

Page 69: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

67 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

though the underlying technical details differ, the classes are almost identical. The only real

differences are as follows:

• The names of the Connection, Command, DataReader, and DataAdapter classes are

different in order to help you distinguish them.

• The connection string (the information you use to connect to the database) differs

depending on what data source you‘re using, where it‘s located, and what type of security

you‘re using.

• Occasionally, a provider may choose to add features, such as methods for specific features

or classes to represent specific data types. For example, the SQL Server Command class

includes a method for executing XML queries that aren‘t part of the SQL standard. In this

chapter, you‘ll focus on the standard functionality, which is shared by all providers and used

for the majority of data access operations.

Direct Data Access The easiest way to interact with a database is to use direct data access. When you use

direct data access, you‘re in charge of building a SQL command and executing it. You use

commands to query, insert, update, and delete information.

When you query data with direct data access, you don‘t keep a copy of the information in

memory. Instead, you work with it for a brief period of time while the database connection

is open, and then close the connection as soon as possible. This is different than

disconnected data access, where you keep a copy of the data in the DataSet object so you

can work with it after the database connection has been closed.

The direct data model is well suited to ASP.NET web pages, which don‘t need to keep a copy

of their data in memory for long periods of time. Remember, an ASP.NET web page is

loaded when the page is requested and shut down as soon as the response is returned to

the user. That means a page typically has a lifetime of only a few seconds.

To query information with simple data access, follow these steps: 1. Create Connection, Command, and DataReader objects.

2. Use the DataReader to retrieve information from the database, and display it in a control

on a web form.

3. Close your connection.

4. Send the page to the user. At this point, the information your user sees and the

information in the database no longer have any connection, and all the ADO.NET objects

have been destroyed.

To add or update information, follow these steps:

Page 70: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

68 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

1. Create new Connection and Command objects.

2. Execute the Command (with the appropriate SQL statement).

Direct data access with ADO.NET

Before creating connection

make sure you import the ADO.NET namespaces.

using System.Data;

using System.Data.SqlClient;

Creating a Connection

Before you can retrieve or update data, you need to make a connection to the data source.

Generally, connections are limited to some fixed number.

if you exceed that number, attempts to create new connections will fail.

you should try to hold a connection open for as short a time as possible. You should also

write your database code inside a Try/Catch error-handling structure so you can respond if

an error does occur, and make sure you close the connection even if you can‘t perform all

your work.

When creating a Connection object, you need to specify a value for its ConnectionString

property. This ConnectionString defines all the information the computer needs to find the

data source, log in, and choose an initial database.

For optimum performance, you should use the SqlConnection object from the SQL Server

provider instead.

Page 71: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

69 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

SqlConnection myConnection = new SqlConnection();

myConnection.ConnectionString = "Data Source=localhost\\SQLEXPRESS; Initial

Catalog=Pubs;Integrated Security=SSPI";

The Connection String The connection string is actually a series of distinct pieces of information separated by

semicolons (;).

Each separate piece of information is known as a connection string property.

Data source: This indicates the name of the server where the data source is located. If the

server is on the same computer that hosts the ASP.NET site, localhost is sufficient. The only

exception is if you‘re using a named instance of SQL Server. For example, if you‘ve installed

SQL Server 2005 Express Edition, you‘ll need to use the data source localhost\SQLEXPRESS,

because the instance name is SQLEXPRESS. You‘ll also see this written with a period, as

.\SQLEXPRESS, which is equivalent.

Initial catalog: This is the name of the database that this connection will be accessing. It‘s

only the ―initial‖ database because you can change it later by using the

Connection.ChangeDatabase() method.

Integrated security: This indicates you want to connect to SQL Server using the Windows

user account that‘s running the web page code, provided you supply a value of SSPI (which

stands for Security Support Provider Interface). Alternatively, you can supply a user ID and

password that‘s defined in the database for SQL Server authentication, although this

method is less secure and generally discouraged.

ConnectionTimeout: This determines how long your code will wait, in seconds, before

generating an error if it cannot establish a database connection. Our example connection

string doesn‘t set the ConnectionTimeout, so the default of 15 seconds is used. You can use

0 to specify no limit, but this is a bad idea. This means that, theoretically, the code could be

held up indefinitely while it attempts to contact the server.

Windows Authentication

The previous example uses integrated Windows authentication, which is the default security

standard for new SQL Server installations. You can also use SQL Server authentication. In

this case, you will explicitly place the user ID and password information in the connection

string.

• With SQL Server authentication, SQL Server maintains its own user account information in

the database. It uses this information to determine whether you are allowed to access

specific parts of a database.

Page 72: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

70 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

• With integrated Windows authentication, SQL Server automatically uses the Windows

account information for the currently logged-in process. In the database, it stores

information about what database privileges each user should have.

User Instance Connections

Every database server stores a master list of all the databases that you‘ve installed on it.

This list includes the name of each database and the location of the files that hold the data.

When you create a database (for example, by running a script or using a management tool),

the information about that database is added to the master list. When you connect to the

database, you specify the database name using the Initial Catalog value in the connection

string.

Interestingly, SQL Server Express has a feature that lets you bypass the master list and

connect directly to any database file, even if it‘s not in the master list of databases. This

feature is called user instances. Oddly enough, this feature isn‘t available in the full edition

of SQL Server 2005.

To use this feature, you need to set the User Instances value to True (in the connection

string) and supply the file name of the database you want to connect to with the

AttachDBFilename value. You don‘t supply an Initial Catalog value.

Here’s an example connection string that uses this approach:

myConnection.ConnectionString = "Data Source=localhost\SQLEXPRESS;" & _

"AttachDBFilename=|DataDirectory|\Northwind.mdf;Integrated Security=True"

There‘s another trick here. The file name starts with |DataDirectory|. This automatically

points to the App_Data folder inside your web application directory. This way, you don‘t

need to supply a full file path, which might not remain valid when you move the web

application to a web server. Instead, ADO.NET will always look in the App_Data directory for

a file named Northwind.mdf.

User instances is a handy feature if you have a web server that hosts many different web

applications that use databases and these databases are frequently being added and

removed.

Storing the Connection String

Typically, all the database code in your application will use the same connection string. For

that reason, it usually makes the most sense to store a connection string in a class member

variable or, even better, a configuration file.

You can also create a Connection object and supply the connection string in one step by

using a dedicated constructor:

Page 73: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

71 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

SqlConnection myConnection = new SqlConnection(connectionString);

// myConnection.ConnectionString is now set to connectionString.

You don‘t need to hard-code a connection string. The <connectionStrings> section of the

web.config file is a handy place to store your connection strings. Here‘s an example:

<configuration>

<connectionStrings>

<add name="Pubs" connectionString=

"Data Source=localhost;Initial Catalog=Pubs;Integrated Security=SSPI"/>

</connectionStrings>

...

</configuration>

You can then retrieve your connection string by name. First, import the

System.Web.Configuration namespace. Then, you can use code like this:

string connectionString =

WebConfigurationManager.ConnectionStrings("Pubs").ConnectionString;

This approach helps to ensure all your web pages are using the same connection string. It

also makes it easy for you to change the connection string for an application, without

needing to edit the code in multiple pages.

Making the Connection

Once you‘ve created your connection you‘re ready to use it.

Closing a connection is just as easy, as shown here:

myConnection.Open()

Closing a connection is just as easy, as shown here:

myConnection.Close()

The Select Command

The Connection object provides a few basic properties that supply information about the

connection, but that‘s about all. To actually retrieve data, you need a few more ingredients:

• A SQL statement that selects the information you want

• A Command object that executes the SQL statement

• A DataReader or DataSet object to access the retrieved records

Page 74: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

72 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

SqlCommand myCommand = new SqlCommand();

myCommand.Connection = myConnection;

myCommand.CommandText = "SELECT * FROM Authors ORDER BY au_lname";

The DataReader Once you‘ve defined your command, you need to decide how you want to use it. The

simplest approach is to use a DataReader, which allows you to quickly retrieve all your

results. The DataReader uses a live connection and should be used quickly and then closed.

The DataReader is also extremely simple. It supports fast-forward-only read-only access to

your results, which is generally all you need when retrieving information.

To create a DataReader, you use the ExecuteReader() method of the command object, as

shown here:

' You don't need the new keyword, as the Command will create the DataReader.

SqlDataReader myReader = default(SqlDataReader);

myReader = myCommand.ExecuteReader();

These two lines of code define a variable for a DataReader and then create it by executing

the command. Once you have the reader, you retrieve a single row at a time using the

Read() method:

myReader.Read() ' The first row in the result set is now available.

You can then access the values in the current row using the corresponding field names.

Textbox1.text = myReader("au_lname")

To move to the next row, use the Read() method again. If this method returns True, a row

of information has been successfully retrieved.

If it returns False, you‘ve attempted to read past the end of your result set.

As soon as you‘ve finished reading all the results you need, close the DataReader and

Connection:

myReader.Close()

myConnection.Close()

Working with sql parameters

A much more robust and convenient approach is to use a parameterized command. A

parameterized command is one that replaces hard-coded values with placeholders. The

placeholders are then added separately and automatically encoded.

Page 75: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

73 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

For example, this SQL statement:

SELECT * FROM Customers WHERE CustomerID = 'ALFKI'

would become this:

SELECT * FROM Customers WHERE CustomerID = @CustomerID

The syntax used for parameterized commands differs from provider to provider. For the SQL

Server provider, parameterized commands use named placeholders with unique names. You

can use any name you want, as long as it begins with the @ character. Usually, you‘ll

choose a parameter name that matches the field name (such as @CustomerID for the

CustomerID value

in the previous example). The OLE DB provider uses a different syntax. It requires that each

hard-coded value is replaced with a question mark. Parameters aren‘t identified by name

but by their position in the SQL string.

SELECT * FROM Customers WHERE CustomerID = ?

In either case, you need to supply a Parameter object for each parameter, which you insert

in the Command.Parameters collection. In OLE DB, you must make sure you add the

parameters in the same order they appear in the SQL string. In SQL Server this isn‘t a

requirement, because the parameters are matched to the placeholders based on their name.

Updating Data Now that you understand how to retrieve data, it isn‘t much more complicated to perform

simple delete and update operations. Once again, you use the Command object, but this

time you don‘t need a DataReader because no results will be retrieved. You also don‘t use a

SQL Select command. Instead, you use one of three new SQL commands: Update, Insert, or

Delete.

To execute an Update, an Insert, or a Delete statement, you need to create a Command

object. You can then execute the command with the ExecuteNonQuery() method. This

method returns the number of rows that were affected, which allows you to check your

assumptions.

Example:

SELECT * FROM Customers WHERE CustomerID = @CustomerID

Adding value to query

SqlCommand.Parameters.AddWithValue("@CustomerID", txtID.Text)

Page 76: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

74 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Disconnected Data Access When you use disconnected data access, you keep a copy of your data in memory using the

DataSet. You connect to the database just long enough to fetch your data and dump it into

the DataSet, and then you disconnect immediately.

There are a variety of good reasons to use the DataSet to hold onto data in memory. Here

are a few:

• You need to do something time-consuming with the data. By dumping it into a DataSet

first, you ensure that the database connection is kept open for as little time as possible.

• You want to use ASP.NET data binding to fill a web control (like a grid) with your data.

Although you can use the DataReader, it won‘t work in all scenarios. The DataSet approach

is more straightforward.

• You want to navigate backward and forward through your data while you‘re processing it.

This isn‘t possible with the DataReader, which goes in one direction only—forward.

• You want to navigate from one table to another. Using the DataSet, you can store several

tables of information. You can even define relationships that allow you to browse through

them more efficiently.

• You want to save the data to a file for later use. DataSet object can be saved in XML

format in an ordinary file.

• You need a convenient package to send data from one component to another. So user can

build a database component that provides its data to a web page using the DataSet. A

DataReader wouldn‘t work in this scenario, because the database component would need to

leave the database connection open, which is a dangerous design.

• You want to store some data so it can be used for future requests.you can use caching

with the DataSet to achieve this result.

UPDATING DISCONNECTED DATA

The DataSet tracks the changes you make to the records inside. This allows you to use the

DataSet to update records. The basic principle is simple. You fill a DataSet in the normal

way, modify one or more records, and then apply your update using a DataAdapter.

ADO.NET‘s disconnected update feature makes far more sense in a desktop application than

in a web application. Desktop applications run for a long time, so they can efficiently store a

batch of changes and perform them all at once. But in a web application, you need to

commit your changes the moment they happen. Furthermore, the point at which you

retrieve the data (when a page is first requested) and the point at which it‘s changed

Page 77: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

75 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

(during a postback) are different, which makes it very difficult to use the same DataSet

object, and maintain the change tracking information for the whole process.

For these reasons, the great majority of ASP.NET web applications use the DataSet to store

data but not to make updates. Instead, they use direct commands to commit changes.

Selecting Disconnected Data With disconnected data access, a copy of the data is retained in memory while your code is

running.

The DataSet family of objects

You fill the DataSet in much the same way that you connect a DataReader. However,

although the DataReader holds a live connection, information in the DataSet is always

disconnected.

Page 78: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

76 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

lstAuthor.Items.Clear();

// Define ADO.NET objects.

string selectSQL = null;

selectSQL = "SELECT au_lname, au_fname, au_id FROM Authors";

SqlConnection con = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand(selectSQL, con);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

DataSet dsPubs = new DataSet();

// Try to open database and read information.

try {

con.Open();

// All the information in transferred with one command.

// This command creates a new DataTable (named Authors)

// inside the DataSet.

adapter.Fill(dsPubs, "Authors");

} catch (Exception err) {

lblResults.Text = "Error reading list of names. ";

lblResults.Text += err.Message;

} finally {

con.Close();

}

foreach (DataRow row in dsPubs.Tables("Authors").Rows) {

ListItem newItem = new ListItem();

newItem.Text = row("au_lname") + ", " + row("au_fname");

newItem.Value = row("au_id").ToString();

lstAuthor.Items.Add(newItem);

}

If you want to extract records from a database and place them in a DataSet, you need to

use a DataAdapter. Every DataAdapter can hold four commands: SelectCommand,

InsertCommand, UpdateCommand, and DeleteCommand.

This allows you to use a single DataAdapter object for multiple tasks. The Command object

supplied in the constructor is automatically assigned to the DataAdapter.SelectCommand

property

The DataAdapter.Fill() method takes a DataSet and inserts one table of information. In this

case, the table is named Authors, but any name could be used. That name is used later to

access the appropriate table in the DataSet.

Page 79: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

77 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

To access the individual DataRows, you can loop through the Rows collection of the

appropriate table. Each piece of information is accessed using the field name, as it was with

the DataReader.

Using a DataSet with ADO.NET

Introducing Data Binding

The basic principle of data binding is this: you tell a control where to find your data and how

you want it displayed, and the control handles the rest of the details. Data binding in

ASP.NET is superficially similar to data binding in the world of desktop or client/server

applications, but in truth, it‘s fundamentally different. In those environments, data binding

involves creating adirect connection between a data source and a control in an application

window. If the user changes a value in the on-screen control, the data in the linked

database is modified automatically. if the database changes while the user is working with

it (for example, another user commits a change), the display can be refreshed

automatically.

ASP.NET data binding is much more flexible than old-style data binding. Many of the most

powerful data binding controls, such as the GridView and DetailsView, give you

Page 80: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

78 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

unprecedented control over the presentation of your data, allowing you to format it, change

its layout, embed it in other ASP.NET controls.

Types of ASP.NET Data Binding Two types of ASP.NET data binding exist: single-value binding and repeated-value

binding.Single-value data binding is by far the simpler of the two, whereas repeated-value

binding provides the foundation for the most advanced ASP.NET data controls.

Single-Value, or “Simple,” Data Binding

You can use single-value data binding to add information anywhere on an ASP.NET page.

You can even place information into a control property or as plain text inside an HTML tag.

Singlevalue data binding doesn‘t necessarily have anything to do with ADO.NET. Instead,

single-value data binding allows you to take a variable, a property, or an expression and

insert it dynamically into a page.

Repeated-Value, or “List,” Binding

Repeated-value data binding allows you to display an entire table (or just a single field from

a table). Unlike single-value data binding, this type of data binding requires a special control

that supports it. Typically, this will be a list control such as CheckBoxList or ListBox, but it

can also be a much more sophisticated control such as the GridView

How Data Binding Works

Data binding works a little differently depending on whether you‘re using single-value or

repeated-value binding. To use single-value binding, you must insert a data binding

expression into the markup in the .aspx file (not the code-behind file). To use repeated-

value binding, you must set one or more properties of a data control. Typically, you‘ll

perform this initialization when the Page.Load event fires.

Once you specify data binding, you need to activate it. You accomplish this task by calling

the DataBind() method. The DataBind() method is a basic piece of functionality supplied in

the Control class. It automatically binds a control and any child controls that it contains.

With repeated-value binding, you can use the DataBind() method of the specific list control

you‘re using. Alternatively, you can bind the whole page at once by calling the DataBind()

method of the current Page object. Once you call this method, all the data binding

expressions in the page are evaluated and replaced with the specified value.

Single-Value Data Binding

Single-value data binding is really just a different approach to dynamic text. To use it, you

add special data binding expressions into your .aspx files. These expressions have the

following format:

Page 81: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

79 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

<%# Country %>

When you call the DataBind() method for the page, this text will be replaced with the value

for Country (for example, India).

A Simple Data Binding Example

This section shows a simple example of single-value data binding. The example has been

stripped to the bare minimum amount of detail needed to illustrate the concept. You start

with a variable defined in your Page class, which is called TransactionCount:

public partial class SimpleDataBinding : System.Web.UI.Page

{

protected int TransactionCount;

// (Additional code omitted.)

}

Note that this variable must be designated as public, protected, or internal, but not private.

this value is set in the Page.Load event handler using some database lookup code.

protected void Page_Load(object sender, EventArgs e)

{

// (You could use database code here

// to look up a value for TransactionCount.)

TransactionCount = 10;

// Now convert all the data binding expressions on the page.

this.DataBind();

}

Two actions actually take place in this event handler: the TransactionCount variable is set to

10, and all the data binding expressions on the page are bound. Currently, no data binding

expressions exist, so this method has no effect.

To add your expression, find the tag for the Label control in .aspx . Modify the text inside

the label

as shown here:

<asp:Label id="lblDynamic" runat="server" Font-Size="X-Large">

There were <%# TransactionCount %> transactions</asp:Label>

------For more examples refer classroom notes-----

Repeated-Value Data Binding

Page 82: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

80 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Although using simple data binding is optional, repeated-value binding is so useful that

almost every ASP.NET application will want to use it somewhere. Repeated-value data

binding works with the ASP.NET list controls .To use repeated-value binding, you link one of

these controls to a data source (such as a field in a data table). When you call DataBind(),

the control automatically creates a full list using all the corresponding values.

To create a data expression for list binding, you need to use a list control that explicitly

supports data binding.

ListBox, DropDownList, CheckBoxList, and RadioButtonList: These web controls

provide a list for a single field of information.

HtmlSelect: This server-side HTML control represents the HTML <select> element and

works essentially the same way as the ListBox web control. Generally, you‘ll use this control

only for backward compatibility.

GridView, DetailsView, FormView, and ListView: These rich web controls allow you to

provide repeating lists or grids that can display more than one field of information at a time.

For example, if you bind one of these controls to a full-fledged table in a DataSet, you can

display the values from multiple fields. These controls offer the most powerful and flexible

options for data binding.

Data Binding with Simple List Controls You need to follow only three steps:

Create and fill some kind of data object. You have numerous options, including an

array, the basic ArrayList and Hashtable collections, the strongly typed List and

Dictionary collections, and the ADO.NET DataTable and DataSet objects.

Link the object to the appropriate control. To do this, you need to set only a couple

of properties, including DataSource. If you‘re binding to a full DataSet, you‘ll also

need to set the DataMember property to identify the appropriate table you want to

use.

Activate the binding. As with single-value binding, you activate data binding by using

the DataBind() method, either for the specific control or for all contained controls at

once by using the DataBind() method for the current page.

This process is the same whether you‘re using the ListBox, the DropDownList, the

CheckBoxList, the RadioButtonList, or even the HtmlSelect control.

A Simple List Binding Example

To try this type of data binding, add a ListBox control to a new web page. Next, import the

System.Collections namespace in your code. Finally, use the Page.Load event handler to

create an ArrayList collection to use as a data source as follows:

Page 83: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

81 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

ArrayList fruit = new ArrayList();

fruit.Add("Kiwi");

fruit.Add("Pear");

fruit.Add("Mango");

fruit.Add("Blueberry");

fruit.Add("Apricot");

fruit.Add("Banana");

fruit.Add("Peach");

fruit.Add("Plum");

Now, you can link this collection to the ListBox control:

lstItems.DataSource = fruit;

Because an ArrayList is a straightforward, unstructured type of object, this is all the

information you need to set. If you were using a DataTable (which has more than one field)

or a DataSet (which has more than one DataTable), you would have to specify additional

information.

To activate the binding, use the DataBind() method:

Me.DataBind()

Strongly Typed Collections

You can use data binding with the Hashtable and ArrayList, two of the more useful collection

classes in the System.Collections namespace.

.NET includes a more stringent set of collections in another namespace:

System.Collections.Generic. These collections are ideal in cases where you want your

collection to hold just a single type of object (for example, just strings). When you use the

generic collections, you choose the item type you want to use, and the collection object is

―locked in‖ to your choice (which is similar to how an array works). This means if you try to

add another type of object that doesn‘t belong in the collection, you‘ll get a compile-time

error.

To use a generic collection, you must import the right namespace:

using System.Collections.Generic

The generic version of the ArrayList class is named List. Here‘s how you create a List

collection object that can only store strings:

List<string> fruit = new List<string>();

fruit.Add("Kiwi");

Page 84: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

82 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

fruit.Add("Pear");

Data Binding with ADO.NET This is an easy way to familiarize yourself with the concepts, and a useful approach in its

own right, you get the greatest advantage of data binding when you use it in conjunction

with a database.

When you‘re using data binding with the information drawn from a database, the data

binding process takes place in the same three steps.

First you create your data source, which will be a DataReader or DataSet object. A

DataReader generally offers the best performance, but it limits your data binding to a single

control because it is a forward-only reader. As it fills a control, it traverses the results from

beginning to end. Once it‘s finished, it can‘t go back to the beginning; so it can‘t be used in

another data binding operation. For this reason, a DataSet is a more common choice.

To fill a DataSet by hand, you need to follow several steps:

1. First, create the DataSet.

2. Next, create a new DataTable, and add it to the DataSet.Tables collection.

3. Next, define the structure of the table by adding DataColumn objects (one for each

field) to the DataTable.Colums collection.

4. Finally, supply the data. You can get a new, blank row that has the same structure as

your DataTable by calling the DataTable.NewRow() method. You must then set the data

in all its fields, and add the DataRow to the DataTable.Rows collection.

' Define a DataSet with a single DataTable.

DataSet dsInternal = new DataSet();

dsInternal.Tables.Add("Users");

' Define two columns for this table.

dsInternal.Tables("Users").Columns.Add("Name");

dsInternal.Tables("Users").Columns.Add("Country");

' Add some actual information into the table.

DataRow rowNew = dsInternal.Tables("Users").NewRow();

rowNew("Name") = "John";

rowNew("Country") = "Uganda";

dsInternal.Tables("Users").Rows.Add(rowNew);

bind the DataTable from the DataSet to the appropriate control.

' Define the binding.

lstUser.DataSource = dsInternal.Tables("Users");

Page 85: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

83 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

lstUser.DataTextField = "Name";

or

' Define the binding.

lstUser.DataSource = dsInternal;

lstUser.DataMember = "Users";

lstUser.DataTextField = "Name";

As always, the last step is to activate the binding:

this.DataBind();

Creating a Record Editor

The next example is more practical. It‘s a good example of how you might use data binding

in a full ASP.NET application. This example allows the user to select a record and update

one piece of information by using data-bound list controls.

private string connectionString =

WebConfigurationManager.ConnectionStrings("Northwind").ConnectionString;

protected void Page_Load(object sender, EventArgs e)

{

if (!this.IsPostBack) {

// Define the ADO.NET objects for selecting products from the database.

string selectSQL = "SELECT ProductName, ProductID FROM Products";

SqlConnection con = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand(selectSQL, con);

// Open the connection.

con.Open();

// Define the binding.

lstProduct.DataSource = cmd.ExecuteReader();

lstProduct.DataTextField = "ProductName";

lstProduct.DataValueField = "ProductID";

// Activate the binding.

this.DataBind();

con.Close();

// Make sure nothing is currently selected in the list box.

lstProduct.SelectedIndex = -1;

Page 86: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

84 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

}

}

Data Source Controls

The data source controls include any control that implements the IDataSource interface. The

.NET Framework includes the following data source controls:

• SqlDataSource: This data source allows you to connect to any data source that has an

ADO.NET data provider. This includes SQL Server, Oracle, and OLE DB or ODBC data

sources. When using this data source, you don‘t need to write the data access code.

• AccessDataSource: This data source allows you to read and write the data in an Access

database file (.mdb).

• ObjectDataSource: This data source allows you to connect to a custom data access class.

This is the preferred approach for large-scale professional web applications, but it forces you

to write much more code.

• XmlDataSource: This data source allows you to connect to an XML file.

• SiteMapDataSource: This data source allows you to connect to a .sitemap file that

describes the navigational structure of your website.

The Page Life Cycle with Data Binding Data source controls can perform two key tasks:

They can retrieve data from a data source and supply it to bound controls. When you use

this feature, your bound controls are automatically filled with data. You don‘t even need

to call DataBind().

They can update the data source when edits take place. In order to use this feature, you

must use one of ASP.NET‘s rich data controls, like the GridView or DetailsView. For example,

if you make an edit in the GridView and click Update, the GridView will trigger the update in

the data source control, and the data source control will then update the database.

Before you can use the data source controls, you need to understand the page life

cycle. The following steps explain the sequence of stages your page goes through

in its lifetime. The two steps in bold (4 and 6) are the steps where the data source

controls will spring into action:

1. The page object is created (based on the .aspx file).

2. The page life cycle begins, and the Page.Init and Page.Load events fire.

Page 87: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

85 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

3. All other control events fire.

4. If the user is applying a change, the data source controls perform their update

operations now. If a row is being updated, the Updating and Updated events fire.

If a row is being inserted, the Inserting and Inserted events fire. If a row is being

deleted, the Deleting and Deleted events fire.

5. The Page.PreRender event fires.

6. The data source controls perform their queries and insert the data they retrieve

into the bound controls. This step happens the first time your page is requested

and every time the page is posted back, ensuring you always have the most up-to-

date data. The Selecting and Selected events fire at this point.

7. The page is rendered and disposed.

The SqlDataSource Data source controls turn up in the .aspx markup portion of your web page like ordinary

controls. Here‘s an example:

<asp:SqlDataSource ID="SqlDataSource1" runat="server" ... />

The SqlDataSource represents a database connection that uses an ADO.NET provider.

However, this has a catch. The SqlDataSource needs a generic way to create the

Connection, Command, and DataReader objects it requires. The only way this is possible is

if your data provider includes something called a data provider factory.

.NET includes a data provider factory for each of its four data providers:

• System.Data.SqlClient

• System.Data.OracleClient

• System.Data.OleDb

• System.Data.Odbc

Here‘s a SqlDataSource that connects to a SQL Server database using the SQL Server

provider:

<asp:SqlDataSource ProviderName="System.Data.SqlClient" ... />

The next step is to supply the required connection string—without it, you cannot make any

connections. Although you can hard-code the connection string directly in the

SqlDataSource tag, it‘s always better to keep it in the <connectionStrings> section of the

web.config file to guarantee greater flexibility and ensure you won‘t inadvertently change

the connection string.

Page 88: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

86 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

To refer to a connection string in your .aspx markup, you use a special syntax in this

format:

<%$ ConnectionStrings:[NameOfConnectionString] %>

This looks like a data binding expression, but it‘s slightly different. (For one thing, it begins

with the character sequence <%$ instead of <%#.)

Selecting Records You can use each SqlDataSource control you create to retrieve a single query. Optionally,

you can also add corresponding commands for deleting, inserting, and updating rows.

The SqlDataSource command logic is supplied through four properties—SelectCommand,

InsertCommand, UpdateCommand, and DeleteCommand—each of which takes a string.

Here‘s a complete SqlDataSource that defines a Select command for retrieving product

information from the Products table:

<asp:SqlDataSource ID="sourceProducts" runat="server"

ProviderName="System.Data.SqlClient"

ConnectionString="<%$ ConnectionStrings:Northwind %>"

SelectCommand="SELECT ProductName, ProductID FROM Products"/>

This is enough to build the first stage of the record editor example shown earlier—namely,

the drop-down list box that shows all the products. All you need to do is set the

DataSourceID property to point to the SqlDataSource you‘ve created.

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

DataSourceID="sourceProducts" DataTextField="ProductName"

DataValueField="ProductID" />

Parameterized Commands

In the previous example (which used the SqlDataSource to retrieve a list of products), the

complete query was hard-coded. Often, you won‘t have this flexibility. Instead, you‘ll want

to etrieve a subset of data, such as all the products in a given category or all the employees

in a specific city.

<asp:SqlDataSource ID="sourceProductDetails" runat="server"

ProviderName="System.Data.SqlClient"

ConnectionString="<%$ ConnectionStrings:Northwind %>"

SelectCommand="SELECT * FROM Products WHERE ProductID=@ProductID">

<SelectParameters>

<asp:ControlParameter ControlID="lstProduct" Name="ProductID"

PropertyName="SelectedValue" />

Page 89: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

87 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

</SelectParameters>

</asp:SqlDataSource>

It defines a parameter (@ProductID) that identifies the ID of the product you want to

retrieve. How do you fill in this piece of information? It turns out you need to add a

<SelectParameters> section to the SqlDataSource tag. Inside this section, you must define

each parameter that‘s referenced by your SelectCommand and tell the SqlDataSource where

to find the value it should use. You do that by mapping the parameter to a value in a

control.

Other Types of Parameters

In the previous example, the @ProductID parameter in the second SqlDataSource is

configured based on the selection in a drop-down list. This type of parameter, which links to

a property in another control, is called a control parameter. But parameter values aren‘t

necessarily drawn from other controls. You can map a parameter to any of the parameter

types defined in Table

Source Control Tag Description

Control

property

<asp:ControlParameter> A property from another control on the page.

Query string

value

<asp:QueryStringParamet

er>

A value from the current query string.

Session state

value

<asp:SessionParameter> A value stored in the current user‘s session.

Cookie value <asp:CookieParameter> A value from any cookie attached to the current

request.

Profile value <asp:ProfileParameter> A value from the current user‘s profile

A form variable <asp:FormParameter> A value posted to the page from an input

control. Usually, you‘ll use a control property

instead, but you might need to grab a value

straight from the Forms collection if you‘ve

disabled view state for the corresponding

control.

The Data Controls

The rich data controls include the following:

• GridView: The GridView is an all-purpose grid control for showing large tables of

information. The GridView is the heavyweight of ASP.NET data controls.

• DetailsView: The DetailsView is ideal for showing a single record at a time, in a table that

has one row per field. The DetailsView also supports editing.

Page 90: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

88 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

• FormView: Like the DetailsView, the FormView shows a single record at a time and

supports editing. The difference is that the FormView is based on templates, which allow

you to combine fields in a flexible layout that doesn‘t need to be table-based.

• ListView: The ListView plays the same role as the GridView—it allows you to show multiple

records. The difference is that the ListView is based on templates. As a result, using the

ListView requires a bit more work and gives you slightly more layout flexibility. The ListView

isn‘t described in this book, although you can learn more about it in the Visual Studio.

The GridView

The GridView is an extremely flexible grid control that displays a multicolumn table. Each

record in your data source becomes a separate row in the grid. Each field in the record

becomes a separate column in the grid. The GridView is the most powerful.

Automatically Generating Columns The GridView provides a DataSource property for the data object you want to display, much

like the list controls.

Once you‘ve set the DataSource property, you call the DataBind() method to perform the

data binding and display each record in the GridView.

the GridView automatically generates a column for every field, as long as the

AutoGenerateColumns property is True (which is the default).

Here‘s all you need to create a basic grid with one column for each field:

<asp:GridView ID="GridView1" runat="server" />

Once you‘ve added this GridView tag to your page, you can fill it with data. Here‘s an

example that performs a query using the ADO.NET objects and binds the retrieved DataSet:

protected void Page_Load(object sender, EventArgs e)

{

// Define the ADO.NET objects.

string connectionString =

WebConfigurationManager.ConnectionStrings("Northwind").ConnectionString;

string selectSQL = "SELECT ProductID, ProductName, UnitPrice FROM Products";

SqlConnection con = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand(selectSQL, con);

SqlDataAdapter adapter = new SqlDataAdapter(cmd);

// Fill the DataSet.

DataSet ds = new DataSet();

adapter.Fill(ds, "Products");

Page 91: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

89 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

// Perform the binding.

GridView1.DataSource = ds;

GridView1.DataBind();

}

Or Here‘s how you would define a SqlDataSource to perform the query shown in the previous

example:

<asp:SqlDataSource ID="sourceProducts" runat="server"

ConnectionString="<%$ ConnectionStrings:Northwind %>"

SelectCommand="SELECT ProductID, ProductName, UnitPrice FROM Products" />

Next, set the GridView.DataSourceID property to link the data source to your grid:

<asp:GridView ID="GridView1" runat="server"

DataSourceID="sourceProducts" />

Defining Columns By default, the GridView.AutoGenerateColumns property is True, and the GridView creates a

column for each field in the bound DataTable. This automatic column generation is good for

creating quick test pages, but it doesn‘t give you the flexibility you‘ll usually want. For

example, what if you want to hide columns, change their order, or configure some aspect of

their display, such as the formatting or heading text? In all these cases, you need to set

AutoGenerateColumns to False and define the columns in the <Columns> section of the

GridView control tag.

Column Types

Class Description

BoundField This column displays text from a field in the data source.

ButtonField This column displays a button in this grid column.

CheckBoxField

This column displays a check box in this grid column. It‘s used

automatically for true/false fields (in SQL Server, these are fields that

use the bit data type).

CommandField This column provides selection or editing buttons.

HyperLinkField This column displays its contents (a field from the data source or static

Page 92: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

90 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

text) as a hyperlink.

ImageField

This column displays image data from a binary field (providing it can be

successfully interpreted as a supported image format).

TemplateField

This column allows you to specify multiple fields, custom controls, and

arbitrary HTML using a custom template. It gives you the highest degree

of control but requires the most work.

The most basic column type is BoundField, which binds to one field in the data object. For

example, here‘s the definition for a single data-bound column that displays the ProductID

field:

<asp:BoundField DataField="ProductID" HeaderText="ID" />

This tag demonstrates how you can change the header text at the top of a column from

ProductID to just ID. Here‘s a complete GridView declaration with explicit columns:

<asp:GridView ID="GridView1" runat="server" DataSourceID="sourceProducts"

AutoGenerateColumns="False">

<Columns>

<asp:BoundField DataField="ProductID" HeaderText="ID" />

<asp:BoundField DataField="ProductName" HeaderText="Product Name" />

<asp:BoundField DataField="UnitPrice" HeaderText="Price" />

</Columns>

</asp:GridView>

Configuring Columns

When you explicitly declare a bound field, you have the opportunity to set other properties.

Property Description

DataField

Identifies the field (by name) that you want to display in this

column.

DataFormatString

Formats the field. This is useful for getting the right

representa-tion of numbers and dates.

ApplyFormatInEditMode

If True, the DataFormat string is used to format the value

even when the value appears in a text box in edit mode. The

default is False, which means the underlying value will be used

(such as 1143.02 instead of $1,143.02).

FooterText, HeaderText, Sets the text in the header and footer region of the grid if this

and HeaderImageUrl

grid has a header (GridView.ShowHeader is True) and footer

(GridView.ShowFooter is True). The header is most commonly

used for a descriptive label such as the field name; the footer

can contain a dynamically calculated value such as a

Page 93: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

91 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

summary. To show an image in the header instead of text, set

the HeaderImageUrl property.

ReadOnly

If True, it prevents the value for this column from being

changed in edit mode. No edit control will be provided.

Primary key fields are often read-only.

InsertVisible

If True, it prevents the value for this column from being set in

insert mode. If you want a column value to be set

programmat-ically or based on a default value defined in the

database, you can use this feature.

Property Description

DataField

Identifies the field (by name) that you want to display in this

column.

DataFormatString

Formats the field. This is useful for getting the right

representa-tion of numbers and dates.

ApplyFormatInEditMode

If True, the DataFormat string is used to format the value

even when the value appears in a text box in edit mode. The

default is False, which means the underlying value will be used

(such as 1143.02 instead of $1,143.02).

FooterText, HeaderText, Sets the text in the header and footer region of the grid if this

and HeaderImageUrl

grid has a header (GridView.ShowHeader is True) and footer

(GridView.ShowFooter is True). The header is most commonly

used for a descriptive label such as the field name; the footer

can contain a dynamically calculated value such as a

summary. To show an image in the header instead of text, set

the HeaderImageUrl property.

ReadOnly

If True, it prevents the value for this column from being

changed in edit mode. No edit control will be provided.

Primary key fields are often read-only.

InsertVisible

If True, it prevents the value for this column from being set in

insert mode. If you want a column value to be set

programmat-ically or based on a default value defined in the

database, you can use this feature.

Once you‘ve created your columns, you can also use some helpful design-time support to

configure the properties of each column (rather than editing the column tag by hand). To do

this, select the GridView, and click the ellipsis ( . . . ) next to the Columns property in the

Properties window. You‘ll see a Fields dialog box that lets you add, remove, and refine your

columns

Page 94: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

92 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Now that you understand the underpinnings of the GridView, you‘ve still only started to

explore its higher-level features. In the following sections, you‘ll tackle these topics:

Formatting: How to format rows and data values

Selecting: How to let users select a row in the GridView and respond accordingly

Editing: How to let users commit record updates, inserts, and deletes

Sorting: How to dynamically reorder the GridView in response to clicks on a column header

Paging: How to divide a large result set into multiple pages of data

Templates: How to take complete control of designing, formatting, and editing by defining

templates

Sorting and Paging the GridView The GridView is a great all-in-one solution for displaying all kinds of data, but it becomes a

little unwieldy as the number of fields and rows in your data source grows. Dense grids

contribute to large pages that are slow to transmit over the network and difficult for the

user to navigate. The GridView has two features that address these issues and make data

more manageable: sorting and paging.

Both sorting and paging can be performed by the database server, provided you craft the

right SQL using the Order By and Where clauses. In fact, sometimes this is the best

approach for performance. However, the sorting and paging provided by the GridView and

SqlDataSource is easy to implement and thoroughly flexible. These techniques are

Page 95: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

93 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

particularly useful if you need to show the same data in several ways and you want to let

the user decide how the data should be ordered.

Sorting

The GridView sorting features allow the user to reorder the results in the GridView by

clicking a column header. It‘s convenient—and easy to implement.

Here‘s how you could define the ProductName column so it sorts by alphabetically ordering

rows:

<asp:BoundField DataField="ProductName" HeaderText="Product Name"

SortExpression="ProductName" />

Selecting Used to select rows from gridview.

Paging

Often, a database search will return too many rows to be realistically displayed in a single

page. If the client is using a slow connection, an extremely large GridView can take a

frustrating amount of time to arrive. Once the data is retrieved, the user may find out it

doesn‘t contain the right content anyway or that the search was too broad and they can‘t

easily wade through all the results to find the important information.

The GridView handles this scenario with an automatic paging feature. When you use

automatic paging, the full results are retrieved from the data source and placed into a

DataSet.

Paging Members of the GridView

Property Description

AllowPaging Enables or disables the paging of the bound records. It is False by default.

PageSize

Gets or sets the number of items to display on a single page of the grid. The

default value is 10.

PageIndex

Gets or sets the zero-based index of the currently displayed page, if paging is

enabled.

PagerSettings

Provides a PagerSettings object that wraps a variety of formatting options for

the pager controls. These options determine where the paging controls are

shown and what text or images they contain. You can set these properties to

fine-tune the appearance of the pager controls, or you can use the defaults.

PagerStyle

Provides a style object you can use to configure fonts, colors, an text alignment

for the paging controls.

Page 96: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

94 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

PageIndexChanging

and Occur when one of the page selection elements is clicked, just

PageIndexChanged

events

before the PageIndex is changed (PageIndexChanging) and just after

(PageIndexChanged).

To use automatic paging, you need to set AllowPaging to True (which shows the page

controls), and you need to set PageSize to determine how many rows are allowed on each

page.

Here‘s an example of a GridView control declaration that sets these properties:

<asp:GridView ID="GridView1" runat="server" DataSourceID="sourceProducts"

PageSize="10" AllowPaging="True" ...>

Data Source and Data-bound Controls Working Together

The SqlDataSource control enables you to quickly create functional, database-driven web

pages. Without writing a whole lot of code, you can create web pages that enable you to

perform all four operations of the CRUD acronym: create, read, update, and delete data.

Create An Application To Insert Update AND Delete Record

Step 1:

Step 2: empty website

Step 3: right click on website in solution exploreradd new itemweb form

Step 4: right click on website in solution exploreradd asp.net folderapp_data

Step5: right click on app_dataadd new itemsql server databasename

testing.mdf

Step6:

Page 97: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

95 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Step7:

Step8:

Step9: add records

Step10:add gridview on asp page and select

Page 98: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

96 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Step11:

Step12:

Connection string = “Data

Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\testing.mdf;Integrate

d Security=True;User Instance=True”

Step13: save connection string

Page 99: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

97 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Step14: select table

Step15:click on advanced button and check the checkbox given below

Step16: nexttest queryfinish

Step17: check checkboxes given in gridview task

Page 100: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

98 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Step18: Drag and drop detailview control

Step19: select SqlDataSource1 which was created previously

Step20: check enable inserting

Code generated behind *.aspx <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs"

Inherits="_Default" %>

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

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

Page 101: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

99 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

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

<head runat="server">

<title></title>

</head>

<body>

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

<div>

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"

AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Emp_Id"

DataSourceID="SqlDataSource1">

<Columns>

<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"

ShowSelectButton="True" />

<asp:BoundField DataField="Emp_Id" HeaderText="Emp_Id" ReadOnly="True"

SortExpression="Emp_Id" />

<asp:BoundField DataField="Emp_Name" HeaderText="Emp_Name"

SortExpression="Emp_Name" />

<asp:BoundField DataField="Emp_Sname" HeaderText="Emp_Sname"

SortExpression="Emp_Sname" />

<asp:BoundField DataField="Off_Id" HeaderText="Off_Id"

SortExpression="Off_Id" />

<asp:BoundField DataField="Emp_Salary" HeaderText="Emp_Salary"

SortExpression="Emp_Salary" />

</Columns>

</asp:GridView>

<asp:SqlDataSource ID="SqlDataSource1" runat="server"

ConnectionString="<%$ ConnectionStrings:ConnectionString %>"

DeleteCommand="DELETE FROM [Employee] WHERE [Emp_Id] = @Emp_Id"

InsertCommand="INSERT INTO [Employee] ([Emp_Id], [Emp_Name], [Emp_Sname],

[Off_Id], [Emp_Salary]) VALUES (@Emp_Id, @Emp_Name, @Emp_Sname, @Off_Id, @Emp_Salary)"

SelectCommand="SELECT * FROM [Employee]"

UpdateCommand="UPDATE [Employee] SET [Emp_Name] = @Emp_Name, [Emp_Sname] =

@Emp_Sname, [Off_Id] = @Off_Id, [Emp_Salary] = @Emp_Salary WHERE [Emp_Id] = @Emp_Id">

<DeleteParameters>

<asp:Parameter Name="Emp_Id" Type="Decimal" />

</DeleteParameters>

<InsertParameters>

<asp:Parameter Name="Emp_Id" Type="Decimal" />

<asp:Parameter Name="Emp_Name" Type="String" />

<asp:Parameter Name="Emp_Sname" Type="String" />

<asp:Parameter Name="Off_Id" Type="Decimal" />

<asp:Parameter Name="Emp_Salary" Type="String" />

</InsertParameters>

<UpdateParameters>

<asp:Parameter Name="Emp_Name" Type="String" />

<asp:Parameter Name="Emp_Sname" Type="String" />

<asp:Parameter Name="Off_Id" Type="Decimal" />

<asp:Parameter Name="Emp_Salary" Type="String" />

<asp:Parameter Name="Emp_Id" Type="Decimal" />

</UpdateParameters>

</asp:SqlDataSource>

<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"

DataKeyNames="Emp_Id" DataSourceID="SqlDataSource1" Height="50px"

Width="125px">

<Fields>

<asp:BoundField DataField="Emp_Id" HeaderText="Emp_Id" ReadOnly="True"

SortExpression="Emp_Id" />

<asp:BoundField DataField="Emp_Name" HeaderText="Emp_Name"

SortExpression="Emp_Name" />

<asp:BoundField DataField="Emp_Sname" HeaderText="Emp_Sname"

SortExpression="Emp_Sname" />

<asp:BoundField DataField="Off_Id" HeaderText="Off_Id"

Page 102: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

100 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

SortExpression="Off_Id" />

<asp:BoundField DataField="Emp_Salary" HeaderText="Emp_Salary"

SortExpression="Emp_Salary" />

<asp:CommandField ShowInsertButton="True" />

</Fields>

</asp:DetailsView>

<br />

</div>

</form>

</body>

</html>

The queries generated in code is executed when and appropriate event is called.

Working with connected data architecture

Code using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Data.SqlClient;

public partial class Default4 : System.Web.UI.Page

{

SqlConnection con = new SqlConnection(@"Data

Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\test12.mdf;Integrated

Security=True;User Instance=True");

SqlCommand cmd = new SqlCommand();

SqlDataReader dr;

Page 103: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

101 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

protected void Page_Load(object sender, EventArgs e)

{

}

protected void Button1_Click(object sender, EventArgs e)

{

cmd.CommandText = "select * from tempemp";

cmd.Connection = con;

con.Open();

dr = cmd.ExecuteReader();

//while (dr.Read())

//{

// Response.Write(dr[0].ToString() + " ---- " + dr[1].ToString()+"<br>");

//}

GridView1.DataSource = dr;

this.DataBind();

con.Close();

}

protected void Button2_Click(object sender, EventArgs e)

{

cmd.CommandText = "insert into tempemp values

("+TextBox1.Text+",'"+TextBox2.Text+"','"+TextBox3.Text+"',"+TextBox4.Text+","+TextBox

5.Text+")";

cmd.Connection = con;

con.Open();

cmd.ExecuteNonQuery();

con.Close();

}

protected void Button3_Click(object sender, EventArgs e)

{

cmd.CommandText = "select * from tempemp where empid = " + TextBox1.Text + "";

cmd.Connection = con;

con.Open();

dr = cmd.ExecuteReader();

dr.Read();

TextBox2.Text = dr[1].ToString();

TextBox3.Text = dr[2].ToString();

TextBox4.Text = dr[3].ToString();

TextBox5.Text = dr[4].ToString();

dr.Close();

con.Close();

}

protected void Button4_Click(object sender, EventArgs e)

{

cmd.CommandText = "update tempemp set empname='" + TextBox2.Text +

"',empsname='" + TextBox3.Text + "',offid=" + TextBox4.Text + ",empsalary=" +

TextBox5.Text + " where empid=" + TextBox1.Text + "";

cmd.Connection = con;

con.Open();

cmd.ExecuteNonQuery();

con.Close();

}

protected void Button5_Click(object sender, EventArgs e)

{

cmd.CommandText = "DELETE FROM TEMPEMP WHERE EMPID = " + TextBox1.Text + "";

cmd.Connection = con;

con.Open();

cmd.ExecuteNonQuery();

Page 104: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

102 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

con.Close();

}

}

Creating User Controls

User controls are added to the site like any other content type: through the Add New Item

dialog box. Similar to pages, you get the option to choose the programming language and

whether you want to place the code in a separate Code Behind file.

Once you add a user control to the site, it is opened in the Document Window automatically.

The first thing you may notice is that a user control doesn‘t have an @ Page directive, but

rather an @ Control directive as shown in this example that uses Code Behind:

<%@ Control Language=‖C#‖ AutoEventWireup=‖true‖ CodeFile=‖WebUserControl.ascx.cs‖

Inherits=‖WebUserControl‖ %>

This marks the file as a user control, so the ASP.NET runtime knows how to deal with it.

Other than that, the directive is identical to a standard ASPX page that doesn‘t use a master

page.

drag drop controls on WebUserControl

now drag drop WebUserControl on Default.aspx

Page 105: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

103 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

LINQ

LINQ enables you to query data from a wide variety of data sources, directly from your

programming code. LINQ is to .NET programming what SQL is to relational databases. With

straightforward, declarative syntax you can query collections for objects that match your

criteria.

LINQ is truly integrated into .NET, giving you a unified way to query data, regardless of

where that data comes from.

LINQ is available in all kinds of projects including web applications, Windows Forms

applications, Console applications, and so on.

To help developers get familiar with LINQ, its syntax is closely modeled after SQL, the most

popular query language for relational databases.

This means that LINQ has keywords such as Select, From, and Where to get data from a data

source.

using System.Linq;

...

string[] authors = new string[] { ―Hanselman, Scott‖, ―Evjen, Bill‖,

―Haack, Phil‖, ―Vieira, Robert‖, ―Spaanjaars, Imar‖ };

var result = from author in authors

where author.Contains(―S‖)

orderby author

select author;

foreach (var author in result)

{

Label1.Text += author + ―<br />‖;

}

LINQ to Objects

This is the purest form of language integration. With LINQ to Objects, you can query

collections in your .NET applications as you saw in the previous example. You‘re not limited

Page 106: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

104 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

to arrays because LINQ enables you to query almost any kind of collection that exists in the

.NET Framework.

LINQ to XML

LINQ to XML is the new .NET way to read and write XML. Instead of typical XML query

languages like XSLT or XPath you can now write LINQ queries that target XML directly in

your application.

LINQ to ADO.NET

ADO.NET is the part of the .NET Framework that enables you to access data and data

services like SQL Server and many other different kinds of data sources. ADO.NET is also

used under the hood by the SqlDataSource control and is commonly used in ―raw data access

code‖; code written in C# or VB.NET that connects to a database without using the

declarative data controls. With LINQ to ADO.NET you can query database-related

information sets, including LINQ to DataSet, LINQ to SQL, and LINQ to Entities.

LINQ to DataSet enables you to write queries against the DataSet, a class that represents an

in memoryversion of a database.

LINQ to SQL enables you to write object-oriented queries in your .NET projects that target

Microsoft SQL Server databases. The LINQ to SQL implementation translates your queries

into SQL statements, which are then sent to the database to perform typical CRUD

operations.

Introducing Query Syntax

Standard Query Operators

LINQ supports a large number of query operators — keywords that enable you to select,

order, or filter data that is to be returned from the query.

Select

var allReviews = from r in myEntities.Reviews

select r;

The r variable in this example is referred to as a range variable that is only available within

the current query. You typically introduce the range variable in the From clause, and then

use it again in the Where and Select clauses to filter the data, and to indicate the data you

want to select. Although you can choose any name you like, you often see single letter

variables like the r (for Review) or you see the singular form of the collection you are

querying (review instead of r in the preceding examples).

From

Page 107: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

105 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Although not considered a standard query operator — because it doesn‘t operate on the

data but rather points to the data — the From clause (from in C#) is an important element in a

LINQ query, because it defines the collection or data source that the query must act upon.

In the previous example, the From clause indicates that the query must be executed against

the Reviews collection that is exposed by the myEntities object in EF.

Order By

var allGenres = from g in myEntities.Genres

orderby g.SortOrder descending, g.Name

select g;

Order By is followed by an optional Ascending or Descending (ascending

and descending in C#) keyword to specify sort order.

Where

enables you to filter the objects returned by the query

var allReviews = from r in myEntities.Reviews

where r.Authorized == true

select r;

Sum, Min, Max, Average, and Count

var numberOfReviews = (from r in myEntities.Reviews select r).Count();

Shaping Data with Anonymous Types

var allReviews = from review in myEntities.Reviews

where review.Authorized == true

select new { review.Id, review.Title, review.Genre.Name };

Page 108: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

106 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Creating an anonymous type is easy; instead of selecting the actual object using something

like Select review, you use the new keyword in C# and New With in Visual Basic and then

define the properties you want to select between a pair of curly braces:

Although the type is anonymous and cannot be accessed by name directly, the compiler is

still able to infer the type, giving you full IntelliSense for the new properties that were

selected in the query.

Using Server Controls with LINQ Queries

First of all, this method does not support the editing, updating, and deleting of data directly.

Secondly, because you define the data source in the Code Behind, the GridView doesn‘t know

what data you‘re feeding it until runtime, so you get no tool support to set up its columns.

These shortcomings are easy to overcome by using the new server controls, including the

ListView and the EntityDataSource control.

Using Data Controls with the Entity Framework

Two of these controls provide a visual interface in your ASP.NET pages, and the third one

works as a bridge between your data-bound controls and your underlying data sources.

Control desCription

EntityDataSource As with the SqlDataSource that you saw in previous chapters, the

EntityDataSource works as a bridge between your data-bound controls

and the underlying data source: EF in this case.

ListView The ListView control provides a visual interface that enables you to

display, insert, edit, and delete items in a database, providing full CRUD

services.

DataPager The DataPageris used together with the ListViewand enables you to

paginate the data in the data source, feeding data to users in bite-sized

chunks instead of all records at once.

Page 109: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

107 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

unit 4

Caching ASP.NET applications are a bit of a contradiction. On the one hand, because they‘re hosted

over the Internet, they have unique requirements—namely, they need to be able to serve

hundreds of clients as easily and quickly as they deal with a single user.

On the other hand, ASP.NET includes some remarkable tricks that let you design and code a

web application in the same way you program a desktop application. These tricks are useful,

but they can lead developers into trouble. The problem is that ASP.NET makes it easy to

forget you‘re creating a web application—so easy, that you might introduce programming

practices that will slow or cripple your application when it‘s used by a large number of users

in the real world.

Fortunately, a middle ground exists. You can use the incredible timesaving features such as

view state, web controls, and session state.

But to finish the job properly, you‘ll need to invest a little extra time to profile and optimize

your website‘s performance. One of the easiest ways to improve perform is to use caching,

a technique that temporarily stores valuable information in server memory so it can be

reused.

caching includes some built-in features that ensure good performance.

Caching is often used to store information that‘s retrieved from a database. This makes

sense—after all, retrieving information from a database takes time. With careful

optimization, you can reduce the time and lessen the burden imposed on the database to a

certain extent, but you can never eliminate it.

Of course, storing information in memory isn‘t always a good idea. Server memory is a

limited resource; if you try to store too much, some of that information will be paged to

disk, potentially slowing down the entire system. That‘s why ASP.NET caching is self-

limiting.

When to Use Caching The secret to getting the most out of caching is choosing the right time to use it. A good

caching strategy identifies the most frequently used pieces of data that are the most time-

consuming to create, and stores them.

Here are two caching guidelines to keep you on the right track:

Page 110: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

108 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Cache data (or web pages) that are expensive: In other words, cache information

that‘s time-consuming to create.

Cache data (or web pages) that are used frequently: There‘s no point setting aside

memory for information that‘s never going to be needed again. But it makes more sense to

cache the list of product categories, because that information will be reused to serve many

different requests.

If you keep these two rules in mind, you can get two benefits from caching at

once—you can improve both performance and scalability.

Performance is a measure of how quickly a web page works for a single user. Caching

improves performance, because it bypasses bottlenecks like the database. As a result, web

pages are processed and sent back to the client more quickly.

Scalability measures how the performance of your web application degrades as more and

more people use it at the same time. Caching improves scalability, because it allows you to

reuse the same information for requests that happen in quick succession.

Caching in ASP.NET ASP.NET really has two types of caching. Your applications can and should use both

types,because they complement each other:

• Output caching: This is the simplest type of caching. It stores a copy of the final

rendered HTML page that is sent to the client. The next client that submits a request for this

page doesn‘t actually run the page. Instead, the final HTML output is sent automatically.

The time that would have been required to run the page and its code is completely

reclaimed.

• Data caching: This is carried out manually in your code. To use data caching, you store

important pieces of information that are time-consuming to reconstruct (such as a DataSet

retrieved from a database) in the cache. Other pages can check for the existence of this

information and use it, thereby bypassing the steps ordinarily required to retrieve it. Data

caching is conceptually the same as using application state, but it‘s much more

serverfriendly because items will be removed from the cache automatically when it grows

too large and performance could be affected. Items can also be set to expire automatically.

Also, two specialized types of caching build on these models:

• Fragment caching: This is a specialized type of output caching—instead of caching the

HTML for the whole page, it allows you to cache the HTML for a portion of it. Fragment

caching works by storing the rendered HTML output of a user control on a page. The next

time the page is executed, the same page events fire (and so your page code will still run),

but the code for the appropriate user control isn‘t executed.

Page 111: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

109 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

• Data source caching: This is the caching that‘s built into the data source controls,

including the SqlDataSource, ObjectDataSource, and XmlDataSource. Technically, data

source caching uses data caching. The difference is that you don‘t need to handle the

process explicitly. Instead, you simply configure the appropriate properties, and the data

source control manages the caching storage and retrieval.

Output Caching

With output caching, the final rendered HTML of the page is cached. When the same page is requested

again, the control objects are not created, the page life cycle doesn’t start, and none of your code

executes. Instead, the cached HTML is served.

public partial class OutputCaching : System.Web.UI.Page { protected void Page_Load(object sender, System.EventArgs e) { lblDate.Text = "The time is now:<br />"; lblDate.Text += DateTime.Now.ToString(); } public OutputCaching() { Load += Page_Load; } }

You can cache an ASP.NET page in two ways. The most common approach is to insert the

OutputCache directive at the top of your .aspx file, just below the Page directive, as shown

here:

<%@ OutputCache Duration="20" VaryByParam="None" %>

The Duration attribute instructs ASP.NET to cache the page for 20 seconds. The

VaryByParam attribute is also required.

When you run the test page, you‘ll discover some interesting behavior. The first time you

access the page, you will see the current time displayed. If you refresh the page a short

time later, however, the page will not be updated. Instead, ASP.NET will automatically send

the cached HTML output to you, until it expires in 20 seconds. If ASP.NET receives a request

after the cached page has expired, ASP.NET will run the page code again, generate a new

cached copy of the HTML output, and use that for the next 20 seconds.

Caching on the Client Side

Another option is to cache the page exclusively on the client side. In this case, the browser

stores a copy and will automatically use this page if the client browses back to the page or

retypes the page‘s URL.

Page 112: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

110 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

<%@ OutputCache Duration="20" VaryByParam="None" Location="Client" %>

Data Caching Data caching is the most flexible type of caching, but it also forces you to take specific

additional steps in your code to implement it. The basic principle of data caching is that you

add items that are expensive to create to a built-in collection object called Cache. Cache is a

property of the Page class, and it returns an instance of the System.Web.Caching.Cache

class.

This object works much like the Application object It’s globally available to all

requests from all clients in the application. But it has three key differences:

The Cache object is thread-safe: This means you don‘t need to explicitly lock or unlock

the Cache object before adding or removing an item. However, the objects in the Cache

object will still need to be thread-safe themselves.

Items in the Cache object are removed automatically: ASP.NET will remove an item if

it expires, if one of the objects or files it depends on changes, or if the server becomes low

on memory. This means you can freely use the cache without worrying about wasting

valuable server memory, because ASP.NET will remove items as needed.

Items in the cache support dependencies: You can link a cached object to a file, a

database table, or another type of resource. If this resource changes, your cached object is

automatically deemed invalid and released.

Adding Items to the Cache You can insert an object into the cache in several ways. You can simply assign it to a new

key name (as you would with the Session or Application collection):

Cache["KeyName"] = objectToCache;

However, this approach is generally discouraged because it doesn‘t give you any control

over the amount of time the object will be retained in the cache. A better approach is to use

the Insert() method.

The Insert() method has four overloaded versions. The most useful one requires five

parameters:

Cache.Insert(key, item, dependencies, absoluteExpiration, slidingExpiration);

Cache.Insert() Parameters

Page 113: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

111 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Parameter Description

key A string that assigns a name to this cached item in the collection and

allows you to look it up later.

item The actual object you want to cache.

dependencies A CacheDependency object that allows you to create a dependency for

this item in the cache. If you don‘t want to create a dependent item,

just specify a null reference (Nothing) for this parameter.

absoluteExpiratio

n

A DateTime object representing the date and time at which the item

will be removed from the cache.

slidingExpiration A TimeSpan object representing how long ASP.NET will wait between

requests before removing a cached item. For example, if this value is

20 minutes, ASP.NET will evict the item if it isn‘t used by any code for

a 20-minute period.

Typically, you won‘t use all of these parameters at once. Cache dependencies, for example,

are a special tool you‘ll consider a little later in the ―Caching with Dependencies‖ section.

Also, you cannot set both a sliding expiration and an absolute expiration policy at the same

time. If you want to use an absolute expiration, set the slidingExpiration parameter to

TimeSpan.Zero:

Cache.Insert("MyItem", obj, Nothing, DateTime.Now.AddMinutes(60), TimeSpan.Zero);

Absolute expirations are best when you know the information in a given item can be

considered valid only for a specific amount of time (such as a stock chart or a weather

report). Sliding expiration, on the other hand, is more useful when you know that a cached

item will always remain valid (such as with historical data or a product catalog) but should

still be allowed to expire if it isn‘t being used. To set a sliding expiration policy, set the

absoluteExpiration parameter to DateTime.MaxValue, as shown here:

Cache.Insert("MyItem", obj, Nothing, DateTime.MaxValue, TimeSpan.FromMinutes(10));

Determining Security Requirements

The first step in securing your applications is deciding where you need security and what it

needs to protect. For example, you may need to block access in order to protect private

information. Or, maybe you just need to enforce a pay-for-content system. Perhaps you

don‘t need any sort of security at all, but you want an optional login feature to provide

personalization for frequent visitors. These requirements will determine the approach you

use. Security doesn‘t need to be complex, but it does need to be wide-ranging and

multilayered.

You probably already know the first line of defense that this website should use—a login

page that forces users to identify themselves before they can see any personal information.

Page 114: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

112 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

However, it‘s important to realize that, on its own, this layer of protection is not enough to

truly secure your system. You also need to protect the back-end database with a strong

password, and you might even choose to encrypt sensitive information before you store it

(scrambling so that it‘s unreadable without the right key to decrypt it).

The ASP.NET Security Model web requests are fielded first by the IIS web server, which examines the file type. If the file

type is registered to ASP.NET, the web server passes the request to ASP.NET.

IIS and ASP.NET interaction

You can apply security at several places in this chain. First, consider the process for an

ordinary (non-ASP.NET) web page request:

1. IIS attempts to authenticate the user. Generally, IIS allows requests from all anonymous

users and automatically logs them in under the IUSR_[ComputerName] account. IIS

security settings are configured on a per-directory basis. (On Windows Vista, this account is

simply named IUSR.)

2. If IIS authenticates the user successfully, it attempts to send the user the appropriate

HTML file. The operating system performs its own security checks to verify that the

authenticated user (typically IUSR) is allowed access to the specified file and directory.

An ASP.NET request requires several additional step as shown in figure. The first and last

steps are similar, but the process has intermediary layers:

Page 115: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

113 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Authenticating a request

Page 116: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

114 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

1. IIS attempts to authenticate the user. Generally, IIS allows requests from all anonymous

users and automatically logs them in under the IUSR account.

2. If IIS authenticates the user successfully, it passes the request to ASP.NET with

additional information about the authenticated user. ASP.NET can then use its own security

services, depending on the settings in the web.config file and the page that was requested.

3. If ASP.NET authenticates the user, it allows requests to the .aspx page or .asmx web

service. Your code can perform additional custom security checks (for example, manually

asking for another password before allowing a specific operation).

4. When the ASP.NET code requests resources (for example, tries to open a file or connect

to a database), the operating system performs its own security checks. In a live website,

ASP.NET code runs under a fixed account. This account is defined in the machine.config file

(if you‘re running IIS 5) or in IIS Manager (if you‘re running IIS 6 or IIS 7). As your code

performs various actions, Windows checks to make sure the account has the required

permissions.

One important and easily missed concept is that the ASP.NET code doesn‘t run under the

IUSR account, even if you‘re using anonymous user access. The reason is the IUSR account

doesn‘t have sufficient privileges for ASP.NET code, which needs to be able to create and

delete temporary files in order to manage the compilation process. Instead, the ASP.NET

account is set through the machine.config file

The Visual Studio Web Server

So far, this discussion assumes you‘re using IIS, which is what all live ASP.NET websites

use. However, IIS isn‘t involved when you test a web application using the integrated web

server in isual Studio. Instead, the Visual Studio web server plays the same role.

Conceptually, the Visual Studio web server works in the same way as the IIS web server.

For example, it handles requests for different types of files (such as HTML pages and

ASP.NET web forms) and passes requests on to ASP.NET when required. However, the

security model is simplified. Because the Visual Studio web server is designed to be used by

one person at a time—the current user of the local computer—it doesn‘t support anonymous

access. Instead, every time you run the Visual Studio web server it logs you on

automatically, using your current Windows identity. As a result, your web page code runs

with the permissions of your Windows user account.

RESTRICTED FILE TYPES

ASP.NET automatically provides a basic level of security by blocking requests for certain file

types (such as configuration and source code files). To accomplish this, ASP.NET registers

the file types with IIS but specifically assigns them to the HttpForbiddenHandler class. This

class has a single role in life—it denies every request it receives.

Page 117: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

115 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

.asax, .ascx, .config, .vb., .vbproj, .cs, .csproj, .resx, .resources

Authentication and Authorization Two concepts form the basis of any discussion about security:

Authentication: This is the process of determining a user‘s identity and forcing users to

prove they are who they claim to be. Usually, this involves entering credentials (typically a

user name and password) into some sort of login page or window.

Authorization: Once a user is authenticated, authorization is the process of determining

whether that user has sufficient permissions to perform a given action (such as viewing a

page or retrieving information from a database).

Authentication and authorization are the two cornerstones of creating a secure userbased

site. The Windows operating system provides a good analogy. When you first boot up your

computer, you supply a user ID and password, thereby authenticating yourself to the

system. After that point, every time you interact with a restricted resource (such as a file,

database, registry key, and so on), Windows quietly performs authorization checks to

ensure your user account has the necessary rights.

You can use two types of authentication to secure an ASP.NET website: Forms authentication: With forms authentication, IIS is configured to allow anonymous

users (which is its default setting). However, you use ASP.NET‘s forms authentication model

to secure parts of your site. This allows you to create a subscription site or e-commerce

store. You can manage the login process easily, and write your own login code for

authenticating

users against a database or simple user account list.

Windows authentication: With Windows authentication, IIS forces every user to log in as a

Windows user. (Depending on the specific configuration you use, this login process may

take place automatically, as it does in the Visual Studio test web server, or it may require

that the user type a name and password into a Login dialog box.)

Forms Authentication

In traditional ASP programming developers often had to create their own security systems.

A common approach was to insert a little snippet of code at the beginning of every secure

page. This code would check for the existence of a custom cookie. If the cookie didn‘t exist,

the user would be redirected to a login page, where the cookie would be created after a

successful login.

ASP.NET uses the same approach in its forms authentication model. You are still responsible

for creating the login page. However, you don‘t need to create the security cookie manually,

or check for it in secure pages, because ASP.NET handles these tasks automatically. You

Page 118: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

116 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

also benefit from ASP.NET‘s support for sophisticated validation algorithms, which make it

all but impossible for users to spoof their own cookies or try other hacking tricks to fool your

application into giving them access.

To implement forms-based security, you need to follow three steps:

1. Set the authentication mode to forms authentication in the web.config file (or use

the WAT).

2. Restrict anonymous users from a specific page or directory in your application.

3. Create the login page.

ASP.NET forms authentication

Using login control

Once you‘ve restricted access to some or all of the pages of your web application, you need

to allow users with the proper permissions to log in and access the restricted pages. In

addition, you may want to provide other features such as allowing users to log out, to

Page 119: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

117 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

create an account by themselves, to recover a forgotten password, or to change a

password. You can use the controls in the Login group of the Toolbox to automatically

handle these tasks.

AJAX in ASP.NET

Ajax: The Good The key benefit of Ajax is responsiveness. An Ajax application, when done properly,

provides a better experience for the user. Even if the user can‘t do anything new (or do

anything faster), this improved experience can make your web application seem more

modern and sophisticated.

If you‘re creating a website that‘s competing against other similar sites, you just might find

that Ajax allows you to distinguish your work from the rest of the pack. Ajax can also

provide genuinely new features that aren‘t possible in traditional web pages. For example,

Ajax pages often use JavaScript code that reacts to client-side events like mouse

movements and key presses. These events occur frequently, so it‘s not practical to deal with

Page 120: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

118 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

them using the postback model. For example, imagine you want to highlight a TextBox

when the user moves the mouse over it. With the postback approach, you‘d need to send

the entire page back to the web server, regenerate it, and refresh it in the browser—by

which point themouse might be somewhere completely different. This approach is clearly

impractical. However, an Ajax page can deal with this scenario because it can react

immediately, updating the page if needed or requesting additional information from the web

server in the background.

Ajax: The Bad

There are two key challenges to using Ajax. The first is complexity. Writing the JavaScript

code needed to implement an Ajax application is a major feat.

The other challenge to using Ajax is browser support. The technology that supports Ajax has

existed for several years, but it‘s only now found consistently in all major browsers.

The ASP.NET AJAX Toolkit

There are a variety of ways to implement Ajax in any web application, including ASP.NET.

To implement it on your own, you need to have a thorough understanding of JavaScript,

because it‘s JavaScript code that runs in the browser, requesting the new information from

the web server when needed and updating the page accordingly. Although JavaScript isn‘t

terribly complex, it‘s remarkably difficult to program correctly, for two reasons:

• The implementation of key JavaScript details varies from browser to browser, which

means you need a tremendous amount of experience to write a solid web page that runs

equally well on all browsers.

• JavaScript is a notoriously loose language that tolerates many minor typos and mistakes.

Catching these mistakes and removing them is a tedious process. Even worse, the mistakes

might be fatal on some browsers and harmless in others, which complicates debugging.

The ScriptManager

In order to use ASP.NET AJAX, you need to place a new web control on your page. This

control

is the ScriptManager, and it‘s the brains of ASP.NET AJAX.

Like all ASP.NET AJAX controls, the ScriptManager is placed on a Toolbox tab named AJAX

Extensions. When you can drag the ScriptManager onto your page, you‘ll end up with this

declaration:

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

Page 121: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

119 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

At design time, the ScriptManager appears as a blank gray box. But when you request a

page that uses the ScriptManager you won‘t see anything, because the ScriptManager

doesn‘t generate any HTML tags. Instead, the ScriptManager performs a different task—it

adds the links to the ASP.NET AJAX JavaScript libraries. It does that by inserting a script

block that looks something like this:

<script src="/YourWebSite/ScriptResource.axd?d=RUSU1mI ..."

type="text/javascript">

</script>

This script block doesn‘t contain any code. Instead, it uses the src attribute to pull the

JavaScript code out of a separate file. However, the ScriptManager is a bit craftier than you

might expect. Rather than use a separate file to get its JavaScript.

Now that you’ve taken a brief overview of Ajax, it’s time to start building Ajax-enabled pages.

• Using partial refreshes to avoid full-page postbacks and page flicker

• Using progress notifications to deal with slower updates

• Using timed refreshes to automatically update a portion of your page

• Using the ASP.NET AJAX Control Toolkit to get a range of slick new controls with Ajax

features

Partial Refreshes The key technique in an Ajax web application is partial refreshes. With partial refreshes, the

entire page doesn‘t need to be posted back and refreshed in the browser. Instead, when

something happens the web page asks the web server for more information. The request

takes place in the background, so the web page remains responsive.

ASP.NET includes a handy control that lets you take an ordinary page with server-side logic

and make sure it refreshes itself in flicker-free Ajax style using partial updates. This control

is the UpdatePanel.

The basic idea is that you divide your web page into one or more distinct regions, each of

which is wrapped inside an invisible UpdatePanel. When an event occurs in a control that‘s

located inside an UpdatePanel, and this event would normally trigger a full-page postback,

the UpdatePanel intercepts the event and performs an asynchronous callback instead.

how it happens:

1. The user clicks a button inside an UpdatePanel.

2. The UpdatePanel intercepts the client-side click. Now, ASP.NET AJAX performs a callback

to the server instead of a full-page postback.

Page 122: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

120 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

3. On the server, your normal page life cycle executes, with all the usual events. Finally, the

page is rendered to HTML and returned to the browser.

4. ASP.NET AJAX receives the full HTML and updates every UpdatePanel on the page by

replacing its current HTML with the new content. (If a change has occurred to content that‘s

not inside an UpdatePanel, it‘s ignored.)

Triggers

The UpdatePanel watches its child controls and intercepts any events that could trigger a

postback. The TextBox.TextChanged and ListBox.SelectedItemChanged events also trigger a

postback, because these controls set the AutoPostBack property to True. Thus, these events

are also intercepted by the UpdatePanel.

Page 123: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

121 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Because the entire page is wrapped in the UpdatePanel, the HTML for the entire page is

refreshed. A better option is to wrap just the label and image that represents the greeting

card in the UpdatePanel.

Unfortunately, this won‘t work. Once you move the other controls out of the UpdatePanel,

their events won‘t be intercepted any longer, and they‘ll trigger full-page postbacks with the

familiar flicker.

The solution is to explicitly tell the UpdatePanel to monitor those controls, even though they

aren‘t inside the UpdatePanel. You can do this by adding triggers to the UpdatePanel. You

add one trigger for each button.

<asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager>

<asp:UpdatePanel ID="UpdatePanel1" runat="server">

<ContentTemplate>

<asp:Panel ID="pnlCard" runat="server" ... >

</asp:Panel>

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTrigger ControlID="lstBackColor" />

<asp:AsyncPostBackTrigger ControlID="lstForeColor" />

</Triggers>

</asp:UpdatePanel>

These triggers tell the UpdatePanel to intercept the default event in these seven controls.

(You could specify the event you want to monitor by setting the EventName property of the

trigger, but you don‘t need to, because you‘re using the most commonly used default event

for each one.) As a result, the page works the same as it did before—it just refreshes a

smaller portion of the page after each asynchronous request.

Technically, the UpdatePanel always uses triggers. All the controls inside an UpdatePanel

automatically become the triggers for the UpdatePanel.

Timed Refreshes In some situations, you might want to force a full or partial page refresh without waiting for

a user action. For example, you might create a page that includes a stock ticker, and you

might want to refresh this ticker periodically (say, every 5 minutes) to ensure it doesn‘t

become drastically outdated. ASP.NET includes a Timer control that allows you to implement

this design easily.

The Timer control is refreshingly straightforward. You simply add it to a page and set its

Interval property to the maximum number of milliseconds that should elapse before an

Page 124: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

122 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

update. For example, if you set Interval to 60000, the timer will force a postback after one

minute elapses.

<asp:Timer ID="Timer1" runat="server" Interval="60000" />

The timer also raises a server-side Tick event, which you can handle to update your page.

<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional">

<ContentTemplate>

...

</ContentTemplate>

<Triggers>

<asp:AsyncPostBackTrigger ControlID="Timer1" EventName="Tick" />

</Triggers>

</asp:UpdatePanel>

ASP.NET Web Services An ASP.NET web service is a program capable of communicating across a network such as

the Internet by using a combination of the open standard SOAP and XML technologies.

(Note that SOAP was previously known as the Simple Object Access Protocol.)

Web services are ideal for creating data-, content-, or processing-related services that can

be made available to associated or third-party applications and clients across distributed

networks such as the Internet.

In this chapter, you will see how to create a simple ASP.NET web service and a client

application to consume, or use, the web service.

In addition, this chapter covers the technologies associated with ASP.NET web services,

such as SOAP and theWeb Services Description Language (WSDL). The chapter briefly

coversMicrosoft‘s latest addition to the web service stable — the Windows Communication

Foundation (WCF) — and you will see how to use Asynchronous JavaScript and XML (AJAX)

technology to create seamless interactions between web services and their consuming

applications.

In this chapter, you‘ll learn how to do the following:

◆ Create a simple ASP.NET web service

◆ Consume an ASP.NET web service

◆ Work with AJAX technologies

Using ASP.NETWeb Services and WCF

Microsoft offers two flavors of web service technology:

Page 125: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

123 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

◆ ASP.NET web services

◆ Windows Communication Foundation (WCF)

ASP.NET web services (also known as XML web services) have been around through all the

incarnations of ASP.NET and offer a simple and effective methodology for making software components

and other resources available over the Internet.

WCF is a recent inclusion into the .NET Framework and is built around the web services architecture.

WCF enables broader integration and interoperability with all the .NET Framework distributed system

technologies, including Microsoft Message Queuing (MSMQ), Common Object Model plus (COM+),

ASP.NET web services, and .NET Framework Remoting. WCF also offers improved performance and

secure data transmission.

ASP.NET Web Services

ASP.NET web services are software resources and components that are able to expose their

functionality and/or deliver data over a network such as the Internet by using a combination

of XML and SOAP. You can restrict a component to be available to only certain applications

or specific users, or you can make it available to many users. The component can be limited

to the local computer or the local network, or made available across the Internet. Services

can be delivered free of charge or on a fee-paying basis.

Virtually any program that can be encapsulated as a component can be expressed as an

ASP.NET web service. For production purposes, you will need a web server to deliver your

ASP.NET web service. However, for development purposes, the built-in ASP.NET

Development Server that ships with Visual Studio 2008 is quite sufficient.

The process of using an ASP.NET web service or incorporating a web service into your client

is called consuming an ASP.NET web service.

The advantages of using ASP.NET web services include the following:

◆ Data and commands are communicated across the standard Internet port: port 80. This greatly

simplifies passage around the Internet and most networks.

◆ The common standards of XML and SOAP are widely supported.

◆ Early problems with web services, such as lack of a robust security model, have been resolved.

◆ Visual Studio provides a simple and straightforward environment in which to create and consume web

services.

Page 126: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

124 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

Windows Communication Foundation (WCF) WCF is built on ASP.NET web services and extends their functionality by integrating with a

number of distributed .NET Framework technologies. WCF offers an integrated approach to

situations inwhich youwould previously have employed a range of different distributed .NET

Framework technologies. Typically, you use WCF as a unified solution enabling you to avoid

having to employ different distributed technologies for each requirement of a distributed

application. For example, you may have employed message queuing for use with portable

devices that are not permanently connected, ASP.NET web services for communication

across the Internet, and .NET Framework Remoting for tightly coupled communication

within the local network. Employing multiple technologies in this manner results in a

complex and potentially unwieldy solution. WCF offers a method of achieving a simpler

unified approach.

However, despite its advantages in simplifying complex situations, WCF remains a complex

technology that requires a significant amount of work even to produce a simple Hello

World–style application. Because of the complexity of WCF, this chapter focuses primarily on

building and working with ASP.NET web services.

Understanding Technologies Associated with WebServices

Several technologies underlie and support ASP.NET web services. They include SOAP,

WSDL, SOAP Discovery, and Universal Description, Discovery, and Integration (UDDI).

SOAP

SOAP was originally known as the Simple Object Access Protocol. This was changed by the World Wide

Web Consortium (W3C) with version 1.2 of the standard in 2003 because the original acronym was

believed to be misleading.

SOAP is a lightweight protocol for exchanging XML messages over Hypertext Transfer Protocol/Secure

Hypertext Transfer Protocol (HTTP/HTTPS). It forms the basis of the web services stack, which is the set

of protocols used to define, locate, and deliver web services. SOAP is an open standard, enabling web

services to be developed and supported across a range of platforms and environments.

There are other services attached to SOAP, including WSDL and SOAP Discovery. Although you are no

longer required to work directly with SOAP when developing ASP.NET web services in Visual Studio, you

will still continue to encounter references to the protocol because it underlies the whole web service

creation, delivery, and consumption process. A SOAP tutorial can be found at

www.w3schools.com/soap/.

Web Services Description Language (WSDL)

WSDL is the language used to create an XML document that describes a web service.

Specifically, the document describes the location of the service and the methods exposed by

Page 127: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

125 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55

the service. You can create and edit WSDL documents directly by using a text editor, but

they can usually be generated automatically by Visual Studio when you add either a web

reference or service reference to your ASP.NET web service. For further information, see the

‗‗Adding a Web Reference‘‘ section later in this chapter. A WSDL tutorial can be found at

www.w3schools.com/wsdl/default.asp.

SOAP Discovery

SOAP Discovery is used to locate theWSDL documents that provide the descriptions for

ASP.NET web services. You use SOAP Discovery when you want to make your web service

publicly available for consumption by third-party applications. For example, you may be

providing a weather service for third-party providers to incorporate into their websites.

There are two types of discovery:

static discovery and dynamic discovery.

In the case of static discovery, an XML document with the .DISCO file extension is used.

This file contains information about the location of the WSDL documents.

If you wish to enable dynamic discovery for your website, you add a specific reference into

the Web.config file. Dynamic discovery enables users to discover all web services and

discovery files beneath the requested URL.

Discovery files (and particularly dynamic discovery) can be a security risk on a production

server because they potentially allow users to search the entire directory tree. Static

discovery files are the safer of the two types because they allow the user to search only

those resources that you choose to nominate. In Visual Studio 2008, you can explicitly

generate a static discovery file by adding a web reference or a service reference. (See

‗‗Adding aWeb Reference‘‘ later in this chapter for more information on creating discovery

files and enabling dynamic discovery.)

Universal Description, Discovery, and Integration (UDDI)

UDDI was originally created as part of the web service specification to act as a form of

yellow pages for web services. Several major players in developing the web services

specification (including Microsoft, IBM, SAP, and OASIS) combined to develop an XML-based

registry for businesses to promote themselves and their web services to both the public

and the corporate world. In 2006, Microsoft, IBM, and SAP closed their public UDDI nodes.

However, you can still create UDDI servers on your local network to provide directory

services for web services available within your network. More information on configuring

Microsoft server technology for UDDI can be found at

www.microsoft.com/windowsserver2003/technologies/idm/uddi/default.mspx. More

information on UDDI can be found at http://uddi.xml.org.

Page 128: Tycs sem 5 asp.net notes unit 1 2 3 4 (2017)

TYBSC-CS (ASP.NET NOTES) SEM 5 (2017)

126 WEIT TUTORIALS CLASSES FOR BSC-IT AND BSC-CS, 302 PARANJPE UDYOG BHAVAN, ABOVE

KHANDELWAL SWEETS, THANE STATION ROAD WEST (400601) PH:8097071144/55