176
1 | Page KnackHook Knowledge Holder [email protected] www.knackhook.com ASP.NET

ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder [email protected]

  • Upload
    others

  • View
    0

  • Download
    0

Embed Size (px)

Citation preview

Page 1: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

1 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ASP.NET

Page 2: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

2 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Table of Contents

1. Introduction of HTML: ......................................................................................... 6

2. HTML Versions: ................................................................................................... 7

3. HTML tags/Elements ........................................................................................... 8

4. HTML 5 Tags ...................................................................................................... 13

HTML Audio Tag ............................................................................................................................. 13

HTML Video Tag ............................................................................................................................. 14

HTML Progress Tag ........................................................................................................................ 14

HTML Meter Tag ............................................................................................................................ 14

HTML Data Tag ............................................................................................................................... 15

HTML Datalist Tag .......................................................................................................................... 15

HTML Header Tag........................................................................................................................... 16

HTML Footer Tag ............................................................................................................................ 17

HTML figure tag ............................................................................................................................. 18

HTML figcaption tag ....................................................................................................................... 18

HTML Article Tag ............................................................................................................................ 19

Narendra Modi ............................................................................................................................... 20

HTML Aside Tag ............................................................................................................................. 20

HTML Dialog Tag ............................................................................................................................ 20

HTML Details Tag ........................................................................................................................... 21

HTML Summary Tag ....................................................................................................................... 22

HTML Section Tag .......................................................................................................................... 23

HTML Time Tag .............................................................................................................................. 24

HTML Main Tag .............................................................................................................................. 24

HTML Wbr Tag ............................................................................................................................... 25

HTML Canvas Tag ........................................................................................................................... 26

HTML SVG ...................................................................................................................................... 27

HTML Drag and Drop ..................................................................................................................... 28

Page 3: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

3 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

5. CSS (Cascading Style Sheets) .............................................................................. 29

Inline CSS ........................................................................................................................................ 29

Internal CSS .................................................................................................................................... 29

External CSS ................................................................................................................................... 30

6. About .Net? ....................................................................................................... 30

7. About .Net Framework ...................................................................................... 31

8. About Common Language Runtime (CLR) and its Services? ........................................................................................................... 35

9. What is managed code in .Net? ......................................................................... 36

10. What is unmanaged code in .Net? ..................................................................... 37

11. About Common Type System? ........................................................................... 37

12. About Common Language Specification? ........................................................... 37

13. About Framework Class Library?........................................................................ 38

14. About Visual Studio? ......................................................................................... 38

15. Asp.Net Overview ............................................................................................. 42

16. About ASP.NET Benifits? .................................................................................... 43

17. About ASP.NET Page Execution? ........................................................................ 43

18. What is a round trip? ......................................................................................... 45

19. About base componens of ASP.NET? ................................................................. 45

20. What is an ASP.NET Web Form? ........................................................................ 45

21. What are the advantages of the code-behind feature? ............................................................................................................ 46

22. In Page Vs Code Behind ..................................................................................... 46

23. ASP.NET - Life Cycle ........................................................................................... 48

ASP.NET Application Life Cycle ...................................................................................................... 48

ASP.NET Page Life Cycle ................................................................................................................. 49

The page life cycle phases are ....................................................................................................... 49

Following are the different stages of an ASP.NET page ................................................................. 49

Page 4: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

4 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ASP.NET Page Life Cycle Events ..................................................................................................... 50

Following are the page life cycle events ........................................................................................ 50

24. ASP.NET – Directives ......................................................................................... 54

The Application Directive ............................................................................................................... 55

The Assembly Directive .................................................................................................................. 55

The Control Directive ..................................................................................................................... 56

The Implements Directive .............................................................................................................. 57

The Import Directive ...................................................................................................................... 57

The Master Directive...................................................................................................................... 58

The MasterType Directive .............................................................................................................. 58

The OutputCache Directive ............................................................................................................ 58

The Page Directive ......................................................................................................................... 58

The PreviousPageType Directive.................................................................................................... 60

The Reference Directive ................................................................................................................. 61

The Register Directive .................................................................................................................... 61

25. ASP.NET Controls............................................................................................... 62

Button Controls .............................................................................................................................. 62

Text Boxes and Labels .................................................................................................................... 63

Check Boxes and Radio Buttons ..................................................................................................... 65

List Controls ................................................................................................................................... 66

The ListItemCollection ................................................................................................................... 68

Radio Button list and Check Box list .............................................................................................. 70

Bulleted lists and Numbered lists: ................................................................................................. 71

HyperLink Control .......................................................................................................................... 72

Image Control ................................................................................................................................ 72

Validation controls ......................................................................................................................... 73

26. Themes and skins .............................................................................................. 93

27. Master Pages ..................................................................................................... 97

28. About User Control? .......................................................................................... 99

29. State Management .......................................................................................... 101

View State .................................................................................................................................... 101

Page 5: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

5 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Query String ................................................................................................................................. 107

Hidden Fields................................................................................................................................ 110

Cookies ......................................................................................................................................... 112

Session State ................................................................................................................................ 115

Application State .......................................................................................................................... 122

Cache ............................................................................................................................................ 124

Profile ........................................................................................................................................... 126

Context.Items ............................................................................................................................... 130

30. Cache Management ......................................................................................... 131

31. ADO.NET ......................................................................................................... 138

DataSet ......................................................................................................................................... 139

DataTable ..................................................................................................................................... 145

DataRow ....................................................................................................................................... 147

DataAdapter ................................................................................................................................. 148

DataReader .................................................................................................................................. 148

SqlCommand and SqlConnection ................................................................................................. 148

32. Machine.config Vs web.config ......................................................................... 154

ASP.NET – Configuration .............................................................................................................. 155

Configuration Section Handler declarations ................................................................................ 157

Application Settings: .................................................................................................................... 158

Connection Strings: ...................................................................................................................... 159

System.Web Element ................................................................................................................... 159

AnonymousIdentification ............................................................................................................ 161

Caching: ........................................................................................................................................ 162

CustomErrors ............................................................................................................................... 162

33. Authentication and Authorization ................................................................... 163

Form Authentication .................................................................................................................... 164

Passport Authentication .............................................................................................................. 167

Windows Authentication ............................................................................................................. 168

34. ASP.NET VNext or ASP.NET 5 ........................................................................... 172

What is ASP.NET 5 ........................................................................................................................ 172

Page 6: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

6 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Why build ASP.NET 5 ................................................................................................................... 172

Services ........................................................................................................................................ 174

Middleware .................................................................................................................................. 174

Servers ......................................................................................................................................... 174

Web root ...................................................................................................................................... 174

Configuration ............................................................................................................................... 175

Introduction of HTML:

HTML is a markup language for describing web documents (web pages).

HTML stands for Hyper Text Markup Language

A markup language is a set of markup tags

HTML documents are described by HTML tags

Each HTML tag describes different document content

HTML Example:

<! DOCTYPE html>

<html>

<head>

<title>Page Title</title>

</head>

<body>

<h1>My First Heading</h1>

<p>My first paragraph. </p>

</body>

</html>

Output:

My First Heading

Page 7: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

7 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

My first paragraph.

Example Explained

The DOCTYPE declaration defines the document type to be HTML

The text between <html> and </html> describes an HTML document

The text between <head> and </head> provides information about the document

The text between <title> and </title> provides a title for the document

The text between <body> and </body> describes the visible page content

The text between <h1> and </h1> describes a heading

The text between <p> and </p> describes a paragraph

Using this description, a web browser can display a document with a heading and a paragraph.

HTML Versions: Since the early days of the web, there have been many versions of HTML:

Version Year

HTML 1991

HTML 2.0 1995

HTML 3.2 1997

HTML 4.01 1999

XHTML 2000

Page 8: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

8 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

HTML5 2014

HTML tags/Elements

HTML tags are keywords (tag names) surrounded by angle brackets:

<tag name>content</tag name>

HTML tags normally come in pairs like <p> and </p>

The first tag in a pair is the start tag, the second tag is the end tag

The end tag is written like the start tag, but with a slash before the tag name

Tag Description

<!--...--> Defines a comment

<!DOCTYPE> Defines the document type

<a> Defines a hyperlink

<abbr> Defines an abbreviation or an acronym

<acronym> Not supported in HTML5. Use <abbr> instead.

Defines an acronym

<address> Defines contact information for the author/owner of a

document

<applet> Not supported in HTML5. Use <embed> or <object>

instead.

Defines an embedded applet

<area> Defines an area inside an image-map

<article> Defines an article

<aside> Defines content aside from the page content

<audio> Defines sound content

<b> Defines bold text

Page 9: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

9 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<base> Specifies the base URL/target for all relative URLs in a

document

<basefont> Not supported in HTML5. Use CSS instead.

Specifies a default color, size, and font for all text in a

document

<bdi> Isolates a part of text that might be formatted in a

different direction from other text outside it

<bdo> Overrides the current text direction

<big> Not supported in HTML5. Use CSS instead.

Defines big text

<blockquote> Defines a section that is quoted from another source

<body> Defines the document's body

<br> Defines a single line break

<button> Defines a clickable button

<canvas> Used to draw graphics, on the fly, via scripting (usually

JavaScript)

<caption> Defines a table caption

<center> Not supported in HTML5. Use CSS instead.

Defines centered text

<cite> Defines the title of a work

<code> Defines a piece of computer code

<col> Specifies column properties for each column within a

<colgroup> element

<colgroup> Specifies a group of one or more columns in a table for

formatting

<datalist> Specifies a list of pre-defined options for input controls

<dd> Defines a description/value of a term in a description list

<del> Defines text that has been deleted from a document

<details> Defines additional details that the user can view or hide

<dfn> Represents the defining instance of a term

Page 10: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

10 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<dialog> Defines a dialog box or window

<dir> Not supported in HTML5. Use <ul> instead.

Defines a directory list

<div> Defines a section in a document

<dl> Defines a description list

<dt> Defines a term/name in a description list

<em> Defines emphasized text

<embed> Defines a container for an external (non-HTML)

application

<fieldset> Groups related elements in a form

<figcaption> Defines a caption for a <figure> element

<figure> Specifies self-contained content

<font> Not supported in HTML5. Use CSS instead.

Defines font, color, and size for text

<footer> Defines a footer for a document or section

<form> Defines an HTML form for user input

<frame> Not supported in HTML5.

Defines a window (a frame) in a frameset

<frameset> Not supported in HTML5.

Defines a set of frames

<h1> to <h6> Defines HTML headings

<head> Defines information about the document

<header> Defines a header for a document or section

<hr> Defines a thematic change in the content

<html> Defines the root of an HTML document

<i> Defines a part of text in an alternate voice or mood

<iframe> Defines an inline frame

<img> Defines an image

<input> Defines an input control

Page 11: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

11 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<ins> Defines a text that has been inserted into a document

<kbd> Defines keyboard input

<keygen> Defines a key-pair generator field (for forms)

<label> Defines a label for an <input> element

<legend> Defines a caption for a <fieldset> element

<li> Defines a list item

<link> Defines the relationship between a document and an

external resource (most used to link to style sheets)

<main> Specifies the main content of a document

<map> Defines a client-side image-map

<mark> Defines marked/highlighted text

<menu> Defines a list/menu of commands

<menuitem> Defines a command/menu item that the user can invoke

from a popup menu

<meta> Defines metadata about an HTML document

<meter> Defines a scalar measurement within a known range (a

gauge)

<nav> Defines navigation links

<noframes> Not supported in HTML5.

Defines an alternate content for users that do not support

frames

<noscript> Defines an alternate content for users that do not support

client-side scripts

<object> Defines an embedded object

<ol> Defines an ordered list

<optgroup> Defines a group of related options in a drop-down list

<option> Defines an option in a drop-down list

<output> Defines the result of a calculation

<p> Defines a paragraph

<param> Defines a parameter for an object

Page 12: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

12 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<pre> Defines preformatted text

<progress> Represents the progress of a task

<q> Defines a short quotation

<rp> Defines what to show in browsers that do not support

ruby annotations

<rt> Defines an explanation/pronunciation of characters (for

East Asian typography)

<ruby> Defines a ruby annotation (for East Asian typography)

<s> Defines text that is no longer correct

<samp> Defines sample output from a computer program

<script> Defines a client-side script

<section> Defines a section in a document

<select> Defines a drop-down list

<small> Defines smaller text

<source> Defines multiple media resources for media elements

(<video> and <audio>)

<span> Defines a section in a document

<strike> Not supported in HTML5. Use <del> or <s> instead.

Defines strikethrough text

<strong> Defines important text

<style> Defines style information for a document

<sub> Defines subscripted text

<summary> Defines a visible heading for a <details> element

<sup> Defines superscripted text

<table> Defines a table

<tbody> Groups the body content in a table

<td> Defines a cell in a table

<textarea> Defines a multiline input control (text area)

<tfoot> Groups the footer content in a table

Page 13: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

13 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<th> Defines a header cell in a table

<thead> Groups the header content in a table

<time> Defines a date/time

<title> Defines a title for the document

<tr> Defines a row in a table

<track> Defines text tracks for media elements (<video> and

<audio>)

<tt> Not supported in HTML5. Use CSS instead.

Defines teletype text

<u> Defines text that should be stylistically different from

normal text

<ul> Defines an unordered list

<var> Defines a variable

<video> Defines a video or movie

<wbr> Defines a possible line-break

HTML 5 Tags

There is a list of newly included tags in HTML 5. These HTML 5 tags (elements) provide a better document

structure. This list shows all HTML 5 tags in alphabetical order with description.

HTML Audio Tag

HTML audio tag is used to define sounds such as music and other audio clips. Currently there are three

supported file format for HTML 5 audio tag.

• mp3

• wav

• ogg

HTML5 supports <video> and <audio> controls. The Flash, Silverlight and similar technologies are used to

play the multimedia items.

Page 14: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

14 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

HTML Audio Tag Example

Let's see the code to play mp3 file using HTML audio tag.

<audio controls>

<source src="koyal.mp3" type="audio/mpeg">

Your browser does not support the html audio tag.

</audio>

HTML Video Tag

HTML 5 supports <video> tag also. The HTML video tag is used for streaming video files such as a movie

clip, song clip on the web page.Currently, there are three video formats supported for HTML video tag:

• mp4

• webM

• ogg

HTML Progress Tag

HTML <progress> tag is used to display the progress of a task. It provides an easy way for web developers

to create progress bar on the website. It is mostly used to show the progress of a file uploading on the

web page. The HTML progress tag is new in HTML5 so you must use new browsers.

HTML Progress Tag Example:

Downloading progress:

<progress value="43" max="100"></progress>

HTML Meter Tag

HTML <meter> tag is used to measure data within a given range. It defines a scalar measurement with

range. It is also known as a gause. It should be used to display disk usage, voting population etc. The HTML

meter tag is new in HTML5 so you must use new browsers.

HTML Meter Tag Example:

<p>Display a gauge:</p>

Page 15: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

15 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<meter value="30" min="1" max="100">30 out of 100</meter><br>

<meter value="0.8">80%</meter>

HTML Data Tag

The HTML <data> tag is used to provide a machine readable version of its own contents. It displays the

data in a special format. It is useful in the case where your data needs to be in a certain format because it

may be processed by a script, but this might not be the format that you'd like your users to see.

The <data> tag is here to solve your problem.

For the users: Write within the <data>....>/data> tag.

For the script: Use value attribute.

<data value="1">One </data>

HTML data tag example:

<ul>

<li><data value="101">Java Tutorial</data></li>

<li><data value="111">SQL tutorial</data></li>

<li><data value="121">HTML tutorial</data></li>

</ul>

Output:

• Java Tutorial

• SQL tutorial0

• HTML tutorial

HTML Datalist Tag

The HTML <datalist> tag is used to provide an auto complete feature on form element. It provides a list

of predefined options to the users to select data. The datalist tag is introduced in HTML5. The <datalist>

tag should be used with an <input< element that contains a "list" attribute. The value of "list" attribute is

linked with the datalist id.

HTML datalist tag example

<label>

Page 16: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

16 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Enter your favorite cricket player: Press any character<br />

<input type="text" id="favCktPlayer" list="CktPlayers">

<datalist id="CktPlayers">

<option value="Sachin Tendulkar">

<option value="Brian Lara">

<option value="Jacques Kallis">

<option value="Ricky Ponting">

<option value="Rahul Dravid">

<option value="Shane Warne">

<option value="Rohit Sharma">

<option value="Donald Bradman">

<option value="Saurav Ganguly ">

<option value="AB diVilliers">

<option value="Mahendra Singh Dhoni">

<option value="Adam Gilchrist">

</datalist>

</label>

Output

Enter your favorite cricket player:

Press any character

HTML Header Tag

HTML <header> tag is used as a container of introductory content or navigation links. Generally a

<header> element contains one or more heading elements, logo or icons or author's information. You can

use several <header> elements in one document, but a <header> element cannot be placed within a

<footer>, <address> or another <header> element.

HTML Header Tag Example

<header>

Page 17: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

17 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<h2>ABCOnline.com</h2>

<p> World's no.1 shopping website</p>

</header>

Output:

ABCOnline.com

World's no.1 shopping website

HTML Footer Tag

HTML <footer> tag is used to define a footer for a document or a section. It is generally used in the last of

the section (bottom of the page). The footer tag is included in HTML5.

HTML <footer> tag contains information about its containing elements for example:

• author information

• contact information

• copyright information

• sitemap

• back to top links

• related documents etc.

HTML Footer Tag Example:

<footer>

<p>Posted by: Hi</p>

<p>

<address> Address

</address>

</p>

<p>Contact information:

<a href="mailto:[email protected]">[email protected]</a>.

</p>

</footer>

Output:

Page 18: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

18 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Posted by: Hi

Address

Contact information: [email protected].

HTML figure tag

HTML <figure> tag is used to mark up a photo in the document on a web page. As we know image tag is

already available in HTML to display the pictures on web pages. But HTML 5 <figure> tag is used to handle

the group of diagrams, photos, code listing etc. with some embedded content. You can also add a caption

for the photo with the help of <figcaption> tag.

HTML figure is new a new tag introduced in HTML5.

HTML figure tag example

<p>The Taj Mahal is widely recognized as "the jewel of Muslim art in India and

one of the universally admired masterpieces of the world's heritage". It is regarded

by many as the finest example of Mughal architecture, a style that combines elements

from Islamic, Persian, Ottoman, Turkish and Indian architectural styles.</p>

<figure>

<img src="htmlpages/images/tajmahal.jpg" alt="Taj Mahal"/>

</figure>

Output:

The Taj Mahal is widely recognized as "the jewel of Muslim art in India and one of the universally admired

masterpieces of the world's heritage". It is regarded by many as the finest example of Mughal

architecture, a style that combines elements from Islamic, Persian, Ottoman, Turkish and Indian

architectural styles.

HTML figcaption tag

Page 19: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

19 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The <figcaption> element is used to provide a caption to an image. It is an optional tag and can appear

before or after the content within the <figure> tag. Only one <figcaption> element can be nested within

a <figure> tag although the <figure> element itself may contain multiple other elements like <img> or

<code>. The <figcaption> element is used with <figure> element and it can be placed as the first or last

child of the <figure> element.

HTML figure tag example

<figure>

<img src="htmlpages/images/tajmahal.jpg" alt="Taj Mahal"/>

<figcaption>Fig.1.1 - A front view of the great Taj Mahal in Agra.</figcaption>

</figure>

Output

Fig.1.1 - A front view of the great Taj Mahal in Agra.

HTML Article Tag

The HTML <article> tag defines an independent self-contained content in a document, page, application

or a site.

The article tag content makes sense on its own. It is independent and complete from other content shown

on the page. This tag is generally used on Forum post, Blog post, News story, comment etc.

HTML article tag example

<article>

<h2>Narendra Modi</h2>

<i>(Naam to suna hi hoga) </i>

<p>Narendra DamodarDas Modi is the 15th and current Prime Minister of India,

Modi, a leader of the Bharatiya Janata Party (BJP), previously served as the Chief Minister

Page 20: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

20 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

of Gujarat state from 2001 to 2014. He is currently the Member of Parliament (MP) from Varanasi.

</p>

</article>

Output

Narendra Modi

(Naam to suna hi hoga)

Narendra DamodarDas Modi is the 15th and current Prime Minister of India, Modi, a leader of the

Bharatiya Janata Party (BJP), previously served as the Chief Minister of Gujarat state from 2001 to 2014.

He is currently the Member of Parliament (MP) from Varanasi.

HTML Aside Tag

The HTML <aside> tag provides information about the main content. According to W3C definition, the

<aside> element represents content that forms the main textual flow of a document. HTML aside is a new

tag introduced in HTML5.

HTML aside tag example

<p>I don't want to live in Hyderabad, I wish; I could buy a flat in Hyderabad.</p>

<aside>

<h3>Hyderabad</h3>

<p>New Delhi is the capital of Telangaga.</p>

</aside>

Output

I don't want to live in Hyderabad, I wish; I could buy a flat in Hyderabad.

Hyderabad

Hyderabad is the capital of Telangana.

HTML Dialog Tag

Page 21: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

21 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

HTML <dialog> tag to create a new popup dialog on a web page. This tag represents a dialog box or other

interactive component like window. The <dialog> element uses a Boolean attribute called open that

activate element and facilitate user to interact with it. HTML dialog is a new tag introduced in HTML5.

HTML dialog tag example

<div>

<dialog id="myFirstDialog" style="width:50%;background-

color:#F4FFEF;border:1px dotted black;">

<p><q>I am so clever that sometimes I don't understand a single word of what I am saying.

</q> - <cite>Oscar Wilde</cite></p>

<button id="hide">Close</button>

</dialog>

<button id="show">Show Dialog</button>

</div>

<!-- JavaScript to provide the "Show/Close" functionality -->

<script type="text/JavaScript">

(function() {

var dialog = document.getElementById('myFirstDialog');

document.getElementById('show').onclick = function() {

dialog.show();

};

document.getElementById('hide').onclick = function() {

dialog.close();

};

})();

</script>

HTML Details Tag

HTML <details> tag is used to specify the additional details on the web page that the user can view or hide

on demand. According to W3C HTML specification, it is used as a disclosure widget from which user can

Page 22: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

22 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

retrieve additional information or control. It is used together with a relevant tag known as <summary>.

Technically, there is no need of summary tag, but if you ignore this then the browser will use some default

text. The <details> tag wraps all the content which you want to show or hide and the <summary> tag

contains the summary and the title of the section. HTML details is a new tag introduced in HTML5. Let's

take an example to understand this clearly.

HTML details tag example

<details>

<summary>Copyright 2011-2014.</summary>

<p> - by KnackHook. All Rights Reserved.</p>

<p>All content and graphics on this web site are the property of the KnackHook.com</p>

</details>

<p><b>Note:</b> The details tag is currently only supported in Opera, Chrome, and in Safari 6.</p>

Output

Copyright 2011-2014.

Note: The details tag is currently only supported in Opera, Chrome, and in Safari 6.

HTML Summary Tag

The HTML <summary> tag is used with <details> tag. It is used as a summary, caption or legend for the

content of a <details> element. It is used within the <details> tag. It must have a closing tag. The

<summary> tag is new and introduced in HTML 5.

HTML summary tag example

<details>

<summary>KnackHook Summary</summary>

<p> KnackHook is a popular tutorial website.</p>

<p>You can learn various tutorials on KnackHook such as HTML, CSS, JavaScript, Java, Android.</p>

</details>

Output

KnackHook Summary

KnackHook is a popular tutorial website.

Page 23: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

23 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

You can learn various tutorials on KnackHook such as HTML, CSS, JavaScript, Java, Android.

HTML Section Tag

The HTML <section> tag is used to define sections in a document. When you put your content on a web

page, it may contains many chapters, headers, footers, or other sections on a web page that is why HTML

<section> tag is used. HTML <section> is a new tag introduced in HTML5.

HTML section tag example

<h2> Indian Leader</h2>

<section>

<h3> Jawaharlal Nehru </h3>

<p> Jawaharlal Nehru was the first Prime Minister of India and a central figure in Indian politics for

much of the 20th century. He emerged as the paramount leader of the Indian independence movem

ent under the tutelage of Mahatma Gandhi. -Source Wikipedia </p>

</section>

<section>

<h3>Subhas Chandra Bose </h3>

<p>Subhas Chandra Bose was an Indian nationalist whose attempt during World War II to

rid India of British rule with the help of Nazi Germany and Japan left a troubled legacy. The honorific

Netaji (Hindustani language: "Respected Leader"), first applied to Bose in German

by the Indian soldiers of the Indische Legion and by the German and Indian officials in the

Special Bureau for India in Berlin, in early 1942, is now used widely throughout India.sourceWikipedi

a</p>

</section>

Output

Indian Leader

Jawaharlal Nehru

Jawaharlal Nehru was the first Prime Minister of India and a central figure in Indian politics for much

of the 20th century. He emerged as the paramount leader of the Indian independence movement

under the tutelage of Mahatma Gandhi. -Source Wikipedia

Page 24: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

24 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Subhas Chandra Bose

Subhas Chandra Bose was an Indian nationalist whose attempt during World War II to rid India of

British rule with the help of Nazi Germany and Japan left a troubled legacy. The honorific Netaji

(Hindustani language: "Respected Leader"), first applied to Bose in Germany, by the Indian soldiers of

the Indische Legion and by the German and Indian officials in the Special Bureau for India in Berlin, in

early 1942, is now used widely throughout India. -source Wikipedia

HTML Time Tag

HTML <time> tag is used to define date and time. It displays time value in a 24-hour clock or a precise

date in a Gregorian calendar in HTML. It is used to encode dates and times in a machine-readable way to

make easy to mark or schedule your task. It also helps search engines to produce smarter search results.

HTML <time> is a new tag and introduced in HTML5.

Let's see the syntax to define date and time.

<time>Define Time and Date here</time>

HTML time tag example

<p>We open our shop at <time>09:00</time> am.</p>

<p>The business meeting is scheduled on <time datetime="2009-02-

18">next wednesday</time>.</p>

<p>The wedding of Salman's sister was scheduled at <time datetime="2014-11-19 T0 7:00-

09:00">7pm last wednesday </time>.</p>

Output

We open our shop at 09:00 am.

The business meeting is scheduled on next Wednesday.

The wedding of Salman's sister was scheduled at 7pm last Wednesday.

HTML Main Tag

HTML <main> tag is used to represent the main content of the <body> tag.

Page 25: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

25 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The <main> tag is written within <body> tag. It is used to accurately describe the primary content of a

page. The content of the main tag is directly related to the central topic of the document. HTML <main>

is a new tag and introduced in HTML5.

HTML main tag example

<main>

<h2>Apples</h1>

<p>The apple is a red color pomaceous fruit of the apple tree. It is a very famous saying about apple

</br> "An apple in a day, keeps the Doctor away".</p>

<article>

<h3>Red Delicious</h3>

<p>These bright red apples are the most common found in many supermarkets.</p>

</article>

<article>

<h3>Granny Smith</h3>

<p>These juicy, green apples make a great filling for apple pies.</p>

</article>

</main>

Output

Apples

The apple is a red color pomaceous fruit of the apple tree. It is a very famous saying about apple.

"An apple in a day, keeps the Doctor away".

Red Delicious

These bright red apples are the most common found in many supermarkets.

Granny Smith

These juicy, green apples make a great filling for apple pies.

HTML Wbr Tag

HTML <wbr> tag is used to specify a line break opportunity within an HTML document. Without wbr tag,

it is very difficult to read a long single word or a sentence. Without wbr tag, single long word can wrap or

Page 26: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

26 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

not wrap at all, it creates problem for the layout of the page. Without <wbr> tag, users will have to scroll

right to read a long complete word or sentence. The <wbr> tag is new and introduced in HTML 5.

HTML wbr tag example

<html>

<body>

<p> This is a world record for the largest word,

a 45-letter word appears in a major dictionary

<i>pneumonoultramicroscopicsilicovolcanoconiosis</i> </p>

<p>Here's what it looks like without using the <code>wbr</code> tag...<br/>

<i> pneumonoultramicroscopicsilicovolcanoconiosis </i></p>

<p> It will look like this after using wbr tag. </p>

<i> pneu<wbr>monoultra<wbr>microsc<wbr>opicsili<wbr>covolcan<wbr>iosis</i>

</body>

</html>

Output

his is a world record for the largest word, a 45-letter word appears in a major

dictionarypneumonoultramicroscopicsilicovolcanoconiosis

Here's what it looks like without using the wbr tag...

pneumonoultramicroscopicsilicovolcanoconiosis

It will look like this after using wbr tag.

Pneumonoultramicroscopicsilicovolcaniosis

HTML Canvas Tag

The HTML canvas element provides HTML a bitmapped surface to work with. It is used to draw graphics

on the web page. The HTML 5 <canvas> tag is used to draw graphics using scripting language like

JavaScript. The <canvas> element is only a container for graphics, you must need a scripting language to

draw the graphics. The <canvas> element allows for dynamic and scriptable rendering of 2D shapes and

Page 27: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

27 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

bitmap images. It is a low level, procedural model that updates a bitmap and does not have a built-in

scene. There are several methods in canvas to draw paths, boxes, circles, text and add images.

How to create a HTML canvas

A canvas is a rectangle like area on an HTML page. It is specified with canvas element. By default, the

<canvas> element has no border and no content, it is like a container.

<canvas id = "mycanvas" width ="200" height ="100"> </canvas>

HTML 5 Canvas Tag Example

<canvas id="myCanvas1" width="300" height="100" style="border:2px solid;">

Your browser does not support the HTML5 canvas tag.

</canvas>

Output

HTML SVG

The HTML SVG is an acronym which stands for Scalable Vector Graphics. HTML SVG is a modularized

language which is used to describe graphics in XML. It describe two-dimensional vector and mixed

vector/raster graphics in XML. It is a W3C recommendation. SVG images and their behaviors are defined

in XML text files. So as XML files, you can create and edit an SVG image with text editor, but generally

drawing programs like inkspace are preferred to create it. SVG is mostly used for vector type diagrams like

pie charts, 2-Dimensional graphs in an X,Y coordinate system etc. The <svg> element specifies the root of

a SVG fragment. You can animate every element and every attribute in SVG files.

Example:

<svg width="100" height="100">

<circle cx="50" cy="50" r="40" stroke="yellow" stroke-width="4" fill="red" />

</svg>

Page 28: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

28 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Here, we are using cx, cy and r attributes of circle tag. These attributes can't be used with svg rect tag.

Output

HTML Drag and Drop

HTML Drag and Drop (DnD) is a feature of HTML5. It is a powerful user interface concept which is used to

copy, reorder and delete items with the help of mouse. You can hold the mouse button down over an

element and drag it to another location. If you want to drop the element there, just release the mouse

button. If you want to achieve the Drag and Drop functionality in traditional HTML4, you must either have

to use complex JavaScript programming or other JavaScript frameworks like jQuery etc.

HTML5 Drag and Drop Example

<script>

function allowDrop(ev) {ev.preventDefault();}

function drag(ev) {ev.dataTransfer.setData("text/html", ev.target.id);}

function drop(ev) {

ev.preventDefault();

var data = ev.dataTransfer.getData("text/html");

ev.target.appendChild(document.getElementById(data));

}

</script>

<p>Drag the KnackHook image into the rectangle:</p>

<div id="div1" style="width:350px;height:100px;padding:10px;border:1px solid #aaaaaa;"

ondrop="drop(event)" ondragover="allowDrop(event)"></div>

<br>

<img id="drag1" src="/htmlpages/images/KnackHook.png" alt="KnackHook image"

draggable="true" ondragstart="drag(event)"/>

Page 29: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

29 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

In the above example, we have used ondrop and ondragover events on div element, and ondragstart

event on img tag.

Output

Drag the KnackHook image into the rectangle:

CSS (Cascading Style Sheets)

CSS is added to HTML pages to format the document according to information in the style sheet. There

are three ways to insert CSS in HTML documents.

1. Inline CSS

2. Internal CSS

3. External CSS

Inline CSS

Inline CSS is used to apply CSS on a single line or element. The inline CSS is also a method to insert style

sheets in HTML document. This method mitigates some advantages of style sheets so it is advised to use

this method sparingly.

For example

<p style="color:blue">Hello CSS</p>

Internal CSS

Internal CSS is used to apply CSS on a single document or page. It can affect all the elements of the page.

It is written inside the style tag within head section of html.

For example

<style>

p{color:blue}

Page 30: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

30 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</style>

External CSS

External CSS is used to apply CSS on multiple pages or all pages. Here, we write all the CSS code in a css

file. Its extension must be .css for example style.css.

For example:

p{color:blue}

You need to link this style.css file to your html pages like this:

<link rel="stylesheet" type="text/css" href="style.css">

The link tag must be used inside head section of html.

About .Net? .Net is a software development platform developed by Microsoft.

Using Dot Net we can build multiple applications like

• Console Application: A console application is an application that takes input and displays output

at a command line console with access to three basic data streams: standard input, standard

output and standard error. Ex : CMD Prompt

• Web Applications: A Web Application is an application which is having GUI and accessible

through the internet in web browser (IE, Crome, Firefox and Safari).A Web Application is a

collection of web pages. Ex : www.msn.com

• Windows Applications (Desktop Applications): An application that target to run in Windows OS

is called Windows Application or Desktop Application. Windows Application doesn’t need Web

Browser to run. Ex : Skype

• Windows Services: A service which runs on Windows environment is called a Windows Service:

Ex: Birthday Alarm of windows system.

• Web Services: Web Service is distribution service where we can host web service and able to

consume it in different applications using internet. Ex : Paypal webservice

• Mobile Applications: An Application which targets to run on Mobile is called Mobile Application.

Ex : Whats App

• WPF Applications (Windows Presentation Foundation): WPF application is an Windows

Application which have good look and fell(GUI)

Page 31: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

31 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

• Silverlight Applications: Silverlight application is a web application with good look and feel.

Dot Net Components:

• Dot Net Framework

• ASP.NET

• Visual Studio

About .Net Framework The .NET Framework is an integral Windows component that supports building and running the next generation of applications. It consists of 2 components.

• Common Language Runtime • Framework Class Library

.Net Framework Versions .Net Framework 1.0 in 2002 .Net Framework 1.1 in 2003 .Net Framework 2.0 in 2005 .Net Framework 3.0 in 2006 .Net Framework 3.5 in 2007 .Net Framework 4.0 in 2010 .Net Framework 4.5 in 2012 .Net Framework 4.5.1 in 2013 .Net Framework 1.1 Features:

1. Introduced ASP.NET Mobile Controls 2. The .NET Framework Data Provider for ODBC, which previously was available as a Web

download only, now ships with the .NET Framework under the namespace System.Data.Odbc 3. The .NET Framework version 1.1 supports side-by-side execution. Side-by-side execution is the

ability to store and execute multiple versions of an application or component on the same computer.

If you have some application requiring assembly version 1.2.0.0 to run properly and some of your application requires same file but having version 1.3.0.0 then you can have both assemblies on your computer and at the same time, you can have both running, using different assemblies at runtime :-) Ajax Tool Kit .Net Framework 2.0 Features:

1. The new generation of 64-bit computers enables the creation of applications that can run faster and take advantage of more memory than is available to 32-bit applications

Page 32: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

32 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

2. The Microsoft .NET Framework 2.0 includes significant enhancements to all areas of ASP.NET, Master pages allow you to create a consistent layout for all the pages in a site, and themes allow you to define a consistent look for controls and static text. To help protect your sites, you can precompile a Web site to produce executable code from source files (both code files and the markup in .aspx pages). You can then deploy the resulting output, which does not include any source information, to a production server.

3. Applications can now access File Transfer Protocol resources using the WebRequest, WebResponse, and WebClient classes.

4. Four Microsoft programming languages explicitly target the .NET Framework: Visual C#, Microsoft C/C++, Visual J#, and Visual Basic.

5. Using the classes in the System.Net.Mail and System.Net.Mime namespaces, applications can send e-mail to one or more recipients. Mail can be sent with alternate views and can include attachments. Sending carbon copies and blind carbon copies is also supported.

6. ClickOnce deployment allows you to deploy self-updating Windows applications that can be installed and run as easily as Web applications. You can deploy Windows client and command-line applications.

.Net Framework 3.0 Features: The .NET Framework version 3.0 was issued solely to include the following technologies in the .NET Framework and in the Windows Software Development Kit (SDK):

• Windows Communication Foundation: Windows Communication Foundation (WCF) is a runtime and a set of APIs for creating systems that send messages between services and clients. The same infrastructure and APIs are used to create applications that communicate with other applications on the same computer system or on a system that resides in another company and is accessed over the Internet. WCF has all features of following distributed technologies: Web Service, Microsoft Message Queuing (MSMQ), Remoting

• Windows Presentation Foundation: Windows Presentation Foundation (WPF) provides developers with a unified programming model for building rich Windows smart client user experiences that incorporate UI, media, and documents.

• Windows Workflow Foundation: Windows Workflow Foundation, a core component of .NET Framework 3.0, provides a programming model, run-time engine, and tools for building workflow applications. A workflow is a discrete series of activities that model the steps involved in a business process.A workflow is created and maintained by the workflow run-time engine. There can be several workflow engines within an application domain, and each workflow engine can support multiple workflows running concurrently. The run-time enables idle workflows to be unloaded from memory, persisted to a store, and reloaded whenever input is received.

• Windows CardSpace: The Internet continues to be increasingly valuable, and yet also faces significant challenges. Online identity theft, fraud, and privacy concerns are rising. Users must track a growing number of accounts and passwords. This burden results in "password fatigue," and that results in insecure practices, such as reusing the same account names and passwords at many sites. CardSpace is Microsoft's implementation of an Identity Metasystem that enables users to choose from a portfolio of identities that belong to them and use them in contexts where they are accepted, independent of the underlying identity systems where the identities originate and are used. This topic explains the issue and the CardSpace solution in greater detail, and outlines how Windows Communication Foundation (WCF) users can use CardSpace.

Page 33: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

33 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Many of these issues are rooted in the lack of a widely adopted identity solution for the Internet. Password security mechanism to authenticate and authorize user access. Windows Cardspace has been replaced with Microsoft Passport authentication.

.Net Framework 3.5 Features:

• Language-Integrated Query (LINQ) is a new feature in Visual Studio 2008 and the .NET Framework 3.5. LINQ extends powerful query capabilities to the language syntax of C# and Visual Basic in the form of standard, easily-learned query patterns.

• The most significant advance is improved support for the development of AJAX-enabled Web sites.

• The .NET Framework 3.5 unifies the Windows Workflow Foundation (WF) and Windows Communication Foundation (WCF) frameworks so that you can use WF as a way to author WCF services or expose your existing WF workflow as a service. This enables you to create services that can be persisted, can easily transfer data in and out of a workflow, and can enforce application-level protocols.

.Net Framework 3.5 SP1 Features: The .NET Framework Client Profile is a subset of the full .NET Framework that targets client applications. This improves the installation experience on computers that do not already have the .NET Framework installed. .Net Framework 4.0 Features:

• The .NET Framework 4 Client Profile supports more platforms than in previous versions and provides a fast deployment experience for your applications.

• The .NET Framework 4 provides background garbage collection. This feature replaces concurrent garbage collection in previous versions and provides better performance.

• The dynamic language runtime (DLR) is a new runtime environment that adds a set of services for dynamic languages to the CLR. The DLR makes it easier to develop dynamic languages to run on the .NET Framework and to add dynamic features to statically typed languages. To support the DLR, the new System.Dynamic namespace is added to the .NET Framework.

• The Managed Extensibility Framework (MEF) is a new library in the .NET Framework 4 that helps you build extensible and composable applications.

• The .NET Framework 4 introduces a new programming model for writing multithreaded and asynchronous code that greatly simplifies the work of application and library developers. The new model enables developers to write efficient, fine-grained, and scalable parallel code in a natural idiom without having to work directly with threads or the thread pool. The new System.Threading.Tasks namespace and other related types support this new model. Parallel LINQ (PLINQ), which is a parallel implementation of LINQ to Objects, enables similar functionality through declarative syntax.

• Web Forms controls, including a new Chart control. • MVC, including new helper methods for views, support for partitioned MVC applications, and

asynchronous controllers. • ADO.NET provides new features for the Entity Framework, including persistence-ignorant

objects, functions in LINQ queries, and customized object layer code generation.

Page 34: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

34 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

.Net Framework 4.5 Features: • Windows Store apps are designed for specific form factors and leverage the power of the

Windows operating system. A subset of the .NET Framework 4.5 is available for building Windows Store apps for Windows by using C# or Visual Basic.

• The Portable Class Library project in Visual Studio 2012 enables you to write and build managed assemblies that work on multiple .NET Framework platforms. Using a Portable Class Library project, you choose the platforms (such as Windows Phone and .NET for Windows Store apps) to target. The available types and members in your project are automatically restricted to the common types and members across these platforms.

• Support for new HTML5 form types. .Net Framework 4.5.1 Features: Debugging Feature Improvements 64-Bit Edit and Continue support in Visual Studio 2013 : in debug mode we can edit and continue the changes. Inspecting Method return value while debugging using Autos Window as well as a pseudo variable $ReturnValue : we can check the result of return value easily. ADO.NET Connection Resiliency :ADO.NET connection recovery has been increased. Application Performance Improvements ASP.NET Application Suspension :We have ablility to suspend the web application when there is no request for that application. On-Demand Large-Object heap compaction :The On-demand large object heap compaction is now supported in .NET framework 4.5.1 to avoid the OutOfMemory exception. Multi-core JIT Improvements : It enhance the launch time of the application 40-50 %

Page 35: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

35 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

About Common Language Runtime (CLR) and its Services?

The common language runtime is the foundation of the .NET Framework. It is responsible for managing

code execution at run time, and provides core services such as compilation, memory management,

thread management, code execution, enforcement of type safety, and code safety verification.

Compilers target the common language runtime, which defines the basic data types available to

application developers. Because it provides a managed environment for code execution, the common

language runtime enhances developer productivity and contributes to the development of robust

applications.

Page 36: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

36 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

• Class loader, which loads classes into CLR.

• MSIL to native code compiles, this converts MSIL code into native code.

• Code manager, this manages the code during execution.

• Memory allocation and Garbage collector, this performs automatic memory management.

• Security engine, this enforces security restrictions as code level security folder level and

machine level security using tools provided by Microsoft .NET and using .NET Framework setting

under control panel.

• Type checker, which enforces strict type checking.(CTS and CLS)

• Thread support, which provides multithreading support to applications.

• Exception manager, which provides a mechanism to handle the run-time exceptions handling.

• Debug engine, which allows developer to debug different types of applications.

• COM marshaler, which allows .NET applications to exchange data with COM applications.

• Base class library support, which provides the classes (types) that the applications need at run

time.

What is managed code in .Net?

The code that runs under the guidance of common language runtime (CLR) is called managed code. The

versioning and registration problem which are formally handled by the windows programming are

solved in .Net with the introduction of managed code. The managed code contains all the versioning and

type information that the CLR use to run the application.

Ex: The code developed by .Net supporting languages like C#.Net, VB.Net, F#.Net etc.

Page 37: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

37 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

What is unmanaged code in .Net?

The code, which is developed outside .NET, Framework is known as unmanaged code.

Applications that do not run under the control of the CLR are said to be unmanaged, and certain

languages such as C++ can be used to write such applications, which, for example, access low - level

functions of the operating system. Background compatibility with code of VB, ASP and COM are

examples of unmanaged code.

Unmanaged code can be unmanaged source code and unmanaged compile code.

Unmanaged code is executed with help of wrapper classes.

Wrapper classes are of two types: CCW (COM Callable Wrapper) and RCW (Runtime Callable Wrapper).

Wrapper is used to cover difference with the help of CCW and RCW.

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

About Common Language Specification?

CLS is a set of specifications that all languages and libraries need to follow

This will ensure interoperability between languages

The CLS rules define a subset of the common type system; that is, all the rules that apply to the common

type system apply to the CLS, except where stricter rules are defined in the CLS. The CLS helps enhance

and ensure language interoperability by defining a set of features that developers can rely on to be

available in a wide variety of languages. The CLS also establishes requirements for CLS compliance; these

help you determine whether your managed code conforms to the CLS and to what extent a given tool

supports the development of managed code that uses CLS features.

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. Components that adhere to the CLS rules and use only the features included in the CLS are said

to be CLS-compliant components.

Most of the members defined by types in the .NET Framework class library are CLS-compliant. However,

some types in the class library have one or more members that are not CLS-compliant. These members

Page 38: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

38 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

enable support for language features that are not in the CLS. (Keywords, Interface methods, Accessor

metadata, Event method metadata, FlagsAttribute and Value encodings).

About Framework Class Library?

The .NET Framework class library is a collection of reusable types that tightly integrate with the common

language runtime. The class library is object oriented, providing types from which your own managed

code can derive functionality. This not only makes the .NET Framework types easy to use, but also

reduces the time associated with learning new features of the .NET Framework. In addition, third-party

components can integrate seamlessly with classes in the .NET Framework.

For example, the .NET Framework collection classes implement a set of interfaces that you can use to

develop your own collection classes. Your collection classes will blend seamlessly with the classes in the

.NET Framework.

About Visual Studio?

Visual Studio .NET is a complete set of development tools for building ASP Web applications, XML Web

services, desktop applications, and mobile applications. Visual Basic .NET, Visual C++ .NET, Visual

C# .NET, and Visual J# .NET all use the same integrated development environment (IDE), which allows

them to share tools and facilitates in the creation of mixed-language solutions. In addition, these

languages leverage the functionality of the .NET Framework, which provides access to key technologies

that simplify the development of ASP Web applications and XML Web services.

Visual Studio includes:

A code editor supporting

Page 39: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

39 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

IntelliSense

Code snippets and

Code refactoring.

The integrated debugger works both

As a source-level debugger and

As a machine-level debugger.

Forms designer for building GUI applications,

Class designer,

And other SW tools

Visual Studio 2005:

Development Environment

Code Editing

Projects, Solutions, and Items

Building, Testing, and Deployment

Visual Studio 2008:

DataRepeater Control

Line and Shape Controls

.NET Framework Client Profile Support

ClickOnce Deployment

Language-Integrated Query (LINQ) is a new set of features in Visual Studio 2008 that extend powerful

query capabilities into the language syntax of C# and Visual Basic.

Visual Studio 2010:

Auto-Implemented Properties

Collection Initializers

Implicit Line Continuation

Multiline Lambda Expressions and Subroutines

New Command-Line Option for Specifying a Language Version

Page 40: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

40 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Type Equivalence Support

Dynamic Support

Covariance and Contravariance

Navigate To

Highlighting References

Generate From Usage

IntelliSense Suggestion Mode

Visual Studio 2012:

Designing and building Windows Store apps

Debugging, optimizing, and publishing Windows Store apps

Designing and building Windows Phone apps

Testing, optimizing, and publishing Windows Phone apps

Developing applications and collaborating more effectively as a team

ASP.NET 4.5 Core Services

ASP.NET 4.5 Web Forms

Visual Studio 2013:

Open the Resolve menu when typing it happens once in a while that you haven’t included the

namespace you need at the top of your file. One common example is Trace found in System.Diagnostics.

If you write Trace, Visual Studio suggests TraceMode and other things, but no Trace. To quickly solve

this, type Trace followed by CTRL + SPACE +. And the Resolve menu comes up where you can select to

include using System.Diagnostics; to make Trace available. Very handy.

64 bit Edit and Continue Have we been waiting for this one or what?!? Finally, by using .Net Framework

4.5.1, we can have the same edit and continue for 64 bits as we’ve been able to with 32 bit code for

ages.

Return value inspection To help out the debugging process you can now easily see return values of

functions being used as parameters in other function calls, for example if you nest several functions in

each other.

Just my code this feature tells the debugger to only step through the code you’ve been writing yourself

and ignore frameworks and other code. The system is doing this by looking at open projects, .pbd files

and program optimisations. For .Net Framework, this came before VS 2013, but what’s new now is that

Page 41: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

41 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

it’s available for C++ and JavaScript as well. To enable or disable Just My Code, open Debug -> Options

and Settings -> General and change the value of Enable Just My Code.

Peek a definition It’s now possible to open up a method definition without having to open that specific

file. You can even open up a section located further up/down in your current file without having to leave

the location you are at now. This feature is called Peek Definition and can be accessed through ALT + F12

or by right clicking the method and select Peek Definition. Here is an example where I’m peeking on the

InitializeComponent () method.

CodeMap – Visual Debugging: When you are in Debug mode, clicking this will open a window which

shows the visual representation of the execution flow

Code Lens

You won’t miss noting this feature when using Visual Studio 2013. There will be indicators sitting atop of

every method in the code editor.

About Garbage Collector?

In the common language runtime (CLR), the garbage collector serves as an automatic memory manager. It provides the following benefits:

Enables you to develop your application without having to free memory. Allocates objects on the managed heap efficiently. Reclaims objects that are no longer being used, clears their memory, and keeps the memory

available for future allocations. Managed objects automatically get clean content to start with, so their constructors do not have to initialize every data field.

Provides memory safety by making sure that an object cannot use the content of another object.

Conditions for a garbage collection

Garbage collection occurs when one of the following conditions is true:

The system has low physical memory. The memory that is used by allocated objects on the managed heap surpasses an acceptable

threshold. This threshold is continuously adjusted as the process runs. The GC.Collect method is called. In almost all cases, you do not have to call this method,

because the garbage collector runs continuously. This method is primarily used for unique situations and testing.

Generations

Page 42: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

42 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The heap is organized into generations so it can handle long-lived and short-lived objects. Garbage collection primarily occurs with the reclamation of short-lived objects that typically occupy only a small part of the heap. There are three generations of objects on the heap:

Generation 0. This is the youngest generation and contains short-lived objects. An example of a short-lived object is a temporary variable. Garbage collection occurs most frequently in this generation. Newly allocated objects form a new generation of objects and are implicitly generation 0 collections, unless they are large objects, in which case they go on the large object heap in a generation 2 collection. Most objects are reclaimed for garbage collection in generation 0 and do not survive to the next generation.

Generation 1. This generation contains short-lived objects and serves as a buffer between short-lived objects and long-lived objects.

Generation 2. This generation contains long-lived objects. An example of a long-lived object is an object in a server application that contains static data that is live for the duration of the process.

Garbage collections occur on specific generations as conditions warrant. Collecting a generation means collecting objects in that generation and all its younger generations. A generation 2 garbage collection is also known as a full garbage collection, because it reclaims all objects in all generations (that is, all objects in the managed heap).

Survival and promotions

Objects that are not reclaimed in a garbage collection are known as survivors, and are promoted to the next generation. Objects that survive a generation 0 garbage collection are promoted to generation 1; objects that survive a generation 1 garbage collection are promoted to generation 2; and objects that survive a generation 2 garbage collection remain in generation 2.

When the garbage collector detects that the survival rate is high in a generation, it increases the threshold of allocations for that generation, so the next collection gets a substantial size of reclaimed memory. The CLR continually balances two priorities: not letting an application's working set get too big and not letting the garbage collection take too much time.

Asp.Net Overview

ASP.NET is a unified Web development model that includes the services necessary for you to build

enterprise-class Web applications with a minimum of coding. ASP.NET is part of the .NET Framework,

and when coding ASP.NET applications you have access to classes in the .NET Framework. You can code

your applications in any language compatible with the common language runtime (CLR), including

Microsoft Visual Basic and C#. These languages enable you to develop ASP.NET applications that benefit

from the common language runtime, type safety, inheritance, and so on.

Page 43: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

43 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ASP.NET provides services to allow the creation, deployment, and execution of Web

Applications and Web Services

Web Applications are built using Web Forms

Web Forms are designed to make building web-based applications as easy as building Visual

Basic applications

Built on .NET Framework: any .NET programming language can be used (C#, Visual Basic)

Complete object model

Separation of code and UI

Maintains page state

Session management

Caching, Debugging, Extensibility

About ASP.NET Benifits?

Separate presentation from code

Object-oriented approach

Component-based development

Event-driven architecture

Code compilation

Extensible architecture

Built-in state management

Many others (data binding, validation, master pages, etc.)

About ASP.NET Page Execution?

ASP.NET applications are executed via a sequence of HTTP requests and HTTP responses Client Web browser request ASPX pages The Web server executes the ASPX page and produce XHTML + CSS + JavaScript response.

The complete request and reponse is called as round trip.

Page 44: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

44 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

STEP 1: Client sends request for the required file to the IIS (Webserver).

STEP 2: IIS will locate the requested file.

STEP 3: If requested file is found, IIS will submit that to ISAPI.dll

ISAPI.dll is known as ASPX Engine.

ISAPI means Internet Services Application Programming Interface.

STEP 4: ISAPI.dll will generate a Page Class file, by separating Client side code, Server side code & by

adding required methods to execute the server side code.

STEP 5: This Page Class is submitted to Compilers (In case of pre-Compilation is not done).

STEP 6: Compilers will compile the Source Code & will generate MSIL code.

STEP 7: MSIL code will be submitted to CLR.

CLR will perform 3 tasks here,

1. Instantiation: Creates object to the respective Page Class

2. Processing: Executes the Result/Code

3. Rendering: Converts the Server side code into Client Understandable format (i.e., HTML

and JAVASCRIPT).

STEP 8: CLR will generate complete Execution Result.

STEP 9: Execution Result will be delivered to IIS.

STEP 10: IIS will deliver the result to CLIENT.

Page 45: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

45 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Once the Result is delivered to the client, The Object at the Server will be destroyed.

What is a round trip?

The trip of a Web page from the client to the server and then back to the client is known as a round

trip.The complete request and response is called as round trip.

About base componens of ASP.NET?

Web Forms – deliver ASP.NET user interface

Web Control – the smallest part we can use in our Web application (e.g. text box)

"Code behind" – contains the server-side code

Web.config – contains ASP.NET application configuration

Machine.config – contains configuration for all applications on the ASP.NET server

Global.asax – class containing application level event handlers

What is an ASP.NET Web Form?

ASP.NET Web forms are designed to use controls and features that are almost as powerful as the ones

used with Windows forms, and so they are called as Web forms. The Web form uses a server-side object

model that allows you to create functional controls, which are executed on the server and are rendered

as HTML on the client.

The attribute, runat="server", associated with a server control indicates that the Web form must be

processed on the server.

A Web form belongs to the System.Web.UI.Page class.

ASP.Net web form has extention as .aspx

It contains two parts designer page which has .aspx and code behind file has extention .aspx.cs

Designer page is responsible for UI elements

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <h1>KnackHook</h1> </div> </form>

Page 46: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

46 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</body> </html>

Code behind page is responsible for writing server side code to implement business logic.

using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace KnackHook { public partial class KnackHook : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //code to implement business logic } } }

What are the advantages of the code-behind feature?

The code-behind feature of ASP.NET offers a number of advantages:

• Makes code easy to understand and debug by separating application logic from HTML tags

• Provides the isolation of effort between graphic designers and software engineers

• Removes the problems of browser incompatibility by providing code files to exist on the Web server

and supporting Web pages to be compiled on demand.

In Page Vs Code Behind

The type of coding style used by ASP developers is known as inline coding, inline code or in-page code because that was the only way to develop an ASP page. In ASP Pages scripting code working for generating desired output was intermixed with HTML code to create user friendly pages as well as specific functionality was added to the web pages. In those days inline code was very popular in VB developers because they had hands on experience in writing long vb scripts to create well defined huge asp web sites. But often, the combined intermixed HTML, JavaScript and VB Scripts become ambiguous for maintaining the readability of large web pages. You can design and code ASP .Net web pages using inline code but it becomes difficult to maintain the server side events of all the server controls on a single page. The New ASP .Net Framework has provided the way out to maintain the code for large web pages. Now you can design the HTML code page with .aspx extension separately and maintain the code files for the same .aspx page of VB and C# separately. This style of coding to develop web pages is called Code-Behind. Code Behind approach is a better way to develop and design the .aspx page having basic

Page 47: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

47 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

layout of a web page containing all the necessary controls required for the GUI of the web page. Then include the VB or C# code behind class file for handling the events of controls. This mechanism separates the web page from design layout from the coding part. Code-Behind Example

ASPX Page with design layout

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

<html>

<head>

<title>Code-Behind Example</title>

</head>

<body>

<form id="form1" runat="server">

<div>

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

<asp:Button ID="btnSubmit" runat="server" Text="Submit" /><br />

<asp:Label ID="lblname" runat="server"></asp:Label></div>

</form>

</body>

</html>

Code-Behind File

Partial Class _Default

Inherits System.Web.UI.Page

Protected Sub btnSubmit_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnS

ubmit.Click

lblname.Text = txtname.Text

End Sub

End Class

Continue to next tutorial: Creating Your First ASP .Net Page to learn creating a web page.

Page 48: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

48 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The code-behind feature of ASP.NET offers a number of advantages:

• Makes code easy to understand and debug by separating application logic from HTML tags

• Provides the isolation of effort between graphic designers and software engineers

• Removes the problems of browser incompatibility by providing code files to exist on the Web server

and supporting Web pages to be compiled on demand.

ASP.NET - Life Cycle

ASP.NET life cycle specifies, how:

ASP.NET processes pages to produce dynamic output

The application and its pages are instantiated and processed

ASP.NET compiles the pages dynamically

The ASP.NET life cycle could be divided into two groups:

Application Life Cycle

Page Life Cycle

ASP.NET Application Life Cycle

The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser sends this request to

the web server.

A unified pipeline receives the first request and the following events take place:

o An object of the class Application Manager is created.

o An object of the class Hosting Environment is created to provide information regarding

the resources.

o Top level items in the application are compiled.

Response objects are created. The application objects such as HttpContext, HttpRequest and

HttpResponse are created and initialized.

Page 49: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

49 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

An instance of the HttpApplication object is created and assigned to the request.

The request is processed by the HttpApplication class. Different events are raised by this class for

processing the request.

ASP.NET Page Life Cycle

When a page is requested, it is loaded into the server memory, processed, and sent to the browser. Then

it is unloaded from the memory. At each of these steps, methods and events are available, which could

be overridden according to the need of the application. In other words, you can write your own code to

override the default code.

The Page class creates a hierarchical tree of all the controls on the page. All the components on the page,

except the directives, are part of this control tree. You can see the control tree by adding trace= "true"

to the page directive. We will cover page directives and tracing under 'directives' and 'event handling'.

The page life cycle phases are

Initialization

Instantiation of the controls on the page

Restoration and maintenance of the state

Execution of the event handler codes

Page rendering

Understanding the page cycle helps in writing codes for making some specific thing happen at any stage

of the page life cycle. It also helps in writing custom controls and initializing them at right time, populate

their properties with view-state data and run control behavior code.

Following are the different stages of an ASP.NET page

Page request - When ASP.NET gets a page request, it decides whether to parse and compile the

page, or there would be a cached version of the page; accordingly the response is sent.

Page 50: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

50 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Starting of page life cycle - At this stage, the Request and Response objects are set. If the request

is an old request or post back, the IsPostBack property of the page is set to true. The UICulture

property of the page is also set.

Page initialization - At this stage, the controls on the page are assigned unique ID by setting the

UniqueID property and the themes are applied. For a new request, postback data is loaded and

the control properties are restored to the view-state values.

Page load - At this stage, control properties are set using the view state and control state values.

Validation - Validate method of the validation control is called and on its successful execution,

the IsValid property of the page is set to true.

Postback event handling - If the request is a postback (old request), the related event handler is

invoked.

Page rendering - At this stage, view state for the page and all controls are saved. The page calls

the Render method for each control and the output of rendering is written to the OutputStream

class of the Response property of page.

Unload - The rendered page is sent to the client and page properties, such as Response and

Request, are unloaded and all cleanup done.

ASP.NET Page Life Cycle Events

At each stage of the page life cycle, the page raises some events, which could be coded. An event handler

is basically a function or subroutine, bound to the event, using declarative attributes such as Onclick or

handle.

Following are the page life cycle events

PreInit - PreInit is the first event in page life cycle. It checks the IsPostBack property and

determines whether the page is a postback. It sets the themes and master pages, creates

dynamic controls, and gets and sets profile property values. This event can be handled by

overloading the OnPreInit method or creating a Page_PreInit handler.

Page 51: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

51 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Init - Init event initializes the control property and the control tree is built. This event can be

handled by overloading the OnInit method or creating a Page_Init handler.

InitComplete - InitComplete event allows tracking of view state. All the controls turn on view-

state tracking.

LoadViewState - LoadViewState event allows loading view state information into the controls.

LoadPostData - During this phase, the contents of all the input fields are defined with the <form>

tag are processed.

PreLoad - PreLoad occurs before the post back data is loaded in the controls. This event can be

handled by overloading the OnPreLoad method or creating a Page_PreLoad handler.

Load - The Load event is raised for the page first and then recursively for all child controls. The

controls in the control tree are created. This event can be handled by overloading the OnLoad

method or creating a Page_Load handler.

LoadComplete - The loading process is completed, control event handlers are run, and page

validation takes place. This event can be handled by overloading the OnLoadComplete method

or creating a Page_LoadComplete handler

PreRender - The PreRender event occurs just before the output is rendered. By handling this

event, pages and controls can perform any updates before the output is rendered.

PreRenderComplete - As the PreRender event is recursively fired for all child controls, this event

ensures the completion of the pre-rendering phase.

SaveStateComplete - State of control on the page is saved. Personalization, control state and

view state information is saved. The HTML markup is generated. This stage can be handled by

overriding the Render method or creating a Page_Render handler.

UnLoad - The UnLoad phase is the last phase of the page life cycle. It raises the UnLoad event for

all controls recursively and lastly for the page itself. Final cleanup is done and all resources and

references, such as database connections, are freed. This event can be handled by modifying the

OnUnLoad method or creating a Page_UnLoad handler.

Page 52: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

52 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections; using System.Configuration; using System.Data; using System.Linq; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.HtmlControls; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Xml.Linq; public partial class PageLiftCycle : System.Web.UI.Page { //1.Check the IsPostBack property to determine whether this is the first time the page is being processed. //2.Create or re-create dynamic controls. //3.Set a master page dynamically. //4.Set the Theme property dynamically. protected void Page_PreInit(object sender, EventArgs e) { Response.Write("<br/>" + "PreInit"); //Dynamically add master page this.MasterPageFile = "KnackHook.master"; //Dynamically add Themes this.Theme = "ThemeName"; //Dynamically create controls TextBox tb = new TextBox(); tb.ID = "tbx1"; tb.Text = "KnackHook"; } //1.This event fires after each control has been initialized. //2.Each control's UniqueID is set and any skin settings have been applied. //3.Use this event to read or initialize control properties. //4.The "Init" event is fired first for the bottom-most control in the hierarchy, and then fired up the hierarchy until it is fired for the page itself. protected void Page_Init(object sender, EventArgs e) { Response.Write("<br/>" + "Init"); } //1.Until now the viewstate values are not yet loaded, hence you can use this event to make changes to the view state that you want to ensure are persisted after the next postback. //2.Raised by the Page object.

Page 53: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

53 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//3.Use this event for processing tasks that require all initialization to be complete. protected void Page_InitComplete(object sender, EventArgs e) { Response.Write("<br/>" + "InitComplete"); } //1.Raised after the page loads view state for itself and all controls, and after it processes postback data that is included with the Request instance. //2.Before the Page instance raises this event, it loads view state for itself and all controls, and then processes any postback data included with the Request instance. //3.Loads ViewState: ViewState data are loaded to controls. //4.Loads Postback data: Postback data are now handed to the page controls. protected override void OnPreLoad(EventArgs e) { Response.Write("<br/>" + "PreLoad"); } //1.The Page object calls the OnLoad method on the Page object, and then recursively does the same for each child control until the page and all controls are loaded. The Load event of individual controls occurs after the Load event of the page. //2.This is the first place in the page lifecycle that all values are restored. //3.Most code checks the value of IsPostBack to avoid unnecessarily resetting state. //4.You may also call Validate and check the value of IsValid in this method. //5.You can also create dynamic controls in this method. //6.Use the OnLoad event method to set properties in controls and establish database connections. protected void Page_Load(object sender, EventArgs e) { //Binding data to grid view and other operations //partial code only don't threat it as complete code for databinding DataSet s=new DataSet(); GridView1.DataSource = s; GridView1.DataBind(); Response.Write("<br/>" + "Load"); } //1.Raised at the end of the event-handling stage. //2.Use this event for tasks that require that all other controls on the page be loaded. protected void Page_LoadComplete(object sender, EventArgs e) { Response.Write("<br/>" + "LoadComplete"); } //1.Raised after the Page object has created all controls that are required in order to render the page, including child controls of composite controls. //2.The Page object raises the PreRender event on the Page object, and then recursively does the same for each child control. The PreRender event of individual controls occurs after the PreRender event of the page. //3.The PreRender event of individual controls occurs after the PreRender event of the page. //4.Allows final changes to the page or its control. //5.This event takes place before saving ViewState, so any changes made here are saved. //6.For example: After this event, you cannot change any property of a button or change any viewstate value. //7.Each data bound control whose DataSourceID property is set calls its DataBind method.

Page 54: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

54 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

//8.Use the event to make final changes to the contents of the page or its controls. protected override void OnPreRender(EventArgs e) { Response.Write("<br/>" + "PreRender"); } //1.Raised after view state and control state have been saved for the page and for all controls. //2.Before this event occurs, ViewState has been saved for the page and for all controls. //3.Any changes to the page or controls at this point will be ignored. //4.Use this event perform tasks that require the view state to be saved, but that do not make any changes to controls. protected override void OnSaveStateComplete(EventArgs e) { Response.Write("<br/>" + "SaveStateComplete"); } //1.This event is used for cleanup code. //2.At this point, all processing has occurred and it is safe to dispose of any remaining objects, including the Page object. //3.Cleanup can be performed on: // ◦Instances of classes, in other words objects //◦Closing opened files //◦Closing database connections. //4.This event occurs for each control and then for the page. //5.During the unload stage, the page and its controls have been rendered, so you cannot make further changes to the response stream. //6.If you attempt to call a method such as the Response.Write method then the page will throw an exception. protected void Page_UnLoad(object sender, EventArgs e) { //Runtime Error : Response is not available in this context. //Response.Write("<br/>" + "UnLoad"); //Error } }

ASP.NET – Directives

ASP.NET directives are instructions to specify optional settings, such as registering a custom control and

page language. These settings describe how the web forms (.aspx) or user controls (.ascx) pages are

processed by the .Net framework.

The syntax for declaring a directive is:

<%@ directive_name attribute=value [attribute=value] %>

Page 55: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

55 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

In this section, we will just introduce the ASP.NET directives and we will use most of these directives

throughout the tutorials.

The Application Directive

The Application directive defines application-specific attributes. It is provided at the top of the

global.aspx file.

The basic syntax of Application directive is:

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

The attributes of the Application directive are:

Attributes Description

Inherits The name of the class from which to inherit.

Description The text description of the application. Parsers and compilers ignore

this.

Language The language used in code blocks.

The Assembly Directive

The Assembly directive links an assembly to the page or the application at parse time. This could appear

either in the global.asax file for application-wide linking, in the page file, a user control file for linking to

a page or user control.

The basic syntax of Assembly directive is:

<%@ Assembly Name ="myassembly" %>

Page 56: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

56 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The attributes of the Assembly directive are:

Attributes Description

Name The name of the assembly to be linked.

Src The path to the source file to be linked and compiled dynamically.

The Control Directive

The control directive is used with the user controls and appears in the user control (.ascx) files.

The basic syntax of Control directive is:

<%@ Control Language="C#" EnableViewState="false" %>

The attributes of the Control directive are:

Attributes Description

AutoEventWireup The Boolean value that enables or disables automatic association of

events to handlers.

ClassName The file name for the control.

Debug The Boolean value that enables or disables compiling with debug

symbols.

Description The text description of the control page, ignored by compiler.

Page 57: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

57 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

EnableViewState The Boolean value that indicates whether view state is maintained

across page requests.

Explicit For VB language, tells the compiler to use option explicit mode.

Inherits The class from which the control page inherits.

Language The language for code and script.

Src The filename for the code-behind class.

Strict For VB language, tells the compiler to use the option strict mode.

The Implements Directive

The Implement directive indicates that the web page, master page or user control page must implement

the specified .Net framework interface.

The basic syntax for implements directive is:

<%@ Implements Interface="interface_name" %>

The Import Directive

The Import directive imports a namespace into a web page, user control page of application. If the Import

directive is specified in the global.asax file, then it is applied to the entire application. If it is in a page of

user control page, then it is applied to that page or control.

The basic syntax for import directive is:

Page 58: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

58 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<%@ namespace="System.Drawing" %>

The Master Directive

The Master directive specifies a page file as being the mater page.

The basic syntax of sample MasterPage directive is:

<%@ MasterPage Language="C#" AutoEventWireup="true" CodeFile="SiteMater.master.cs"

Inherits="SiteMaster" %>

The MasterType Directive

The MasterType directive assigns a class name to the Master property of a page, to make it strongly

typed.

The basic syntax of MasterType directive is:

<%@ MasterType attribute="value"[attribute="value" ...] %>

The OutputCache Directive

The OutputCache directive controls the output caching policies of a web page or a user control.

The basic syntax of OutputCache directive is:

<%@ OutputCache Duration="15" VaryByParam="None" %>

The Page Directive

The Page directive defines the attributes specific to the page file for the page parser and the compiler.

The basic syntax of Page directive is:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default"

Trace="true" %>

Page 59: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

59 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The attributes of the Page directive are:

Attributes Description

AutoEventWireup The Boolean value that enables or disables page events that are being

automatically bound to methods; for example, Page_Load.

Buffer The Boolean value that enables or disables HTTP response buffering.

ClassName The class name for the page.

ClientTarget The browser for which the server controls should render content.

CodeFile The name of the code behind file.

Debug The Boolean value that enables or disables compilation with debug

symbols.

Description The text description of the page, ignored by the parser.

EnableSessionState It enables, disables, or makes session state read-only.

EnableViewState The Boolean value that enables or disables view state across page

requests.

Page 60: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

60 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ErrorPage URL for redirection if an unhandled page exception occurs.

Inherits The name of the code behind or other class.

Language The programming language for code.

Src The file name of the code behind class.

Trace It enables or disables tracing.

TraceMode It indicates how trace messages are displayed, and sorted by time or

category.

Transaction It indicates if transactions are supported.

ValidateRequest The Boolean value that indicates whether all input data is validated

against a hardcoded list of values.

The PreviousPageType Directive

The PreviousPageType directive assigns a class to a page, so that the page is strongly typed.

The basic syntax for a sample PreviousPagetype directive is:

<%@ PreviousPageType attribute="value"[attribute="value" ...] %>

Page 61: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

61 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The Reference Directive

The Reference directive indicates that another page or user control should be compiled and linked to the

current page.

The basic syntax of Reference directive is:

<%@ Reference Page ="somepage.aspx" %>

The Register Directive

The Register derivative is used for registering the custom server controls and user controls.

The basic syntax of Register directive is:

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

Provide control over many options affecting the compilation and execution of the web form.

Important directives:

@Page – main directive of the page

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

Inherits="KnackHook.KnackHook" %>

Which is used to define Language and CodeBehind properties of a Page and its events.

@Import – imports a namespace into the form

<%@Import namespace="System.Drawing" %>

@Assembly – attaches an assembly to the form when it is compiled

<%@ Assembly Name ="myassembly" Src="~/KnackHook1.aspx.cs" %>

@OutputCache – controls the ability of the forms to use cache feature

<%@OutputCache Duration="15" VaryByParam="None" %>

@Register – registers a user control to be used in a web form

<%@Register Src="~/Login.ascx" TagName="Login" TagPrefix="Uc" %>

@Master – defines a master for an application.

Page 62: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

62 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.master.cs"

Inherits="WebApplication1.KnackHook" %>

ASP.NET Controls

ASP.NET Web server controls are objects on ASP.NET Web pages that run when the page is requested and

that render markup to a browser. Many Web server controls resemble familiar HTML elements, such as

buttons and text boxes. Other controls encompass complex behavior, such as a calendar controls, and

controls that manage data connections.

Button Controls

ASP.NET provides three types of button control:

Button : It displays text within a rectangular area.

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

Image Button : It displays an image.

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

Basic syntax of button control:

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

Common properties of the button control:

Property Description

Text The text displayed on the button. This is for button and link button

controls only.

Page 63: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

63 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ImageUrl For image button control only. The image to be displayed for the

button.

AlternateText For image button control only. The text to be displayed if the browser

cannot display the image.

CausesValidation Determines whether page validation occurs when a user clicks the

button. The default is true.

CommandName A string value that is passed to the command event when a user clicks

the button.

CommandArgument A string value that is passed to the command event when a user clicks

the button.

PostBackUrl The URL of the page that is requested when the user clicks the

button.

Text Boxes and Labels

Text box controls are typically used to accept input from the user. A text box control can accept one or

more lines of text depending upon the settings of the TextMode attribute.

Label controls provide an easy way to display text which can be changed from one execution of a page

to the next. If you want to display text that does not change, you use the literal text.

Basic syntax of text control:

Page 64: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

64 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

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

Common Properties of the Text Box and Labels:

Property Description

TextMode Specifies the type of text box. SingleLine creates a standard text box,

MultiLIne creates a text box that accepts more than one line of text

and the Password causes the characters that are entered to be

masked. The default is SingleLine.

Text The text content of the text box.

MaxLength The maximum number of characters that can be entered into the text

box.

Wrap It determines whether or not text wraps automatically for multi-line

text box; default is true.

ReadOnly Determines whether the user can change the text in the box; default

is false, i.e., the user can change the text.

Columns The width of the text box in characters. The actual width is

determined based on the font that is used for the text entry.

Page 65: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

65 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Rows The height of a multi-line text box in lines. The default value is 0,

means a single line text box.

The mostly used attribute for a label control is 'Text', which implies the text displayed on the label.

Check Boxes and Radio Buttons

A check box displays a single option that the user can either check or uncheck and radio buttons present

a group of options from which the user can select just one option. To create a group of radio buttons,

you specify the same name for the GroupName attribute of each radio button in the group. If more than

one group is required in a single form, then specify a different group name for each group. If you want

check box or radio button to be selected when the form is initially displayed, set its Checked attribute to

true. If the Checked attribute is set to true for multiple radio buttons in a group, then only the last one is

considered as true.

Basic syntax of check box:

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

</asp:CheckBox>

Basic syntax of radio button:

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

</asp: RadioButton>

Common properties of check boxes and radio buttons:

Property Description

Text The text displayed next to the check box or radio button.

Page 66: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

66 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Checked Specifies whether it is selected or not, default is false.

GroupName Name of the group the control belongs to.

List Controls

ASP.NET provides the following controls

Drop-down list,

List box,

Radio button list,

Check box list,

Bulleted list.

These control let a user choose from one or more items from the list. List boxes and drop-down lists

contain one or more list items. These lists can be loaded either by code or by the ListItemCollection

editor.

Basic syntax of list box control:

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

OnSelectedIndexChanged="ListBox1_SelectedIndexChanged">

</asp:ListBox>

Basic syntax of drop-down list control:

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

OnSelectedIndexChanged="DropDownList1_SelectedIndexChanged">

</asp:DropDownList>

Common properties of list box and drop-down Lists:

Page 67: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

67 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Property Description

Items The collection of ListItem objects that represents the items in the

control. This property returns an object of type ListItemCollection.

Rows Specifies the number of items displayed in the box. If actual list

contains more rows than displayed then a scroll bar is added.

SelectedIndex The index of the currently selected item. If more than one item is

selected, then the index of the first selected item. If no item is

selected, the value of this property is -1.

SelectedValue The value of the currently selected item. If more than one item is

selected, then the value of the first selected item. If no item is

selected, the value of this property is an empty string ("").

SelectionMode Indicates whether a list box allows single selections or multiple

selections.

Common properties of each list item objects:

Property Description

Text The text displayed for the item.

Selected Indicates whether the item is selected.

Page 68: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

68 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Value A string value associated with the item.

It is important to notes that:

To work with the items in a drop-down list or list box, you use the Items property of the control.

This property returns a ListItemCollection object which contains all the items of the list.

The SelectedIndexChanged event is raised when the user selects a different item from a drop-

down list or list box.

The ListItemCollection

The ListItemCollection object is a collection of ListItem objects. Each ListItem object represents one item

in the list. Items in a ListItemCollection are numbered from 0.

When the items into a list box are loaded using strings like: lstcolor.Items.Add("Blue"), then both the

Text and Value properties of the list item are set to the string value you specify. To set it differently you

must create a list item object and then add that item to the collection.

The ListItemCollection Editor is used to add item to a drop-down list or list box. This is used to create a

static list of items. To display the collection editor, select edit item from the smart tag menu, or select

the control and then click the ellipsis button from the Item property in the properties window.

Common properties of ListItemCollection:

Property Description

Item(integer) A ListItem object that represents the item at the specified index.

Page 69: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

69 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Count The number of items in the collection.

Common methods of ListItemCollection:

Methods Description

Add(string) Adds a new item at the end of the collection and assigns the string

parameter to the Text property of the item.

Add(ListItem) Adds a new item at the end of the collection.

Insert(integer, string) Inserts an item at the specified index location in the collection, and

assigns string parameter to the text property of the item.

Insert(integer, ListItem) Inserts the item at the specified index location in the collection.

Remove(string) Removes the item with the text value same as the string.

Remove(ListItem) Removes the specified item.

RemoveAt(integer) Removes the item at the specified index as the integer.

Clear Removes all the items of the collection.

FindByValue(string) Returns the item whose value is same as the string.

Page 70: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

70 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

FindByValue(Text) Returns the item whose text is same as the string.

Radio Button list and Check Box list

A radio button list presents a list of mutually exclusive options. A check box list presents a list of

independent options. These controls contain a collection of ListItem objects that could be referred to

through the Items property of the control.

Basic syntax of radio button list:

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

OnSelectedIndexChanged="RadioButtonList1_SelectedIndexChanged">

</asp:RadioButtonList>

Basic syntax of check box list:

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

OnSelectedIndexChanged="CheckBoxList1_SelectedIndexChanged">

</asp:CheckBoxList>

Common properties of check box and radio button lists:

Property Description

RepeatLayout This attribute specifies whether the table tags or the normal html

flow to use while formatting the list when it is rendered. The default

is Table.

Page 71: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

71 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

RepeatDirection It specifies the direction in which the controls to be repeated. The

values available are Horizontal and Vertical. Default is Vertical.

RepeatColumns It specifies the number of columns to use when repeating the

controls; default is 0.

Bulleted lists and Numbered lists:

The bulleted list control creates bulleted lists or numbered lists. These controls contain a collection of

ListItem objects that could be referred to through the Items property of the control.

Basic syntax of a bulleted list:

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

</asp:BulletedList>

Common properties of the bulleted list:

Property Description

BulletStyle This property specifies the style and looks of the bullets, or numbers.

RepeatDirection It specifies the direction in which the controls to be repeated. The

values available are Horizontal and Vertical. Default is Vertical.

RepeatColumns It specifies the number of columns to use when repeating the

controls; default is 0.

Page 72: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

72 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

HyperLink Control

The HyperLink control is like the HTML <a> element.

Basic syntax for a hyperlink control:

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

HyperLink

</asp:HyperLink>

It has the following important properties:

Property Description

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

NavigateUrl Target link URL.

Text The text to be displayed as the link.

Target The window or frame which loads the linked page.

Image Control

The image control is used for displaying images on the web page, or some alternative text, if the image

is not available.

Basic syntax for an image control:

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

Page 73: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

73 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

It has the following important properties:

Property Description

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

ImageAlign Alignment options for the control.

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

Validation controls

ASP.NET validation controls validate the user input data to ensure that useless, unauthenticated, or

contradictory data don't get stored.

ASP.NET provides the following validation controls:

RequiredFieldValidator

RangeValidator

CompareValidator

RegularExpressionValidator

CustomValidator

ValidationSummary

BaseValidator Class

Page 74: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

74 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The validation control classes are inherited from the BaseValidator class hence they inherit its properties

and methods. Therefore, it would help to take a look at the properties and the methods of this base class,

which are common for all the validation controls:

Members Description

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message is shown.

EnableClientScript Indicates whether client side validation will take.

Enabled Enables or disables the validator.

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.

IsValid Indicates whether the value of the control is valid.

SetFocusOnError It indicates whether in case of an invalid control, the focus should

switch to the related input control.

ValidationGroup The logical group of multiple validators, where this control belongs.

Page 75: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

75 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Validate() This method revalidates the control and updates the IsValid property.

RequiredFieldValidator Control

The RequiredFieldValidator control ensures that the required field is not empty. It is generally tied to a

text box to force input into the text box.

Syntax

<asp:RequiredFieldValidator ID="rfvcandidate"

runat="server" ControlToValidate ="ddlcandidate"

ErrorMessage="Please choose a candidate"

InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

RangeValidator Control

The RangeValidator control verifies that the input value falls within a predetermined range.

It has three specific properties:

Properties Description

Type It defines the type of the data. The available values are: Currency,

Date, Double, Integer, and String.

MinimumValue It specifies the minimum value of the range.

Page 76: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

76 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:

<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"

ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"

MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator Control

The CompareValidator control compares a value in one control with a fixed value or a value in another

control.

It has the following specific properties:

Properties Description

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare with.

ValueToCompare It specifies the constant value to compare with.

Page 77: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

77 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Operator It specifies the comparison operator, the available values are: Equal,

NotEqual, GreaterThan, GreaterThanEqual, LessThan,

LessThanEqual, and DataTypeCheck.

The basic syntax of the control is as follows:

<asp:CompareValidator ID="CompareValidator1" runat="server"

ErrorMessage="CompareValidator"></asp:CompareValidator>

RegularExpressionValidator

The RegularExpressionValidator allows validating the input text by matching against a pattern of a regular

expression. The regular expression is set in the ValidationExpression property.

The following table summarizes the commonly used syntax constructs for regular expressions:

Character Escapes Description

\b Matches a backspace.

\t Matches a tab.

\r Matches a carriage return.

\v Matches a vertical tab.

Page 78: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

78 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

\f Matches a form feed.

\n Matches a new line.

\ Escape character.

Apart from single character match, a class of characters could be specified that can be matched, called

the metacharacters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

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

\w Matches any alphanumeric character and underscore.

Page 79: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

79 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

\W Matches any non-word character.

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

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

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

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.

{N} N matches.

{N,} N or more matches.

Page 80: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

80 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{N,M} Between N and M matches.

The syntax of the control is as given:

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"

ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator

The CustomValidator control allows writing application specific custom validation routines for both the

client side and the server side validation. The client side validation is accomplished through the

ClientValidationFunction property. The client side validation routine should be written in a scripting

language, such as JavaScript or VBScript, which the browser can understand.

The server side validation routine must be called from the control's ServerValidate event handler. The

server side validation routine should be written in any .Net language, like C# or VB.Net.

The basic syntax for the control is as given

<asp:CustomValidator ID="CustomValidator1" runat="server"

ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>

Validation Summary

The ValidationSummary control does not perform any validation but shows a summary of all errors in

the page. The summary displays the values of the ErrorMessage property of all validation controls that

failed validation.

Page 81: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

81 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The following two mutually inclusive properties list out the error message:

ShowSummary : shows the error messages in specified format.

ShowMessageBox : shows the error messages in a separate window.

The syntax for the control is as given

<asp:ValidationSummary ID="ValidationSummary1" runat="server"

DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

Validation Groups

Complex pages have different groups of information provided in different panels. In such situation, a

need might arise for performing validation separately for separate group. This kind of situation is handled

using validation groups.

To create a validation group, you should put the input controls and the validation controls into the same

logical group by setting their ValidationGroupproperty.

Example

The following example describes a form to be filled up by all the students of a school, divided into four

houses, for electing the school president. Here, we use the validation controls to validate the user input.

This is the form in design view:

Page 82: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

82 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The content file code is as given:

<form id="form1" runat="server">

<table style="width: 66%;">

<tr>

<td class="style1" colspan="3" align="center">

<asp:Label ID="lblmsg"

Text="President Election Form : Choose your president" runat="server" />

</td>

</tr>

<tr>

<td class="style3"> Candidate:</td>

<td class="style2">

<asp:DropDownList ID="ddlcandidate" runat="server" style="width:239px">

<asp:ListItem>Please Choose a Candidate</asp:ListItem>

Page 83: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

83 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<asp:ListItem>M H Kabir</asp:ListItem>

<asp:ListItem>Steve Taylor</asp:ListItem>

<asp:ListItem>John Abraham</asp:ListItem>

<asp:ListItem>Venus Williams</asp:ListItem>

</asp:DropDownList>

</td>

<td>

<asp:RequiredFieldValidator ID="rfvcandidate"

runat="server" ControlToValidate ="ddlcandidate"

ErrorMessage="Please choose a candidate"

InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

</td>

</tr>

<tr>

<td class="style3">House:</td>

<td class="style2">

<asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">

<asp:ListItem>Red</asp:ListItem>

<asp:ListItem>Blue</asp:ListItem>

<asp:ListItem>Yellow</asp:ListItem>

Page 84: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

84 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<asp:ListItem>Green</asp:ListItem>

</asp:RadioButtonList>

</td>

<td>

<asp:RequiredFieldValidator ID="rfvhouse" runat="server"

ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >

</asp:RequiredFieldValidator>

<br />

</td>

</tr>

<tr>

<td class="style3">Class: </td>

<td class="style2">

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

</td>

<td>

<asp:RangeValidator ID="rvclass” runat="server" ControlToValidate="txtclass"

ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"

MinimumValue="6" Type="Integer">

</asp:RangeValidator>

</td>

</tr>

Page 85: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

85 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<tr>

<td class="style3">Email: </td>

<td class="style2">

<asp:TextBox ID="txtemail" runat="server" style="width:250px"></asp:TextBox>

</td>

<td>

<asp:RegularExpressionValidator ID="remail" runat="server"

ControlToValidate="txtemail" ErrorMessage="Enter your email"

ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

</asp:RegularExpressionValidator>

</td>

</tr>

<tr>

<td class="style3" align="center" colspan="3">

<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"

style="text-align: center" Text="Submit" style="width:140px" />

</td>

</tr>

</table>

<asp:ValidationSummary ID="ValidationSummary1" runat="server"

DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />

Page 86: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

86 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</form>

The code behind the submit button:

protected void btnsubmit_Click(object sender, EventArgs e)

{

if (Page.IsValid)

{

lblmsg.Text = "Thank You";

}

else

{

lblmsg.Text = "Fill up all the fields";

}

}

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%--Helps to make sure value needs to submit for the control associate with RequiredFieldValidator control, probably TextBox control--%> <div><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator></div> <%--Helps to make sure value needs to be specified in the given range like age b/w 18-30, for the control associate with RangeValidator control, probably TextBox control--%> <div><asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="RangeValidator"></asp:RangeValidator></div>

Page 87: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

87 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<%--Helps to make sure value needs to be specified format like Email address, for the control associate with RegularExpressionValidator control, probably TextBox control--%> <div><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator></div> <%--Helps to make sure value needs to be same like Password and ConfirmPassword, for the control associate with CompareValidator control, probably TextBox control--%> <div><asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator"></asp:CompareValidator></div> <%--Helps to display all error messages at common place--%> <div><asp:ValidationSummary ID="ValidationSummary1" runat="server" /></div> <%--Helps to build own logic to validate user input if none of the avalilable Validation Controls not meet the requirement--%> <div><asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator"></asp:CustomValidator></div> </div> </form> </body> </html>

Controls Examples:

Standard Controls

Data Controls

Validation Controls

Navigation Controls

Login Controls

Web Parts Controls

AJAX Extension Controls

Dynamic Data Controls

Reporting Controls

Standard Controls: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server">

Page 88: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

88 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<div> <%--Helps to display textbox to get input from user--%> <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox> <%--Helps to place plain text on the browser window--%> <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label> <%--Helps to submit form to the server and perform business logic based on user interaction--%> <asp:Button ID="Button1" runat="server" Text="Button" /> <%--Helps to select date from the control--%> <asp:Calendar ID="Calendar1" runat="server"></asp:Calendar> <%--Helps to select multiple options from the given options--%> <asp:CheckBox ID="CheckBox1" runat="server" /> <%--Helps to select only one option from the given options--%> <asp:RadioButton ID="RadioButton1" runat="server" /> <%--Helps to select one or more options from the given list of options--%> <asp:DropDownList ID="DropDownList1" runat="server"></asp:DropDownList> <%--Helps to browse and upload specified file to the server--%> <asp:FileUpload ID="FileUpload1" runat="server" /> <%--Helps to navigate from one page to the another page or website--%> <asp:HyperLink ID="HyperLink1" runat="server">HyperLink</asp:HyperLink> <%--Helps to place image on the website--%> <asp:Image ID="Image1" runat="server" /> <%--Acts as a container for other controls available in the Asp.Net--%> <asp:PlaceHolder ID="PlaceHolder1" runat="server"></asp:PlaceHolder> <%--Helps to place Advertisements on the webpage very easyly.--%> <asp:AdRotator ID="AdRotator1" runat="server" /> </div> </form> </body> </html>

Data Controls: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>

Page 89: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

89 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%--Data Bound Controls--%> <%--Helps to display data in the form of graphical representation,like Bar Graphs, Line Graphs ,Column Graphs and Pie Chart etc.--%> <asp:Chart ID="Chart1" runat="server"> <Series> <asp:Series Name="Series1"></asp:Series> </Series> <ChartAreas> <asp:ChartArea Name="ChartArea1"></asp:ChartArea> </ChartAreas> </asp:Chart> <%--Helps to display data in the form of tabular format--%> <asp:DataList ID="DataList1" runat="server"></asp:DataList> <%--Helps to display data in the form of tabular format--%> <asp:GridView ID="GridView1" runat="server"></asp:GridView> <%--Helps to display data in the form of user defined format--%> <asp:Repeater ID="Repeater1" runat="server"></asp:Repeater> <%--Data Sourse Controls--%> <%--Helps to provide connection to the Sql Server database objects--%> <asp:SqlDataSource ID="SqlDataSource1" runat="server"></asp:SqlDataSource> <%--Helps to provide connection to the Xml objects--%> <asp:XmlDataSource ID="XmlDataSource1" runat="server"></asp:XmlDataSource> <%--Helps to provide connection to the LINQ objects--%> <asp:LinqDataSource ID="LinqDataSource1" runat="server"></asp:LinqDataSource> </div> </form> </body> </html>

Validation Controls: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %>

Page 90: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

90 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%--Helps to make sure value needs to submit for the control associate with RequiredFieldValidator control, probably TextBox control--%> <div><asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator></div> <%--Helps to make sure value needs to be specified in the given range like age b/w 18-30, for the control associate with RangeValidator control, probably TextBox control--%> <div><asp:RangeValidator ID="RangeValidator1" runat="server" ErrorMessage="RangeValidator"></asp:RangeValidator></div> <%--Helps to make sure value needs to be specified format like Email address, for the control associate with RegularExpressionValidator control, probably TextBox control--%> <div><asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator></div> <%--Helps to make sure value needs to be same like Password and ConfirmPassword, for the control associate with CompareValidator control, probably TextBox control--%> <div><asp:CompareValidator ID="CompareValidator1" runat="server" ErrorMessage="CompareValidator"></asp:CompareValidator></div> <%--Helps to display all error messages at common place--%> <div><asp:ValidationSummary ID="ValidationSummary1" runat="server" /></div> <%--Helps to build own logic to validate user input if none of the avalilable Validation Controls not meet the requirement--%> <div><asp:CustomValidator ID="CustomValidator1" runat="server" ErrorMessage="CustomValidator"></asp:CustomValidator></div> </div> </form> </body> </html>

Navigation Controls: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %>

Page 91: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

91 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<%@ Register Assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%-- Helps to provide Menu for applications --%> <asp:Menu ID="Menu1" runat="server"></asp:Menu> <%-- Helps to provide SiteMap like Bread craumbs for the website--%> <asp:SiteMapPath ID="SiteMapPath1" runat="server"></asp:SiteMapPath> <%-- Helps to display information in a hierarchy level --%> <asp:TreeView ID="TreeView1" runat="server"></asp:TreeView> </div> </form> </body> </html>

Login Controls: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%-- Helps to build login form with membership providers very easily --%> <div><asp:Login ID="Login1" runat="server"></asp:Login></div> <%-- Helps to build ChangePassword form with membership providers very easily --%> <div><asp:ChangePassword ID="ChangePassword1" runat="server"></asp:ChangePassword></div> <%-- Helps to build Create new user form with membership providers very easily --%> <div><asp:CreateUserWizard ID="CreateUserWizard1" runat="server">

Page 92: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

92 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<WizardSteps> <asp:CreateUserWizardStep ID="CreateUserWizardStep1" runat="server"> </asp:CreateUserWizardStep> <asp:CompleteWizardStep ID="CompleteWizardStep1" runat="server"> </asp:CompleteWizardStep> </WizardSteps> </asp:CreateUserWizard></div> <%-- Helps to get Login Name with membership providers very easily --%> <div><asp:LoginName ID="LoginName1" runat="server" /></div> <%-- Helps to get Login Status with membership providers very easily --%> <div><asp:LoginStatus ID="LoginStatus1" runat="server" /></div> <%-- Helps to get Login View with membership providers very easily --%> <div><asp:LoginView ID="LoginView1" runat="server"></asp:LoginView></div> <%-- Helps to get PasswordRecovery View with membership providers very easily --%> <div><asp:PasswordRecovery ID="PasswordRecovery1" runat="server"></asp:PasswordRecovery></div> </div> </form> </body> </html>

AJAX Extension Controls: <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <%-- Helps to implement Asynchronous PostBack behaviour for the webform --%> <div><asp:ScriptManager ID="ScriptManager1" runat="server"></asp:ScriptManager></div> <%-- Helps to implement Asynchronous PostBack behaviour for the webform --%> <div><asp:UpdatePanel ID="UpdatePanel1" runat="server"></asp:UpdatePanel></div> </div> </form> </body>

Page 93: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

93 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</html>

Themes and skins

Themes and skins provide an easy way to define the look of pages and controls and apply the style across

all the pages and controls on the site or multiple sites. Themes are made up of skins, cascading style sheets

(CSS), images, and other resources, and they are created within special folders in the server structure.

Themes are like CSS styles - they both define a set of common attributes that can be applied to controls

and elements on any page, however CSS is limited to the presentation elements of a control. Themes

allow the customisation of any property of an Asp.net control, such as text values, icon glyphs, template

layouts and so on. Unlike CSS themes do not cascade, so by default any property values defined in a theme

referenced by a page's Theme property override the property values declaratively set on a control, unless

you explicitly apply the theme using the StyleSheetTheme property. You can only set one theme per page.

A skin is a set of properties and templates that can be used to standardise the font, size and other

characteristics of controls on a page. A theme can consist of multiple skins and style sheets to define the

overall look and feel of the web application.

Creating and Using Themes:

Let's start off with a standard ASP.Net page with a few controls loaded on.

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

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h1>Theme Demo Page</h1>

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

Page 94: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

94 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<asp:Button ID="Button1" runat="server" Text="Button" /><br />

<br />

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

</div>

</form>

</body>

</html>

By default this looks a little boring, but we can quickly create a theme to brighten up this page.

Themes are located within an App_Theme folder in the website structure. You must create this using the

Solution Explorer by right clicking on the project, then Add ASP.Net Folder, then Theme. This will create

the App_Theme folder and a default Theme1 folder. You should rename this to whatever you want the

theme to be called. In this example I am using "default".

Page 95: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

95 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

To create a skin for a control, right click on the 'default' folder and add new item. Select Skin from the list.

Visual Studio will present a default skin which you should delete. We will start off by changing the look of

the textbox control on the form.

We can create a customised skin for the control by keying in a declaration for an asp textbox control,

which is just the same as declaration of a server-side control in an ASPX, except that we don't set the ID

or value properties in the skin. The runtime will apply the property values and styles in this skin to all of

the textbox controls on every page using the 'default' theme.

The Skin file for a textbox looks like this:

<asp:TextBox runat="server" BorderColor="#3366CC" BorderWidth="1px" ForeColor="#003399" Font-

Names="Verdana" Font-Size="8pt"></asp:TextBox>

This will automatically style every textbox on every page that uses this theme. I have also created a skin

for the button and the calendar controls show below.

<asp:Button runat="server" BorderWidth="1px" BorderColor="#3366CC" ForeColor="#003399" Font-

Names="Verdana" Font-Size="8pt" />

Skin for ASP Button

<asp:Calendar runat="server" BackColor="White"

BorderColor="#3366CC" BorderWidth="1px" CellPadding="1"

DayNameFormat="Shortest" Font-Names="Verdana" Font-Size="8pt"

ForeColor="#003399" Height="200px" Width="220px">

<SelectedDayStyle BackColor="#009999" Font-Bold="True"

ForeColor="#CCFF99" />

<SelectorStyle BackColor="#99CCCC" ForeColor="#336666" />

<WeekendDayStyle BackColor="#CCCCFF" />

<OtherMonthDayStyle ForeColor="#999999" />

<TodayDayStyle BackColor="#99CCCC" ForeColor="White" />

<NextPrevStyle Font-Size="8pt" ForeColor="#CCCCFF" />

<DayHeaderStyle BackColor="#99CCCC" ForeColor="#336666" Height="1px" />

<TitleStyle BackColor="#003399" BorderColor="#3366CC" BorderWidth="1px"

Font-Bold="True"

Page 96: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

96 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Font-Size="10pt" ForeColor="#CCCCFF" Height="25px" />

</asp:Calendar>

Skin for ASP Calendar control

Applying Themes to Specific Pages:

Now, all we need to do is link our asp page to our default theme. This is done by adding a Theme attribute

to the page directive.

<%@ Page Language="C#" Theme="default" AutoEventWireup="true" CodeFile="Default.aspx.cs"

Inherits="_Default" %>

Page 97: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

97 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Now when you run the application the page looks much brighter, with a colourful calendar control.

Applying Themes to All Pages:

Instead of individually applying themes to your pages you can specify the theme to use for all pages in the

web.config file. Under the System.Web section simply add a page node as show below, replacing default

with you themes name.

<?xml version="1.0"?>

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

<system.web>

<pages theme="default" />

<compilation debug="true"/>

<authentication mode="Windows"/>

</system.web>

</configuration>

Excluding Controls:

You may find that you do not need or require a theme on particular controls on a page. You can tell the

runtime not to apply a theme to an asp control by specifying an additional parameter in the control

declaration: EnableTheming="false".

<asp:Button EnableTheming="false" ID="Button1" runat="server" Text="Button" />

Master Pages

Master pages allow you to create a consistent look and behavior for all the pages (or group of pages) in

your web application. A master page provides a template for other pages, with shared layout and

functionality. The master page defines placeholders for the content, which can be overridden by content

pages. The output result is a combination of the master page and the content page. The content pages

contain the content you want to display. When users request the content page, ASP.NET merges the

pages to produce output that combines the layout of the master page with the content of the content

page.

Master Page Example:

Page 98: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

98 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<%@ Master %>

<html>

<body>

<h1>Standard Header From Masterpage</h1>

<asp:ContentPlaceHolder id="CPH1" runat="server">

</asp:ContentPlaceHolder>

</body>

</html>

The master page above is a normal HTML page designed as a template for other pages. The @

Master directive defines it as a master page. The master page contains a placeholder

tag <asp:ContentPlaceHolder> for individual content. The id="CPH1" attribute identifies the

placeholder, allowing many placeholders in the same master page. This master page was saved with the

name "master1.master".

Content Page With Controls

<%@ Page MasterPageFile="master1.master" %>

<asp:Content ContentPlaceHolderId="CPH1" runat="server">

<h2>KnackHook</h2>

<form runat="server">

<asp:TextBox id="textbox1" runat="server" />

<asp:Button id="button1" runat="server" text="Button" />

</form>

</asp:Content>

The content page above demonstrates how .NET controls can be inserted into the content page just like

an into an ordinary page.

Master pages in ASP.NET works as a template that you can reference this page in all other content

pages. Master pages enable you to define the look and feel of all the pages in your site in a single

location. If you have done changes in master page, then the changes will reflect in all the web pages that

reference master pages. 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.

Page 99: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

99 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ContentPlaceHolder control is available only on master page. You can use more than one

ContentPlaceHolder control in master page. To create regions that content pages can fill in, you need to

define ContentPlaceHolder controls in master page as follows:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.master.cs" Inherits="WebApplication1.KnackHook" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <div> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> </asp:ContentPlaceHolder> </div> </form> </body> </html> The page-specific content is then put inside a Content control that points to the relevant

ContentPlaceHolder:

<%@ Page Title="" Language="C#" MasterPageFile="~/KnackHook.Master" AutoEventWireup="true" CodeBehind="KnackHook2.aspx.cs" Inherits="WebApplication1.KnackHook2" %> <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server"> My Content Page Heading </asp:Content> <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server"> <h1>My Content Page Body</h1> </asp:Content>

Note that the ContentPlaceHolderID attribute of the Content control points to the ContentPlaceHolder

that is defined in the master page. The master page is identified by a special @ Master directive that

replaces the @ Page directive that is used for ordinary .aspx pages.

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.master.cs"

Inherits="WebApplication1.KnackHook" %>

About User Control?

User Control provides reusability behavior for asp.net webforms.It’s having extention as .ascx

Page 100: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

100 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Here we are developing Login form as User Control,this Login User Control will be used in any of the

applications or forsms by using register directive.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="LoginUserControl.ascx.cs" Inherits="WebApplication1.LoginUserControl" %> <div> <table> <tr> <%-- Email --%> <td> <asp:Label ID="lblName" runat="server"></asp:Label></td> <td> <asp:TextBox ID="tbxEmail" runat="server"></asp:TextBox></td> <td> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbxEmail" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator></td> </tr> <%-- Password --%> <tr> <td> <asp:Label ID="lblPassword" runat="server"></asp:Label></td> <asp:TextBox ID="tbxPassword" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="tbxPassword" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> </tr> <tr> <td colspan="2"><asp:Button ID="btnLogin" Text="Login" runat="server" /></td> <td><asp:Button ID="btnReset" Text="Reset" runat="server" /></td> </tr> </table> </div>

Usage of Login User control.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <%@Register Src="~/LoginUserControl.ascx" TagName="Login" TagPrefix="Uc" %> <!DOCTYPE html>

Page 101: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

101 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <Uc:Login id="Login" runat="server"></Uc:Login> </div> </form> </body> </html>

State Management

View State

The view state is the state of the page and all its controls. It is automatically maintained across posts by

the ASP.NET framework.

Page 102: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

102 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

When a page is sent back to the client, the changes in the properties of the page and its controls are

determined, and stored in the value of a hidden input field named _VIEWSTATE. When the page is again

posted back, the _VIEWSTATE field is sent to the server with the HTTP request.

The view state could be enabled or disabled for:

The entire application by setting the EnableViewState property in the <pages> section of

web.config file.

A page by setting the EnableViewState attribute of the Page directive, as <%@ Page

Language="C#" EnableViewState="false" %>

A control by setting the Control.EnableViewState property.

It is implemented using a view state object defined by the StateBag class which defines a collection of

view state items. The state bag is a data structure containing attribute value pairs, stored as strings

associated with objects.

Properties

Properties Description

Item(name) The value of the view state item with the specified name. This is the

default property of the StateBag class.

Count The number of items in the view state collection.

Keys Collection of keys for all the items in the collection.

Page 103: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

103 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Values Collection of values for all the items in the collection.

The StateBag class has the following methods

Methods Description

Add(name, value) Adds an item to the view state collection and existing item is

updated.

Clear Removes all the items from the collection.

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

object.

Finalize Allows it to free resources and perform other cleanup operations.

GetEnumerator Returns an enumerator that iterates over all the key/value pairs of

the StateItem objects stored in the StateBag object.

GetType Gets the type of the current instance.

IsItemDirty Checks a StateItem object stored in the StateBag object to evaluate

whether it has been modified.

Page 104: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

104 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Remove(name) Removes the specified item.

SetDirty Sets the state of the StateBag object as well as the Dirty property of

each of the StateItem objects contained by it.

SetItemDirty Sets the Dirty property for the specified StateItem object in the

StateBag object.

ToString Returns a string representing the state bag object.

Example:

The following example demonstrates the concept of storing view state. Let us keep a counter, which is

incremented each time the page is posted back by clicking a button on the page. A label control shows

the value in the counter.

The markup file code is as follows

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

Inherits="statedemo._Default" %>

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

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>

Untitled Page

</title>

Page 105: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

105 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</head>

<body>

<form id="form1" runat="server">

<div>

<h3>View State demo</h3>

Page Counter:

<asp:Label ID="lblCounter" runat="server" />

<asp:Button ID="btnIncrement" runat="server" Text="Add Count" onclick="btnIncrement_Click"/>

</div>

</form>

</body>

</html>

The code behind file for the example is shown here

public partial class _Default : System.Web.UI.Page

{

public int counter

{

get

{

if (ViewState["pcounter"] != null)

{

Page 106: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

106 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

return ((int)ViewState["pcounter"]);

}

else

{

return 0;

}

}

set

{

ViewState["pcounter"] = value;

}

}

protected void Page_Load(object sender, EventArgs e)

{

lblCounter.Text = counter.ToString();

counter++;

}

}

It would produce the following result:

Page 107: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

107 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Query String

Query String is passed in the URL. They store the value in the form of Key-Value pair. You will have to

maintain the Query Strings when you pass it from one page to second page and second page to the third

page. when redirecting a request from one page to another page, you can pass the Query String.

Example:

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

<!DOCTYPE html>

<script runat="server"></script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>asp.net QueryString example: how to use QueryString</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h2 style="color:Navy">QueryString Example</h2>

<asp:HyperLink

ID="HyperLink1"runat="server"

NavigateUrl="~/Image.aspx?ImageID=1&ImageName=Elephant"

Text="Test QueryString">

</asp:HyperLink>

</div>

</form>

</body>

Page 108: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

108 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</html>

Image.aspx

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

<!DOCTYPE html>

<script runat="server">

protected void Page_Load(object sender, System.EventArgs e) {

string ID = Request.QueryString["ImageID"];

string Name = Request.QueryString["ImageName"];

Label1.Text = "ImageID: "+ ID;

Label2.Text = "Image name: "+ Name;

Image1.ImageUrl = "~/Images/"+Name+".jpg";

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>asp.net QueryString example</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h2 style="color:Red">QueryString Example: Image View</h2>

<asp:Label

ID="Label1"

runat="server"

Font-Size="Large"

ForeColor="SeaGreen”>

</asp:Label>

<br />

<asp:Label

Page 109: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

109 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ID="Label2"

runat="server"

Font-Size="Large"

ForeColor="SeaGreen">

</asp:Label>

<br />

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

</div>

</form>

</body>

</html>

Output

Page 110: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

110 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Hidden Fields

Hidden Fields are similar to a text box but does not get displayed on the UI. However you can see the

value of hidden fields when you view page source in the browser. Using Hidden Fields, you can pass

information from one page to another page without the end user's knowledge, primarily for internal

processing.

Example

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

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

Page 111: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

111 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h2>Hidden Field Contro Example</h2>

<p>

<asp:Button ID="Button1" runat="server" onclick="Button1_Click"

Text="Click Me!" />

</p>

</div>

<asp:HiddenField ID="HiddenField1" runat="server" />

<br />

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

</form>

</body>

</html>

Code Behind Code

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

Page 112: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

112 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{

HiddenField1.Value = "Welcome to dotprogramming";

}

protected void Button1_Click(object sender, EventArgs e)

{

Label1.Text = HiddenField1.Value;

}

}

Output

Cookies

Cookies are small files that are created in the web browser’s memory or on the client’s hard disk. The

maximum size of a cookie file is 4 KB. You can create two types of cookies. Transient Cookie (memory)

and Persistent Cookie (hard disk). Transient Cookies are accessible till the time the browser is running.

Persistent Cookies are cookies which have an expiry time. When you don't set expiry time for the cookie,

the cookies are treated as transient cookies.

Example

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

<%@ Import Namespace="System.Net" %>

<!DOCTYPE html>

Page 113: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

113 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<script runat="server">

protected void Page_Load(object sender, System.EventArgs e) {

HttpCookie userCookie = new HttpCookie("UserInfo");

userCookie["Country"] = "Italy";

userCookie["City"] = "Rome";

userCookie["Name"] = "Jones";

userCookie.Expires = DateTime.Now.AddDays(3);

Response.Cookies.Add(userCookie);

Label1.Text = "Cookie created successfully!";

HttpCookie cookie = Request.Cookies["UserInfo"];

if (cookie != null)

{

string country = cookie["Country"];

string city = cookie["City"];

string name = cookie["Name"];

Label2.Text = "Cookie found and read....<br />";

Label2.Text += "Name: " + name;

Label2.Text += "<br />Country: " + country;

Label2.Text += "<br />City: " + city;

}

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>How to create a cookie in asp.net</title>

</head>

<body style="padding:25px">

<form id="form1" runat="server">

<div>

<h2 style="color:MidnightBlue; font-style:italic;">

Page 114: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

114 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

How to create a Cookie

</h2>

<hr width="450" align="left" color="Gainsboro" />

<asp:Label

ID="Label1"

runat="server"

Font-Bold="true"

Font-Names="Comic Sans MS"

ForeColor="Green"

Font-Size="X-Large"

/>

<br /><br/>

<asp:Label

ID="Label2"

runat="server"

Font-Bold="true"

Font-Names="Comic Sans MS"

ForeColor="Navy"

Font-Italic="true"

Font-Size="X-Large"

/>

</div>

</form>

</body>

</html>

Page 115: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

115 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Session State

When a user connects to an ASP.NET website, a new session object is created. When session state is

turned on, a new session state object is created for each new request. This session state object becomes

part of the context and it is available through the page. Session state is generally used for storing

application data such as inventory, supplier list, customer record, or shopping cart. It can also keep

information about the user and his preferences, and keep the track of pending operations. Sessions are

identified and tracked with a 120-bit SessionID, which is passed from client to server and back as cookie

or a modified URL. The SessionID is globally unique and random. The session state object is created from

the HttpSessionState class, which defines a collection of session state items.

The HttpSessionState class has the following properties:

Properties Description

SessionID The unique session identifier.

Page 116: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

116 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Item(name) The value of the session state item with the specified name. This is

the default property of the HttpSessionState class.

Count The number of items in the session state collection.

TimeOut Gets and sets the amount of time, in minutes, allowed between

requests before the session-state provider terminates the session.

The HttpSessionState class has the following methods:

Methods Description

Add(name, value) Adds an item to the session state collection.

Clear Removes all the items from session state collection.

Remove(name) Removes the specified item from the session state collection.

RemoveAll Removes all keys and values from the session-state collection.

Page 117: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

117 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

RemoveAt Deletes an item at a specified index from the session-state

collection.

The session state object is a name-value pair to store and retrieve some information from the session

state object. You could use the following code for the same:

void StoreSessionInfo()

{

String fromuser = TextBox1.Text;

Session["fromuser"] = fromuser;

}

void RetrieveSessionInfo()

{

String fromuser = Session["fromuser"];

Label1.Text = fromuser;

}

The above code stores only strings in the Session dictionary object, however, it can store all the primitive

data types and arrays composed of primitive data types, as well as the DataSet, DataTable, HashTable,

and Image objects, as well as any user-defined class that inherits from the ISerializable object.

Example

The following example demonstrates the concept of storing session state. There are two buttons on the

page, a text box to enter string and a label to display the text stored from last session.

The mark up file code is as follows

Page 118: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

118 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

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

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>

Untitled Page

</title>

</head>

<body>

<form id="form1" runat="server">

<div>

&nbsp; &nbsp; &nbsp;

<table style="width: 568px; height: 103px">

<tr>

<td style="width: 209px">

<asp:Label ID="lblstr" runat="server" Text="Enter a String" style="width:94px">

</asp:Label>

</td>

<td style="width: 317px">

<asp:TextBox ID="txtstr" runat="server" style="width:227px">

</asp:TextBox>

Page 119: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

119 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</td>

</tr>

<tr>

<td style="width: 209px"> </td>

<td style="width: 317px"> </td>

</tr>

<tr>

<td style="width: 209px">

<asp:Button ID="btnnrm" runat="server"

Text="No action button" style="width:128px" />

</td>

<td style="width: 317px">

<asp:Button ID="btnstr" runat="server"

OnClick="btnstr_Click" Text="Submit the String" />

</td>

</tr>

<tr>

<td style="width: 209px"> </td>

<td style="width: 317px"> </td>

</tr>

<tr>

Page 120: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

120 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<td style="width: 209px">

<asp:Label ID="lblsession" runat="server" style="width:231px" >

</asp:Label>

</td>

<td style="width: 317px"> </td>

</tr>

<tr>

<td style="width: 209px">

<asp:Label ID="lblshstr" runat="server">

</asp:Label>

</td>

<td style="width: 317px"> </td>

</tr>

</table>

</div>

</form>

</body>

</html>

It should look like the following in design view:

Page 121: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

121 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The code behind file is given here

public partial class _Default : System.Web.UI.Page

{

String mystr;

protected void Page_Load(object sender, EventArgs e)

{

this.lblshstr.Text = this.mystr;

this.lblsession.Text = (String)this.Session["str"];

}

protected void btnstr_Click(object sender, EventArgs e)

{

this.mystr = this.txtstr.Text;

this.Session["str"] = this.txtstr.Text;

this.lblshstr.Text = this.mystr;

this.lblsession.Text = (String)this.Session["str"];

}

}

Execute the file and observe how it works

Page 122: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

122 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Application State

The ASP.NET application is the collection of all web pages, code and other files within a single virtual

directory on a web server. When information is stored in application state, it is available to all the users.

To provide for the use of application state, ASP.NET creates an application state object for each

application from the HTTPApplicationState class and stores this object in server memory. This object is

represented by class file global.asax. Application State is mostly used to store hit counters and other

statistical data, global application data like tax rate, discount rate etc. and to keep the track of users

visiting the site.

The HttpApplicationState class has the following properties:

Properties Description

Item(name) The value of the application state item with the specified name. This

is the default property of the HttpApplicationState class.

Count The number of items in the application state collection.

Methods:

Page 123: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

123 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Methods Description

Add(name, value) Adds an item to the application state collection.

Clear Removes all the items from the application state collection.

Remove(name) Removes the specified item from the application state collection.

RemoveAll Removes all objects from an HttpApplicationState collection.

RemoveAt Removes an HttpApplicationState object from a collection by index.

Lock() Locks the application state collection so only the current user can

access it.

Unlock() Unlocks the application state collection so all the users can access it.

Application state data is generally maintained by writing handlers for the events:

Application_Start

Application_End

Application_Error

Session_Start

Session_End

The following code snippet shows the basic syntax for storing application state information:

Void Application_Start(object sender, EventArgs e)

Page 124: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

124 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

{

Application["startMessage"] = "The application has started.";

}

Void Application_End(object sender, EventArgs e)

{

Application["endtMessage"] = "The application has ended.";

}

Cache

The Cache object is an instance of the System.Web.Caching.Cache class. Cache is stored on the server

side and is more scalable in nature, as ASP.NET removes objects if the memory becomes scarce. This

also makes it unreliable in some cases. Cache objects can have expiration polices set on them and is

shared across users. You can implement Page Caching and Data Caching.

OutputCaching.aspx

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

<%@ OutputCache Duration="60" VaryByParam="None" %>

<!DOCTYPE html>

<script runat="server">

protected void Page_Load(object sender, System.EventArgs e) {

Label2.Text = "Present Time: ";

Label2.Text += DateTime.Now.ToString();

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>asp.net caching example: how to use output caching</title>

</head>

Page 125: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

125 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<body>

<form id="form1" runat="server">

<div>

<h2 style="color:Red">asp.net example: Output Caching</h2>

<asp:Label ID="Label1"runat="server"Font-Size="Large" ForeColor="SeaGreen"

Text="Output Caching Duration: 60 seconds.">

</asp:Label>

<br /><br />

<asp:Label ID="Label2" runat="server"Font-Size="Large" ForeColor="DodgerBlue" >

</asp:Label>

</div>

</form>

</body>

</html>

Output:

Page 126: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

126 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Profile

Page 127: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

127 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Profile data is stored in the SQL Server database by default. This database structure is preset, so if you

want any custom user details to be stored, you will need to create a custom database and write a custom

provider for it. Profiles are designed to store information permanently.

Example:

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

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

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

protected void Button1_Click(object sender, System.EventArgs e) {

Profile.FirstName = TextBox1.Text;

Profile.LastName = TextBox2.Text;

Profile.Age = TextBox3.Text;

Profile.City = TextBox4.Text;

Label1.Text = "Profile stored successfully!<br />" +

"<br />First Name: " + Profile.FirstName +

"<br />Last Name: " + Profile.LastName +

"<br />Age: " + Profile.Age +

"<br />City: " + Profile.City;

}

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Profile Example: how to use profile in asp.net</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="Label1" runat="server" Font-Size="Large" ForeColor="Crimson"></asp:Label>

<br /><br />

Page 128: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

128 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<asp:Label ID="Label2" runat="server" Text="First Name"

AssociatedControlID="TextBox1"></asp:Label>

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

<br />

<asp:Label ID="Label3" runat="server" Text="Last Name"

AssociatedControlID="TextBox2"></asp:Label>

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

<br />

<asp:Label ID="Label4" runat="server" Text="Age" AssociatedControlID="TextBox3"></asp:Label>

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

<br />

<asp:Label ID="Label5" runat="server" Text="City" AssociatedControlID="TextBox4"></asp:Label>

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

<br />

<asp:Button ID="Button1" runat="server" Text="Add to profile" OnClick="Button1_Click" />

</div>

</form>

</body>

</html>

Output:

Page 129: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

129 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Page 130: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

130 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Context.Items

The HttpContext object is provided by the Page.Context property. The HttpContext.Items collection can

be used to temporarily store data across postback. View state and session state can be used for a similar

effect, but they assume longer-term storage. Context can be used for storing data for one request only.

We can store it as a key/value pair as shown below -

Context.Items["SocialPinNo"] = 3666736;

Response.Write(Context.Items["SocialPinNo"].ToString());

Page 131: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

131 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Cache Management

In a web application, sometimes we require to store data in the server side to avoid costly data retrieval

operation from data stores and time consuming data formatting logic to improve application performance

as well as to re-use the same data in subsequent requests via users, machines and applications.So, to

achieve this we need to store cache data on the serverside. In ASP.NET, we come across features like

Cache objects, Session and Application, but it is important to understand the difference between them in

order to effectively uset hem in web applications.

Caching

Caching data is extremely important for boosting performance in ASP.NET, as the pages and controls are

dynamically generated here. Caching places frequently used data in quickly accessed media like the

random access memory of the computer. The ASP.NET runtime consists of a key-value map of CLR

objects called cache. This resides with the application and is available via the System.Web.UI.Page and

HTTpContext.

In some respect, caching is similar to storing the state objects. Yet, the storing information in state objects

is deterministic, that is, you can count on the data being stored there, and caching of data in

nondeterministic. The data will not be available if its lifetime come to an end, or the application releases

its memory, or caching does not take place for any reason. You can access items in the cache using an

indexer and may control the lifetime of objects in the cache and set up links between the cached objects

and their physical sources.

Advantages:

Performance - Caching improves application performance due to less data retrieval and formatting

operations.

Scalability - Since caching minimizes data retrieval and formatting operations, it reduces the load on

Page 132: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

132 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

server resources thus increasing the scalability of the application.

Availability - As the application uses data from a cache, the data will be accurately available according to

the time frame.

Types of caching in ASP.NET

1. Application caching

2.Page output caching

Application caching

ASP.NET provides built in Cache object from System.Web.Caching namespace. This object contains

'Insert' method to store any collection into the application cache.

Key: This is the primary name to access the cached object in the Cache collection. The key must be

unique in the cache.

Value: This is the data as an Object that you want to cache.

Dependencies: It is the associated item for Cache. Framework will trigger the signal during the changes

in this dependency object.

AbsoluteExpiration: This is the time as a DateTime object at which the object should be removed from

the cache.

SlidingExpiration: This is the time as a TimeSpan object after which the object should be removed from

the cache if it has not been accessed by a user.

Priority: This is a CacheItemPriority enumeration value that you can use to determine which objects are

removed first during scavenging (i.e., when memory starts to run low). Lower priority objects are

removed sooner.

onRemoveCallback: This is an event handler that is called when the object is removed from the cache.

This can be null if you don't want to specify a callback method.Example:

Page output caching

Output cache is a mechanism that keeps a copy of a rendered ASP.NET web page in memory. This behavior

helps to improve performance by returning a response of the cached web page instantly and by reducing

the need to render the page in every client request. If a page takes a lot of time to render using output

cache can significantly improve the performance. Even though, the output cache has a very big drawback.

If your site needs to enable customization for users or needs to show dynamic information you don’t want

your users to have the same version of the page. ASP.NET supports configuration options to avoid this

drawback with the output cache making it very flexible and powerful.

Page 133: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

133 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Configure Output Cache for a Single Page in Declarative Way you can control the output cache’s behavior

in a declarative way by using the @OutputCache page directive. The only required parameter for the

output cache is the Duration all the other parameters can be used if you want to.

Parameters

Duration – the duration in seconds for the web page to be cached.

Location – the location to save the cached object. You can save the cached object on the server, client,

both or all the other options in the OutputCacheLocation enum.

VaryBy* (where * is in the set of [Param/Header/Custom/Control]) - The most useful parameters in the

parameters list is the VaryBy parameters. With these parameters you indicate semicolon-separated list of

strings to vary the output cache. These strings can be parameters if query string (Param), ID property

values of ASP.NET server controls that where declared in a user contorl (Control) and etc. These

parameters are used to vary caching of page/control by the given parameters therefore enabling the

caching of the same page/control with different behaviors.

SqlDependency – a string value that identifies a set of database and table name pairs that the page or

control’s output cache depends on. Every update of items in the table will result in the removal of the

items from the cache when using table based polling.

Lets look at an example of the declarative way

<%@ OutputCache Duration="30" Location="Client" VaryByParam="PageNumber;Count" %>

In the example the output cache will last for 30 seconds, will be saved on the client side and will vary the

the PageNumber and Count query string parameters.

Configure Output Cache for a Single Page in Runtime

We can use the declarative way but sometimes we want to use caching in runtime. The output cache

can be configured in runtime using the Response.Cache property. In the programmatic way there are

few methods to use than in the declarative way.

The available methods are

SetExpires – indicates the number of seconds that the page will be cached.

Page 134: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

134 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

SetCacheability – uses an enum to indicate where the cache will be stored.

SetValidUntilExpires – if the method get true as parameter the cache ignores

invalidation headers.

State management is a technique to manage a state of an object on different request. The HTTP

protocol is the fundamental protocol of the World Wide Web. HTTP is a stateless protocol means every

request is from new user with respect to web server. HTTP protocol does not provide you with any

method of determining whether any two requests are made by the same person. Maintaining state is

important in any web application. There are two types of state management system in ASP.NET.

Client Side State Management: Cookies, Viewstate, Querystring and Hidden Fields

Advantages: Better scalability

Support for multiple browser

• - Cookies: Cookies are small piece of information that server creates on the browser. Cookies store a

value in the user’s browser that the browser sends with every page request to the web server.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="KnackHook.aspx.cs" Inherits="KnackHook.KnackHook" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title></title> </head> <body> <form id="form1" runat="server"> <div> <table> <tr> <%-- Email --%> <td> <asp:Label ID="lblName" runat="server"></asp:Label></td> <td> <asp:TextBox ID="tbxEmail" runat="server"></asp:TextBox></td> <td> <asp:RegularExpressionValidator ID="RegularExpressionValidator1" ValidationExpression="\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*" ControlToValidate="tbxEmail" runat="server" ErrorMessage="RegularExpressionValidator"></asp:RegularExpressionValidator></td> </tr> <%-- Password --%> <tr> <td>

Page 135: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

135 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<asp:Label ID="lblPassword" runat="server"></asp:Label></td> <asp:TextBox ID="tbxPassword" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="RequiredFieldValidator2" ControlToValidate="tbxPassword" runat="server" ErrorMessage="RequiredFieldValidator"></asp:RequiredFieldValidator> </tr> <tr> <td colspan="2"> <asp:Button ID="btnLogin" Text="Login" runat="server" /></td> <td> <asp:Button ID="btnReset" Text="Reset" runat="server" /></td> </tr> </table> </div> </form> </body> </html>

Storing Cookies

using System; using System.Collections.Generic; using System.Data; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace KnackHook { public partial class KnackHook : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { //Storing Cookie Email and Password values inside cookies if (tbxEmail.Text != string.Empty && tbxPassword.Text != string.Empty) { //Cookies creation HttpCookie userInfo = new HttpCookie("UserCredentails"); userInfo["UserName"] = tbxEmail.Text; userInfo["Password"] = tbxPassword.Text; userInfo.Expires = DateTime.Now.AddMinutes(5);//This Cookie will be expire in 5 mins Response.Cookies.Add(userInfo);

Page 136: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

136 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

} } } }

Retrieving Cookies information

//Cookies HttpCookie reqCookies = Request.Cookies["UserCredentails"]; if (reqCookies != null) { UserName = reqCookies["UserName"].ToString(); Password = reqCookies["Password"].ToString(); }

• - view state ASP.NET uses view state to track values in controls between page requests. It works within

the page only. You cannot use view state value in next page.

Stroring:

ViewState["UserName"] = tbxEmail.Text;

Retrieving:

string s = ViewState["UserName"].ToString();

• - control state: You can persist information about a control that is not part of the view state. If view

state is disabled for a control or the page, the control state will still work.

• - hidden fields: It stores data without displaying that control and data to the user’s browser. This data

is presented back to the server and is available when the form is processed. Hidden fields data is

available within the page only (page-scoped data).

• - Query strings: In query strings, values are stored at the end of the URL. These values are visible to the

user through his or her browser’s address bar. Query strings are not secure. You should not send secret

information through the query string.

//Sending Query String Response.Redirect("StateManagement.aspx?UserName=" + tbxEmail.Text +

",Password=" + tbxPassword.Text);

Retrieving:

//Query String string s = Request.QueryString["UserName"].ToString();

Server Side State Management:

Session State(w3wp.exe,asp.net state service), Application State(w3wp.exe) and Cache

Page 137: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

137 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Advantages: Better security

Reduced bandwidth

The following objects are used to store the information on the server:

Session State: Session object stores user-specific data between individual requests. This object is same

as application object but it stores the data about particular user.

Storing:

////Session Session["UserName"] = tbxEmail.Text;

Retrieving:

string s = Session["UserName"].ToString();

Session Mode in Web.config file

<?xml version="1.0"?> <!-- For more information on how to configure your ASP.NET application, please visit http://go.microsoft.com/fwlink/?LinkId=169433 --> <configuration> <connectionStrings> <add name="InIndiaV3.0ConnectionString" connectionString="Data Source=PTGHYDM\MAMIDALA;Initial Catalog=InIndiaV3.0;Integrated Security=True" providerName="System.Data.SqlClient" /> </connectionStrings> <system.web> <sessionState mode="InProc" timeout="20"></sessionState> <compilation debug="true" targetFramework="4.5"> <assemblies> <add assembly="System.Web.DataVisualization, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/> </assemblies> </compilation> <httpRuntime targetFramework="4.5"/> </system.web> </configuration>

InProc: In this Mode, session data stroed inside IIS worker process which is w3wp.exe, when IIS

restarted automatically InProc mode session automatically lost.

StateServer: In this Mode, session data stroed inside ASP.NET State Service which is windows service.

Even when IIS restarted, StateServer mode session data still remains available for the usage.

<sessionState mode="StateServer" timeout="20"

stateConnectionString="tcpip=localhost:42424"></sessionState>

Page 138: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

138 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Sql Server: In this Mode, session data stroed inside Sql Server. Even when IIS restarted, Sql Server mode

session data still remains available for the usage.

<sessionState mode="SQLServer" timeout="20" sqlConnectionString="data source=.;integrated

security=SSPI;"></sessionState>

Application State: This object stores the data that is accessible to all pages in a given Web application.

The Application object contains global variables for your ASP.NET application.

Cache Object: Caching is the process of storing data that is used frequently by the user. Caching

increases your application’s performance, scalability, and availability. You can catch the data on the

server or client.

ADO.NET

ADO.NET provides a bridge between the front end controls and the back end database. The ADO.NET

objects encapsulate all the data access operations and the controls interact with these objects to display

data, thus hiding the details of movement of data.

The following figure shows the ADO.NET objects at a glance:

Page 139: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

139 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

DataSet

The dataset represents a subset of the database. It does not have a continuous connection to the

database. To update the database a reconnection is required. The DataSet contains DataTable objects

and DataRelation objects. The DataRelation objects represent the relationship between two tables.

Following table shows some important properties of the DataSet class:

Properties Description

CaseSensitive Indicates whether string comparisons within the data tables are

case-sensitive.

Page 140: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

140 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Container Gets the container for the component.

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

DefaultViewManager Returns a view of data in the data set.

DesignMode Indicates whether the component is currently in design mode.

EnforceConstraints Indicates whether constraint rules are followed when attempting

any update operation.

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

ExtendedProperties Gets the collection of customized user information associated with

the DataSet.

HasErrors Indicates if there are any errors.

IsInitialized Indicates whether the DataSet is initialized.

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

the table.

Namespace Gets or sets the namespace of the DataSet.

Page 141: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

141 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

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

DataSet.

Relations Returns the collection of DataRelation objects.

Tables Returns the collection of DataTable objects.

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

Methods Description

AcceptChanges Accepts all changes made since the

DataSet was loaded or this method was

called.

BeginInit Begins the initialization of the DataSet.

The initialization occurs at run time.

Clear Clears data.

Clone Copies the structure of the DataSet,

including all DataTable schemas,

Page 142: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

142 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

relations, and constraints. Does not copy

any data.

Copy Copies both structure and data.

CreateDataReader() Returns a DataTableReader with one

result set per DataTable, in the same

sequence as the tables appear in the

Tables collection.

CreateDataReader(DataTable[]) Returns a DataTableReader with one

result set per DataTable.

EndInit Ends the initialization of the data set.

Equals(Object) Determines whether the specified Object

is equal to the current Object.

Finalize Free resources and perform other

cleanups.

GetChanges Returns a copy of the DataSet with all

changes made since it was loaded or the

AcceptChanges method was called.

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

made since it was loaded or the

Page 143: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

143 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

AcceptChanges method was called,

filtered by DataRowState.

GetDataSetSchema Gets a copy of XmlSchemaSet for the

DataSet.

GetObjectData Populates a serialization information

object with the data needed to serialize

the DataSet.

GetType Gets the type of the current instance.

GetXML Returns the XML representation of the

data.

GetXMLSchema Returns the XSD schema for the XML

representation of the data.

HasChanges() Gets a value indicating whether the

DataSet has changes, including new,

deleted, or modified rows.

HasChanges(DataRowState) Gets a value indicating whether the

DataSet has changes, including new,

deleted, or modified rows, filtered by

DataRowState.

Page 144: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

144 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

IsBinarySerialized Inspects the format of the serialized

representation of the DataSet.

Load(IDataReader, LoadOption, DataTable[]) Fills a DataSet with values from a data

source using the supplied IDataReader,

using an array of DataTable instances to

supply the schema and namespace

information.

Load(IDataReader, LoadOption, String[]) Fills a DataSet with values from a data

source using the supplied IDataReader,

using an array of strings to supply the

names for the tables within the DataSet.

Merge() Merges the data with data from another

DataSet. This method has different

overloaded forms.

ReadXML() Reads an XML schema and data into the

DataSet. This method has different

overloaded forms.

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

This method has different overloaded

forms.

RejectChanges Rolls back all changes made since the last

call to AcceptChanges.

Page 145: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

145 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

WriteXML() Writes an XML schema and data from the

DataSet. This method has different

overloaded forms.

WriteXMLSchema() Writes the structure of the DataSet as an

XML schema. This method has different

overloaded forms.

DataTable

The DataTable class represents the tables in the database. It has the following important properties;

most of these properties are read only properties except the PrimaryKey property:

Properties Description

ChildRelations Returns the collection of child relationship.

Columns Returns the Columns collection.

Constraints Returns the Constraints collection.

DataSet Returns the parent DataSet.

DefaultView Returns a view of the table.

ParentRelations Returns the ParentRelations collection.

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

Page 146: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

146 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Rows Returns the Rows collection.

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

Methods Description

AcceptChanges Commits all changes since the last AcceptChanges.

Clear Clears all data from the table.

GetChanges Returns a copy of the DataTable with all changes made since the

AcceptChanges method was called.

GetErrors Returns an array of rows with errors.

ImportRows Copies a new row into the table.

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

any.

Merge Merges the table with another DataTable.

NewRow Creates a new DataRow.

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

Page 147: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

147 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Reset Resets the table to its original state.

Select Returns an array of DataRow objects.

DataRow

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

Properties Description

HasErrors Indicates if there are any errors.

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

ItemArrays Gets or sets all the values for the row.

Table Returns the parent table.

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

Methods Description

AcceptChanges Accepts all changes made since this method was called.

Page 148: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

148 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

BeginEdit Begins edit operation.

CancelEdit Cancels edit operation.

Delete Deletes the DataRow.

EndEdit Ends the edit operation.

GetChildRows Gets the child rows of this row.

GetParentRow Gets the parent row.

GetParentRows Gets parent rows of DataRow object.

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

DataAdapter

The DataAdapter object acts as a mediator between the DataSet object and the database. This helps the

Dataset to contain data from multiple databases or other data source.

DataReader

The DataReader object is an alternative to the DataSet and DataAdapter combination. This object provides

a connection oriented access to the data records in the database. These objects are suitable for read-only

access, such as populating a list and then breaking the connection.

SqlCommand and SqlConnection

The SqlConnection object represents a connection to the data source. The connection could be shared

among different command objects.

Page 149: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

149 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The SqlCommand object represents the command or a stored procedure sent to the database from

retrieving or manipulating data.

Example

So far, we have used tables and databases already existing in our computer. In this example, we will

create a table, add column, rows and data into it and display the table using a GridView object.

The source file code is as given

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

Inherits="createdatabase._Default" %>

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

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >

<head runat="server">

<title>Untitled Page</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:GridView ID="GridView1" runat="server"></asp:GridView>

</div>

</form>

</body>

</html>

The code behind file is as given:

Page 150: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

150 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

namespace createdatabase

{

public partial class _Default : System.Web.UI.Page

{

protected void Page_Load(object sender, EventArgs e)

{

if (!IsPostBack)

{

DataSet ds = CreateDataSet();

GridView1.DataSource = ds.Tables["Student"];

GridView1.DataBind();

}

}

private DataSet CreateDataSet()

{

//creating a DataSet object for tables

DataSet dataset = new DataSet();

creating the student table

DataTable Students = CreateStudentTable();

dataset.Tables.Add(Students);

return dataset;

}

Page 151: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

151 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

private DataTable CreateStudentTable()

{

DataTable Students = new DataTable("Student");

// adding columns

AddNewColumn(Students, "System.Int32", "StudentID");

AddNewColumn(Students, "System.String", "StudentName");

AddNewColumn(Students, "System.String", "StudentCity");

// adding rows

AddNewRow(Students, 1, "M H Kabir", "Kolkata");

AddNewRow(Students, 1, "Shreya Sharma", "Delhi");

AddNewRow(Students, 1, "Rini Mukherjee", "Hyderabad");

AddNewRow(Students, 1, "Sunil Dubey", "Bikaner");

AddNewRow(Students, 1, "Rajat Mishra", "Patna");

return Students;

}

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

{

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

}

Adding data into the table

private void AddNewRow(DataTable table, int id, string name, string city)

{

Page 152: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

152 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

DataRow newrow = table.NewRow();

newrow["StudentID"] = id;

newrow["StudentName"] = name;

newrow["StudentCity"] = city;

table.Rows.Add(newrow);

}

}

}

When you execute the program, observe the following

The application first creates a data set and binds it with the grid view control using the DataBind()

method of the GridView control. The Createdataset() method is a user defined function, which creates a

new DataSet object and then calls another user defined method CreateStudentTable() to create the

table and add it to the Tables collection of the data set. The CreateStudentTable() method calls the user

defined methods AddNewColumn() and AddNewRow() to create the columns and rows of the table as

well as to add data to the rows. When the page is executed, it returns the rows of the table as shown:

Page 153: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

153 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.IO; using System.Linq; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters.Binary; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace KnackHook { public partial class KnackHook : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { // 1. Instantiate the connection SqlConnection conn = new SqlConnection( "Data Source=(local);Initial Catalog=Northwind;Integrated Security=SSPI"); SqlDataReader rdr = null; try { // 2. Open the connection conn.Open();

Page 154: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

154 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

// 3. Pass the connection to a command object SqlCommand cmd = new SqlCommand("select * from Customers", conn); // // 4. Use the connection // // get query results rdr = cmd.ExecuteReader(); // print the CustomerID of each record while (rdr.Read()) { Console.WriteLine(rdr[0]); } } finally { // close the reader if (rdr != null) { rdr.Close(); } // 5. Close the connection if (conn != null) { conn.Close(); } } } } }

Machine.config Vs web.config

The machine.config file is the master configuration file on your system with a lot of default settings.

Web.config is the file for the local settings to be applied for a website which store configuration data in

XML format. The settings of Machine.config file are applied to the whole asp.net applications on your

server whereas the settings made in the Web.config file are applied to that particular web application

only.

Page 155: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

155 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Each .NET Framework version has only one machine.config file, at the same time, each web application

has its own web.config file. Directories inside a web application can also have web.config files too. The

machine.config file is at the highest level in the configuration hierarchy while Web.config file is to override

the settings from the machine.config file.

The machine.config would be to share values between many applications on the server such as SMTP

server settings while Web.config files contain application specific items such as database connection

strings. If you make any changes to the web.config, web application will immediately load the changes but

in case of machine.config you will have to restart the application.

The machine.config file will automatically installed when you install Visual Studio.Net and it exist exists

inthec:\windows\microsoft.net\framework\version\configfolderwhereasweb.configwillautomatically

created when you create an ASP.Net webapplication project.

Machine.config is configuration file for all the application in the IIS, but Web.config is a configuration file

for a particular application or folder.

ASP.NET – Configuration

Machine Vs Web Config files: The behavior of an ASP.NET application is affected by different settings in

the configuration files:

machine.config

web.config

The machine.config file contains default and the machine-specific value for all supported settings. The

machine settings are controlled by the system administrator and applications are generally not given

access to this file.

An application however, can override the default values by creating web.config files in its roots folder.

The web.config file is a subset of the machine.config file.

If the application contains child directories, it can define a web.config file for each folder. Scope of each

configuration file is determined in a hierarchical top-down manner.

Page 156: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

156 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Any web.config file can locally extend, restrict, or override any settings defined on the upper level.

Visual Studio generates a default web.config file for each project. An application can execute without a

web.config file, however, you cannot debug an application without a web.config file.

The following figure shows the Solution Explorer for the sample example used in the web services:

In this application, there are two web.config files for two projects i.e., the web service and the web site

calling the web service.

The web.config file has the configuration element as the root node. Information inside this element is

grouped into two main areas: the configuration section-handler declaration area, and the configuration

section settings area.

The following code snippet shows the basic syntax of a configuration file:

<configuration>

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

Page 157: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

157 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<configSections>

<section name="section1" type="section1Handler" />

<section name="section2" type="section2Handler" />

</configSections>

<!-- Configuration section settings area. -->

<section1>

<s1Setting1 attribute1="attr1" />

</section1>

<section2>

<s2Setting1 attribute1="attr1" />

</section2>

<system.web>

<authentication mode="Windows" />

</system.web>

</configuration>

Configuration Section Handler declarations

The configuration section handlers are contained within the <configSections> tags. Each configuration

handler specifies name of a configuration section, contained within the file, which provides some

configuration data. It has the following basic syntax:

<configSections>

<section />

<sectionGroup />

Page 158: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

158 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<remove />

<clear/>

</configSections>

It has the following elements

Clear - It removes all references to inherited sections and section groups.

Remove - It removes a reference to an inherited section and section group.

Section - It defines an association between a configuration section handler and a configuration element.

Section group - It defines an association between a configuration section handler and a configuration

section.

Application Settings:

The application settings allow storing application-wide name-value pairs for read-only access. For

example, you can define a custom application setting as:

<configuration>

<appSettings>

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

</appSettings>

</configuration>

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

<configuration>

<appSettings>

<add key="appISBN" value="0-273-68726-3" />

<add key="appBook" value="Corporate Finance" />

Page 159: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

159 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

</appSettings>

</configuration>

Connection Strings:

The connection strings show which database connection strings are available to the website.

Example:

<connectionStrings>

<add name="ASPDotNetStepByStepConnectionString"

connectionString="Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=E:\\projects\datacaching\ /

datacaching\App_Data\ASPDotNetStepByStep.mdb"

providerName="System.Data.OleDb" />

<add name="booksConnectionString"

connectionString="Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=C:\ \databinding\App_Data\books.mdb"

providerName="System.Data.OleDb" />

</connectionStrings>

System.Web Element

The system.web element specifies the root element for the ASP.NET configuration section and contains

configuration elements that configure ASP.NET Web applications and control how the applications

behave.

It holds most of the configuration elements needed to be adjusted in common applications. The basic

syntax for the element is as given:

Page 160: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

160 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<system.web>

<anonymousIdentification>

<authentication>

<authorization>

<browserCaps>

<caching>

<clientTarget>

<compilation>

<customErrors>

<deployment>

<deviceFilters>

<globalization>

<healthMonitoring>

<hostingEnvironment>

<httpCookies>

<httpHandlers>

<httpModules>

<httpRuntime>

<identity>

<machineKey>

<membership>

Page 161: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

161 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<mobileControls>

<pages>

<processModel>

<profile>

<roleManager>

<securityPolicy>

<sessionPageState>

<sessionState>

<siteMap>

<trace>

<trust>

<urlMappings>

<webControls>

<webParts>

<webServices>

<xhtmlConformance>

</system.web>

The following table provides brief description of some of common sub elements of

the system.web element:

AnonymousIdentification

This is required to identify users who are not authenticated when authorization is required.

Page 162: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

162 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Authentication

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

<authentication mode="[Windows|Forms|Passport|None]">

<forms>...</forms>

<passport/>

</authentication>

Authorization:

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

<authorization>

<allow .../>

<deny .../>

</authorization>

Caching:

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

<caching>

<cache>...</cache>

<outputCache>...</outputCache>

<outputCacheSettings>...</outputCacheSettings>

<sqlCacheDependency>...</sqlCacheDependency>

</caching>

CustomErrors

Page 163: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

163 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

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

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

<error. . ./>

</customErrors>

Deployment

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

<deployment retail="true|false" />

HostingEnvironment

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

<hostingEnvironment idleTimeout="HH:MM:SS" shadowCopyBinAssemblies="true|false"

shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" />

Identity

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

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

password="<secure password>"/>

Authentication and Authorization

Authentication is the process for checking the identity of a user based on the user’s credentials. Generally,

user’s credentials are in the form of user ID and password, and we check their credentials from database

or equivalent alternative, if it exists then user is a valid candidate for next process – authorization.

Authorization also known as “Permission Control” will come after authentication. Authorization is the

process of deciding what kind of resource a user can access based on their identity and checking whether

the authenticated user has sufficient rights to access the requested resources. Typically a resource can be

an ASP.NET web page, media files (MP4, GIF, JPEG etc), compressed file (ZIP, RAR) etc.

Page 164: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

164 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ASP.NET default authentication Providers

Form Authentication

Normally, form authentication is based on cookies, the authentication and permission settings are stored

in cookies. However, we can also use form authentication without cookies, and in cookie-less form

authentication we can use query string for passing user details. Remember, the key concept is always

ONLY allow the user with correct credential also enough permission to view certain resources, so we need

to capture their information and compare with what we have stored in the database. And no matter what

kind of form authentication we use, after we receive the data on server end, we will compare them with

the data stored in any storage method/provider. For example, we can store username and password in

the web.config file, a JSON file, or a database table.

Forms authentication flow

When a user requests a page for the application, ASP.NET checks session cookie. If the cookie exists and

valid, ASP.NET assumes the user is authenticated and processes the request. If session cookies does not

exists or not valid then it redirect to login form. User will enter username and password and if they are

valid then he will get authenticated and authorized.

Example:

Login.aspx

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

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

Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Label ID="idError" EnableViewState="false" ForeColor="Red" runat="server" />

<br />

<br />

<asp:Label ID="Name" Text="User Name:" AssociatedControlID="idtxtName" runat="server" />

Page 165: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

165 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<br />

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

<br /><br />

<asp:Label ID="Password" Text="Password:" AssociatedControlID="idtxtPswd" runat="server"/>

<br />

<asp:TextBox ID="idtxtPswd" TextMode="Password" runat="server" />

<br /><br />

<asp:CheckBox ID="idchkRememberMe" Text="Remember Me" runat="server" />

<br /> <br />

<asp:Button ID="idbtnlogin" Text="Login" OnClick="idbtnlogin_Click" runat="server" />

</div>

</form>

</body>

</html>

Login.aspx

Partial Class Login

Inherits System.Web.UI.Page

Protected Sub idbtnlogin_Click(sender As Object, e As System.EventArgs) Handlesidbtnlogin.Click

If FormsAuthentication.Authenticate(idtxtName.Text, idtxtPswd.Text) Then

FormsAuthentication.RedirectFromLoginPage(idtxtName.Text, idchkRememberMe.Checked)

Response.Redirect("~/welcome.aspx")

Else

idError.Text = "Invalid user name/password"

End If

End Sub

End Class

Web.config

<?xml version="1.0"?>

<configuration>

<system.web>

<authentication mode="Forms">

<forms>

<credentials passwordFormat="Clear">

<user name="Clark" password="password123"/>

<user name="Ricky" password="password@123"/>

Page 166: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

166 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

<user name="Hussey" password="password@1"/>

</credentials>

</forms>

</authentication>

<compilation debug="true" strict="false" explicit="true" targetFramework="4.0"/>

</system.web>

</configuration>

Welcome.aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="welcome.aspx.vb"Inherits="welcome"

%>

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

Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title></title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h2 style="color:Red;font-weight:bold">Hi</h2><br />

<h2 style="color:Red;font-weight:bold">Welcome to our website.</h2>

</div>

</form>

</body>

</html>

Output:

Page 167: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

167 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Click on Login button

Output:

Passport Authentication

Page 168: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

168 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Passport authentication is a centralized authentication service provided by Microsoft. The .NET Passport

single sign-in service. When we use passport authentication then user authentication in your application

is managed by Microsoft’s passport service. Passport authentication uses encrypted cookies to manage

the authentication.

How Password authentication works

Users do not need to retype their sign-in name and password when moving from site to site. Those .NET

Passport–enabled sites will issue a set of encrypted cookies in the .NET Passport central servers’ domain

to facilitate silent and seamless sign-in across sites. In some cases, sites owners will first redirect their

end-users to .NET Passport sign-in and to authenticate upon first viewing of their site. If the users are

logged in already, they’ll get authenticated by ASP.NET, and if they are not logged in they will get

redirected to passport servers (i.e hotmail, Live etc.) to login first. If user successfully authenticates

himself, it will return a token to your website.

Windows Authentication

We use windows authentication when we are creating a web application for a limited number of users

who already have Windows account and this type of authentication is quite useful in an intranet

environment. This authentication method uses local users windows account ‘credentials’ for to validate

the user. Dot Net web application generally hosted on IIS(Internet Information Server) so the requests go

directly to IIS to provide the authentication process in a Windows-based authentication model.

The entire responsibility of authentication is done by IIS. It first takes the user’s credentials from the

domain login. If this process fails, IIS displays an alert dialog box so the user can enter or re-enter his login

information.

Windows authentication have some advantages and disadvantages:

Windows authentication Advantage

Developers need to write less line of code for managing user’s authentication.

Users can use their existing windows accounts for login.

Windows authentication dis-Advantage

Page 169: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

169 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

You can’t control windows authentication process.

Windows authentication only works on Microsoft OS you can’t use it on others OS.

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

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

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>LoginName Example: How to show login name in asp.net</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<asp:Login ID="Login1" runat="server" BackColor="#F7F6F3" BorderColor="#E6E2D8"

BorderPadding="4" BorderStyle="Solid" BorderWidth="1px" Font-Names="Verdana"

Font-Size="0.8em" ForeColor="#333333">

<TextBoxStyle Font-Size="0.8em" />

<LoginButtonStyle BackColor="#FFFBFF" BorderColor="#CCCCCC" BorderStyle="Solid"

BorderWidth="1px" Font-Names="Verdana" Font-Size="0.8em" ForeColor="#284775" />

<InstructionTextStyle Font-Italic="True" ForeColor="Black" />

<TitleTextStyle BackColor="#5D7B9D" Font-Bold="True" Font-Size="0.9em"

ForeColor="White" />

</asp:Login>

</div>

</form>

</body>

</html>

D e f a u l t . a s p x

Page 170: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

170 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

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

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

"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<script runat="server">

</script>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

<title>Using LoginName Control</title>

</head>

<body>

<form id="form1" runat="server">

<div>

<h1>Wellcome my site</h1>

<asp:LoginStatus ID="LoginStatus1" runat="server" />

<br />

<asp:LoginName ID="LoginName1" runat="server" FormatString="{0} logged in." Font-

Size="Medium" ForeColor="BlueViolet" />

<br /><br />

<asp:LoginName ID="LoginName2" runat="server" FormatString="Hi {0}!" Font-Size="XX-Large"

ForeColor="Crimson" />

</div>

</form>

</body>

</html>

Output

Page 171: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

171 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

\

Page 172: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

172 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

ASP.NET VNext or ASP.NET 5

What is ASP.NET 5

ASP.NET 5 is a new open-source and cross-platform framework for building modern cloud-based Web

applications using .NET. We built it from the ground up to provide an optimized development framework

for apps that are either deployed to the cloud or run on-premises. It consists of modular components with

minimal overhead, so you retain flexibility while constructing your solutions. You can develop and run

your ASP.NET 5 applications cross-platform on Windows, Mac and Linux.

Why build ASP.NET 5

The first preview release of ASP.NET 1.0 came out almost 15 years ago. Since then millions of developers

have used it to build and run great web applications, and over the years we have added and evolved many,

many capabilities to it.

With ASP.NET 5 we are making a number of architectural changes that make the core web framework

much leaner and more modular. ASP.NET 5 is no longer based on System.Web.dll, but is instead based on

a set of granular and well factored NuGet packages allowing you to optimize your app to have just what

you need. You can reduce the surface area of your application to improve security, reduce your servicing

burden and also to improve performance in a true pay-for-what-you-use model.

ASP.NET 5 is built with the needs of modern Web applications in mind, including a unified story for building

Web UI and Web APIs that integrate with today’s modern client-side frameworks and development

workflows. ASP.NET 5 is also built to be cloud-ready by introducing environment-based configuration and

by providing built-in dependency injection support.

To appeal to a broader audience of developers, ASP.NET 5 supports cross-platform development on

Windows, Mac and Linux. The entire ASP.NET 5 stack is open source and encourages community

contributions and engagement. ASP.NET 5 comes with a new, agile project system in Visual Studio while

also providing a complete command-line interface so that you can develop using the tools of your choice.

In summary, with ASP.NET 5 you gain the following foundational improvements:

New light-weight and modular HTTP request pipeline

Page 173: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

173 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Ability to host on IIS or self-host in your own process

Built on .NET Core, which supports true side-by-side app versioning

Ships entirely as NuGet packages

Integrated support for creating and using NuGet packages

Single aligned web stack for Web UI and Web APIs

Cloud-ready environment-based configuration

Built-in support for dependency injection

New tooling that simplifies modern web development

Build and run cross-platform ASP.NET apps on Windows, Mac and Linux

Open source and community focused

Application anatomy

ASP.NET 5 applications are built and run using the new .NET Execution Environment (DNX). Every

ASP.NET 5 project is a DNX project. ASP.NET 5 integrates with DNX through the ASP.NET Application

Hosting package.

ASP.NET 5 applications are defined using a public Startup class:

public class Startup{

public void ConfigureServices(IServiceCollection services)

{

}

public void Configure(IApplicationBuilder app)

{

}

}

The ConfigureServices method defines the services used by your application and the Configuremethod is

used to define what middleware makes up your request pipeline. See Understanding ASP.NET 5 Web

Apps for more details.

Page 174: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

174 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

Services

A service is a component that is intended for common consumption in an application. Services are made

available through dependency injection. ASP.NET 5 includes a simple built-in inversion of control (IoC)

container that supports constructor injection by default, but can be easily replaced with your IoC

container of choice. See Dependency Injection for more details.

Services in ASP.NET 5 come in three varieties: singleton, scoped and transient. Transient services are

created each time they’re requested from the container. Scoped services are created only if they don’t

already exist in the current scope. For Web applications, a container scope is created for each request, so

you can think of scoped services as per request. Singleton services are only ever created once.

Middleware

In ASP.NET 5 you compose your request pipeline using Middleware. ASP.NET 5 middleware perform

asynchronous logic on an HttpContext and then optionally invoke the next middleware in the sequence

or terminate the request directly. You generally “Use” middleware by invoking a corresponding extension

method on the IApplicationBuilder in your Configure method.

Servers

The ASP.NET Application Hosting model does not directly listen for requests, but instead relies on an HTTP

server implementation to surface the request to the application as a set of feature interfaces that can be

composed into an HttpContext.

ASP.NET 5 includes server support for running on IIS or self-hosting in your own process. On Windows you

can host your application outside of IIS using the WebListener server, which is based on HTTP.sys. You can

also host your application on a non-Windows environment using the cross-platform Kestrel web server.

Web root

Page 175: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

175 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com

The Web root of your application is the root location in your project from which HTTP requests are

handled (ex. handling of static file requests). The Web root of an ASP.NET 5 application is configured using

the “webroot” property in your project.json file.

Configuration

ASP.NET 5 uses a new configuration model for handling of simple name-value pairs that is not based on

System.Configuration or web.config. This new configuration model pulls from an ordered set of

configuration providers. The built-in configuration providers support a variety of file formats (XML, JSON,

INI) and also environment variables to enable environment-based configuration. You can also write your

own custom configuration providers. Environments, like Development and Production, are a first-class

notion in ASP.NET 5 and can also be set up using environment variables

Client-side development

var builder = new ConfigurationBuilder()

.AddJsonFile("appsettings.json")

.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

if (env.IsDevelopment())

{

// For more details on using the user secret store see http://go.microsoft.com/fwlink/?LinkID=532709

builder.AddUserSecrets();

}

builder.AddEnvironmentVariables();

Configuration = builder.Build();

See Configuration for more details on the new configuration system and Working with Multiple

Environments for details on how to work with environments in ASP.NET 5.

Page 176: ASPknackhook.com/Tutorials/ASP.NETTutorial.pdf · 1 | P a g e KnackHook Knowledge Holder info@knackhook.com

176 | P a g e

KnackHook Knowledge Holder

[email protected] www.knackhook.com