Sie sind auf Seite 1von 153

ASP.

NET USING C#

TYBSC(IT) SEM 5

COMPILED BY : SIDDHESH ZELE

302 PARANJPE UDYOG BHAVAN, NEAR KHANDELWAL SWEETS, NEAR THANE


STATION , THANE (WEST)
PHONE NO: 8097071144 / 8097071155 / 8655081002
SYLLABUS
UNIT TOPICS PAGE NO
Unit-I Review of .NET frameworks, Introduction to C#, Variables and expressions,
flow controls, functions, debugging and error handling, OOPs with C#, 1
Defining classes and class members.
Unit-II Assembly, Components of Assembly, Private and Shared Assembly, Garbage
Collector, JIT compiler. Namespaces Collections, Delegates and Events.
40
Introduction to ASP.NET 4: Microsoft.NET framework, ASP.NET lifecycle. CSS:
Need of CSS, Introduction to CSS, Working with CSS with visual developer.
Unit-III ASP.NET server controls: Introduction, How to work with button controls,
Textboxes, Labels, checkboxes and radio buttons, list controls and other web
server controls, web.config and global.asax files. Programming ASP.NET web 65
pages: Introduction, data types and variables, statements, organizing code,
object oriented basics.
Unit-IV Validation Control: Introduction, basic validation controls, validation
techniques, using advanced validation controls. State Management: Using
view state, using session state, using application state, using cookies and URL
encoding. Master Pages: Creating master pages, content pages, nesting 73
master pages, accessing master page controls from a content page.
Navigation: Introduction to use the site navigation, using site navigation
controls.
Unit-V Databases: Introduction, using SQL data sources, GridView Control,
DetailsView and FormView Controls, ListView and DataPager controls, Using
88
object datasources. ASP.NET Security: Authentication, Authorization,
Impersonation, ASP.NET provider model
Unit-VI LINQ: Operators, implementations, LINQ to objects,XML,ADO.NET, Query
Syntax. ASP.NET Ajax: Introducing AJAX, Working of AJAX, Using ASP.NET AJAX
131
server controls. JQuery: Introduction to JQuery, JQuery UI Library, Working of
JQuery
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

UNIT 1
Q: Reviews of .NET Framework?

Ans: is a revolutionary platform created by Microsoft for developing applications.

note that it doesn‟t „„develop applications on the Windows operating system.‟‟


Although the Microsoft release of the .NET Framework runs on the Windows
operating system, it is possible to find alternative versions that will work on other
systems.

One example of this is Mono, an open-source version of the .NET Framework (including a C#
compiler) that runs on several operating systems, including various flavors of Linux and Mac
OS you can use the Microsoft .NET Compact Framework

.NET Framework enables the creation of Windows applications, Web applications, Web services,
and pretty much anything else you can think of.

The .NET Framework has been designed so that it can be used from any language, including
C#, C++, Visual Basic, JScript, and even older languages such as COBOL.

Not only all of these languages have access to the .NET Framework, but they can also
communicate with each other. It is perfectly possible for C# Developers to make use of code
written by Visual Basic programmers, and vice versa.

Q: What is .NET Framework?

The .NET Framework consists primarily of a gigantic library of code that you use from your
client languages (such as C#) using object-oriented programming (OOP) techniques.

This library is categorized into different modules — you use portions of it depending on the
results you want to achieve.

one module contains the building blocks for Windows applications, another for Network
programming, and another for Web development

.NET Framework library defines some basic types. A type is a representation of data, and
specifying some of the most fundamental of these (such as „„a 32-bit signed integer‟‟) facilitates
interoperability between languages using the .NET Framework. This is called the Common Type
System (CTS).

WE-IT TUTORIALS Page 1


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

As well as supplying this library, the .Net Framework also includes the .NET Common Language
Runtime (CLR), which is responsible for maintaining the execution of all applications
developed using the .NET library

In order for C# code to execute, it must be converted into a language that the target operating
system understands, known as native code.

This conversion is called compiling code, an act that is performed by a compiler. Under the
.NET Framework, this is a two-stage process.

Q: CIL and JIT

When you compile code that uses the .NET Framework library, you don‟t immediately create
operating-system-specific native code. Instead, you compile your code into Common
Intermediate Language (CIL) code. This code isn‟t specific to any operating system (OS) and
isn‟t specific to C#. Other .NET languages — Visual Basic .NET, for example — also compile to
this language as a first stage. This compilation step is carried out by VS or VCE when you
develop C# applications.

Obviously, more work is necessary to execute an application. That is the job of a just-in-time
(JIT) compiler, which compiles CIL into native code that is specific to the OS and machine
architecture being targeted. Only at this point can the OS execute the application.

In the past, it was often necessary to compile your code into several applications, each of
which targeted a specific operating system and CPU architecture. Typically, this was a form of
optimization (to get code to run faster on an AMD chipset, for example), but at times it was
critical (for applications to work in both Win9x and WinNT/2000 environments, for example).
This is now unnecessary, because JIT compilers (as their name suggests) use CIL code, which
is independent of the machine, operating system, and CPU. Several JIT compilers exist, each
targeting a different architecture, and the appropriate one is used to create the native code
required.

The beauty of all this is that it requires a lot less work on your part — in fact, you can forget
about system-dependent details and concentrate on the more interesting functionality of your
code.

Q: Explain Assemblies?

When you compile an application, the CIL code created is stored in an assembly. Assemblies
include both executable application files that you can run directly from Windows without the
need for any other programs (these have a .exe file extension) and libraries (which have a .dll
extension) for use by other applications.

In addition to containing CIL, assemblies also include meta information (that is, information
about the information contained in the assembly, also known as metadata) and optional
resources (additional data used by the CIL, such as sound files and pictures). The meta
information enables assemblies to be fully self-descriptive. You need no other information to
use an assembly, meaning you avoid situations such as failing to add required data to the
system registry and so on, which was often a problem when developing with other platforms.

This means that deploying applications is often as simple as copying the files into a directory
on a remote computer. Because no additional information is required on the target systems,
you can just run an executable file from this directory and (assuming the .NET CLR is installed)
you‟re good to go.

Page 2 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Of course, you won‟t necessarily want to include everything required to run an application in
one place. You might write some code that performs tasks required by multiple applications. In
situations like that, it is often useful to place the reusable code in a place accessible to all
applications. In the .NET Framework, this is the global assembly cache (GAC). Placing code in
the GAC is simple — you just place the assembly containing the code in the directory
containing this cache.

Q: Managed Code

The role of the CLR doesn‟t end after you have compiled your code to CIL and a JIT compiler
has compiled that to native code. Code written using the .NET Framework is managed when it
is executed (a stage usually referred to as runtime). This means that the CLR looks after your
applications by managing memory, handling security, allowing cross-language debugging, and
so on. By contrast, 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. However, in C# you can write
only code that runs in a managed environment. You will make use of the managed features of
the CLR and allow .NET itself to handle any interaction with the operating system.

Q: Garbage Collection

One of the most important features of managed code is the concept of garbage collection. This
is the .NET method of making sure that the memory used by an application is freed up
completely when the application is no longer in use. Prior to .NET this was mostly the
responsibility of programmers, and a few simple errors in code could result in large blocks of
memory mysteriously disappearing as a result of being allocated to the wrong place in
memory. That usually meant a progressive slowdown of your computer followed by a system
crash.

.NET garbage collection works by periodically inspecting the memory of your computer and
removing anything from it that is no longer needed. There is no set time frame for this; it
might happen thousands of times a second, once every few seconds, or whenever, but you can
rest assured that it will happen.

Q: steps required to create a .NET application

Ans:

1. Application code is written using a .NET-compatible language

2. That code is compiled into CIL, which is stored in an assembly

3. When this code is executed it must first be compiled into native code using a JIT
compiler

WE-IT TUTORIALS Page 3


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

4. The native code is executed in the context of the managed CLR

Q: Linking

Note one additional point concerning this process. The C# code that compiles into CIL in step 2
needn‟t be contained in a single file. It‟s possible to split application code across multiple
source code files, which are then compiled together into a single assembly. This extremely
useful process is known as linking. It is required because it is far easier to work with several
smaller files than one enormous one. You can separate out logically related code into an
individual file so that it can be worked on independently and then practically forgotten about
when completed. This also makes it easy to locate specific pieces of code when you need them
and enables teams of developers to divide the programming burden into manageable chunks,
whereby individuals can „„check out‟‟ pieces of code to work on without risking damage to
otherwise satisfactory sections or sections other people are working on.

Q: Introduction to C#

Ans: C# is a relatively new language that was unveiled to the world when Microsoft announced
the first version of its .NET Framework in July 2000.

Since then its popularity has rocketed and it has arguably become the language of choice for
both Windows and Web developers who use the .NET framework.

Part of the appeal of C# comes from its clear syntax, which derives from C/C++ but simplifies
some things that have previously discouraged some programmers.

• Fully object oriented language like java and first component oriented language
• Designed to support key features of .NET framework
• Its is simple, effective, productive, type-safe
• Belongs to family of C/C++
• It is designed to build robust, reliable and durable components to handle real world
applications

Page 4 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Q: starting with VISUAL STUDIO 2010

Ans :
1. Start visual studio 2010 IDE

2. Click on new project

3. Click on visual c# language, click on console application

WE-IT TUTORIALS Page 5


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

4. Visual studio 2010 IDE creates basic code for start

These are the namespaces imported using using keyword

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication2
{
class Program
{
static void Main(string[] args)
{
}
}
}
-------------------------------------------------------------
namespace ConsoleApplication2

//works like a container which holds namespaces and classes inside it.
-----------------------------------------------
class Program

//It is a class which can hold classes and methods, function, fields etc.

static void Main(string[] args)


{
Page 6 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

//This is a Method from which the execution starts


-----------------------------------------------

Variables and Expressions


BASIC C# SYNTAX

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

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


Because whitespace is ignored, multiple statements can appear on one line, although for
readability it is usual to add carriage returns after semicolons, to avoid multiple statements on
one line.

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


blocks, which are delimited with curly brackets ({ and }), may contain any number of
statements, or none at all.

COMMENTS IN C#

/* This is a comment */

Multiline comment

/* And so...

... is this! *

Single line comment

// this is comment line

code outlining functionality


You can do this with the #region and #endregion

#region Using directives


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
#endregion

C# syntax for declaring variables


<type> <name>;
String ename

number of different integer types can be used to store various ranges of numbers
u characters before some variable names are shorthand for unsigned

WE-IT TUTORIALS Page 7


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

floating-point values

three other simple types

Declaring and assigning values to variables


class Program
{
static void Main(string[] args)
{
string strEname; //declaring variable
strEname = "We-It tutorials"; //initalizing value
Console.WriteLine(strEname); //printing value of variable
}
}

Naming Conventions

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

camelCase variable names:

age
firstName
timeOfDeath

Page 8 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

These are PascalCase:

Age
LastName
WinterOfDiscontent

Literal Values

String Literals

Eg :

If we want to print

"sid"s place"

Solution use escape character

"sid\"s\ place"

WE-IT TUTORIALS Page 9


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

EXPRESSIONS

By combining operators with variables and literal values (together referred to as operands when
used with operators), you can create expressions, which are the basic building blocks of
computation

Unary— Act on single operands


Binary—Act on two operands
Ternary—Act on three operands

Mathematical Operators

Page 10 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Assignment Operators

Operator Precedence

Namespaces
namespaces. These are the .NET way of providing containers for application code, such that code
and its contents may be uniquely identified. Namespaces are also used as a means of
categorizing items in the .NET Framework.

namespace outer
{
namespace inner
{
namespace moreinner
{
}
}
}

Using namespaces

using outer.inner.moreinner;

WE-IT TUTORIALS Page 11


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Flow Control
Boolean logic and how to use it
How to branch code
How to loop code

 BOOLEAN LOGIC

conditional Boolean operators

THE GOTO STATEMENT


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

goto <labelName>;

Page 12 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

class Program
{
static void Main(string[] args)
{
string strEname; //declaring variable
goto jumpon;
strEname ="sid\"s place"; //initalizing value
Console.WriteLine(strEname); //printing value of variable
jumpon:
Console.ReadKey();
}
}

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

The Ternary Operator

<test> ? <resultIfTrue>: <resultIfFalse>


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

output:
value of a “its true”

The if Statement

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

if (1 == 1)
{
Console.WriteLine(“condition true”);
}

The If else

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

if (1 == 1)
{
Console.WriteLine("condition true");// condition true
}
else
{
Console.WriteLine("condition false");
}

Checking More Conditions Using if Statements

if (1 == 2)
{
Console.WriteLine("condition true");
}
else
{
Console.WriteLine("condition false");
WE-IT TUTORIALS Page 13
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

if (2 == 2)
{
Console.WriteLine("inside next condition check");
}
}

The switch Statement


switch (<testVar>)
{
case <comparisonVal1>:
<code to execute if <testVar> == <comparisonVal1> >
break;
case <comparisonVal2>:
<code to execute if <testVar> == <comparisonVal2> >
break;
default:
<code to execute if <testVar> != comparisonVals>
break;
}

int a = 2;
switch (a)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");// executes
break;
default:
Console.WriteLine("default");
break;
}

Fall through in switch case

int a = 2;
switch (a)
{
case 1:
Console.WriteLine("one");
break;
case 2:
Console.WriteLine("two");// executes
Goto default:
default:
Console.WriteLine("default");//executes
break;
}

LOOPING

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


very handy because it means that you can repeat operations as many times as you want
(thousands, even millions, of times) without having to write the same code each time.

Page 14 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

do Loops

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

do
{
<code to be looped>
} while (<Test>);

Do while loop is also called as exit condition checking loop, means it will check the
condition while exiting loop.
Eg:
int i = 0;//initialization
do
{
System.Console.Write(" " + i.ToString());
i++; //increment
} while (i != 10); //condition

while Loops

The Boolean test in a while loop takes place at the start of the loop cycle, not at the end
“entry level checking”

while (<Test>)
{
<code to be looped>
}
Eg:

int i = 1; //initialization
while (i <= 10) // condition
{
Console.WriteLine(i);
i++; // increment
}
for Loops

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

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


{
<code to loop>
}
Eg:

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


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

Interrupting Loops

break—Causes the loop to end immediately

WE-IT TUTORIALS Page 15


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

continue—Causes the current loop cycle to end immediately (execution continues with
the next loop cycle)
goto—Allows jumping out of a loop to a labeled position
return— Jumps out of the loop and its containing function

About Variables
 How to perform implicit and explicit conversions between types
 How to create and use enum types
 How to create and use struct types
 How to create and use arrays
 How to manipulate string values

Enumerations: Variable types that have a user-defined discrete set of possible values
that can be used in a human-readable way. (user defined integer datatype)

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


types. (userdefined datatype)

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

Declaring and initialization of variables

string s1, s2, s3; // declaration


int i1, i2, i3; // declaration

s1 = "hello"; // initialization
s2 = "world"; // initialization

i1 = 2; // initialization
i3 = 3; // initialization

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


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

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


circumstances or where the rules for conversion are complicated enough to merit
additional processing of some kind.

Page 16 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Implicit conversion chart

Explicit conversion

Converting string to integer

private void Form1_Load(object sender, EventArgs e)


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

WE-IT TUTORIALS Page 17


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Convert class for explicit conversions

Overflow checking
Two keywords exist for setting what is called the overflow checking context for an
expression: checked and unchecked. You use these in the following way:

checked(<expression>)

unchecked(<expression>)

if you replace checked with unchecked in this code, you get the result shown earlier,
and no error occurs. That is identical to the default behavior

Page 18 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Enumerations
enum <typeName> : <underlyingType>
{
<value1> = <actualVal1>,
<value2>,
<value3> = <value1>,
<value4>,
...
<valueN> = <actualValN>
}

Structs
struct employee
{
public int empno;
public string empname;
public string empsname;
}
private void button1_Click(object sender, EventArgs e)
{
string s; // this is how we declare
// variable of predefined datatype

employee e; // this is how we declare


// variable of userdefined datatype

e.empno = 1; // initalization
e.empname = "max"; // initalization
e.empsname = "payne"; // initalization

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


}

WE-IT TUTORIALS Page 19


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Output:

Arrays

All the types you‟ve seen so far have one thing in common: Each of them stores a single
value (or a single set of values in the case of structs). Sometimes, in situations where you
want to store a lot of data, this isn‟t very convenient. You may want to store several values of
the same type at the same time, without having to use a different variable for each value.

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

Declaring Arrays

<baseType>[ ] <name>;

This type declaration is also called as dynamic size array.

int[ ] myArray; //

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

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

Declaring and initializing array


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

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

myArray[0] = 1;
myArray[1] = 2;
myArray[2] = 3;
myArray[3] = 4;
myArray[4] = 5;

eg:
int[] myarray; // declaration

public void test()


{

int[] myarray = new int[2];

/* You can either specify the complete contents of the array in a literal form or specify the size
of the array and use the new keyword to initialize all array elements. */
Page 20 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

myarray[0] = 1; // initialization
myarray[1] = 2; // initialization

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


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

Op: 1 2 in messagebox

Working with foreach Loops

Syntax:

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


{
// can use <name> for each element
}

Eg:
for (int i = 0; i < myarray.Length; i++)
{
MessageBox.Show(myarray[i].ToString()); // retrival
}

Same thing can be achived by foreach loop

foreach (int x in myarray)


{
MessageBox.Show(x.ToString());
}

Multidimensional Arrays

A multidimensional array is simply one that uses multiple indices to access its elements.
You might specify a position using two coordinates, x and y. You want to use these two
coordinates as indices.

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

<baseType>[ , ] <name>;

Arrays of more dimensions simply require more commas:

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

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

public void test()


{
myarray[0, 0] = 1; // initalization
myarray[0, 1] = 2;
myarray[1, 0] = 3;
myarray[1, 1] = 4; // initalization

foreach (int x in myarray)


{
MessageBox.Show(x.ToString());
}

WE-IT TUTORIALS Page 21


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

}
Op: 1 2 3 4 in message box

Arrays of Arrays

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


because each „„row‟‟ is the same size. Using the last example, you can have a y coordinate of 0
to 3 for any of the possible x coordinates.

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

Eg:

public void test()


{

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


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

/* 0 1 2
* 0 3 4
* 1 5 6 6
*
*/
myarr[0][0] = 3; // initialize value
myarr[0][1] = 4; // initialize value
myarr[1][0] = 5; // initialize value
myarr[1][1] = 6; // initialize value
myarr[1][2] = 7; // initialize value

foreach (int[] x in myarr)


{
foreach (int a in x)
{
MessageBox.Show(a.ToString());
}
}
}

Another way of writing jagged array:


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

Collection
SYSTEM . COLLECTIONS

An ArrayList is a class that holds values like an array, but elements can be added or
removed at will (dynamic array).
They offer greater functionality over an array, but they also have a larger overhead.
ArrayLists are not type safe, meaning that each element of the ArrayList can be of a
different type.

Eg:
using System.Collections;
ArrayList myArrayList = new ArrayList(); //variable length

Page 22 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

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


myArrayList.Add("Hello");
myArrayList.Add("World");
myArrayList.Add(10);

Arraylist properties and methods

properties description
Capacity Contains the allocated length of the arraylist
Count Contains the number of items currently in the arraylist

methods description
Add() Adds an item to the arraylist and returns the newly added
index
a.add(“abc”) ;
Clear() Clears all items from the arraylist
a.Clear();
Contains() Returns True if the given object is in the current arraylist
a.Contains(“a”);
CopyTo() Copies all or part of the current arraylist to another arraylist
that is passed in as an argument.
Eg a.copyto(onedimentionarray);
Insert() Inserts an item into the arraylist
a.Insert(index,object);
Remove() Removes an item from the arraylist
a.Remove(“a”);
RemoveAt() Removes an item from the arraylist by index
a.RemoveAt(index);
RemoveRange() Removes a range of items from the arraylist
a.RemoveRange(index,range) ;
Sort() Sorts the items in the arraylist
a.sort();

STRING MANIPULATION
Your use of strings so far has consisted of writing strings to the console, reading strings
from the console, and concatenating strings using the + operator.

Eg:

string str1, str2;


string[] strArray = new string[3];
strArray[0] = "abc";
strArray[1] = "def";
strArray[2] = "jkl";
str1 = "we-it tutorials";
str2 = "hello world";
//public int IndexOf(char value);
MessageBox.Show(str1.IndexOf('-').ToString()); // op: 2

//public int IndexOf(string value);


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

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


MessageBox.Show(str1.IndexOf('i',6).ToString()); // op: 11
WE-IT TUTORIALS Page 23
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

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


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

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


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

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


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

//public int LastIndexOf(string value);


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

//public string Remove(int startIndex);


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

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


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

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


string[] xyz = str2.Split(' ');
foreach (string temp in xyz) { MessageBox.Show(temp); } // op: hello and world

//public string Substring(int startIndex);


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

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


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

//public string ToLower();


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

//public string ToUpper();


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

//public string Trim();


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

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

This is how we write Main method in c# also called entry method from which the
program starts execution

Syntax:

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


{
Return <datatype>;
}

Eg:

Public static int add()


{
Page 24 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Return 2+2;
}

Public : access specifier


Static : no class object needed to access function
Int : return type
Add : name of the method

Parameters
Syntax:

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


{
...
return <returnValue>;
}

Eg:

Public int add(int a, int b)


{
Return a + b;
}

Calling the function

Int sum = add(10,20);

Passing Array as parameter


Public int add(int[] x)
{
Return x.length;
}

Int[] x : is a array parameter

Parameter Arrays

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

Eg:
class Test
{
static void F(params int[] args) {
Console.Write("Array contains {0} elements:", args.Length);
foreach (int i in args)
Console.Write(" {0}", i);
Console.WriteLine();
}
static void Main() {
int[] arr = {1, 2, 3};
F(arr);
F(10, 20, 30, 40);
F();
}
}

WE-IT TUTORIALS Page 25


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Op:
Array contains 3 elements: 1 2 3
Array contains 4 elements: 10 20 30 40
Array contains 0 elements:

Parameters by ref and by val


Ref : shares same memory location of variable
Val : copies value from one variable to another (default)

Eg:
class Program
{
static void Main(string[] args)
{
int x = 10;
Program.swap(ref x);
Console.Write(x); // op : 20
Console.ReadLine();
}

public static void swap(ref int a)


{
a = 20;
}
}

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

Eg:
class Program
{
static void Main(string[] args)
{
int x = 10;
int ret;
Program.test(x,out ret);
Console.Write(ret); // op : 20
Console.ReadLine();
}

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


{
b = 20;
}
}

Command line arguments

Eg:
class Program
{
static void Main(string[] args)
{
foreach (string x in args)
{
Page 26 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Console.WriteLine(x);
}
Console.ReadLine();
}
}

Op:

program.exe hello world


Hello
World
Overloading function

It allows the programmer to make one or several parameters optional, by giving them a
default value.

class Program
{
static void Main(string[] args)
{
Program pp = new Program();
Console.WriteLine(pp.add(10, 20).ToString);
Console.WriteLine(pp.add(10, 20, 30).ToString);
Console.ReadLine();
}

public int add(int a, int b)


{
return a + b;
}
public int add(int a, int b, int c)
{
return a + b + c;
}

Debugging and Error Handling


Outputting Debugging Information

Writing text to the Output window at runtime is easy.

There are two commands you can use to do this:


Debug.WriteLine()
Trace.WriteLine()
To use the commands we use System.Diagnostics namespace

WE-IT TUTORIALS Page 27


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Tracepoints

An alternative to writing information to the Output window is to use tracepoints.

1. Position the cursor at the line where you want the tracepoint to be inserted. The
tracepoint will be processed before this line of code is executed.

2. Right-click the line of code and select Breakpoint ➪ Insert Tracepoint.

3. Type the string to be output in the Print a Message text box in the When Breakpoint
Is Hit dialog that appears. If you want to output variable values, enclose the variable
name in curly braces.

4. Click OK. A red diamond appears to the left of the line of code containing a tracepoint,
and the line of code itself is shown with red highlighting.

1.Right click on codebreakpointinsert tracepoint

Page 28 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

2.print a message “value of a and b {a} {b}” click ok

WE-IT TUTORIALS Page 29


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

3.while debugging the output of trace is shown output window

Entering Break Mode

The simplest way to enter break mode is to click the Pause button in the IDE while an
application is running.

 Pause the application and enter break mode.


 Stop the application completely (this doesn‟t enter break mode, it just quits).
 Restart the application

Breakpoints

A breakpoint is a marker in your source code that triggers automatic entry into break
mode.

These features are available only in debug builds. If you compile a release build, all
breakpoints are ignored. There are several ways to add breakpoints. To add simple breakpoints
that break when a line is reached, just left-click on the far left of the line of code, right-click on
the line, and select Breakpoint ➪ Insert Breakpoint; select Debug ➪ Toggle Breakpoint from the
menu; or press F9.
A breakpoint appears as a red circle next to the line of code

Page 30 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

A drop-down list offers the following options: (right click on breakpoint)

 Break always
 Break when the hit count is equal to
 Break when the hit count is a multiple of
 Break when the hit count is greater than or equal to

Stepping Through Code

The yellow arrow on breakpoint shows you what point execution has reached when
break mode is entered. At this point, you can have execution proceed on a line-by-line basis.

 Step Into: Execute and move to the next statement to execute.


 Step Over: Similar to Step Into, but won‟t enter nested blocks of code, including
functions.
 Step Out: Run to the end of the code block and resume break mode at the
statement that follows.

ERROR HANDLING
Error handling is the term for all techniques of this nature, and this section looks at
exceptions and how you can deal with them. An exception is an error generated either in your
code or in a function called by your code that occurs at runtime.

WE-IT TUTORIALS Page 31


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

try . . . catch . . . finally

The C# language includes syntax for structured exception handling (SEH). Three keywords
mark code as being able to handle exceptions, along with instructions specifying what to do
when an exception occurs: try, catch, and finally. Each of these has an associated code block and
must be used in consecutive lines of code. The basic structure is as follows:

Syntax:

try
{
...
}
catch (<exceptionType> e)
{
...
}
finally
{
...
}

It is also possible, however, to have a try block and a finally block with no catch block,
or a try block with multiple catch blocks. If one or more catch blocks exist, then the finally
block is optional.

Without try catch program terminated unexceptionally

Page 32 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

With try catch program dint stopped working

Nested try
Try block inside try block is called nested try

The usage of try catch blocks


try— Contains code that might throw exceptions („„throw‟‟ is the C# way of saying
„„generate‟‟ or „„cause‟‟ when talking about exceptions)

catch—Contains code to execute when exceptions are thrown. catch blocks may be set to
respond only to specific exception types (such as System.IndexOutOfRangeException) using
<exceptionType>, hence the ability to provide multiple catch blocks. It is also possible to omit this
parameter entirely, to get a general catch block that responds to all exceptions.

finally— Contains code that is always executed, either after the try block if no exception
occurs, after a catch block if an exception is handled, or just before an unhandled exception
moves „„up the call stack.‟‟ This phrase means that SEH allows you to nest try...catch...finally blocks
inside each other, either directly or because of a call to a function within a try block.

Object-Oriented Programming
WHAT IS OBJECT-ORIENTED PROGRAMMING?

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


applications that seeks to address many of the problems with traditional programming
techniques. The type of programming you have seen so far is known as functional (or procedural)
programming, often resulting
in so-called monolithic applications, meaning all functionality is contained in a few
modules of code (often just one). With OOP techniques, you often use many more modules of
code, each offering specific functionality, and each module may be isolated or even completely
independent of the others. This
modular method of programming gives you much more versatility and provides more
opportunity for code reuse.

What Is an Object?
An object is a building block of an OOP application. This building block encapsulates part
of the application, which may be a process, a chunk of data, or a more abstract entity.
WE-IT TUTORIALS Page 33
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Eg:

class Program
{
#region fields
public string empname;
private string empid;
#endregion

#region properties
//properties are used to access private fields
public string accessempid
{get{return empid;} set { empid = value; }}
#endregion

#region constructor
//constructor is used to set values to private fields
//while initialization the object of the classs
public Program() // default constructor
{

public Program(string a) // parametarized constructor


{
empid = a;
}

#endregion

#region destructor
~Program()
{
// destructor code
}
#endregion

#region methods and functions

static void Main(string[] args)


{
Program p = new Program(); // creating object of program class
Program p1 = new Program("testing"); // passing value to constructor
p.accessempid = "12"; // accessing property
}

#endregion
}

The Life Cycle of an Object

Construction: When an object is first instantiated it needs to be initialized. This


initialization is known as construction and is carried out by a constructor function, often referred
to simply as a constructor for convenience.

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

Page 34 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Destruction: When an object is destroyed, there are often some clean-up tasks to
perform, such as freeing memory. This is the job of a destructor function, also known as a
destructor.

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

Static and Instance Class Members

Static properties and fields enable you to access data that is independent of any object
instances, and static methods enable you to execute commands related to the class type but
not specific to object instances. When using static members, in fact, you don‟t even need to
instantiate an object.

Static Constructors

A class can have a single static constructor, which must have no access modifiers and
cannot have any parameters. A static constructor can never be called directly; instead, it is
executed when one of the following occurs:

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


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

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

Static Classes

Often, you will want to use classes that contain only static members and cannot be used
to instantiate objects (such as Console). A shorthand way to do this, rather than make the
constructors of the class private, is to use a static class. A static class can contain only static
members and can‟t have instance constructors, since by implication it can never be
instantiated.

OOP TECHNIQUES
Interfaces

An interface is a collection of public instance (that is, nonstatic) methods and properties
that are grouped together to encapsulate specific functionality. After an interface has been
defined, you can implement it in a class. This means that the class will then support all of the
properties and members specified by the interface.

public interface int1 //interface


{
void display();// abstract method
}

public interface int2 //interface


{
void display();// abstract method
}

public class testing : int1, int2


// interface supports multiple inheritance
{
void int1.display()
{
Console.WriteLine("interface1 method");
}

WE-IT TUTORIALS Page 35


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

void int2.display()
{
Console.WriteLine("interface2 method");
}
}

Inheritance

Inheritance is one of the most important features of OOP. Any class may inherit from
another, which means that it will have all the members of the class from which it inherits. In
OOP terminology, the class being inherited from (derived from) is the parent class (also known as
the base class).

When using inheritance from a base class, the question of member accessibility
becomes an important one. Private members of the base class are not accessible from a
derived class, but public members are. However, public
members are accessible to both the derived class and external code.

To get around this, there is a third type of accessibility, protected, in which only derived
classes have access to a member.

public class parent


{
public void display()
{
Console.WriteLine("display method");
}
}
public class child : parent
{
// no methods or functions
}

class Program
{
static void Main(string[] args)
{
child c = new child(); // creating object of child class
c.display();// even though child class doesnt have methods display() method is
accessible because if inheritance
}
}

virtual, override , new

public class parent


{
public virtual void display() // virtual method
{
Console.WriteLine("display method");
}
}
public class child : parent
{
public override void display() // overridden method
{
Console.WriteLine("new display");
}
Page 36 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

class Program
{
static void Main(string[] args)
{
child c = new child(); // creating object of child class
c.display(); // it will call display() of child class
}
}

Virtual method in base class can be overridden in derived class using override keyword.
when virtual keyword is not written in base class method we can not use override. Override can
be written only when virtual keyword is written.
This can be done by a new keyword

public class parent


{
public void display()
{
Console.WriteLine("display method");
}
}
public class child : parent
{
public new void display() // suppress base method
{
Console.WriteLine("new display");
}
}

class Program
{
static void Main(string[] args)
{
child c = new child(); // creating object of child class
c.display(); // it will call display() of child class
}
}

Sealed class and sealed method


public sealed class parent

sealed class cannot be further inherited

public sealed void display()

sealed method cannot be overridden

Abstract class and abstract method


public abstract class parent // abstract class
{
public abstract void display();// abstract method
}

WE-IT TUTORIALS Page 37


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

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

Abstract classes has abstract methods, it can not be used directly that‟s why it is
inhearited and method are overrided.

Polymorphism

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


us to define methods in a base class and override them with derived class implementations.
Thus if you have a base class object that might be holding one of several derived class objects,
polymorphism when properly used allows you to call a method that will work differently
according to the type of derived class the object belongs to.

Operator Overloading
There are times when it is logical to use operators with objects instantiated from your
own classes. This is possible because classes can contain instructions regarding how operators
should be treated.
Use of same operator but performs different on different class

Eg:
1+2
Output is 3

“a” + “b”
Output is “ab”

Even though operator is same it works different on string class and integer class

Code:
private void button1_Click(object sender, EventArgs e)
{
overload o1 = new overload();
overload o2 = new overload();
overload o3 = new overload();
o1.x = 5;
o2.x = 6;
o3 = o1 + o2; // calling operator overloading method
MessageBox.Show(o3.x.ToString());
}
}
public class overload
{
public int x;
public static overload operator +(overload a, overload b)
{
a.x = a.x * b.x;
return a;
}
}

Page 38 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Output:

WE-IT TUTORIALS Page 39


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

UNIT 2
Assemblies
Every software has executable files (.exe). apart from the executable file, there are some Dynamic
Link Libraries (DLL) & Library (LIB) files, which conyain the complicated code of some
commonly used functions. These files come along with software. Any software package includes the
executable file along with some DLLs & LIB files, which are necessary to run the application. In
terms of .NET runtime, the process of packaging is called assembling. An assembly contains MSIL,
metadata, & other files required to execute .NET program successfully.

In .NET Framework, assemblies play an important role. An assembly is an fundamental unit of


deployment. Deployment is the process wherein an application installed on a machine. Assemblies
can be created with the help of some development tools like Visual Studio or with the help of tools
provided in .NET framework SDK. Assemblies can be make in form of .dll or .exe files using
Visual Studio. When source code is compiled, the EXE/DLL, generated by default, is actually an
assembly.

Assemblies Overview
Assemblies are a fundamental part of programming with the .NET Framework. An assembly
performs the following functions:

 It contains code that the common language runtime executes. Microsoft intermediate
language (MSIL) code in a portable executable (PE) file will not be executed if it does not
have an associated assembly manifest. Note that each assembly can have only one entry
point (that is, DllMain, WinMain, or Main).
 It forms a security boundary. An assembly is the unit at which permissions are requested and
granted
 It forms a type boundary. Every type's identity includes the name of the assembly in which it
resides. A type called MyType loaded in the scope of one assembly is not the same as a type
called MyType loaded in the scope of another assembly.
 It forms a reference scope boundary. The assembly's manifest contains assembly metadata
that is used for resolving types and satisfying resource requests. It specifies the types and
resources that are exposed outside the assembly. The manifest also enumerates other
assemblies on which it depends.
 It forms a version boundary. The assembly is the smallest versionable unit in the common
language runtime; all types and resources in the same assembly are versioned as a unit. The
assembly's manifest describes the version dependencies you specify for any dependent
assemblies.
 It forms a deployment unit. When an application starts, only the assemblies that the
application initially calls must be present. Other assemblies, such as localization resources or
assemblies containing utility classes, can be retrieved on demand. This allows applications to
be kept simple and thin when first downloaded
Page 40 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

 It is the unit at which side-by-side execution is supported.

Assemblies can be static or dynamic. Static assemblies can include .NET Framework types
(interfaces and classes), as well as resources for the assembly (bitmaps, JPEG files, resource files,
and so on). Static assemblies are stored on disk in portable executable (PE) files. You can also use
the .NET Framework to create dynamic assemblies, which are run directly from memory and are not
saved to disk before execution. You can save dynamic assemblies to disk after they have executed.

There are several ways to create assemblies. You can use development tools, such as Visual Studio
2005, that you have used in the past to create .dll or .exe files. You can use tools provided in the
Windows Software Development Kit (SDK) to create assemblies with modules created in other
development environments. You can also use common language runtime APIs, such
as Reflection.Emit, to create dynamic assemblies.

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

 End users and developers are familiar with versioning and deployment issues that arise from
today's component-based systems. Some end users have experienced the frustration of
installing a new application on their computer, only to find that an existing application has
suddenly stopped working. Many developers have spent countless hours trying to keep all
necessary registry entries consistent in order to activate a COM class.

 Many deployment problems have been solved by the use of assemblies in the .NET
Framework. Because they are self-describing components that have no dependencies on
registry entries, assemblies enable zero-impact application installation. They also simplify
uninstalling and replicating applications.

Versioning Problems
Currently two versioning problems occur with Win32 applications:

 Versioning rules cannot be expressed between pieces of an application and enforced by the
operating system. The current approach relies on backward compatibility, which is often
difficult to guarantee. Interface definitions must be static, once published, and a single piece
of code must maintain backward compatibility with previous versions. Furthermore, code is
typically designed so that only a single version of it can be present and executing on a
computer at any given time.
 There is no way to maintain consistency between sets of components that are built together
and the set that is present at run time.

These two versioning problems combine to create DLL conflicts, where installing one application
can inadvertently break an existing application because a certain software component or DLL was
installed that was not fully backward compatible with a previous version. Once this situation occurs,
there is no support in the system for diagnosing and fixing the problem.

WE-IT TUTORIALS Page 41


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

An End to DLL Conflicts


Microsoft® Windows® 2000 began to fully address these problems. It provides two features that
partially fix DLL conflicts:

 Windows 2000 enables you to create client applications where the dependent .dll files are
located in the same directory as the application's .exe file. Windows 2000 can be configured
to check for a component in the directory where the .exe file is located before checking the
fully qualified path or searching the normal path. This enables components to be
independent of components installed and used by other applications.
 Windows 2000 locks files that are shipped with the operating system in the System32
directory so they cannot be inadvertently replaced when applications are installed.

The common language runtime uses assemblies to continue this evolution toward a complete
solution to DLL conflicts.

The Assembly Solution


To solve versioning problems, as well as the remaining problems that lead to DLL conflicts, the
runtime uses assemblies to do the following:

 Enable developers to specify version rules between different software components.


 Provide the infrastructure to enforce versioning rules.
 Provide the infrastructure to allow multiple versions of a component to be run
simultaneously (called side-by-side execution).

Assembly Contents(Components Of Assembly)

In general, a static assembly can consist of four elements:

 The assembly manifest, which contains assembly metadata.


 Type metadata.
 Microsoft intermediate language (MSIL) code that implements the types.
 A set of resources.

Only the assembly manifest is required, but either types or resources are needed to give the
assembly any meaningful functionality.

There are several ways to group these elements in an assembly. You can group all elements in a
single physical file, which is shown in the following illustration.

Page 42 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Single-file assembly

Alternatively, the elements of an assembly can be contained in several files. These files can be
modules of compiled code (.netmodule), resources (such as .bmp or .jpg files), or other files
required by the application. Create a multifile assembly when you want to combine modules written
in different languages and to optimize downloading an application by putting seldom used types in a
module that is downloaded only when needed.

In the following illustration, the developer of a hypothetical application has chosen to separate some
utility code into a different module and to keep a large resource file (in this case a .bmp image) in its
original file. The .NET Framework downloads a file only when it is referenced; keeping
infrequently referenced code in a separate file from the application optimizes code download.

Multifile assembly

The files that make up a multifile assembly are not physically linked by the file system. Rather, they
are linked through the assembly manifest and the common language runtime manages them as a
unit.

In this illustration, all three files belong to an assembly, as described in the assembly manifest
contained in MyAssembly.dll. To the file system, they are three separate files. Note that the file
Util.netmodule was compiled as a module because it contains no assembly information. When the
assembly was created, the assembly manifest was added to MyAssembly.dll, indicating its
relationship with Util.netmodule and Graphic.bmp.

As you currently design your source code, you make explicit decisions about how to partition the
functionality of your application into one or more files. When designing .NET Framework code, you
will make similar decisions about how to partition the functionality into one or more assemblies.

Private Assembly

WE-IT TUTORIALS Page 43


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

 When you deploy an assembly which can be use by single application, than this
assembly is called a private assembly.
 Private assemblies can be used by only one application they are deployed with.
 Private assemblies are deployed in the directory where the main application is installed.

Shared Assembly

 When you deploy an assembly which can be used by several application, than this
assembly is called shared assembly.
 Shared assemblies are stored in a special folder called Global Assembly Cache (GAC),
which is accessible by all applications.
 Shared assemblies must have a strong name. A strong name consists of an assembly
name, a version number, a culture, a public key and an optional digital signature.
 GAC is capable of maintaining multiple copies of an assembly with the same name but
different versions.

Q:Metadata Overview
Metadata is binary information describing program that is stored either in a common language
runtime portable executable (PE) file or in memory. When code is complied into a PE file,
metadata is inserted into one portion of the file, while code is converted to Microsoft
intermediate language (MSIL) and inserted into another portion of the file. Every type and
member defined and referenced in a module or assembly is described within metadata. When
code is executed, the runtime loads metadata into memory and references it to discover
information about code's classes, members, inheritance, and so on.

Metadata describes every type and member defined in code in a language-neutral manner.
Metadata stores the following information:

 Description of the assembly.


o Identity (name, version, culture, public key).
o The types that are exported.
o Other assemblies that this assembly depends on.
o Security permissions needed to run.
 Description of types.
o Name, visibility, base class, and interfaces implemented.
o Members (methods, fields, properties, events, nested types).
 Attributes.
o Additional descriptive elements that modify types and members.

Benefits of Metadata
Metadata is the key to a simpler programming model, eliminating the need for Interface
Definition Language (IDL) files, header files, or any external method of component reference.
Metadata allows .NET languages to describe themselves automatically in a language-neutral
manner, unseen by both the developer and the user. Additionally, metadata is extensible
through the use of attributes. Metadata provides the following major benefits:

 Self-describing files.

Page 44 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Common language runtime modules and assemblies are self-describing. A module's


metadata contains everything needed to interact with another module. Metadata
automatically provides the functionality of IDL in COM, allowing to use one file for both
definition and implementation. Runtime modules and assemblies do not even require
registration with the operating system. As a result, the descriptions used by the runtime
always reflect the actual code in compiled file, which increases application reliability.

 Language interoperability and easier component-based design.

Metadata provides all the information required about compiled code for programmer to
inherit a class from a PE file written in a different language. Programmer can create an
instance of any class written in any managed language (any language that targets the
common language runtime) without worrying about explicit marshaling or using custom
interoperability code.

 Attributes.

The .NET Framework allows programmer to declare specific kinds of metadata, called
attributes, in compiled file. Attributes can be found throughout the .NET Framework and
are used to control in more detail how program behaves at run time. Additionally,
programmer can emit his/her own custom metadata into .NET Framework files through
user-defined custom attributes.

Microsoft intermediate language(MSIL)


Definition:

 It is a set of CPU independent instructions that are generated by the language compiler
when the project is compiled.

 MSIL code is not executable but further processed by CLR/other runtime environments
before it becomes executable.

 MSIL is contained in the assembly of the .NET application.

Features:
MSIL instructions map to the code that is written in .NET Language and are used for

1. loading,
2. storing,
3. initializing,
4. and calling methods on objects,
5. as well as for arithmetic and logical operations,
6. control flow,
7. direct memory access,
8. exception handling,
9. and other operations.

CLS(Common language Specification) provides the infrastructure for MSIL.

Benefits:

MSIL provides language interoperability as the code in any .NET language is compiled
into MSIL.
WE-IT TUTORIALS Page 45
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Same performance for all the .NET Languages:

 Support for different runtime environments


 CLR can understand MSIL.
 Non .NET environments also support MSIL.

The JIT Compiler in CLR converts the MSIL code into native machine code which is then
executed by the OS

VB.NET VB.NET
Source Code
Compiler

C# Source C#.NET JIT Native


MSIL Code
Code Machine
Compiler Compiler Code

Other.NET Other.NET
Source Code
Compiler

Garbage collector(GC)
The Microsoft .NET Framework provides an automated mechanism for reclaiming an object that
is no longer in use. This process is usually referred as Garbage Collection.

The Microsoft .NET Framework CLR reserves space for each object instantiated in the system.

Since memory is not infinite, CLR needs to get rid of those objects that are no longer in use so
that the space can be used for other objects.

1. The very first step in Garbage Collection is identifying those objects that can be wiped
out.
2. To accomplish this step, CLR maintains the list of references for an object.
3. If an object has no more references, i.e. there is no way that the object could be
referred to by the application, CLR considers that object as garbage.
4. During Garbage Collection, CLR reclaims memory for all garbage objects.

benefits of garbage collector


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

Page 46 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

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

JIT Compilers

JIT compilers play a major role in the .NET platform because all .NET PE files contain IL and
metadata, not native code. The JIT compilers convert IL to native code so that it can execute
on the target operating system. For each method that has been successfully verified for type
safety, a JIT compiler in the CLR will compile the method and convert it into native code.

One advantage of a JIT compiler is that it can dynamically compile code that is optimized for
the target machine. If you take the same .NET PE file from a one-CPU machine to a two-CPU
machine, the JIT compiler on the two-CPU machine knows about the second CPU and may be
able to spit out the native code that takes advantage of the second CPU. Another obvious
advantage is that you can take the same .NET PE file and run it on a totally different platform,
whether it be Windows, Unix, or whatever, as long as that platform has a CLR.

For optimization reasons, JIT compilation occurs only the first time a method is invoked. Recall
that the class loader adds a stub to each method during class loading. At the first method
invocation, the VES reads the information in this stub, which tells it that the code for the
method has not been JIT-compiled. At this indication, the JIT compiler compiles the method
and injects the address of the native method into this stub. During subsequent invocations to
the same method, no JIT compilation is needed because each time the VES goes to read
information in the stub, it sees the address of the native method. Because the JIT compiler
only performs its magic the first time a method is invoked, the methods you don't need at
runtime will never be JIT-compiled.

The compiled, native code lies in memory until the process shuts down and until the garbage
collector clears off all references and memory associated with the process. This means that the
next time you execute the process or component, the JIT compiler will again perform its magic.

If you want to avoid the cost of JIT compilation at runtime, you can use a special tool called
ngen.exe, which compiles your IL during installation and setup time. Using ngen, you can JIT-
compile the code once and cache it on the machine so that you can avoid JIT compilation at
runtime (this process is referred to as pre-JITting). In the event that the PE file has been
updated, you must PreJIT the PE file again. Otherwise, the CLR can detect the update and
dynamically command the appropriate JIT compiler to compile the assembly.

Q:: What are the different types of collections in .NET?


ANS: At its simplest, an object holds a single value. At its most complex, it holds references to
many other objects. The .NET Framework provides collections—these include List and
Dictionary. They are often useful.

List
First, the List type provides an efficient and dynamically-allocated array. It does not provide
fast lookup in the general case—the Dictionary is better for this. List is excellent when used in
loops.

example::

using System;
using System.Collections.Generic;

WE-IT TUTORIALS Page 47


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

class Program
{
static void Main()
{
// Use the List type.
List<string> list = new List<string>();
list.Add("cat");
list.Add("dog");

foreach (string element in list)


{
Console.WriteLine(element);
}
}
}

output::
cat
dog

Dictionary
The Dictionary type in the base class library is an important one. It is an implementation of a
hashtable, which is an extremely efficient way to store keys for lookup. The Dictionary in .NET
is well-designed.

We try to reference items in a table directly by doing arithmetic operations to transform keys
into table addresses.

code:

using System;
using System.Collections.Generic;

class Program
{
static void Main()
{
// Use the dictionary.
Dictionary<string, int> dict = new Dictionary<string, int>();
dict.Add("cat", 1);
dict.Add("dog", 4);

Console.WriteLine(dict["cat"]);
Console.WriteLine(dict["dog"]);
}
}

output::
1
4

Page 48 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Note:This program shows how the Dictionary can be used with type parameters to store keys and
values of specific types.

ArrayList
Next, the ArrayList is a collection found in System.Collections and it can store objects of any
derived type. You don't need to worry about the type of the elements, at least until you need
to use them.

Hashtable
To continue, the Hashtable is a lookup data structure that uses a hash code to find elements
quickly. The newer Dictionary collection is usually more appropriate for programs when
available.

code:

using System;
using System.Collections;

class Program
{
static void Main()
{
Hashtable table = new Hashtable();
table["one"] = 1;
table["two"] = 2;

// ... Print value at key.


Console.WriteLine(table["one"]);
}
}

output::

DELEGATES

A delegate is a type that enables you to store references to functions. Although this sounds
quite involved, the mechanism is surprisingly simple.

class Program
{
public delegate void ashok(string letter); // delegate declaration
static void Main(string[] args)
{
Program pp = new Program();
ashok a = new ashok(pp.soniya); // delegate instance
a("increase taxes"); // delegate invokation
}

public void soniya(string msg) // delegate method


{
Console.WriteLine("inside display");
}
WE-IT TUTORIALS Page 49
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Events

Objects may raise (and consume) events as part of their processing. Events are important
occurrences

that you can act on in other parts of code, similar to (but more powerful than) exceptions.

The special kind of function that is called when the event occurs. You also need to configure
this handler to listen for the event you are interested in.

Eg: button click

How to create custom events and attach (wiring) event to function

Code:

private void button1_Click(object sender, EventArgs e)


{
button2.Click += new EventHandler(this.willbecalled);
// line above will add method to call when button2 is clicked
}

private void willbecalled(object sender, EventArgs e)


{
MessageBox.Show("thanks for wiring \n event to me");
}

Output:

Introduction to ASP.NET 4

When you type a web address like www.facebook.com/weittutorial in your web browser and
press Enter, the browser sends a request to the web server at that address. This is done
through HTTP, the HyperText Transfer Protocol. HTTP is the protocol by which web browsers
and web servers communicate. When you send the address, you send a request to the server.
When the server is active and the request is valid, the server accepts the request,
processes it, and then sends the response back to the client browser. The
relationship between the request and response

Page 50 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

The stages of Page life cycle are as follows :


Methods Description
Page_Init Page Initialization
LoadViewState View State Loading
LoadPostData Postback Data Processing
Page_Load Page Loading
RaisePostDataChangedEvent PostBack Change Notification
RaisePostBackEvent PostBack Event Handling
Page_PreRender Page Pre Rendering Phase
SaveViewState View State Saving
Page_Render Page Rendering
Page_Unload Page Unloading

Page_Init :
The Page_Init event is the first event to be triggered in the page life cycle. In this the
control tree has been created, the controls declared in the .aspx file are initialized. The
viewstate is not available at this stage. We can create or re-create the controls that need to be
created or re-created dynamically.

LoadViewState :
The Viewstate contains stored information that is set by the page and controls of the
page. But the load view state event only occurs when the page has been posted back. Due to
viewstate control's and page itself store information that is persistent among web requests. It
contains the state of the controls the last time the page was processed on the server.

LoadPostData :
After viewstate is loaded the control are updated with posted values or values that are
entered or changed by user.

WE-IT TUTORIALS Page 51


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Page_Load :
After Loadpostdata the page_load event is fired. In this event code written inside page
load is executed once at the beginning of the page.

RaisePostDataChangedEvent :
In this event when user clicks submit button or any other button then it changes state
of the page and the event related to that button is raised.

RaisePostBackEvent :
This methods knows which event has occurred and which related method you need to
call like btnsubmit is clicked then it will call method related to it like “btnsubmit_click” to
perform its functionality.

Page_PreRender :
At this stage page is prepared for Rendering and if user wants to chage anything he can
change it here only as in this event viewstate is not saved and output is not rendered.

SaveViewState :
In this event values of viewstate is saved to control own viewstate collection. The
resultant viewstate is serialized, hashed, base24 encoded and associated with the _viewstate
hidden field.

Page_Render :
This method takes the HtmlWriter object and uses it to accumulate all HTML text to be
generated for the control. For each control the page calls the render method and caches the
HTML output.

Page_unload :
During this method, data can be released to free up resources on the server for other
processes. Once this method is completed, the HTML is sent to the browser for client side
processing.

Web Files
Web Files are specific to web applications and can either be requested by a browser
directly

File type extension Description


Web Form .aspx The workhorses of any ASP.NET web site,
Web Forms rep-resent the pages that your
users view in their browser.
Master Page .master Enable you to define the global structure and
the look and feel of a web site.
Web User .ascx Contains page fragments that can be reused
Control in multiple pages in your site.
Can be used to display static HTML in your
HTML Page .htm / .html
web site.
Style Sheet .css Contains CSS code that enables you to style
and format your web site
Page 52 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Web .config Contains global configuration information that


Configuration is used
File throughout the site. You see how to use the
web.config
Site Map .sitemap Contains a hierarchical representation of files
in your site in an XML format. The Site Map is
used for

JScript File .js Contains JavaScript (which Microsoft calls


JScript) that can be executed in the client‟s
browser.
Skin File .skin Contains design information for controls in
your web site.

Code Files

File type extension Description


Web Service .asmx Can be called by other systems, including browsers,
and
can contain code that can be executed on your server.

Class .cs / .vb Can contain code to program your web site. Note that
Code Behind files (discussed later) also have this
exten-
sion because they are essentially class files. C# uses
files
with the .cs extension and Visual Basic uses .vb files.

Global .asax Can contain code that is fired in response to


Application interesting
Class things that happen in your site, such as the start of
the
application or when an error occurs somewhere in the
site.

Data Files

File type extension Description


XML File .xml Used to store data in XML format. In addition to plain
XML
files, ASP.NET supports a few more XML-based files,
two
of which you briefly saw before: web.config and the
Site Map.

SQL .mdf Files with an .mdf extension are databases that are
Server used
Database by Microsoft SQL Server.

ASP.NET Themes and Skins


A theme is a collection of property settings that allow you to define the look of pages and
controls, and then apply the look consistently across pages in a Web application, across an
entire Web application, or across all Web applications on a server.

WE-IT TUTORIALS Page 53


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Themes and Control Skins

 Themes are made up of a set of elements: skins, cascading style sheets (CSS), images,
and other resources.
 At a minimum, a theme will contain skins.
 Themes are defined in special directories in your Web site

Skins

 A skin file has the file name extension .skin and contains property settings for individual
controls such as Button, Label, TextBox, or Calendar controls.

 Control skin settings are like the control markup itself, but contain only the properties
you want to set as part of the theme.

o For example, the following is a control skin for a Button control:

o <asp:button runat="server" BackColor="lightblue" ForeColor="black" />

Cascading Style Sheets

 A theme can also include a cascading style sheet (.css file). When you put a .css file in
the theme folder, the style sheet is applied automatically as part of the theme.

Page Themes

 A page theme is a theme folder with control skins, style sheets, graphics files and other
resources created as a subfolder of the \App_Themes folder in your Web site. Each
theme is a different subfolder of the \App_Themes folder. The following example shows
a typical page theme, defining two themes named BlueTheme and PinkTheme.

Applying themes to website


1.create a website

2.Add theme folder to website

Page 54 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

3.Now add theme folder in App_Themes

4.Now add new item to theme folder(SIDD)

5.Now Add skin file

WE-IT TUTORIALS Page 55


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

6.Now Apply style to controls in .skin

7.Now Apply style to Webpage using theme

click on any .aspx page and set Theme name to the folder name in App_Theme

Page 56 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

8.Now View the page in browser

Cascading Style Sheets


What CSS is and why you need it??

The text was formatted using plain HTML, using tags like <strong> to make the text
bold, and the <font> tag to influence the font family, size, and color. Web developers soon
realized that they needed more power to format their pages, so CSS was created to address
some of HTML‟s styling.

One of the problems with using HTML for formatting is that it offers only a limited set of
options to style your pages. You can use tags like <em>, <strong>, and <font> to change the
appearance of text and use attributes like bgcolor to change the background color of HTML
elements

<p>
<font face=”Arial” color=”red” size=”+1”>
This is red text in an Arial type face and slightly larger than the default text.
</font>
</p>

formatting with HTML suffers from the following problems:

➤➤Its feature set severely limits the formatting possibilities that your pages require.
➤➤ Data and presentation are mixed within the same file.
➤➤ HTML doesn‟t allow you to easily switch formatting at runtime in the browser.
➤➤ The required formatting tags and attributes make your pages larger and thus slower to
load and display.

How CSS Fixes Formatting Problems


CSS is designed to format your web pages in almost every possible way. It offers a rich
set of options to change every little aspect of your web page, including fonts (size, color,
family, and so on), colors and background colors, borders around HTML elements, positioning
of elements in your page, and much more. CSS is widely understood by all major browsers
today, so it‟s the language for visual presentation of web pages and very popular among web
developers.

CSS file defines how you want to display it, enabling you to change or replace one of
the two documents, leaving the other unmodified. In addition, CSS can be placed directly in an
HTML or ASPX page, which gives you a chance to add small snippets of CSS exactly where you
need them.

WE-IT TUTORIALS Page 57


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Working and principles of stylesheet:

Types of css

 Inline css
 Internal css
 External css

Inline css
<b style="background-color:Red;color:White> we-it tutorials</b>

Internal css
<head runat="server">
<style type="text/css">
b
{
background-color:Aqua;
color:Black;
}
body
{
background-color:Green;
}
</style>
</head>

External css

Filename: stylesheet.css
/*setting style to body tag*/
body
{
background-color: #C0C0C0;
border-style: dotted;
border-width: thin;
}
/*custom class*/
.custom
{
Page 58 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

font-size: xx-large;
font-weight: 400;
}
/* custom class*/
.fivestar
{
font-family: 'Arial Black';
color: #800080;
}
/* style with class*/
body.class1
{
color:Green;
}

Filename: Default.aspx
<html>
<head>
<link type="text/css" rel="Stylesheet" href="StyleSheet.css" />
</head>
<body class="class1">
<form id="form1" runat="server">
<div>
<b class="fivestar"> we-it tutorials</b>
</div>
</form>
</body>
</html>

Selectors

As its name implies, a selector is used to select or point to one or more specific elements within
your page. A number of different selectors are available, giving you fine control over what
elements you want to style.

The Universal Selector

The Universal selector, indicated by an asterisk (*), applies to all elements in your page. The
Universal selector can be used to set global settings like a font family. The following rule set
changes the font for all elements in your page to Arial:

*
{
font-family: Arial;
}

The Type Selector

The Type selector enables you to point to an HTML element of a specific type. With a Type
selector, all HTML elements of that type will be styled accordingly.

h1
{
color: Green;
}

The ID Selector

The ID selector is always prefixed by a hash symbol (#) and enables you to refer to a single
element in the page. Within an HTML or ASPX page, you can give an element a unique ID using
WE-IT TUTORIALS Page 59
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

the id attribute. With the ID selector, you can change the behavior for that single element, like
this:

#IntroText
{
font-style: italic;
}

<p id=”IntroText”>I am italic because I have the right ID.</p>

The Class Selector

The Class selector enables you to style multiple HTML elements through the class attribute.
This is handy when you want to give the same type of formatting to a number of unrelated
HTML

.Highlight
{
font-weight: bold;
color: Red;
}

<span class=”Highlight”>this is Red and Bold.</span>

Grouping and Combining Selectors

CSS also enables you to group multiple selectors by separating them with a comma.
This is handy if you want to apply the same styles to different elements.

h1, h2, h3, h4, h5, h6


{
color: Red;
}

Properties

Properties are the part of the element that you want to change with your style sheet.

property Description exaMple


background- Specifies the background-color: White;
color background background-image: url(Image.jpg);
background- color or image of an
image element.
border Specifies the border of border: 3px solid black;
an element.

color Changes the font color. color: Green;


display Changes the way ele- display: none;
ments are displayed, This causes the element to be hidden,
enabling you to hide or and
show them. not take up any screen space.

float Enables you to “float” float: left;


an This setting causes other content
element in the page following
using a float to be placed at the top-right
a left or right float. corner of
Other the element.
content is then placed
Page 60 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

on
the opposite side.

font-family Changes the font-family: Arial;


font-size appearance font-size: 18px;
of fonts used on your
font-style font-style: italic;
page.
font-weight font-weight: bold;
height Sets the height or height: 100px;
width width width: 200px;
of elements in your
margin padding: 0;
page.
padding Sets the amount of free margin: 20px;
and outside (margin) of
an element.
visibility Controls whether an visibility: hidden;
element is visible in This causes the element to be invisible.
the page. Invisible ele- However, it still takes up its original
ments still take up space in
screen the page. It‟s as if the element is still
space; you just don‟t there,
see but completely transparent.
them.

Working with css with visual developer

Click style sheet

WE-IT TUTORIALS Page 61


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Right click on elements and click on Add style rule

Select element and click on > button and click ok

Page 62 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Right click on element from css outline and click build style

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

How to attach style sheet

WE-IT TUTORIALS Page 63


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Page 64 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

UNIT 3
ASP.NET Server Controls
Introduction to Server Controls

It‟s important to understand how server controls operate and how they are completely
different from the way you define controls in other languages like classic ASP or PHP — another
popular programming language creating dynamic web sites.

Eg:

To create a text box with a message and the current time in it in classic ASP, you can
use the following code:

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

As you can see, this code contains plain HTML, mixed with a server-side block, delimited
by <% and %> that outputs the current time using the equals (=) symbol. This type of coding has
a major disadvantage: the HTML and server-side code is mixed, making it difficult to write and
manage your pages.

Server controls work differently. In ASP.NET, the controls “live” on the server inside an
ASPX page. When the page is requested in the browser, the server-side controls are processed
by the ASP.NET runtime — the engine that is responsible for receiving and processing requests
for ASPX pages. The controls then emit client-side HTML code that is appended to the final
page output. It‟s this HTML code that eventually ends up in the browser, where it‟s used to
build up the page.

instead of defining HTML controls in your pages directly, you define an ASP.NET Server
Control with the following syntax

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

Types of Controls

ASP.NET 4 comes with a large number of server controls, supporting most of your web
development needs. To make it easy for you to find the right controls, they have been placed
in separate control categories in the Visual Web Developer Toolbox

WE-IT TUTORIALS Page 65


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Common Properties for All Controls


Most of the server controls you find in the VWD Toolbox share some common behavior.
Part of this behavior includes the so-called properties that define the data a control can contain
and expose.

Each server control has an ID to uniquely identify it in the page, a Runat attribute that
is always set to Server to
indicate the control should be processed on the server, and a ClientID that contains the
client-side ID attribute that will be assigned to the element in the final HTML.

propertY desCription

AccessKey Enables you to set a key with which a control can be accessed at
the client by pressing the associated letter.

BackColor ForeColor Enables you to change the color of the background (BackColor)
and text (ForeColor) of the control.

BorderColor Changes the border of the control in the browser. The similarities
BorderStyle with the CSS border properties you saw in the previous chapter
BorderWidth are no coincidence. Each of these three ASP.NET properties maps
directly to its CSS counterpart.
CssClass Lets you define the HTML class attribute for the control in the
browser. This class name then points to a CSS class you defined
in the page or an external CSS file.

Enabled Determines whether the user can interact with the control in the
browser. For
example, with a disabled text box (Enabled=”False”) you cannot
change its text.

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


Size, Font-Names, and Font-Bold.
Height Width Determines the height and width of the control in the browser.
TabIndex Sets the client-side HTML tab index attribute that determines the
order in which users can move through the controls in the page
by pressing the Tab key.

ToolTip Enables you to set a tooltip for the control in the browser. This
tooltip, rendered as a title attribute in the HTML, is shown when
the user hovers the mouse over the relevant HTML element.

Visible Determines whether or not the control is sent to the browser. You
should really see this as a server-side visibility setting because an
invisible control is never sent to the browser at all. This means it‟s
quite different from the CSS display and visibility properties you
saw in the previous chapter that hide the element at the client.

Types of Controls

Standard Controls
The Standard category contains many of the basic controls that almost any web page
needs. You‟ve already seen some of them, like the TextBox, Button, and Label controls

Page 66 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Simple Controls
The Toolbox contains a number of simple and straightforward controls, including
TextBox, Button, Label, HyperLink, RadioButton, and CheckBox.

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

Container Controls
Quite often it‟s desirable to have the ability to group related content and controls. This
grouping can be done by putting the controls (and other markup) in one of the container
controls, like the Panel, the PlaceHolder, the MultiView, or the Wizard.

LinkButton and ImageButton


The LinkButton and the ImageButton controls operate similarly to an ordinary Button
control. Both of them cause a postback to the server when they are clicked. The LinkButton
presents itself as a simple <a> element but posts back (using JavaScript) instead of requesting
a new page. The ImageButton does the same, but displays an image that the user can click to
trigger the postback.

Image and ImageMap


These controls are pretty similar in that they display an image in the browser. The
ImageMap enables you to define hotspots on the image that when clicked either cause a
postback to the server or navigate to a different page.

Calendar
The Calendar control presents a rich interface that enables a user to select a date. You
see more of it toward the end of this chapter when the ASP.NET state engine is discussed.

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

AdRotator
The AdRotator control enables you to display random advertisements on your web site.
The ads come from an XML file that you create on your server.

HiddenField
The HiddenField control enables you to store data in the page that is submitted with
each request.This is useful if you want the page to remember specific data without the user
seeing it on the page.

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

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

HTML Controls
The HTML category of the Toolbox contains a number of HTML controls that look similar
to the ones found in the Standard category.
For example, you find the Input (Button) that looks like the <asp:Button>. Similarly,
there is a Select control that has the <asp:DropDownList> and <asp:ListBox> as its
counterparts.
In contrast to the ASP.NET Server Controls, the HTML controls are client-side controls
and end up directly in the final HTML in the browser. You can expose them to server-side code

WE-IT TUTORIALS Page 67


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

by adding a Runat=”Server” attribute to them. This enables you to program against them from
the Code Behind of a Web Form, to influence things like their visibility.

Data Controls
offer an easy way to access various data sources like databases, XML files, and objects.
Instead of writing lots of code to access the data source as you had to do in earlier versions of
ASP.NET

Validation Controls
Validation controls enable you to rapidly create Web Forms with validation rules that
prohibit users from entering invalid data.

Navigation Controls
The controls you find under the Navigation category of the Toolbox are used to let users
find their way through your site.
The TreeView control presents a hierarchical display of data and can be used to show
the structure of your site, giving easy access to all the pages in the site.
The Menu control does a similar thing and provides options for horizontal and vertical
fold-out menus.

Login Controls
Just like the Data and Navigation controls, the Login controls were introduced in
ASP.NET 2.0 and are still strongly present in ASP.NET 4. With very little effort, login controls
enable you to create secure web sites where users need to sign up and log in before they can
access specific parts of the web site (or even the entire web site). In addition, they provide the
tools for users to change their password, or request a new password if they forget the old one,
and enable you to display different data depending on the logged-in status and role of the user.

Ajax Extensions
These extensions enable you to create flicker-free web applications that are able to
retrieve data from the server from client-side JavaScript without a full postback.

WebParts
ASP.NET WebParts are a set of controls that enables an end user of a web page to
change the appearance and behavior of a web site. With a few simple actions, users can
change the entire appearance of a web site by rearranging content, hiding or showing parts of
the web page, and adding other content fragments to the page.

Dynamic Data
The controls in this category are used in Dynamic Data Web Sites. Dynamic Data sites
enable you to quickly build a user interface to manage data in a database.

ASP.NET Configuration
Every web application includes a web.config file that configures fundamental settings.

They are never locked: You can update web.config settings at any point, even while
your application is running. If there are any requests currently under way, they‟ll
continue touse the old settings, while new requests will get the changed settings right
away.

They are easily accessed and replicated: Provided you have the appropriate
network rights, you can change a web.config file from a remote computer. You can
also copy the web.config file and use it to apply identical settings to another
application or another web server that runs the same application.

Page 68 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

The settings are easy to edit and understand: The settings in the web.config file
are humanreadable, which means they can be edited and understood without needing
a special configuration tool.

The web.config File


The web.config file uses a predefined XML format. The entire content of the file is nested in a
root <configuration> element.

Inside this element are several more subsections, some of which you’ll never change, and
others which are more important.

basic skeletal structure of the web.config file, with the three most important sections
highlighted in bold:

<?xml version="1.0" ?>


<configuration>
<configSections>...</configSections>
<appSettings>...</appSettings>
<connectionStrings>...</connectionStrings>
<system.web>...</system.web>
<system.codedom>...</system.codedom>
<system.webServer>...</system.webServer>
</configuration>
1. The <appSettings> section allows you to add your own miscellaneous pieces of
information.
2. The <connectionStrings> section allows you to define the connection information
for accessing a database.
3. The <system.web> section holds every ASP.NET setting you’ll need to
configure.

Nested Configuration

WE-IT TUTORIALS Page 69


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Every web server starts with some basic settings that are defined in two configuration files
These two files are machine.config and web.config.

web.config setting for several reasons


To centralize an important setting that needs to be used in many different pages: For
example, you could create a variable that stores a database query. Any page that needs to use
this query can then retrieve this value and use it.

To make it easy to quickly switch between different modes of operation: For example,
you might create a special debugging variable. Your web pages could check for this variable
and, if it‟s set to a specified value, output additional information to help you test the
application.

To set some initial values: Depending on the operation, the user might be able to modify
these values, but the web.config file could supply the defaults.

You can enter custom settings using an <add> element that identifies a unique variable name
(key) and the variable contents (value).

<appSettings>
<add key="DataFilePath"
value="e:\NetworkShare\Documents\WebApp\Shared" />
</appSettings>

Retrieving value from web.config file

WebConfigurationManager.AppSettings["DataFilePath"]

The Global.asax File


The Global.asax file allows you to write code that responds to global application events. These
events fire at various points during the lifetime of a web application, including when the
application domain is first created (when the first request is received for a page in your website
folder).

To add a Global.asax file to an application in Visual Studio,

choose Website ➤ Add New Item, and select the Global Application Class file type. Then, click
OK.

The Global.asax file looks similar to a normal .aspx file, except that it can‟t contain any HTML
or ASP.NET tags.

Page 70 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Application Events
Event-Handling Description
Method
Application_Start() Occurs when the application starts, which is the first time it
receives a request from any user. It doesn‟t occur on sub-
sequent requests. This event is commonly used to create or
cache some initial information that will be reused later.

Application_End() Occurs when the application is shutting down, generally because


the web server is being restarted. You can insert cleanup code
here.

Application_BeginRequest() Occurs with each request the application receives, just before the
page code is executed.

Application_EndRequest() Occurs with each request the application receives, just after the
page code is executed.
Session_Start() Occurs whenever a new user request is received and a session is
started.

Session_End() Occurs when a session times out or is programmatically ended.


This event is only raised if you are using in-process session state
storage (the InProc mode, not the StateServer or SQLServer
modes).

Application_Error() Occurs in response to an unhandled error.

Programming ASP.NET web pages


data types and variables, statements

refer unit 1 notes for data types and statements

Organizing Code with Namespaces


Namespaces are intended to solve two major problems: to organize the enormous amount of
functionality in the .NET Framework and in your own code, and to avoid name collisions, where
two different data types share the same name. One common misconception about namespaces
is that there is a direct relation with .NET assemblies (files with a .dll extension that are loaded
and used by the .NET Framework) but that‟s not the case. Although you typically find
namespaces like System.Web.UI in a DLL called System.Web.dll it‟s possible (and common) to have
multiple namespaces defined in a single DLL or to have a namespace be spread out over
multiple assemblies.

public partial class Demos_CalculatorDemo : System.Web.UI.Page

{}

In this code, Page is the name of a class (a data type), which is defined in the System.Web.UI
namespace. By placing the Page class in the System.Web.UI namespace, developers (and
compilers) can see this class is about a web page.

Object Orientation Basics

WE-IT TUTORIALS Page 71


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Object orientation, or object-oriented programming, is a highly popular style of programming


where the software is modeled as a set of objects interacting with each other. Object
orientation is at the heart of the .NET Framework. Literally everything inside the framework is
an object, from simple things like integers to complex things like a DropDownList control, a
connection to the database, or a data-driven control.

refer unit 1 notes for object oriented programming

Page 72 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

UNIT 4
Validating User Controls
Validating user input in Web forms

People concerned with validating user input often use the mantra: Never trust user input.
Although this may seem like paranoia at first, it is really important in any open system. Even if
you think you know who your users are and even if you trust them completely, they are often
not the only users that can access your system.

A Warning on Client-Side Validation

Although client-side validation may seem enough to prevent users from sending invalid data to
your system, you should never rely on it as the only solution to validation. It‟s easy to disable
JavaScript in the browser, rendering the client-side validation routines useless. In addition, a
malicious user can easily bypass the entire page in the browser and send information directly
to the server, which will happily accept and process it if you don‟t take countermeasures.

Introduction Validation Controls:


This set of controls provide Rapid Application Development (RAD) features for automatically
checking the specified validity of user inputs. These controls are available in the
System.Web.UI.WebControls namespace.

One of the most tiresome tasks when building interactive web applications is the requirement
for validating values that the user enters into the input controls. This is particularly the case if
we need to perform client-side as well as server side validation. Mostly, we use JavaScript for
client side coding. Help is at hand with the range of validation controls that are included in
ASP.NET.

The ASP.NET Validation Controls

One of the most tiresome tasks when building interactive web applications is the requirement
for validating values that the user enters into the input controls. This is particularly the case if
we need to perform client-side as well as server side validation. Mostly, we use JavaScript for
client side coding. Help is at hand with the range of validation controls that are included in
ASP.NET.

RequiredFieldValidator::

<asp:RequiredFieldValidator>

Checks that the validated control contains a value. It cannot be empty. Can be used in
conjunction with other validators on a control to trap empty values. Simply, we can use it to
check if the input control has any value. The most important property in the
RequiredFieldValidator is InitialValue.

<asp:RequiredFieldValidator id="validTxtName runat="server"


controlToValidate="txtName"
errorMessage="Name must be entered" display="static">

WE-IT TUTORIALS Page 73


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

</asp:RequiredFieldValidator>

RegularExpressionValidator:
<asp:RegularExpressionValidator>

Checks the value against a regular expression (pattern). Checks that the value in the control
matches a specified regular expression. If the validated control is empty, no validation takes
place. The most important property in the RegularExpressionValidator is ValidationExpression.

<asp:RegularExpressionValidator id="regvH"
runat="server" display="static" controlToValidate="txtH"
errorMessage="Hours must be 1-3 digits only"
validationExpression="\d{1,3}">

</asp:RegularExpressionValidator>

CompareValidator:

<asp:CompareValidator>

Checks if the value is acceptable compared to a given value or compared to the content of
another control. In other words, it checks that the value in the validated control matches the
value in another control or a specific value. The data type and comparison operation can be
specified. If the validated control is empty, no validation takes place. The most important
properties in the CompareValidator are ValueToCompare, ControlToCompare, Operator, and
type.

<asp:CompareValidator id="comvR" runat="server" display="static"


controlToValidate="txtR" errorMessage="Rate must be numeric"
type="Double" operator="DataTypeCheck"></asp:CompareValidator>

RangeValidator:
<asp:RangeValidator>

Checks if the input control‟s value is within a specified range. In other words, it checks that the
value in the validated control is within the specified text or numeric range. If the validated
control is empty, no validation takes place. The most important properties in the
RangeValidator are MaximumValue, MinimumValue, and type.

<asp:RangeValidator id="ranvDependents" runat="server"


display="static" controlToValidate="txtDependents"
errorMessage="Must be from 0 to 10"
type="Integer" minimumValue=0 maximumValue=10>
</asp:RangeValidator>

CustomValidator:
<asp:CustomValidator>

Allows you to develop custom validation. Performs user-defined validation on an input control
using a specified function (client-side, server-side, or both). If the validated control is empty,

Page 74 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

no validation takes place. The most important property in the CustomValidator is


ClientValidationFunction.

<asp:CustomValidator id="cusvDeptNum" runat="server"


display="static" controlToValidate="txtDeptNum"
onServerValidate="validateDeptNum"
errorMessage="Must be in multiples of 10" >
</asp:CustomValidator>

ValidationSummary:
<asp:ValidationSummary>

Displays a summary of all current validation errors. In other words, reports a summary of all
errors. The most important properties in the ValidationSummary are DisplayMode,
ShowHeaderText, ShowMessageBox, and ShowSummary.

<asp:ValidationSummary id="valSummary" runat="server"


headerText="Please correct the following errors"
display="static" showSummary= "True" />

State Management
The ASP .NET State Engine
The text in the text box is maintained by the ASP.NET state engine, a feature that is deeply
integrated into the ASP.NET runtime. It enables controls to maintain their state across
postbacks, so their values and settings remain available after every postback of the page.
When a form is submitted in classic ASP, all form values are cleared. Suppose you have
submitted a form with a lot of information and the server comes back with an error. You will
have to go back to the form and correct the information. You click the back button, and what
happens.......ALL form values are CLEARED, and you will have to start all over again! The site
did not maintain your ViewState.

When a form is submitted in ASP .NET, the form reappears in the browser window together
with all form values. How come? This is because ASP .NET maintains your ViewState. The
ViewState indicates the status of the page when submitted to the server. The status is defined
through a hidden field placed on each page with a <form runat="server"> control. The source
could look something like this:

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


<input type="hidden" name="__VIEWSTATE"
value="dDwtNTI0ODU5MDE1Ozs+ZBCF2ryjMpeVgUrY2eTj79HNl4Q=" />
.....some code
</form>

__VIEWSTATE The hidden form field that is used to transfer the state from the server to
the client and back

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

WE-IT TUTORIALS Page 75


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

View state concepts


 View state is an ASP.NET feature that provides for retaining the values of page and
control properties that change from one execution of a page to another.

 Before ASP.NET sends a page back to the client, it determines what changes the pro-
gram has made to the properties of the page and its controls. These changes are
encoded into a string that‟s assigned to the value of a hidden input field named
_VIEWSTATE.

 When the page is posted back to the server, the _VIEWSTATE field is sent back to the
server along with the HTTP request. Then, ASP.NET retrieves the property values from
the _VIEWSTATE field and uses them to restore the page and control properties.

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

 View state is not used to restore data entered by a user into a text box or any other
input
control unless the control responds to change events.

 If view state is enabled for a data-bound control, the control will not be rebound when
the page is reposted. Instead, the control‟s values will be restored from view state.

How to use view state for your own data


Although view state is designed to automatically save page and control property values across
round trips to the browser, you can also add your own data to view state. To do that, you store
the data in a view state object that‟s created from the StateBag class as shown in figure

Indexer Description
[name] The value of the view slate item with the
specified name. If you set the value
of an item that doesn’t exist, that item is
created.
Property Description
Count The number of items in the view state collection.
Keys A collection of keys for all of the items in the
view state collection.
Values A collection of values for all of the items in the
view state collection.
Method Description
Add(name, value) Adds an item to the view state collection. If the
item you name already exists,
its value is updated.
Clear() Removes all items from the view state collection.
Remove(name) Removes the item with the specified name from the
view state collection.

A statement that adds or updates a view state item

ViewState.Add("TimeStamp", Now);

Another way to add or update a view state item

ViewState ["TimeStamp"] = DateTime.Now;


Page 76 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

A statement that retrieves the value of a view state item

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

A statement that removes an item from view state

ViewState.Remove("TimeStamp");

Like the session state object, the view state object contains a collection of key/value pairs that
represent the items saved in view state. To access this object, you use the ViewStatc property
of the page. Then, you can use the methods listed in this figure to work with the view state
object.

To illustrate, the first two examples in this figure show how you can add or update a view state
item named TimeStamp. The third example shows how to retrieve that item. And the last
example shows how to remove it. Notice in the third example that because a view state item is
stored as an object type, the code must cast the object to the DateTime data type.

Keep in mind that you usually use session state, not view state, to save data across round trips
to the browser. Occasionally, though, it does make sense to use view state for passing small
amounts of data, especially when you want to associate the data with a specific page.

Session State
ASP.NET uses session state to track the state of each user of an application. To do that, it
creates a session stale object that contains a unique session ID for each user‟s session. This ID
is passed back to the browser as part of the response and then eturned to the server with the
next request. ASP.NET can then use the session ID to get the session state object that‟s
associated with the request.

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

Indexer Description
[name] The value of the session state item with the
specified name. If you set the
value of an item that doesn’t exist, that item is
created.
Property Description
SessionID The unique II) of the session.
Count The number of items in die session state
collection.
Method Description
Add(name, value) Adds an item to the session state collection. If
the item you name already
exists, its value is updated.
Clear() Removes all items from the session state
collection.
Remove(name) Removes the item with the specified name from the
session state collection.

A statement that adds or updates a session state item

Session["EMail"] = email;

A statement that retrieves the value of a session state item


WE-IT TUTORIALS Page 77
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

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

A statement that removes an item from session state

Session.Remove("EMail");

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

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

Description
 ASP.NET uses session state to track the state of each user of an application. To do that,
it
creates a session state object that contains a session ID. This ID is passed to the
browser
and then back to the server with the next request so the server can identify the session
associated with that request.

 Because session state sends only the session ID to the browser, it doesn‟t slow
response time. By default, though, session state objects are maintained in server
memory so they can slow performance on the server side.

 To work with the data in session state, you use the HttpSessionState class, which
defines a collection of session state items.

 To access the session state object from the code-behind file for a web form, use the
Session property of the page.

 To access the session state object from a class other than a code-behind file, use the
Current property of the HttpContext class to get the HttpContext object for the current
request. Then, use the Session property to get the session state object.

Four options for storing session state data

 In-process mode (the default) stores session state data in IIS server memory in the
same process as the ASP.NET application. This is the session state mode that‟s used the
most, hut it‟s suitable only when a single server is used for the application.

 State Server mode stores session state data in server memory under the control of a
separate service called the ASP.NF.T state service. This service can be accessed by
other IIS servers, so it can be used when an application is hosted on a web farm that
consists of more than one IIS server. In that case, each request for the application can
be processed by a different server, so the session state information must be available to
all the servers.

 SQL Server mode stores session state data in a SQL Server database. Like State Server
mode, SQL Server mode is used for applications that require more than one IIS server.
Although this mode is slower than In-process mode and State Server mode, it‟s also the
most reliable.

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

Page 78 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Two options for tracking session IDs

 By default, ASP.NET uses cookie-based session tracking to keep track of user sessions.
However, if a browser doesn‟t support cookies, this doesn‟t work.

 With cookieless session tracking, the session ID is encoded as part of the URL. As a
result, cookieless session state works whether or not the browser supports cookies.

Application State
In contrast to session state, which stores data for a single user session, application state lets
you store data that is shared by all users of an application.

To start, an application is made up of all the pages, code, and other files
that arc located under a single directory in an IIS web server. The first time a user requests a
page that resides in an application‟s directory, ASP.NET initializes the application. During that
process, ASP.NET creates an application object from the HttpApplication class. This object is
represented by a special class file named global.asax.

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


This object exists until the application ends, which normally doesn‟t happen until IIS shuts
down. However, the application is automatically restarted each
time you rebuild the application or edit the application‟s web.config file.

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


it also creates an application state object from the HttpApplicationState class.
You can use this object to store data in server memory that can be accessed by
any page that‟s part of the application.

Common members of the HttpApplicationState class


Indexer Description
[name] The value of the application state item with the
specified name. If you set the
value of an item that doesn’t exist, that item is
created.
Property Description
Count The number of items in the application state
collection.
Method Description
Add(name, Adds an item to the application state collection.
value) Removes all items from the application state
Clear() collection.
Remove(name) Removes the item with the specified name from the
Lock() application state collection.
Unlock() Locks the application state collection so only the
current user can access it.
Unlocks the application state collection so other
users can access it.

A statement that retrieves an item from application state

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

A statement that adds an item to application state


WE-IT TUTORIALS Page 79
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Application.Add("ClickCount", 0);

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

int applicationCount = Convert.ToInt32

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

Code that locks application state while retrieving and updating an item

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

How to use cookies and URL encoding


To create a cookie, you instantiate an object from the HttpCookie class. Then, you include it in
the HTTP response that the server sends back to the browser, and the user‟s browser stores
the cookie either in its own memory or in a text file on the client machine‟s disk.

A cookie that‟s stored in the browser‟s memory is called a session cookie because it exists only
for that session. When the browser session ends, the contents of any session cookies are lost.
Session cookies arc what ASP.NET uses to track session ID‟s. In contrast, persistent cookies arc
written to disk, so they are maintained after the browser session ends. Whether session or
persistent, though, once a cookie is sent to a browser, it‟s automatically returned to the server
with each HTTP request.

Besides using cookies for session IDs, you can use cookies to save information that identifies
each user so the users don‟t have to enter that information each time they visit your web site.
You can also use cookies to store information that lets you personalize the web pages that are
displayed for a user.

When you use cookies to store this type of information, you should keep in mind that some
users may have disabled cookies on their browsers. In that case, you won‟t be able to save
cookies on the user‟s computer. Unfortunately, ASP.NET doesn‟t provide a way for you to
determine whether a user has disabled cookies. As a result, if you use cookies in an
application, you may need to notify the user that cookies must be enabled to use it.

Two ways to create a cookie


 New HttpCookie(name)
 New HttpCookie(name, value)

Common properties of the HttpCookie class


Property Description
Expires A DateTime value that indicates when the cookie should
expire.
Name The cookie’s name.
Secure A Boolean value that indicates whether the cookie
should be sent only when a secure connection is used.
See chapter 18 for information on secure connections.
Value The string value assigned to the cookie.

Code that creates a session cookie


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

Page 80 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Code that creates a persistent cookie


HttpCookie nameCookie = new HttpCookie("UserName");
nameCookie.Value = userName;
nameCookie.Expires = DateTime.Now.AddYears(1);

Description

 A cookie is a name/value pair that‟s stored in the user‟s browser or on the user‟s disk.

 A web application sends a cookie to a browser via an HTTP response. Then, each time
the browser sends an HTTP request to the server, it attaches any cookies that are
associated with that server.

 By default, ASP.NET uses a cookie to store the session ID for a session, but you can also
create and send your own cookies to a user‟s browser.

 A session cookie is kept in the browser‟s memory and exists only for the duration of the
browser session. A persistent cookie is kept on the user‟s disk and is retained until the
cookie‟s expiration date.

 To create a cookie, you specify its name or its name and value. To create a persistent
cookie, you must also set the Expires property to the time you want the cookie to
expire.

Common members of the HttpCookieCollection class


Indexer Description
[name] The cookie with the specified name.
Property Description
Count The number of cookies in the collection.
Method Description
Add(cookie) Adds a cookie to the collection.
Clear() Removes all cookies from the collection.
Remove(name) Removes the cookie with the specified name from the
collection.

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

private void AddCookie()


{

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


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

Response.Cookies.Add(nameCookie);

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

protected void Page_Load(object sender, EventArgs e)


{
if (!IsPostBack)
{
if (!(Request.Cookies["UserName"] == null))
lblUserName.Text = "Welcome back " + Request.Cookies["UserName"].value;
WE-IT TUTORIALS Page 81
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

}
}

A method that deletes a persistent cookie

private void DeleteCookie()


{
HttpCookie nameCookie = new HttpCookie("UserName");
nameCookie.Expires = DateTime.Now.AddSeconds(-1);
Response.Cookies.Add(nameCookie);
}
How to use URL encoding

URL encoding provides another way to maintain state by storing information in a page on the
client. This information is stored in a query string that‟s added to the end of the URL. Since
using query strings is a common technique, you‟ve probably seen them used on search sites
like Google (www.google.com) and shopping sites like Ebay (www.ebay.com) and Amazon
(www.amazon.com).

At the top of this figure, you can sec two URLs that include query strings. The first one includes
a single attribute named cat, and the second one includes two attributes named cat and prod.
As you can see, you add a query string by coding a question mark after the URL. Then, you
code the name of the first attribute, an equal sign, and the value you w-ant to assign to the
attribute. To include another attribute, you code an ampersand (&), followed by the name and
value of the attribute.

Two URLs with query strings


Order.aspx?cat=costumes
Order.aspx?cat=props&prod=rat01

A hyperlink with a URL that includes a query string


<asp:HyperLink ID="HyperLinkl" runat="server"
NavigateUrl="~/Product.aspx?cat=fx&amp;prod=fogOl">Pog machine
</asp:HyperLink>

An anchor element with a URL that includes a query string


<a href="product.aspx?cat=fx&prod=fog01“>Fog machine</a>

Statements that retrieve the values of the query string attributes


string categorylD = Request.QueryString[“cat"];
string productID = Request.QueryString["prod"];

Code that uses a URL with a query string in a Redirect method


Response.Redirect("Order.aspx?cat=" + categorylD);

Master Pages
ASP.NET master pages allow you to create a consistent layout for the pages in your application.
A single master page defines the look and feel and standard behavior that you want for all of
the pages (or a group of pages) in your application. You can then create individual content
pages that contain the content you want to display. When users request the content pages,
they merge with the master page to produce output that combines the layout of the master
page with the content from the content page.
Page 82 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

A master page is an ASP.NET file with the extension .master (for example, MySite.master) with
a predefined layout that can include static text, HTML elements, and server controls. The
master page is identified by a special @ Master directive that replaces the @ Page directive
that is used for ordinary .aspx pages. The directive looks like the following.

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

The @ Master directive can contain most of the same directives that a @ Control directive can
contain. For example, the following master-page directive includes the name of a code-behind
file, and assigns a class name to the master page.

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

Replaceable Content Placeholders

the master page also includes one or more ContentPlaceHolder controls. These placeholder
controls define regions where replaceable content will appear. In turn, the replaceable content
is defined in content pages.

Content Pages

You define the content for the master page's placeholder controls by creating individual content
pages, which are ASP.NET pages (.aspx files and, optionally, code-behind files) that are bound
to a specific master page. The binding is established in the content page's @ Page directive by
including a MasterPageFile attribute that points to the master page to be used.

Advantages of Master Pages

Master pages provide functionality that developers have traditionally created by copying
existing code, text, and control elements repeatedly; using framesets; using include files for
common elements; using ASP.NET user controls; and so on. Advantages of master pages
include the following:

 They allow you to centralize the common functionality of your pages so that you can
make updates in just one place.

 They make it easy to create one set of controls and code and apply the results to a set
of pages. For example, you can use controls on the master page to create a menu that
applies to all pages.

 They give you fine-grained control over the layout of the final page by allowing you to
control how the placeholder controls are rendered.

 They provide an object model that allows you to customize the master page from
individual content pages.

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

Steps:

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

2.Add label on master page

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

WE-IT TUTORIALS Page 83


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

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

</asp:ContentPlaceHolder>
</div>
</form>

3.Add public property in MasterPage.master.cs

public partial class MasterPage : System.Web.UI.MasterPage


{
public String AccessLabelText
{
set
{
Label1.Text = value;
}
get
{
return Label1.Text;
}
}
}

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

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

<%@ Page Title="" Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true"


CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ MasterType TypeName="MasterPage" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
</asp:Content>

6.Add code to button click

protected void Button1_Click(object sender, EventArgs e)


{
MasterPage mp = (MasterPage)this.Master;
mp.AccessLabelText = "ACCESSED MASTER PAGE LABLE THROUGH CONTENT PAGE";
}

output:

Refer classroom notes for example

Page 84 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Navigation
When you think about important parts of a navigation system, the first thing that you may
come up with is a menu. Menus come in all sorts and sizes, ranging from simple and static
HTML links to complex, fold-out menus driven by CSS or JavaScript. But there‟s more to
navigation than menus alone. ASP.NET comes with a number of useful navigation controls that
enable you to set up a navigation system in no time. These controls include the Menu,
TreeView, and SiteMapPath

Besides visual controls like Menu, navigation is also about structure. A well-organized site is easy
for your users to navigate. The Web.sitemap file that is used by the navigation controls helps
you define the logical structure of your site.

Different Ways to Move Around Your Site

The most common way to let a user move from one page to another is by using the <a>
element.

<a href=”Login.aspx”>You can log in here</a>

 The <a> element has a server-side counterpart called the HyperLink, which can be created
in the markup using <asp:HyperLink>.

 It eventually ends up as an <a> element in the page.

 The NavigateUrl property of this control maps directly to the href attribute of the <a>
element.

<asp:HyperLink runat=”server” id=”LoginLink” NavigateUrl=”Login.aspx”>You can log in


here</asp:HyperLink>

Understanding Absolute and Relative URLs


 Key to working with links in your site is a good understanding of the different forms a
Uniform Resource Locator (URL) to a resource inside or outside your web site can take.

 A URL is used to uniquely identify a resource in your or another web site.

Absolute URL

In addition to several other meanings, the word absolute, in English, means "not dependent on
anything else". It also means "free from doubt".

 An Absolute URL is, thus, something that is independent or free from any relationship.
 When you use an absolute URL, you point directly to a file. Hence,
 An absolute URL specifies the exact location of a file/directory on the internet.

For example: http://www.webdevelopersnotes.com/images/email.gif

<img src="http://www.webdevelopersnotes.com/images/email.gif"

width="..." height="..." />

WE-IT TUTORIALS Page 85


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Relative URL

A relative URL points to a file/directory in relation to the present file/directory

<img src="../images/email.gif" width="..." height="..." />

Using the Navigation Controls

ASP.NET 4 offers three useful navigation tools: SiteMapPath, TreeView, and Menu.

Architecture of the Navigation Controls

To make it easy to show relevant pages in your site using a Menu, a TreeView, or a
SiteMapPath, ASP.NET uses an XML-based file that describes the logical structure of your web
site. By default, this file is called Web.sitemap. This file is then used by the navigation controls
in your site to present relevant links in an organized way. Simply by hooking up one of the
navigation controls to the Web.sitemap file you can create complex user interface elements like
fold-out menus or a tree view.

Web.sitemap File

By default, you should call the site map file Web.sitemap. This enables the controls to find the
right file automatically.

A basic version of the site map file can look like this:

<?xml version=”1.0” encoding=”utf-8” ?>


<siteMap xmlns=”http://schemas.microsoft.com/AspNet/SiteMap-File-1.0”>
<siteMapNode url=”~/” title=”Home” description=”Go to the homepage”>
<siteMapNode url=”~/Reviews” title=”Reviews” description=”Reviews published on this site”
/>
<siteMapNode url=”~/About” title=”About” description=”About this site” />
</siteMapNode>
</siteMap>

Page 86 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Key Elements of the Web.sitemap File

Each siteMapNode can have many child nodes (but there can only be one siteMapNode directly
under the siteMap element), enabling you to create a site structure that can be both wide and
deep at the same time. The siteMapNode elements in this example have three of their
attributes set: url, title, and description.

 The url attribute should point to a valid page in your web site.
 The title attribute is used in the navigation controls to display the name of the page.
 The description attribute is used as a tooltip for the navigation elements.

For code Refer classroom notes

programmatic redirection
Programmatic redirection is very useful and common in ASP.NET pages. For example, imagine
a page that enables a user to enter a review into the database. As soon as she clicks the Save
button, the review is saved and the user is taken to another page where she can see the entire
review.

ASP.NET supports three major ways to redirect users to a new page programmatically. The first
two, Response.Redirect and Response.RedirectPermanent (which is new in ASP.NET 4), send
an instruction to the browser to fetch a new page. The third option, Server.Transfer, executes
at the client. Because there‟s quite a difference in client- and server-side redirection.

programmatically redirecting the Client to a Different page


Response.Redirect(newUrl)
Response.RedirectPermanent(newUrl)

The difference between Redirect and RedirectPermanent mainly has to do with search engine
optimization. Using Redirect tells the client that the page has moved temporarily.

RedirectPermanent tells the client the page has moved permanently. This is useful if you want
to tell a search engine to stop looking at an old page, and index the new one instead.

server-side redirects
Server-side redirects are great if you want to send out a different page without modifying the
client‟s address bar. This enables you to hide details of page names and query strings, which
may lead to cleaner URLs from a user‟s point of view.

Server-side transfers are carried out with the Server object. Just like the Request and Response
objects you saw earlier give you information about the request and the response, so does the
Server object provide you with information about the server the page is running on. You can
use it to get information about the server name, its IP address, and so on. One of its methods
is Transfer, which performs a server-side transfer.

Server.Transfer can only be used to redirect to other pages within your site.
Server.Transfer(“Target.aspx?Test=SomeValue”)

WE-IT TUTORIALS Page 87


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

UNIT 5
Databases
What Is a Database?
By its simplest definition, a database is a collection of data that is arranged so it can easily be
accessed, managed, and updated.The most popular type of database is the relational database.

A relational database has the notion of tables where data is stored in rows and columns, much
like a spreadsheet. Each row in a table contains the complete information about an item that is
stored in the table. Each column, on the other hand, contains information about a specific
property of the records in the table.

Using SQL to Work with Database


To get data in and out of a database, you need to use Structured Query Language (SQL).
This is the de facto language for querying relational databases that almost all relational
database systems understand.

Retrieving and Manipulating Data with SQL


When interacting with databases, you‟ll spend a good deal of time retrieving and manipulating
data. Most of it comes down to four distinct types of operations, grouped under the CRUD
acronym: Create, Read, Update, and Delete.

Selecting Data
To read data from one or more database tables, you use the SELECT statement. In its most
basic form, the SELECT statement looks like this:

SELECT ColumnName [, AnotherColumnName] FROM TableName

Filtering Data

To filter data, you use the WHERE clause, with which you indicate the criteria that you want
your data to match. For example, to retrieve the ID of the Grunge genre you use the following
SQL statement:

SELECT Id FROM Genre WHERE Name = „Grunge‟

Ordering Data
The ORDER BY clause comes at the end of the SQL statement and can contain one or more
column names or expressions, which can optionally include ASC or DESC to determine if items
are sorted in ascending order (with ASC, which is the default if you leave out the keyword) or
in descending order

(using DESC).

For example, to retrieve all genres from the Genre table and sort them alphabetically by their
name in ascending order, you can use this SQL statement:

Page 88 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

SELECT Id, Name FROM Genre ORDER BY Name

Joining Data
A JOIN in your query enables you to express a relationship between one or more tables. For
example, you can use a JOIN to find all the reviews from the Review table that have been
published in a specific genre and then select some columns from the Review table together
with the Name of the genre.

The basic syntax for a JOIN looks like the following bolded code:

SELECT
SomeColumn
FROM
LeftTable
INNER JOIN RightTable ON LeftTable.SomeColumn = RightTable.SomeColumn

Creating Data
To insert new records in a SQL Server table, you use the INSERT statement. It comes in a few
different flavors, but in its simplest form it looks like this:

INSERT INTO TableName (Column1 [, Column2]) VALUES (Value1 [, Value2])

Updating Data
To update data in a table, you use the UPDATE statement:

UPDATE TableName SET Column1 = NewValue1 [, Column2 = NewValue2] WHERE Column3 =


Value3

Deleting Data
Just as with the SELECT and UPDATE statements, you can use the WHERE clause in a DELETE
statement to limit the number of records that get deleted. This WHERE clause is often very
important, because you will otherwise wipe out the entire table instead of just deleting a few
records. When you write a DELETE statement, you don‟t need to specify any column names. All
you need to do is indicate the table that you want to delete records from and an (optional)
WHERE clause to limit the number of records that get deleted. The following example deletes
the record that was inserted and updated in the previous two examples:

DELETE FROM Genre WHERE Id = 13

If you leave out the WHERE clause, all records will be deleted from the table.

working with ADO.NET


1. What is ADO.NET?

ADO.NET is the new database technology of the .NET (Dot Net) platform, and it builds on
Microsoft ActiveX® Data Objects (ADO).

WE-IT TUTORIALS Page 89


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

ADO is a language-neutral object model that is the keystone of Microsoft's Universal Data
Access strategy.

ADO.NET is an integral part of the .NET Compact Framework, providing access to relational
data, XML documents, and application data. ADO.NET supports a variety of development
needs. You can create database-client applications and middle-tier business objects used by
applications, tools, languages or Internet browsers.

ADO.NET defines DataSet and DataTable objects which are optimized for moving
disconnected sets of data across intranets and Internets, including through firewalls. It also
includes the traditional Connection and Command objects, as well as an object called a
DataReader that resembles a forward-only, read-only ADO recordset. If you create a new
application, your application requires some form of data access most of the time.

ADO.NET provides data access services in the Microsoft .NET platform.

You can use ADO.NET to access data by using the new .NET Framework data providers which are:

 Data Provider for SQL Server (System.Data.SqlClient).


 Data Provider for OLEDB (System.Data.OleDb).
 Data Provider for ODBC (System.Data.Odbc).
 Data Provider for Oracle (System.Data.OracleClient).

ADO.NET is a set of classes that expose data access services to the .NET developer. The
ADO.NET classes are found in System.Data.dll and are integrated with the XML classes in
System.Xml.dll.

There are two central components of ADO.NET classes: the DataSet, and the .NET Framework
Data Provider.

Data Provider is a set of components including:

 the Connection object (SqlConnection, OleDbConnection, OdbcConnection,


OracleConnection)
 the Command object (SqlCommand, OleDbCommand, OdbcCommand, OracleCommand)
 the DataReader object (SqlDataReader, OleDbDataReader, OdbcDataReader,
OracleDataReader)
 and the DataAdapter object (SqlDataAdapter, OleDbDataAdapter, OdbcDataAdapter,
OracleDataAdapter).

DataSet object represents a disconnected cache of data which is made up of DataTables and
DataRelations that represent the result of the command.

How the basic ADO.NET components work

Page 90 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Figure presents the primary ADO.NET objects that are used when you develop database
applications. To start, the data used by an application is stored in a dataset that contains one
or more data tables. To load data into a data table, you use a data adapter.

The main function of the data adapter is to manage the flow of data between a dataset and a
database. To do that, it uses commands that define the SQL statements to be issued. The
command for retrieving data, for example, typically defines a Select statement. Then, the
command connects to the database using a connection and passes the Select statement to the
database. After the Select statement is executed, the result set it produces is sent back to the
data adapter, which stores the results in the data table.

To update the data in a database, the data adapter uses a command that defines an Insert,
Update, or Delete statement for a data table. Then, the command uses the connection to
connect to the database and perform the requested operation.

Although it‟s not apparent in this figure, the data in a dataset is independent of the database
that the data was retrieved from. In fact, the connection to the database is typically closed
after the data is retrieved from the database. Then, the connection is opened again when it‟s
needed. Because of that, the application must work with the copy of the data that‟s stored in
the dataset. The architecture that‟s used to implement this type of data processing is referred
to as a disconnected data architecture. Although this is more complicated than a connected
architecture, the advantages offset the complexity.

One of the advantages of using a disconnected data architecture is improved system


performance due to the use of fewer system resources for maintaining connections. Another
advantage is that it works well with ASP.NET web applications, which are inherently
disconnected.

The ADO.NET classes that are responsible for working directly with a database are provided by
the .NET data providers. These data providers include the classes you use to create data
adapters, commands, and connections. The .NET Framework currently includes data providers
for SQL Server, Oracle, OLE DB, and ODBC, although the Oracle data provider has been
deprecated. Other third-party providers are also available.

Description

WE-IT TUTORIALS Page 91


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

 ADO.NET uses two types of objects to access the data in a database: datasets, which
can contain one or more data tables, and NET data provider objects, which include data
adapters, commands, and connections.

 A dataset stores data from the database so it can be accessed by the application. The
.NET data provider objects retrieve data from and update data in the database.

 To retrieve data from a database and store it in a data table, a data adapter object
issues a Select statement that‟s stored in a command object. Next, the command object
uses a connection object to connect to the database and retrieve the data. Then, the
data is passed back to the data adapter, which stores the data in a table within the
dataset.

 To update the data in a database based on the data in a data table, the data adapter
object issues an Insert, Update, or Delete statement that‟s stored in a command object.
Then, the command object uses a connection to connect to the database and update the
data.

 The data provider remains connected to the database only long enough to retrieve or
update the specified data. Then, it disconnects from the database and the application
works with the data via the dataset object. This is referred to as a disconnected data
architecture.

 All of the ADO.NET objects arc implemented by classes in the System.Data namespace
of the .NET Framework. However, the specific classes used to implement the
connection, command, and data adapter objects depend on the .NET data provider you
use.

Concurrency and the disconnected data architecture


 Although the disconnected data architecture has advantages, it also has some
disadvantages. One of those is the conflict that can occur when two or more users
retrieve and then try to update data in the same row of a table. This is called a
concurrency problem. This is possible because once a program retrieves data from a
database, the connection to that database is dropped. As a result, the database
management system can‟t manage the update process.

 When you use ADO.NET, you have two choices for concurrency control. By default, a
program uses optimistic concurrency, which checks whether a row
has been changed since it was retrieved. If it has, the update or deletion will be
refused and a concurrency exception will be thrown. Then, the program should
handle the error. For example, it could display an error message that tells the
user that the row could not be updated and then retrieve the updated row so the
user can make the change again.

 In contrast, the “last in wins” technique works the way its name implies.
Since no checking is done with this technique, the row that‟s updated by the last
user overwrites any changes made to the row by a previous user.

What happens when two users try to update the same row
 When two or more users retrieve the data in the same row of a database table at the
same time, it is called concurrency. BecauseADO.NET uses a disconnected data
architecture, the database management system can‟t prevent this from happening.

Page 92 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

 If two users try to update the same row in a database table at the same time, the
second user‟s changes could overwrite the changes made by the first user. Whether or
not that happens depends on the concurrency control that the programs use.

 By default, ADO.NET uses optimistic concurrency. This means that the program checks
to sec whether the database row that‟s going to be updated or deleted has been
changed since it was retrieved. If it has, a concurrency exception occurs and the update
or deletion is refused. Then, the program should handle the exception.

 If optimistic concurrency isn‟t in effect, the program doesn‟t check to see whether a row
has been changed before an update or deletion takes place. Instead, the operation
proceeds without throwing an exception. This is referred to as “last in wins” because the
last update overwrites any previous update. And this can lead to errors in the database.

How to avoid concurrency errors


 For many applications, concurrency errors rarely occur. As a result, optimistic
concurrency is adequate because the users will rarely have to resubmit an update or
deletion that is refused.

 If concurrency is likely to be a problem, a program that uses a dataset can be designed


so it updates the database and refreshes the dataset frequently. That way, concurrency
errors are less likely to occur.

 Another way to avoid concurrency errors is to design a program so it retrieves and


updates just one row at a time. That way, there‟s less chance that two users will
retrieve and update the same row at the same time.

How to work with data without using a data adapter

As you can see, you still use command and connection objects to access the
database. Instead of using a data adapter to execute the commands, though, you
execute the commands directly. When you do that, you also have to provide
code to handle the result of the command. If you issue a command that contains
an Insert, Update, or Delete statement, for example, the result is an integer that
WE-IT TUTORIALS Page 93
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

indicates the number of rows that were affected by the operation. You can use
that information to determine if the operation was successful.

If you execute a command that contains a Select statement, the result is a


result set that contains the rows you requested. To read through the rows in the
result set, you use a data reader object. Although a data reader provides an
efficient way of reading the rows in a result set, you can‟t use it to modify those
rows. In addition, it only lets you read rows in a forward direction. Once you
read the next row, the previous row is unavailable. Because of that, you typically
use a data reader to retrieve and work with a single database row at a time.

Description
 Instead of using a data adapter to execute commands to retrieve, insert, update, and
delete data from a database, you can execute those commands directly

 To retrieve data from a database, you execute a command object that contains a Select
statement. Then, the command object uses a connection to connect to the database and
retrieve the data. You can then read the results one row at a time using a data reader
object.

 To insert, update, or delete data in a database, you execute a command object that
contains an Insert, Update, or Delete statement. Then, the command object uses a
connection to connect to the database and update the data. You can then check the
value that‟s returned to determine if the operation was successful.

 If you use this technique in an application that maintains the data in a database, you
typically work with a single row at a time. Because of that, the chance of a concurrency
error is reduced.

The SqlConnection class


The most important property of this class is ConnectionString. A connection
string is a string that provides the information that‟s needed to connect to a
database. That means it includes information such as the name of the database and
the database server. It can also contain authentication information such as a user-id
and password.

The two methods of this class that are shown in this figure let you open and
close the connection. In general, you should leave a connection open only while
data is being retrieved or updated. When you use a data adapter, though, the
connection is opened and closed for you so you don‟t need to use these methods.

Common members of the SqlConnection class

Property Description
ConnectionString Contains information that lets you connect to a
SQL Server database,
including the server name, the database name, and
login information.
Method Description
Open Opens a connection to a database.
Close Closes a connection to a database.

Page 94 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

The SqlCommand class


To execute a SQL statement against a SQL Server database, you create a
SqlCommand object that contains the statement. Notice that the Connection
property of this class associates the command with a SqlConnection object, and
the CommandText property contains the SQL statement to be executed.

The CommandType property indicates how the command object should


interpret the value of the CommandText property. Instead of specifying a SQL
statement for the CommandText property, for example, you can specify the name
of a stored procedure, which consists of one or more SQL statements that have
been compiled and stored with the database.

You can execute a command object directly by


using one of the three Execute methods show. If, for example, you
use ExecuteReader for a Select statement, the results are returned as a DataReader
object. If you use ExecuteScalar, only the value in the first column and row of the
query results is returned.

If the command contains an Insert, Update, or Delete statement, you‟ll use the
ExecuteNonQuery method to execute it. This method returns an integer value that
indicates the number of rows that were affected by the command. If, for example,
the command deletes a single row, the ExecuteNonQuery method returns 1.

Common members of the SqlCommand class

Property Description
Connection The SqlConnection object used to connect to the
database.
CommandText The text of the SQL statement or the name of a
stored procedure.
CommandType A constant in the CommandType enumeration that
indicates whether
the CommandText property contains a SQL statement
(Text) or the
name of a stored procedure (StoredProcedure).
Parameters The collection of parameters used by the command.
Method Description
ExecuteReader Executes a query and returns the result as a Sql
DataReader objcct.
ExecuteNonQuery Executes the command and returns an integer
representing the
number of rows affected.
ExecuteScalar Executes a query and returns the first column of
the first row
returned by the query.

The SqlParameter class

WE-IT TUTORIALS Page 95


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

The SqlParameter class lets you pass parameter


values to a SQL command. Parameters arc commonly used to limit the number
of rows retrieved by a Select statement. For example, you can retrieve the
Product row for a specific product by passing the ProductlD as a parameter. Or,
you can retrieve all of the products for a given category by passing the
CategorylD as a parameter. Parameters are also commonly used to pass column
values to Insert, Update, and Delete statements.

Common members of the SqlParameter class

Property Description
ParameterName The name of the parameter.
Value The value assigned to the parameter.
SqlDbType The SQL data type for the parameter.

The SqlDataReader class


This class is used to create a data reader object, which provides an efficient
way to read the rows in a result set returned by a database query. In fact, when
you use a data adapter to retrieve data, the data adapter uses a data reader to
read through the rows in the result set and store them in a dataset.

Description

 A SqlConnection object is required to establish a connection to a SQL Server database.


 A SqlCommand object is used to execute a SQL command against a SQL Server
database.
 A SqlParameter object is used to pass variable information to a SQL command.

Common members of the SqlDataReader class

Indexer Description
[index] Accesses the column with the specified index from the
current row.
[name] Accesses the column with the specified name from the
current row.
Property Description
IsClosed Gets a Boolean value that indicates if the data
reader is closed.
Method Description
Read Reads the next row. Returns True if there are more
rows.
Otherwise, returns False.
Close Closes the data reader.

The SqlDataAdapter class


The job of a data adapter is to provide a link between a
database and a dataset. The four properties of the SqlDataAdapter class listed in
figure for example, identify The four SQL commands that the data
adapter uses to transfer data from the database to the dataset and vice versa. The
SelectCommand property identifies the command object that‟s used to retrieve

Page 96 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

data from the database. And the DeleteCommand, InsertCommand, and


UpdateCommand properties identify the commands that are used to update the
database based on changes made to the data in the dataset.

To execute the command identified by the SelectCommand property and


place the data that‟s retrieved in a dataset, you use the Fill method. Then, the
application can work with the data in the dataset without affecting the data in
the database. If the application makes changes to the data in the dataset, it can
use ihc data adapter‟s Update method to execute the commands identified by the
DeleteCommand, InsertCommand, and UpdateCommand properties and post
the changes back to the database.

Common members of the SqlDataAdapter class

Property Description
SelectCommand A SqlCommand object representing the Select
statement used to query the database.
DeleteCommand A SqlCommand object representing the Delete
statement used to delete a row from the database.
InsertCommand A SqlCommand object representing the Insert
statement used to add a row to the database.
UpdateCommand A SqlCommand object representing the Update
statement used to update a row in the database.
Method Description
Fill Executes the command identified by the
SelectCommand property and loads the result into a
dataset object.
Update Executes the commands identified by the
DeleteCommand, InsertCommand, and UpdateCommand
properties for each row in the dataset that was
deleted, added, or updated.

Description

 A data reader provides read-only, forward-only access to the data in a database.


Because it doesn‟t require the overhead of a dataset, it‟s more efficient than using a
data adapter. However, it can‟t be used to update data.

 When the Fill method of a data adapter is used to retrieve data from a database, the
data adapter uses a data reader to load the results into a dataset.

How to use SQL data sources


Aspx code generated for a basic SqlDataSource control

<asp:SqlDataSource ID="SqlDataSourcel" runat="server"


ConnectionString="<%$ConnectionStrings:HalloweenConnectionString%>"
SelectCommand="SELECT [CategoryID], [LongName] FROM [Categories]
ORDER BY [LongName]">
</asp:SqlDataSource>

Basic SqlDataSource control attributes


WE-IT TUTORIALS Page 97
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Attribute Description
ID The ID for the SqlDataSource control.
Runat Must specify “server.”
ConnectionString The connection string. In most cases, you should
use a <%$
expression to specify the name of a connection
string saved in the web.config file.
ProviderName The name of the provider used to access the
database. Values can be
System.Data.Odbc, System.Data.Oledb,
System.Data.OracleClient, or
System.Data.SqlClient. The default is
System.Data.SqlClient.
SelectCommand The SQL Select statement executed by the data
source to retrieve data.

How to define the connection

 The first step in configuring a SqlDataSource control is to create the connection for the
data source

 click the New Connection button to display the Add Connection dialog box. This dialog
box helps you identify the database that you want to access and provide the information
you need to access it.

 In the Add Connection dialog box, you select the name of the server that
contains the database you want to access, enter the information that‟s required
to log on to the server, and select the name of the database you want to access.

 If you‟re using SQL Server Express on your own PC, you can type localhost\sqlexpress
for the server name.

 For the logon information, you can click on the Use Windows Authentication option.
Then, SQL Server Express will use the login name and password that you use for your
computer as the name and password for the database too. As a result, you won‟t need
to provide a separate user name and password in this dialog box. Last, you select the
name of the database that you want to connect to. When you‟re done, you can click on
the Test Connection button to be sure that the connection works.

 Once you establish a connection to a database, you can use that connection for all of
the applications that use that database.

How to save the connection string in the web.config file

the web.config file has a connectionStrings element that contains an add element for each
connection string. In the example, the connection string is named HalloweenConnectionString,
and the connection string refers to a database named Halloween on the server named
localhost\sqlexpress.

The ConnectionStrings section of the web.config file

<connectionStrings>
<add name="HalloweenConnectionString" connectionString="Data
Source=localhost\sqlexpress; Initial Catalog=Halloween;Integrated Security=True"
providerName="System.Data.SqlClient" />
Page 98 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

</connectionStrings>

Aspx code that refers to a connection string in the web.config file

<asp:SqlDataSource ID="SqlDataSource" runat="server"


ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString %>
SelectCommand="SELECT [CategoryID], [LongName] FROM [Categories]
ORDER BY [LongName]">
</asp:SqlDataSource>

How to configure Select , where , and parameters

Its the next step of configure select clause, where clause and select the parameters. usually it
is done using wizard.

The aspx code for a SqlDataSource control that includes a select parameter

<asp:SqlDataSource ID="SqlDataSource2" runat = "server" ConnectionString="<%$


ConnectionStrings:HalloweenConnectionString %>"

SelectCommand="SELECT [ProductID] , [Name] , [UnitPrice] , [OnHand] FROM


[Products] WHERE ([CategoryID] = @CategoryID) ORDER BY [ProductID]">

<SelectParameters>
<asp:ControlParameter Name="CategoryID" Type=”String" ControlID="ddlCategory"
PropertyName="SelectedValue" />
</SelectParameters>

</asp:SqlDataSource>

Elements used to define select parameters

Element Description
SelectParameters Contains a child element for each parameter
used by the data
source’s Select statement.
Parameter Defines a parameter with a constant value.
ControlParameter Defines a parameter that gels its value from a
control on the page.
QueryStringParameter Defines a parameter that gets its value from a
query string in the
URL used to request the page.
FormParameter Defines a parameter that gets its value from an
HTML form field.
SessionParameter Defines a parameter that gets its value from an
item in session state.
ProfileParameter Defines a parameter that gets its value from a
profile property.
CookieParameter Defines a parameter that gels ils value from a
cookie.

WE-IT TUTORIALS Page 99


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Attributes of the ControlParameter element

Attribute Description
Name The parameter name.
Type The SQL data type of the parameter.
ControlID The ID of the web form control that supplies the
value for the
parameter.
PropertyName The name of the property from the web form control
that supplies
the value for the parameter.

How to create a Select statement with the Query Builder

The Query Builder makes it easy to generate SQL statements without even knowing the proper
syntax for them. Even if you do know the proper syntax, it can be much easier to use the
Query Builder than to enter your own custom statements.

Description

 The Query Builder is displayed if you choose to enter a custom SQL statement, and then
click the Query Builder button in the dialog box that follows.

 The Query Builder lets you build a Select statement by choosing columns from one or
more tables and views and specifying the sort order and filter criteria for each column.

Page 100 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

 When you first start the Query Builder, a dialog box is displayed that lets you select the
database tables you want to include in the query. Each table you select is displayed in
the diagram pane at the top of the Query Builder window.

 If you add two related tables to the diagram pane, the Query Builder automatically joins
the two tables by including a Join phrase in the From clause.

 To include a column from a table, use the check box that appears next to the column in
the diagram pane. This adds the column to the grid pane. Then, you can specify any
sorting or filtering requirements for the column.

 You can use a parameter in an expression in the Filter column to create a parameterized
query. If you use one or more parameters in the query, the Data Source Configuration
Wizard lets you specify the source of each parameter value.

 As you select columns and specify sort and selection criteria, the Query Builder builds
the Select statement and displays it in the SQL pane.

 To display the results of the query in the results pane, click the Execute Query button. If
the query includes parameters, you will be asked to enter the value of each parameter.

How to use the DataList control

A DataList control displays items from a repeating data source such as a data table.

The aspx code for the DataList control

<asp:DataList ID="DataList" runat="server" DataSourceID="SqlDataSource2">


<ItemTemplate>
<asp:Label ID="lblName“ runat="server" Text='<%# Eval("Name") %>'></asp:Label>
<asp:Label ID="lblUnitPrice" runat=“server" Text='<%# Eval("UnitPrice", "{0:C}")
%>'></asp:Label>
</ItemTemplate>
</asp:DataList>

Basic attributes of the DataList control


Attribute Description
ID The ID for the DataList control
Runat Must specify “server.”
DataSourceID The ID of the data source to bind the data list
to.
Description

WE-IT TUTORIALS Page 101


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

 A data list displays a list of items from the data source that it‟s bound to. To bind a data
list to a data source, use the Choose Data Source command in the control‟s smart tag
menu.
 To define the information to be displayed in a data list, you create one or more
templates. Visual Studio provides a designer interface you can use to create the
templates.
 To display the data from a column in the data source in a data list, you add a control to
a template and then bind that control.
 You can use a DataList control for edit operations as well as display operations.
However, you‟re more likely to use the Grid View, Details View, Form View, and List
View controls for edit operations.

How to define the templates for a data list

The only template that‟s required for a data list is the Item template, which defines how each
item in the data source is displayed. Depending on the requirements of your application,
though, you may need to use one or more of the other templates as well.

Common template elements for a data list


Element Description
HeaderTemplate Displayed before the first item in the
data source.
FooterTemplate Displayed after the last item in the
data source.
ItemTemplate Displayed for each item in the data
source.
AlternatingltemTemplate Displayed for alternating items in the
data source.
SeparatorTemplate Displayed between items.

Description

 The templates you define for a data list specify what content to display and what
controls to use to display it. At the least, you must create an Item template that defines
the items from the data source that you want to display.
Page 102 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

 To create a template, choose Edit Templates from the smart tag menu for the control to
display the control in template-editing mode. Then, select the template or group of
templates you want to edit from the smart tag menu.

 To add text to a template, click in the template and begin typing. To add a control to a
template, drag the control from the Toolbox onto the template, then use the Properties
window or the control‟s smart tag menu to set its properties. When you‟re finished,
choose End Template Editing from the smart tag menu.

 To line up the text and controls in two or more templates, place them in tables within
the templates and set the column widths to the same values.

 When you set the data source for a DataList control, Visual Studio creates a default
Item template. This template includes a text box for each column in the data source
preceded by text that identifies the column.

How to bind a list control to a data source

List control attributes for data binding

Attribute Description
DataSourcelD The ID of the data source to bind the list to.
DataTextField The name of the data source field that should
be displayed in the list.
DataValueField The name of the data source field whose value
should be returned by the SelectedValue
property of the list.

<asp:DropDownList ID="ddlCategory" runat="server"


AutoPostBack="True"
DataSourceID="SqlDataSourcel"
DataTextField="LongName"
DataValueField="CategoryID">
</asp:DropDownList>

Description

 You can bind any of the controls that inherit the ListControl class to a data source. That
includes the list box control, the drop-down list control, the check box list control, the
radio button list control, and the bulleted list control.

 You can use the Data Source Configuration Wizard to select the data source for a list
control, the data field to display in the list, and the data value to return for the selected
item.

 You can also use the DataTextFormatString attribute of a list control to specify a format
string you want to apply to the text that‟s displayed in the control.

The syntax of the Eval and Bind methods

WE-IT TUTORIALS Page 103


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

<%# {Eval|Bind}(NameString [, FormatString]) %>

Code examples

<%# Eval("Name") %>


<%# Eval("UnitPrice", "{0:C}") %>
<%# Bind("UnitPrice", "{0:C}") %>

Description

The Eval method provides only for displaying data from a data source in a control. In contrast,
the Bind method provides for two-way binding, which means that it can be used to display as
well update data from a data source.

How to change the data source mode

ADO.NET provides two basic ways to retrieve data from a database. You can either retrieve the
data into a dataset, which retains a copy of the data in memory so it can be accessed
multiple times and updated if necessary. Or, you can retrieve the data using a
data reader, which lets you retrieve the data in forward-only, read-only fashion.

When you create a SQL data source, the data is retrieved into a dataset by
default. If the data will be readjust once and not updated, though, you can
usually improve the application‟s performance by retrieving the data using a
data reader. To do that, just set the value of the DataSourceMode attribute

The DataSourceMode attribute

Attribute Description
DataSourceMode DataSet or DataReader. The default is DataSet, but
you can specify DataReader if the data source is
read-only.

A SqlDataSource control that uses a data reader

<asp:SqlDataSource ID="SqlDataSourcel" runat="server"


ConnectionString="<%$ ConnectionStrings:HalloweenConnectionString
%>" DataSourceMode="DataReader" SelectCommand="SELECT [CategorylD],
[LongName] FROM [Categories]ORDER BY [LongName]"
</asp:SqlDataSource>

Description

 The DataSourceMode attribute lets you specify that data should be retrieved using a
data reader rather than being stored in a dataset. For read-only data, a data reader is
usually more efficient.

Page 104 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

 The data source caching attributes let you specify that data should be stored in cache
storage for a specified period of time. For data that changes infrequently, caching can
improve performance.

GridView control
The GridView control. This control lets you display the data from a data source in the rows and
columns of a table. It includes many advanced features, such as automatic paging and sorting.
It lets you update and delete data with minimal C# code. And its appearance is fully
customizable.

The GridView control displays data provided by a data source in a row and column format. In
fact, the GridView control renders its data as an HTML table with one Tr element for each row
in the data source, and one Td element for each column in the data source.

The aspx code for the GridView control shown above

<asp:GridView ID="GridViewl" runat="server"


AutoGenerateColumns="False"
DataSourceID="SqlDataSource1" DataKeyNames = "CategoryID">
<Columns>
<asp:BoundField DataField="CategoryID" HeaderText="ID"
Readonly="True" SortExpression="CategorylD">
cltemStyle Widths"10Opx" />
</asp:BoundField>
<asp:BoundField DataField="ShortName" HeaderText="Short Name"
SortExpression="ShortName" >
<ItemStyle Width="150px“ />
</asp:BoundField>
<asp:BoundField DataField="LongName" HeaderText="Long Name"
SortExpres sion="LongName">
<ItemStyle Width="200px" />
</asp:BoundField>
<asp:CommandField ButtonType="Button” ShowEditButton="True"
CausesValidation=“False" />
<asp:CommandField ButtonType="Button" ShowDeleteButton="True”
CausesValidation="False" />
</Columns>
</asp:GridView>

Basic attributes of the GridView control

Attribute Description

WE-IT TUTORIALS Page 105


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

ID The ID of the control.


Runat Must specify “server.”
DataSourceID The ID of the data source to bind to.
DataKeyNames The names of the primary key fields separated
by commas.
AutoGenerateColumns Specifics whether the control’s columns should
be
automatically generated.
Selectedlndex Specifies the row to be initially selected.

Description

 The GridView control displays data from a data source in a row and column format. The
data is rendered as an HTML table.

 To create a GridView control, drag the GridView icon from the Data group of the
Toolbox.

 To bind a GridView control to a data source, use the smart tag menu‟s Choose Data
Source command.

Commonly used field properties

Property Description
DataField For a bound field, the name of the
column in the underlying
data source that the field should be
bound to.
DataFormatString A format string used to format the data.
For example, use
{0:c} to format a decimal value as
currency.
ItemStyle.Width The width of the field.
Readonly True if the field is used for display
only.
NullDisplayText The text that’s displayed if the data
field is null.
ConvertEmptyStringToNull If True (the default), empty strings are
treated as nulls when
data is updated in the database. Set
this property to False if
the underlying database field doesn’t
allow nulls.
HeaderText The text that’s displayed in the header
row for the field.
ShowHeader True if the header should be displayed
for this field.

Elements used to create and format fields

The GridView control uses several different types of child elements to create and format its
fields. The first element listed here is the Columns element, which defines the collection of

Page 106 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

columns that are displayed by the control. This element should be placed between the start
and end tags for the GridView control.

Column field elements

Element Description
Columns The columns that are displayed by a GridView
control.
asp:BoundField A field bound to a data source column.
asp:ButtonField A field that displays a button.
asp:CheckBoxField A field that displays a check box.
asp:CommandField A field that contains Select, Edit, Delete,
Update, or Cancel buttons.
asp:HyperLinkField A field that displays a hyperlink.
asp:ImageField A field that displays an image.
asp:TemplateField Lets you create a column with custom content.

Style elements

Element Description
RowStyle The style used for data rows.
AlternatingRowStyle The style used for alternating data rows.
SelectedRowStyle The style used when the row is selected.
EditRowStyle The style used when the row is being edited.
EmptyDataRowStyle The style used when the data source is
empty.
ItemStyle The style used for an individual field.
HeaderSlyle The style used to format the header row.
FooterSlyle The style used to format the footer row.
PagerSlyle The style used to formal the pager row.

How to enable sorting

The GridView control has a built-in ability to let the user sort the rows
based on any or all of the columns displayed by the control. all you have to do to enable
sorting is set the AllowSorting attribute to True and provide a SortExpression attribute for each
column you want to allow sorting for. When sorting is enabled for a column, the user can sort
the data by clicking the column header. The first time it‟s clicked, the data will be sorted in
ascending sequence. The second time it‟s clicked, the data will be sorted in
descending sequence. And so on.

WE-IT TUTORIALS Page 107


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

The aspx code for the control shown above

<asp:GridView ID="GridViewl" runat="server" AllowSorting="True"


AutoGenerateColumns="False" DataKeyNames="ProductID"
DataSourceID="SqlDataSource1">
<Columns>

<asp:BoundField DataField="ProductID" HeaderText="ID"


ReadOnly="True" SortExpression="ProductID">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle Width="75px" />
</asp:BoundField>

<asp:BoundField DataField="Name" HeaderText="Name"


SortExpression="Name">
<HeaderStyle HorizontalAlign="Left" />
<ItemStyle Width="200px" />
</asp:BoundField>

<asp:BoundField DataField="CategoryID" HeaderText="Category"


SortExpression="CategoryID, Name" />

<asp:BoundField DataField="UnitPrice" DataFormatString="{0:c


HeaderText="Unit Price">
<ItemStyle Width="85px" HorizontalAlign="Right" />
<HeaderStyle HorizontalAlign="Right" />
</asp:BoundField>

<asp:BoundField DataField="OnHand" HeaderText=“On Hand">


<ltemStyle Width="85px" HorizontalAlign="Right" />
<HeaderStyle HorizontalAlign="Right" />
</asp:BoundField>

</Columns>

<HeaderStyle BackColor="LightGray" />

</asp:GridView>

How to enable paging

Page 108 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Paging refers to the ability of the GridView control to display bound data
one page at a time, along with paging controls that let the user select which
page of data to display next. The GridView control lets you enable paging simply by setting the
AllowPaging attribute to True.

When you enable paging, an additional row is displayed at the bottom of the
GridView control to display the paging controls.

paging works only for data sources that are in DataSet mode.

Attributes of the GridView control that affect paging

Attribute Description
AllowPaging Set to True to enable paging.
PageSize Specifies the number of rows to display on each
page. The default is 10.

Attributes of the PagerSettings element

Attribute Description
Mode Controls what buttons are displayed in the
pager area. You can specify
NextPrevious, NextPreviousFirstLast. Numeric,
or NumericFirstLast.
FirstPageText The text to display for the first page button.
The default is &lt,&lt;,
which displays as <<.
FirstPageImageUrl The URL of an image file used to display the
first page button.
PreviousPageText The text to display for the previous page
button. The default is &lt;,
which displays as <.
PreviousPageImageUrl The URL of an image file used to display the
previous page button.
NextPageText The text to display for the next page button.
The default is &gt;, which
displays as >.
NextPagcImageUrl The URL of an image file used to display the
next page button.
LastPageText The text to display for the last page button.
The default is &gt;&gt;,
which displays as >>.
LastPagelmageUrl The URL of an image file used to display the
last page button.
PageButtonCount The number of page buttons to display if the
Mode is set to Numeric or NumericFirstLast.
Position The location of the pager area. You can specify
Top, Bottom, or TopAndBottom.
Visible Set to False to hide the pager controls.

WE-IT TUTORIALS Page 109


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

How to update GridView data

Another impressive feature of the GridView control is its ability to update data
in the underlying data source with little additional code. Before you can set that
up, though, you must configure the data source with Update, Delete, and Insert
statements.

Attributes of the CommandField element

Attribute Description
ButtonType Specifies the type of button displayed in the command field. Valid options
are Button, Link, or Image.

Causes Validation Specifies whether validation should be performed if the user clicks the
button.

ValidationGroup Specifies the name of the group to be validated if Causes Validation is


True.

Page 110 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Attributes that show buttons and set the text or images they display

Button Show Text Image


Cancel ShowCancelButton CancelText CancelImage

Delete ShowDeleteButton DeleteText DeleteImage

Edit ShowEditButton EditText EditImage

Select ShowSelectButton SelectText SelectImage

Update n/a UpdateText UpdateImage

How to use the DetailsView and FormView controls


The DetailsView control is designed to display the data for a single item of a data source. To
use this control effectively, you must provide some way for the user to select which data item
to display. The most common way to do that is to use the DetailsView control in combination
with another control such as a GridView control or a drop-down list.

A DetailsView control can be displayed in one of three modes. In Readonly


mode, the data for the current data source row is displayed but can’t be modified. In Edit
mode, the user can modify the data for the current row. And in
Insert mode, the user can enter data that will be inserted into the data source as
a new row.

Three modes of the DetailsView control

Mode Description
Readonly Used to display an item from the data source.
Edit Used to edit an item in the data source
Insert Used to insert a new item into the data source.

DetailsView control attributes

Attribute Description
ID The ID of this control.
Runat Must specify “server”.
DataSourcelD The ID of the data source to bind the DetailsView
WE-IT TUTORIALS Page 111
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

control to.
DataKeyNames A list of field names that form the primary key
for the data source.
AutoGenerateRows If True, a row is automatically generated for
each field in the data source. If False, you must
define the rows in the Fields element.
DefaultMode Sets the initial mode of the DetailsView control.
Valid options are Edit, Insert, or Readonly.
AllowPaging Set to True to allow paging.

DetailsView child elements

Element Description
Fields The fields that are displayed by a DetailsView
control.
RowStyle The style used for data rows in ReadOnly mode.
AlternatingRowStyle The style used for alternate rows.
EditRowStyle The style used for data rows in Edit mode.
InsertRowStyle The style used for data rows in Insert mode.
CommandRowStyle The style used for command rows.
EmptyDalaRowSlyle The style used for data rows when the data
source is empty.
EmptyDataTemplate The template used when the data source is empty.
HeaderStyle The style used for the header row.
HeaderTemplate The template used for the header row.
FooterStyle The style used for the footer row.
FooterTemplate The template used for the footer row.
PagerSetlings The settings used lo control the pager row.
PagerStyle The style used for the pager row.
PagerTemplate The template used for the pager row.

Fields child elements

Element Description
asp:BoundField A field bound to a data source column.
asp:ButtonField A field that displays a button.
asp:CheckBoxField A field that displays a check box.
asp:CommandField A field that contains command buttons.
asp:HyperlinkField A field that displays a hyperlink.
asp:ImageField A field that displays an image.
asp:TemplateField A column with custom content.

How to update DetailsView data

Much like the GridView control, the DetailsView control uses command buttons to let the user
edit and delete data. Thus, the DetailsView control provides Edit, Delete, Update, and Cancel
buttons. In addition, the DetailsView control lets the user insert data, so it provides for two
more buttons. The New button places the DetailsView control into Insert mode, and the Insert
button accepts the data entered by the user and writes it to the data source.

Page 112 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Command buttons

Button Description
Edit Places the DetailsView control in Edit mode.
Delete Deletes the current item and leaves the DetailsView
control in ReadOnly mode.
New Places the DetailsView control in Insert mode.
Update Displayed only in Edit mode. Updates the data source,
then returns to ReadOnly mode.
Insert Displayed only in Insert mode. Inserts the data, then
returns to ReadOnly mode.
Cancel Displayed in Edit or Insert mode. Cancels the operation
and returns to ReadOnly mode.

Attributes that generate command buttons

Attribute Description
AutoGenerateDeleteButton Generates a Delete button.
AutoGenerateEditButton Generates an Edit button.
AutoGeneratelnsertButton Generates a New button.

How to use events raised by the DetailsView control

These events are similar to the events raised by the GridView


control.

Most of these events come in pairs: one that‟s raised before an operation occurs, and another
that‟s raised after the operation completes. For example, the ItemDeleting event is raised
before an item is deleted, and the IlemDeleted event is raised after an item has been deleted.

As with the GridView control, the most common reason to handle the before events for the
DetailsView control is to provide data validation. For example, when the user clicks the Update
button, you can handle the ItemUpdating event to make sure the user has entered correct
data. Then, you can set the e argument‟s Cancel property to True if the user hasn‟t entered
correct data. This cancels the update.

The after action events let you check that database operations have completed successfully. To
do that, you need to check for two types of errors as
illustrated in the example in this figure. First, you should check for database
exceptions by testing the Exception property of the e argument. If it is not null,
WE-IT TUTORIALS Page 113
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

a database exception has occurred. Then, you should display an appropriate


error message to let the user know about the problem.

If the data source uses optimistic concurrency, you should also check to
make sure there hasn‟t been a concurrency error. You can do that by testing the
AffectedRows property of the c argument. If a concurrency error has occurred,
this property will be set to zero meaning that no rows have been changed. Then,
you can display an appropriate error message.

If no errors occurred during the update operation, the ItemUpdated event


shown in this figure ends by calling the DataBind method for the drop-down list
control. This is necessary because view state is enabled for this control. As a
result, this control will continue to display the old data unless you call its
DataBind method to refresh its data. If view state were disabled for this control,
the DataBind call wouldn't be necessary.

Events raised by the DetailsView control

Event Description
ItemCommand Raised when a button is clicked.
ItemCreated Raised when an item is created.
DataBound Raised when data binding completes for an item.
ItemDeleted Raised when an item has been deleted.
ItemDeleting Raised when an item is about to be deleted.
Itemlnserted Raised when an item has been inserted.
Itemlnserting Raised when an item is about to be inserted.
ItemUpdated Raised when an item has been updated.
ItemUpdating Raised when an item is about to be updated.
PagelndexChanged Raised when the index of the displayed item has
changed.
PagelndexChanging Raised when the index of the displayed item is
about to change.

How to use the FormView control

The FormView control is designed to display data for a single item from a data source.

the FormView control is similar to the DetailsView control, it differs in several key ways. Most
importantly, the FormView control isn‟t restricted by the HTML table layout of the DetailsView
control, in which each field is rendered as a table row. Instead, the FormView control uses
templates to render all of the fields as a single row by default. This gives you complete control
over the layout of the fields within the row.

When you create a FormView control and bind it to a data source, the Web Forms Designer will
automatically create default templates for you. Then, you can edit the templates to achieve the
layout you want. To do that, choose Edit Templates from the smart tag menu.

For most applications, you‟ll use just the Item, Editltem, and Insertltem templates.

Page 114 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

How the FormView control differs from the DetailsView control

 The DetailsView control can be easier to work with, but the FormView control provides
more formatting and layout options.

 The DetailsView control can use BoundField elements or TemplateField elements with
templates that use data binding expressions to define bound data fields. The FormView
control can use only templates with data binding expressions to display bound data.

 The DetailsView control renders each field as a table row, but the FormView control
renders all the fields in a template as a single table row.

Description

 A FormView control is similar to a DetailsView control, but its templates give you more
control over how its data is displayed. To accomplish that, all the columns in the data
source can be laid out within a single template.

 After you create a FormView control and assign a data source to it, you can edit the
control‟s templates so the data is displayed the way you want.

How to use the ListView and DataPager controls


The ASP.NET ListView control enables you to bind to data items that are returned from a data
source and display them. You can display data in pages. You can display items individually, or
you can group them.

WE-IT TUTORIALS Page 115


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

The ListView control displays data in a format that you define by using templates and styles. It
is useful for data in any repeating structure, similar to the DataList and Repeater controls.
However, unlike those controls, with the ListView control you can enable users to edit, insert,
and delete data, and to sort and page data, all without code.

Basic attributes of the ListView control


Attribute Description
ID The ID of the control.
Runat Must specify “server.”
DataSourcelD The ID of the data source to bind to.
DataKeyNames The names of the primary key fields separated by
commas.
InsertltemPosition The location within the ListView control where
the Insertltem
template is rendered. You can specify Firstltem,
Lastltem, or None.

Template elements used by the ListView control

Element Description
LayoutTemplate Defines the basic layout of the control.
ItemTemplate The template used for each item in the data
source.
ItemSeparatorTemplate The template used to separate items in the
data source.
AltematingltemTemplate The template used for alternating items in
the data source.
EditltemTemplate The template used when a row is being edited.
InsertltemTemplate The template used for inserting a row.
EmptyDataTemplate The template used when the data source is
empty.
SelectedltemTemplate The template used when a row is selected.
GroupTemplate The template used to define a group layout.
GroupSeparatorTemplate The template used to separate groups of
items.
EmptyltemTemplate The template used for empty items in a group.

Description
Page 116 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

 The ListView control displays data from a data source using templates. It can be used to
edit and delete data as well as insert data.

 The template elements define the formatting that‟s used to display data. These
templates are generated automatically when you configure a ListView control.

 The Layout template defines the overall layout of the control. This template includes an
element that‟s used as a placeholder for the data. Then, the other templates are
substituted for this placeholder as appropriate.

How to provide for paging

To provide paging for a ListView control, you use the DataPager control. The easiest way to
create this control is to select the Enable Paging option from the Configure ListView dialog box.
When you do that, a drop-down list becomes available that lets you choose whether you want
to add a next/previous pager or a numeric pager.

Description

 To provide paging for a ListView control, you use a DataPager control. To add a
DataPager control to a ListView control, you can select the Enable Paging option in the
Configure ListView dialog box and then select Next/Previous Pager or Numeric Pager
from the drop-down list that‟s displayed.

 The DataPager control contains a Fields element that can contain two types of pager
elements. The NextPreviousPagerField element can display first, previous, next, and last
buttons. The NumericPagerField element can display page numbers as well as an ellipsis
button if additional pages are available.

 You can customize the appearance of a DataPager control by adding two or more pager
elements to it.

 You can also create a DataPager control by dragging it from the Toolbox. When you do
that, however, you have to add the Fields element and the pager elements manually.

WE-IT TUTORIALS Page 117


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Attributes of the DataPager control

Attribute Description
ID The ID of the control.
Runat Must specify “server.”
PageSize Specifies the number of items to be displayed on
each page. The default is 10.
PagedControlID The ID of the ListView control that the DataPager
control provides paging for. Used only if the
DataPager control is placed outside the ListView
control.

Attributes of the NextPreviousPagerField element

ATTRIBUTE DESCRIPTION

ButtonType The type of buttons to be used. You can


specify Button, Image, or Link.
ShowFirstPageButton Determines whether the first page button
is displayed. The default is False.
ShowPreviousPageButton Determines whether the previous page
button is displayed. The default is
True.
ShowNextPageButton Determines whether the next page button
is displayed. The default is True.
ShowLastPageButton Determines whether the last page button
is displayed. The default is False.

Attributes of the NumericPagerField element

Attribute Description
ButtonCount The maximum number of buttons to be displayed.
ButtonType The type of buttons to be used. You can specify
Button, Image, or Link.
Page 118 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Description

 You can use the PageSize attribute of the DataPager control to specify the number of
items to display on each page.

 You can place a DataPager control outside of the ListView control. Then, you must set
the PagedControlID attribute of the DataPager control to the ID of the ListView control
you want to use it with.

 The NextPreviousPagerField and NumericPagerField elements also have attributes that


let you change the text or image for the buttons that are displayed.

How to use object data sources


An introduction to object data sources

Most development experts recommend a 3-layer architecture for web applications that
separates the presentation, business rules, and data access components of the application. The
presentation layer includes the web pages that define the user interface. The middle layer
includes the classes that manage the data access for those pages, and it may also include
classes that implement business rules such as data validation requirements or discount
policies. The database layer consists of the database itself.

When you use an ObjectDataSource control, you must create a data access
class to handle the data access for the control. This class provides at least one
method that retrieves data from the database and returns it in a form that the
ObjectDataSource control can handle. It can also provide methods to insert,
update, and delete data. The data access class should be placed in the
application's App_Code folder.

WE-IT TUTORIALS Page 119


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

The three layers

The presentation layer consists of the ASP.NET pages that manage the appearance of
the application. This layer can include bound data controls and ObjectDataSource
objects that bind the data controls to the data.

The middle layer contains the data access classes that manage the data access for the
application. This layer can also contain business objects that represent business entities
such as customers, products, or employees and that implement business rules such as
credit and discount policies.

The database layer consists of the database that contains the data for the application.
Ideally, the SQL statements that do the database access should be saved in stored procedures
within the database, but the SQL statements arc often stored in the data access
classes.

Basic attributes of the ObjectDataSource control

Attribute Description
ID The ID of the control.
Runat Must specify “server.”
TypeName The name of the data access class.
SelectMethod The name of the method that retrieves the
data.
UpdateMethod The name of the method that updates the data.
Page 120 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

DeleteMethod The name of the method that deletes the data.


InsertMethod The name of the method that inserts the data.
DataObjectTypeName The name of a class that provides properties
that are used to pass parameter values.
ConflictDetection Specifies how concurrency conflicts will be
detected. Compare All Values uses optimistic
concurrency checking. Overwrite Values, which
is the default, does no concurrency checking.

Data Source and Data-bound Controls Working Together


The SqlDataSource control enables you to quickly create functional, database-driven web pages.
Without writing a whole lot of code, you can create web pages that enable you to perform all
four operations of the CRUD acronym: create, read, update, and delete data.

Create An Application To Insert Update AND Delete Record

Step 1:

Step 2: empty website

Step 3: right click on website in solution exploreradd new itemweb form

Step 4: right click on website in solution exploreradd asp.net folderapp_data

Step5: right click on app_dataadd new itemsql server databasename


testing.mdf

Step6:

Step7:

Step8:

WE-IT TUTORIALS Page 121


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Step9: add records

Step10:add gridview on asp page and select

Step11:

Step12:

Connection string = “Data


Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\testing.mdf;Integrated
Security=True;User Instance=True”

Step13: save connection string

Page 122 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Step14: select table

Step15:click on advanced button and check the checkbox given below

Step16: nexttest queryfinish

Step17: check checkboxes given in gridview task

Step18: Drag and drop detailview control

WE-IT TUTORIALS Page 123


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Step19: select SqlDataSource1 which was created previously

Step20: check enable inserting

Code generated behind *.aspx


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

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


"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>

<asp:GridView ID="GridView1" runat="server" AllowPaging="True"


AllowSorting="True" AutoGenerateColumns="False" DataKeyNames="Emp_Id"
DataSourceID="SqlDataSource1">
<Columns>
<asp:CommandField ShowDeleteButton="True" ShowEditButton="True"
ShowSelectButton="True" />
<asp:BoundField DataField="Emp_Id" HeaderText="Emp_Id" ReadOnly="True"
SortExpression="Emp_Id" />
<asp:BoundField DataField="Emp_Name" HeaderText="Emp_Name"
SortExpression="Emp_Name" />
<asp:BoundField DataField="Emp_Sname" HeaderText="Emp_Sname"
SortExpression="Emp_Sname" />
<asp:BoundField DataField="Off_Id" HeaderText="Off_Id"
SortExpression="Off_Id" />
<asp:BoundField DataField="Emp_Salary" HeaderText="Emp_Salary"
SortExpression="Emp_Salary" />
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
DeleteCommand="DELETE FROM [Employee] WHERE [Emp_Id] = @Emp_Id"

Page 124 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

InsertCommand="INSERT INTO [Employee] ([Emp_Id], [Emp_Name], [Emp_Sname],


[Off_Id], [Emp_Salary]) VALUES (@Emp_Id, @Emp_Name, @Emp_Sname, @Off_Id, @Emp_Salary)"
SelectCommand="SELECT * FROM [Employee]"
UpdateCommand="UPDATE [Employee] SET [Emp_Name] = @Emp_Name, [Emp_Sname] =
@Emp_Sname, [Off_Id] = @Off_Id, [Emp_Salary] = @Emp_Salary WHERE [Emp_Id] = @Emp_Id">
<DeleteParameters>
<asp:Parameter Name="Emp_Id" Type="Decimal" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Emp_Id" Type="Decimal" />
<asp:Parameter Name="Emp_Name" Type="String" />
<asp:Parameter Name="Emp_Sname" Type="String" />
<asp:Parameter Name="Off_Id" Type="Decimal" />
<asp:Parameter Name="Emp_Salary" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Emp_Name" Type="String" />
<asp:Parameter Name="Emp_Sname" Type="String" />
<asp:Parameter Name="Off_Id" Type="Decimal" />
<asp:Parameter Name="Emp_Salary" Type="String" />
<asp:Parameter Name="Emp_Id" Type="Decimal" />
</UpdateParameters>
</asp:SqlDataSource>
<asp:DetailsView ID="DetailsView1" runat="server" AutoGenerateRows="False"
DataKeyNames="Emp_Id" DataSourceID="SqlDataSource1" Height="50px"
Width="125px">
<Fields>
<asp:BoundField DataField="Emp_Id" HeaderText="Emp_Id" ReadOnly="True"
SortExpression="Emp_Id" />
<asp:BoundField DataField="Emp_Name" HeaderText="Emp_Name"
SortExpression="Emp_Name" />
<asp:BoundField DataField="Emp_Sname" HeaderText="Emp_Sname"
SortExpression="Emp_Sname" />
<asp:BoundField DataField="Off_Id" HeaderText="Off_Id"
SortExpression="Off_Id" />
<asp:BoundField DataField="Emp_Salary" HeaderText="Emp_Salary"
SortExpression="Emp_Salary" />
<asp:CommandField ShowInsertButton="True" />
</Fields>
</asp:DetailsView>
<br />

</div>
</form>
</body>
</html>

The queries generated in code is executed when and appropriate event is called.

WE-IT TUTORIALS Page 125


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Working with connected data architecture

Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Default4 : System.Web.UI.Page


{
SqlConnection con = new SqlConnection(@"Data
Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\test12.mdf;Integrated
Security=True;User Instance=True");
SqlCommand cmd = new SqlCommand();
SqlDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{

}
protected void Button1_Click(object sender, EventArgs e)
{
cmd.CommandText = "select * from tempemp";
cmd.Connection = con;

con.Open();
dr = cmd.ExecuteReader();
//while (dr.Read())
//{
// Response.Write(dr[0].ToString() + " ---- " + dr[1].ToString()+"<br>");
//}
GridView1.DataSource = dr;
this.DataBind();
con.Close();

}
protected void Button2_Click(object sender, EventArgs e)
{

Page 126 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

cmd.CommandText = "insert into tempemp values


("+TextBox1.Text+",'"+TextBox2.Text+"','"+TextBox3.Text+"',"+TextBox4.Text+","+TextBox5.T
ext+")";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();

}
protected void Button3_Click(object sender, EventArgs e)
{
cmd.CommandText = "select * from tempemp where empid = " + TextBox1.Text + "";
cmd.Connection = con;
con.Open();
dr = cmd.ExecuteReader();
dr.Read();
TextBox2.Text = dr[1].ToString();
TextBox3.Text = dr[2].ToString();
TextBox4.Text = dr[3].ToString();
TextBox5.Text = dr[4].ToString();
dr.Close();
con.Close();

}
protected void Button4_Click(object sender, EventArgs e)
{
cmd.CommandText = "update tempemp set empname='" + TextBox2.Text + "',empsname='"
+ TextBox3.Text + "',offid=" + TextBox4.Text + ",empsalary=" + TextBox5.Text + " where
empid=" + TextBox1.Text + "";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
protected void Button5_Click(object sender, EventArgs e)
{
cmd.CommandText = "DELETE FROM TEMPEMP WHERE EMPID = " + TextBox1.Text + "";
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}

ASP.NET Security: Authentication, Authorization, Impersonation,


ASP.NET provider model

An introduction to authentication
If you want to limit access to all or part of your ASP.NET application to certain users, you can use
authentication to verify each user’s identity. Then, once you have authenticated the user, you can
use authorization to check if the user has the appropriate privileges for accessing a page. That way,
you can prevent unauthorized users from accessing pages that they shouldn’t be able to access.

Windows-based authentication

 Causes the browser to display a login dialog box when the user attempts to access a
restricted page.
 Is supported by most browsers.
 Is configured through the IIS management console.
 Uses Windows user accounts and directory rights to grant access to restricted pages.

WE-IT TUTORIALS Page 127


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Forms-based authentication
 lets developers code a login form that gets the user name and password.
 The user name and password entered by the user are encrypted if the login page uses a
secure connection.
 Doesn’t rely on Windows user accounts. Instead, the application determines how to
authenticate users.

Windows Live ID authentication


 Windows Live ID is a centralized authentication service offered by Microsoft.
 Windows Live ID lets users maintain a single user account that lets them access any web
site that participates in Windows Live ID. 1116 advantage is that the user only has to
maintain one user name and password.
 To use Windows Live ID. you must register your web site with Microsoft to obtain an
application ID and then download the Windows Live ID Web Authentication SDK.

Description
 Authentication refers to the process of validating the identity of a user so the user can be
granted access to an application. A user must typically supply a user name and password
to be authenticated.
 After a user is authenticated, the user must still be authorized to use the requested
application. The process of granting user access to an application is called authorization.

Authorization
Authorization is the process that verifies if the authenticated user has access to the requested
resources.
ASP.NET offers the following authorization providers:

 FileAuthorization
 UrlAuthorization

FileAuthorization

The FileAuthorizationModule class performs file authorization and is active when you use
Windows authentication. FileAuthorizationModule is responsible for performing checks on
Windows Access Control Lists (ACLs) to determine whether a user should have access.

UrlAuthorization

UrlAuthorizationModule implements both positive and negative authorization assertions;


that is, you can use the module to selectively allow or deny access to arbitrary parts of the URI
namespace for users, roles (such as manager, testers, and administrators), and verbs (such as
GET and POST)

ASP.NET Impersonation

Another important security feature is the ability to control the identity under which code is
executed. Impersonation is when ASP.NET executes code in the context of an authenticated
and authorized client. By default, ASP.NET does not use impersonation and instead executes all
code using the same user account as the ASP.NET process, which is typically the ASPNET
Page 128 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

account. This is contrary to the default behavior of ASP, which uses impersonation by default.
In Internet Information Services (IIS) 6, the default identity is the NetworkService account.

We can use the impersonation in this two scenarios:

1. To give each web application different permissions.


2. To use existing Windows user permission.

These two scenario are fundamentally different. In the first one, impersonation defines a
single, specific account. In this case, no matter what user access the application, and no
matter what type of user-level security you use, the code will run under the account you've
set. In the second one, the user must be authenticated by IIS. The web-page code will then
execute under the identity of the appropriate user.

Implement Impersonation:

Impersonate the Microsoft IIS Authenticated Account or User:

To impersonate the IIS authenticating user on every request for every page in an ASP.NET
application, we must include an <identity> tag in the Web.config file of this application and set
the impersonate attribute to true.

<identity impersonate="true" />

Impersonate a Specific User:

To impersonate a specific user for all the requests on all pages of an ASP.NET application, you
can specify the userName and password attributes in the <identity> tag of the Web.config file
for that application.

<identity impersonate="true" userName="AccountNAME" password="Password" />

ASP.NET provider model


The provider model is a design pattern formulated by Microsoft for use in the ASP.NET Starter
Kits and formalized in .NET version 2.0. It is used to allow an application to choose from one of
multiple implementations or "condiments" in the application configuration, for example, to
provide access to different data stores to retrieve login information, or to use different storage
methodologies such as a database, binary to disk, XML, etc.

The .NET extensible provider model allows a "component" to have multiple implementations
using an abstract factory pattern approach. Providers are a subclass of the ProviderBase class
and typically instantiated using a factory method.

The provider model in ASP.NET 2.0 provides extensibility points for developers to plug their
own implementation of a feature into the runtime. Both the membership and role features in
ASP.NET 2.0 follow the provider pattern by specifying an interface, or contract. The provider
model begins with the abstract class ProviderBase. ProviderBase exists to enforce the contract
that all providers need public Name and Description properties, as well as a public Initialize
method. Inheriting from ProviderBase are the MembershipProvider and RoleProvider abstract
classes. These classes add additional properties and methods to define the interface for their
specific areas of functionality.

WE-IT TUTORIALS Page 129


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Page 130 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

UNIT 6
LINQ
LINQ enables you to query data from a wide variety of data sources, directly from your
programming code. LINQ is to .NET programming what SQL is to relational databases. With
straightforward, declarative syntax you can query collections for objects that match your criteria.

LINQ is not just an add-on that is part of the .NET Framework. On the contrary, LINQ has been
designed and implemented as a true part of the programming languages in .NET. This means that
LINQ is truly integrated into .NET, giving you a unified way to query data, regardless of where that
data comes from. In addition, because it is integrated into the language and not in a certain project
type, LINQ is available in all kinds of projects including web applications, Windows Forms
applications, Console applications, and so on. To help developers get familiar with LINQ, its syntax
is closely modeled after SQL, the most popular query language for relational databases. This means
that LINQ has keywords such as Select, From, and Where to get data from a data source.

To give you an idea of what a LINQ query looks like, here’s a quick example that shows a list of
Wrox authors whose names contain the letter S:

LINQ has a great power of querying on any source of data, data source could be the collections of
objects, database or XML files. We can easily retrieve data from any object that implements the
IEnumerable<T> interface. Microsoft basically divides LINQ into three areas and that are give
below.

 LINQ to Object {Queries performed against the in-memory data}


o LINQ to ADO.Net
o LINQ to SQL (formerly DLinq) {Queries performed against the relation database
only Microsoft SQL Server Supported}
 LINQ to DataSet {Supports queries by using ADO.NET data sets and data tables}
 LINQ to Entities {Microsoft ORM solution}
 LINQ to XML (formerly XLinq) { Queries performed against the XML source}

LINQ to Object provided main types of Operator Type

Operator Types Operator Name


Aggregation Aggregate
Average
Count
LongCount,
Max,
Min,
Sum
Conversion Cast,
OfType,
ToArray,
ToDictionary,
WE-IT TUTORIALS Page 131
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

ToList,
ToLookup,
ToSequence
Element DefaultIfEmpty,
ElementAt,
ElementAtOrDefault,
First,
FirstOrDefault,
Last,
LastOrDefault,
Single,
SingleOrDefault
Equality EqualAll
Generation Empty,
Range,
Repeat
Grouping GroupBy
Joining GroupJoin,
Join
Ordering OrderBy,
ThenBy,
OrderByDescending,
ThenByDescending,
Reverse
Partitioning Skip,
SkipWhile,
Take,
TakeWhile
Quantifiers All,
Any,
Contains
Restriction Where
Selection Select,
SelectMany
Set Concat,
Distinct,
Except,
Intersect,
Union

Eg

int[] nums = new int[] {0,1,2};


var res = from a in nums
where a < 3
orderby a
select a;
foreach(int i in res)
{
Console.WriteLine(i);
}
Output:
0
1
2
Page 132 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Eg
Linq with datagrid

using System.Linq;

string[] authors = new string[] { “Hanselman, Scott”, “Evjen, Bill”, “Haack, Phil”, “Vieira,
Robert”, “Spaanjaars, Imar” };

var result = from author in authors


where author.Contains(“S”)
orderby author
select author;

gridview1.DataSource = result;
dridview1.DataBind();

Given an array of strings containing author names, you can simply select all the authors whose
names contain the capital letter S and order them in ascending order.

LINQ to Objects
This is the purest form of language integration. With LINQ to Objects, you can query collections in
your .NET applications as you saw in the previous example. You’re not limited to arrays because
LINQ enables you to query almost any kind of collection that exists in the .NET Framework.

LINQ to XML

LINQ to XML is the new .NET way to read and write XML. Instead of typical XML query
languages like XSLT or XPath you can now write LINQ queries that target XML directly in your
application.

LINQ to ADO .NET


ADO.NET is the part of the .NET Framework that enables you to access data and data services like
SQL Server and many other different kinds of data sources. ADO.NET is also used under the hood
by the SqlDataSource control and is commonly used in “raw data access code”; code written in C#
or VB.NET that connects to a database without using the declarative data controls. With LINQ to
ADO.NET you can query database-related information sets, including LINQ to DataSet, LINQ to
SQL, and LINQ to Entities.

LINQ to DataSet enables you to write queries against the DataSet, a class that represents an in
memory version of a database.

LINQ to SQL enables you to write object-oriented queries in your .NET projects that target
Microsoft SQL Server databases. The LINQ to SQL implementation translates your queries into
SQL statements, which are then sent to the database to perform typical CRUD operations.

WE-IT TUTORIALS Page 133


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Introducing the ADO .NET Entity Framework


With the ADO.NET Entity Framework (EF), you take a bunch of database objects like tables and
turn them into .NET objects that you can access in your code. You can then use these objects in
queries or use them directly in data-binding scenarios.

EF also enables you to do the reverse: design an object model first and then let EF create the
necessary database structure for you. Working with EF is pretty easy and quite flexible. Using a
diagram designer, you drag and drop objects like tables from your database into your Entity model.
The objects you drop on the diagram become available as objects.

Query Syntax

LINQ supports a large number of query operators — keywords that enable you to select, order, or
filter data that is to be returned from the query.

examples uses the object model and the ObjectContext object called myEntities

Select
var allReviews = from r in myEntities.Reviews
select r;
 The r variable in this example is referred to as a range variable that is only available within
the current query. You typically introduce the range variable in the From clause, and then
use it again in the Where and Select clauses to filter the data, and to indicate the data you
want to select. Although you can choose any name you like, you often see single letter
variables like the r (for Review) or you see the singular form of the collection you are
querying

From
 Although not considered a standard query operator — because it doesn’t operate on the data
but rather points to the data — the From clause (from in C#) is an important element in a LINQ
query, because it defines the collection or data source that the query must act upon.

Order By
 With Order By (orderby in C#, without the space that VB.NET uses) you can sort the items
in the result collection. Order By is followed by an optional Ascending or Descending
(ascending and descending in C#) keyword to specify sort order. You can specify multiple
criteria by separating them with a comma. The following query returns a list of genres first
sorted by SortOrder in descending order, then sorted on their Name in ascending order (the
default):

var allGenres = from g in myEntities.Genres


orderby g.SortOrder descending, g.Name
select g;

Where
 Just like the WHERE clause in SQL, the Where clause in LINQ (where in C#) enables you
to filter the objects returned by the query.

Page 134 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

var allReviews = from r in myEntities.Reviews


where r.Authorized == true
select r;

Sum, Min, Max, Average, and Count


 These aggregation operators enable you to perform mathematical calculations on the objects
in the result set. For example, to retrieve the number of reviews, you can execute this query:

var numberOfReviews = (from r in myEntities.Reviews


select r).Count();

Introducing Ajax
The server processes that page and sends back the resulting HTML. The browser then parses
that HTML and

renders the page to the user, optionally downloading any external resources like images, script
files, and CSS style sheets. When a user then interacts with the page (for example, by clicking
a button to submit a filled-in contact form) the page is posted back to the server, after which
the entire page is loaded in the browser again.

Though this model has been used for years to serve web pages, it has a few big drawbacks.
First, because the entire page is loaded after a postback, the HTML sent to the browser is much
larger than it needs to be.

The second drawback of a full page reload has to do with the way the browser renders the
page. Because the entire page is replaced, the browser has to dismiss the old one and then
draw the new one. This causes the page to “flicker,” which results in an unattractive user
experience.

Ajax techniques can be deployed to overcome these two problems

The concepts behind Ajax have been around for many years. Browsers since Internet Explorer
5 have shipped with the XMLHttpRequest object that enabled you to make calls to the server
from JavaScript to send and receive data.

WE-IT TUTORIALS Page 135


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

ASP.NET AJAX enables you to:

 Create flicker-free pages that enable you to refresh portions of the page without a full reload
and without affecting other parts of the page
 Provide feedback to your users during these page refreshes
 Update sections of a page and call server-side code on a scheduled basis using a timer
 Access server-side web services and page methods and work with the data they return
 Use the rich, client-side programming framework to access and modify elements in your
page, and get access to a code model and type system that looks similar to that of the .NET
Framework

ASP.NET AJAX consists of two important parts: the ASP.NET AJAX Server Controls and the
client-side ASP.NET AJAX Library.

Description
 A rich Internet application (RIA) is an application that is displayed in a web browser, but
has some of the features of a desktop application such as an enhanced user interface and
quick response time.

 Asynchronous JavaScript and XML (AJAX) is one way to build a RIA. It lets you update
part of a web page without having to reload the entire page. This can also reduce the load
on the web server.

 Each time a standard HTTP request and response cycle is performed, the entire page is
returned from the server and the page is loaded into the browser. This type of request and
response is required the first time a page is requested even if the page is AJAX-enabled.

 With an AJAX HTTP request and response cycle, the browser can request just the
information it needs to update the page. Then, the updated information that’s returned
from the server can be used to update the page without having to reload it.

HOW AJAX WORKS

The technologies that enable AJAX web applications are JavaScript, the Document Object Model
(DOM), Cascading Style Sheets (CSS), the XMLHttpRequest object, a server-side scripting
language, Extensible Markup Language (XML), and JavaScript Object Notation (JSON).
JavaScript, DOM, and CSS, together with HTML, are used to implement Dynamic HTML
{DHTML), which provides for interactive and animated web pages.

JavaScript is a programming language that’s built into the web browser that can read and write the
properties of HTML tags on a web page. The JavaScript language has no built-in mechanisms for
gathering input or displaying output. It only provides mathematical capabilities, structured
programming statements, and a few data types and objects. It has to rely on its host environment to
provide other facilities.

The DOM provides most of JavaScript’s input and output facilities in a web browser. It consists of a
hierarchy of objects that represents the content on the web page. It is built by the web browser from
the HTML and CSS in the web page, and it is made available to the JavaScript environment. The

Page 136 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

browser object model provides the rest of JavaScript’s input and output capabilities, but these
capabilities aren’t typically used in an AJAX-based web application.

JavaScript can read the properties of objects in the DOM to find out what’s on the web page. These
properties include the style of text elements, the contents of form fields, and the state of form
controls. When JavaScript code updates an object in the DOM, the web browser updates the web
page that’s displayed to reflect the changes.

When an event occurs on an object in the DOM, JavaScript code can run to handle the event. These
events include user actions such as when the user clicks the mouse, types on the keyboard, or
changes elements on a form. They can also include events initiated by the web page, such as a timer
expiring.

The XMLHttpRequest object is also provided by the web browser. It has methods that can initiate
an HTTP request to the web server. The scripting language on the web server then processes the
data in the request and generates a response that’s sent back to the browser. When the browser
receives the response, it stores it in the XMLHttpRequest object for JavaScript to use as a
basis for updating the web page by manipulating the DOM.

Although the XMLHttpRequest object was designed to send and receive XML documents, any text-
based format can be used. Because XML documents are hard to create and process in JavaScript,
they’re typically used only to send data to the server. Then, JSON, which provides a plain text
representation of a JavaScript object, is used to send data back to the browser.

The architecture of AJAX

How AJAX updates the contents of a web page

1. An event happens on the web page. This can be the user moving the mouse, clicking a
button, or changing a field. Or, this can be a timer going off. This event triggers
JavaScript code to execute.
2. JavaScript prepares a request and sends it to the web server. The request contains
information about the event and the current state of the controls on the web page.
3. The server receives the data and processes it. Although processing can take place on the
client, some actions, such as database access, must happen on the server.
4. The server prepares a response and sends it back to the browser. The response contains
the updated state of the controls on the web page.
5. JavaScript parses the response and uses the data it contains to update the contents of the
web page by modifying objects in the DOM. The browser then updates the user’s screen.

WE-IT TUTORIALS Page 137


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Description

 The web page that is downloaded from the web server contains HTML, CSS, and JavaScript.
JavaScript is a programming language that’s built into the web browser.

 The web browser uses the HTML and CSS to build the Document Object Model
(DOM),which is an object-oriented representation of the content in the page. This content is
displayed on the screen for the user. Whenever the objects in the DOM arc modified, the
web browser updates the content on the screen to display those changes.

 JavaScript is used to run code when events occur in the web page. JavaScript also has access
to the DOM to determine the state of controls on the page and to make changes to the DOM
that are shown to the user.

 The XMLHttpRequest object that’s built into the web browser is used to communicate with
the web server. JavaScript is used to access the functionality of the XMLHttpRequest object.

 When AJAX was first developed, it used XML to format the data that’s sent between the
web browser and web server. For most requests, JavaScript Object Notation (JSON) is now
used to send data back to the web browser.

The ASP.NET AJAX server controls


Introduction
ASP.NET AJAX enables a process known as an asynchronous postback. This is similar to a
standard postback in that the view state of controls on the page is sent to the server in response to an
event on the page. In an asynchronous postback, however, the XMLHttpRequest object is used to
send the view state to the server. Then, the response that’s returned by the server is used to update
the controls on the page without having to reload the entire web page in the browser.

Figure shows the three components of ASP.NET AJAX and illustrates how they work. The
ASP.NET AJAX client-side framework is a JavaScript library that is loaded by the web browser
when an AJAX-enabled ASP.NET page is displayed. It allows JavaScript code to interact with the
ASP.NET application server through the XMLHttpRequest object it encapsulates.

ASP.NET AJAX also provides five server controls. They are used to AJAX-enable the ASP.NET
web page so that other ASP.NET server controls can be updated in the web browser without having
to reload the page. These controls render JavaScript code as part of the web page just as other
controls render HTML and CSS. The code they render uses the ASP.NET AJAX client-side
framework to process events in the web page, manage and update controls in the web page, and
trigger an asynchronous postback to interact with the server.

The ASP.NET AJAX client-side framework and the ASP.NET AJAX server
controls are built into ASP.NET 4 and Visual Studio 2010.

Page 138 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Components of ASP.NET AJAX

Component Description
ASP.NET AJAX client-side A JavaScript library that’s loaded on the client to support the
framework ASP.NET AJAX server controls.

ASP.NET AJAX server controls Five server controls that encapsulate other ASP.NET controls
on the web page to indicate that they will be controlled on the
client by the ASP.NET AJAX client-side framework.

ASP.NET AJAX Control Toolkit An open source project that provides more than 40 ASP.NET
controls that you can use to build AJAX-enabled web
applications.

Figure describes the five ASP.NET AJAX server controls that you can use to enable and manage
asynchronous postbacks on a web page. These controls allow the other controls on the page to
participate in an asynchronous postback. You’ll find these controls in the AJAX Extensions group
of the Toolbox in Visual Studio.

The ScriptManager control is the primary control that enables asynchronous postbacks, and it must
be on a page for ASP.NET AJAX to work. It is often placed on a Master page so all the pages that
use the Master page are AJAX- enabled. The other AJAX controls can then be placed on either the
Master page or content pages.

In addition to enabling asynchronous postbacks, the ScriptManager control provides for loading and
managing additional JavaScript files. It also provides for registering web services or WCF services
so they can be accessed by JavaScript code on the client. Web services and WCF services both

WE-IT TUTORIALS Page 139


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

provide a way for one web site to communicate with another web site. Because WCF is a
newer technology, it’s the technology Microsoft recommends you use.

Note that you can have only one ScriptManager control on a page. In addition, if you add a
ScriptManager control to a Master page, you can’t also add one to a content page that uses the
master page. However, you can add a ScriptManagerProxy control to the content page. This control
lets you load additional JavaScript files or register additional services needed by the content
page but not by all the pages that use the Master page.

The ScriptManager control


 You can only have one ScriptManagcr control on a page. This includes master and
content pages. If you put a ScriptManagcr control on a master page, you can’t use one on
a content page. If there is more than one ScriptManager control on a page, an Invalid
Operation exception is generated.
 The ScriptManager control can also be used to load and manage additional JavaScript
files and to register web services or WCF services so they can be accessed by JavaScript
code on the client.

The ScriptManagerProxy control


 The ScriptManagerProxy control lets you load JavaScript files and register WCF services
or web services. It can be used in a content page if the master page contains a
ScriptManager control.

The UpdatePanel control


 The UpdatePanel control is a container control that holds other server controls that will
be updated during an asynchronous postback. All controls inside an UpdatePanel control
will be updated at the same time. A page can contain multiple UpdatePanel controls,
each with a different set of controls.

The UpdateProgress control


 The UpdateProgress control provides a visual indication that an asynchronous postback
is in progress. Then, the user will know to wait until the postback completes before
doing anything else on the page.

The Timer control


 When one or more UpdatePanel controls need to be updated automatically, you can use
the Timer control to trigger partial-page updates at a set time interval.

Creating Flicker-Free Pages


To avoid full postbacks in your ASPX pages and update only part of the page, you can use the
UpdatePanel server control. For this control to operate correctly, you also need a
ScriptManager control.

The UpdatePanel Control


The UpdatePanel control is a key component in creating flicker-free pages. In its most basic
application, you simply wrap the control around content you want to update, add a ScriptManager
to the page, and you‟re done. Whenever one of the controls within the UpdatePanel causes a
postback to the server, only the content within that UpdatePanel is refreshed.
Page 140 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Common UpdatePanel Properties


property description
ChildrenAsTriggers This property determines whether controls located within the
UpdatePanel
can cause a refresh of the UpdatePanel. The default value is
True, as you saw in the previous exercise. When you set this
value to False, you have to set the UpdateMode to Conditional.
Note that controls defined within the UpdatePanel still cause a
postback to the server with this property set to
False; they just don‟t update the panel automatically anymore.
Triggers The Triggers collection contains PostBackTrigger and
AsyncPostBackTrigger elements. The first is useful if you want
to force a complete page refresh, whereas the latter is useful if
you want to update an UpdatePanel with a control that is
defined outside the panel.
RenderMode This property can be set to Block or Inline to indicate whether
the UpdatePanel renders itself as a <div> or <span> element.

UpdateMode This property determines whether the control is always


refreshed (the
UpdateMode is set to Always) or only under certain conditions,
for example,
when one of the controls defined in the <Triggers> element is
causing a
postback (the UpdateMode is set to Conditional).
ContentTemplate Although not visible in the Properties Grid for the UpdatePanel,
the
<ContentTemplate> is an important property of the
UpdatePanel. It‟s
the container in which you place controls as children of the
UpdatePanel.
If you forget this required ContentTemplate, VWD gives you a
warning.

The ScriptManager Control

The ScriptManager control serves as the bridge between the client page and the
server. It manages script resources (the JavaScript files used at the client), takes care
of partial-page updates as shown earlier, and handles interaction with your web site
for things like web services and the ASP.NET application services such as membership,
roles, and profile.

place the ScriptManager control directly in a content page if you think you need Ajax capabilities
on only a handful of pages.

place the ScriptManager in a master page so it becomes available throughout the entire site.

Create an ajax enabled page


1. Create .aspx page drag and drop updatePanel and ScriptManager from AJAX Extensions

WE-IT TUTORIALS Page 141


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

2. place a lable in update panel and button outside update panel

3. click on update panel and update trigger property

4. add controlID and EvemtName

Page 142 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Code behind button1


protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToString();
}

Jquery
Introduction to jQuery
The main focus of the jQuery library has always been to simplify the way you access the elements
in your web pages, provide help in working with client-side events, enable visual effects like
animations, and make it easier to use Ajax in your applications. In January 2006, John Resig
announced the first version of jQuery

Adding jQuery Library in webpage


store all my client-side script files in a Scripts folder in the root of my site, so a reference to the
jQuery library (called jquery-1.4.1.min.js) will end up like this:

<script src=”/Scripts/jquery-1.4.1.min.js” type=”text/javascript”></script>

Adding the reference to jQuery in the master page of your site is quite convenient, because all pages
based on this master page automatically get access to the jQuery functionality.

Features of jQuery
Feature Description
Cross-browser compatibility Makes it easy to write codc that is compatible with all modem
web browsers.

Event handling Makes it easy to register functions as event listeners.

DOM selection Makes it easy to select DOM elements.

DOM manipulation Makes it easy to modify DOM elements.

CSS manipulation Makes it easy to modify the CSS for a DOM element.

Effects and animations Makes it easy to apply special effects and animations to DOM
elements such as fading in or out, sliding up or down, and so on.

AJAX Makes it easy to send an AJAX request to the server and use the
data in the AJAX response to update the DOM for a web page.

Extensibility Allows jQuery to work with plug-ins such as the controls in the
jQuery UI library'.

WE-IT TUTORIALS Page 143


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Working with jquery


Launching Code on Document Ready
jQuery has a simple statement that checks the document and waits until it's ready to be manipulated,
known as the ready event:
$(document).ready(function(){
// Your code here
});

Inside the ready event, add a click handler to the link:


$(document).ready(function(){
$("a").click(function(event){
alert("Thanks for visiting!");
});
});

Save your HTML file and reload the test page in your browser. Clicking the link on the page should
make a browser's alert pop-up, before leaving to go to the main jQuery page.

jQuery Selectors

Selector Example Selects

* $("*") All elements

#id $("#lastname") The element with id=lastname

.class $(".intro") All elements with class="intro"

element $("p") All p elements

.class.class $(".intro.demo") All elements with the classes "intro" and "demo"

:first $("p:first") The first p element

:last $("p:last") The last p element

:even $("tr:even") All even tr elements

:odd $("tr:odd") All odd tr elements

:eq(index) $("ul li:eq(3)") The fourth element in a list (index starts at 0)

:gt(no) $("ul li:gt(3)") List elements with an index greater than 3

:lt(no) $("ul li:lt(3)") List elements with an index less than 3

:not(selector) $("input:not(:empty)") All input elements that are not empty

:header $(":header") All header elements h1, h2 ...

:animated $(":animated") All animated elements

Page 144 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

:contains(text) $(":contains('W3Schools')") All elements which contains the text

:empty $(":empty") All elements with no child (elements) nodes

:hidden $("p:hidden") All hidden p elements

:visible $("table:visible") All visible tables

s1,s2,s3 $("th,td,.intro") All elements with matching selectors

[attribute] $("[href]") All elements with a href attribute

[attribute=value] $("[href='default.htm']") All elements with a href attribute value equal to


"default.htm"

[attribute!=value] $("[href!='default.htm']") All elements with a href attribute value not equal to
"default.htm"

[attribute$=value] $("[href$='.jpg']") All elements with a href attribute value ending with ".jpg"

[attribute^=value] $("[href^='jquery_']") All elements with a href attribute value starting with
"jquery_"

:input $(":input") All input elements

:text $(":text") All input elements with type="text"

:password $(":password") All input elements with type="password"

:radio $(":radio") All input elements with type="radio"

:checkbox $(":checkbox") All input elements with type="checkbox"

:submit $(":submit") All input elements with type="submit"

:reset $(":reset") All input elements with type="reset"

:button $(":button") All input elements with type="button"

:image $(":image") All input elements with type="image"

:file $(":file") All input elements with type="file"

:enabled $(":enabled") All enabled input elements

:disabled $(":disabled") All disabled input elements

:selected $(":selected") All selected input elements

:checked $(":checked") All checked input elements

jQuery Event Methods

Event methods trigger, or bind a function to an event for all matching elements.

WE-IT TUTORIALS Page 145


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

Binding example:

$("button").click(function(){$("img").hide()}) - binds a function to the click event.

Method Description

bind() Add one or more event handlers to matching elements

blur() Triggers, or binds a function to the blur event of selected


elements

change() Triggers, or binds a function to the change event of selected


elements

click() Triggers, or binds a function to the click event of selected


elements

dblclick() Triggers, or binds a function to the dblclick event of selected


elements

delegate() Add one or more event handlers to current, or future,


specified child elements of the matching elements

die() Remove all event handlers added with the live() function

error() Triggers, or binds a function to the error event of selected


elements

event.currentTarget The current DOM element within the event bubbling phase

event.data Contains the optional data passed to jQuery.fn.bind when


the current executing handler was bound

event.isDefaultPrevented() Returns whether event.preventDefault() was called for the


event object

event.isImmediatePropagationStopped() Returns whether event.stopImmediatePropagation() was


called for the event object

event.isPropagationStopped() Returns whether event.stopPropagation() was called for the


event object

event.pageX The mouse position relative to the left edge of the


document

event.pageY The mouse position relative to the top edge of the


document

event.preventDefault() Prevents the default action of the event

event.relatedTarget The other DOM element involved in the event, if any

event.result This attribute contains the last value returned by an event


handler that was triggered by this event, unless the value
Page 146 WE-IT TUTORIALS
TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

was undefined

event.stopImmediatePropagation() Prevents other event handlers from being called

event.stopPropagation() Prevents the event from bubbling up the DOM tree,


preventing any parent handlers from being notified of the
event

event.target The DOM element that initiated the event

event.timeStamp This attribute returns the number of milliseconds since


January 1, 1970, when the event is triggered

event.type Describes the nature of the event

event.which Which key or button was pressed for a key or button event

focus() Triggers, or binds a function to the focus event of selected


elements

focusin() Binds a function to the focusin event of selected elements

focusout() Binds a function to the focusout event of selected elements

hover() Binds one or two functions to the hover event of selected


elements

keydown() Triggers, or binds a function to the keydown event of


selected elements

keypress() Triggers, or binds a function to the keypress event of


selected elements

keyup() Triggers, or binds a function to the keyup event of selected


elements

live() Add one or more event handlers to current, or future,


matching elements

load() Triggers, or binds a function to the load event of selected


elements

mousedown() Triggers, or binds a function to the mouse down event of


selected elements

mouseenter() Triggers, or binds a function to the mouse enter event of


selected elements

mouseleave() Triggers, or binds a function to the mouse leave event of


selected elements

mousemove() Triggers, or binds a function to the mouse move event of


selected elements

WE-IT TUTORIALS Page 147


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

mouseout() Triggers, or binds a function to the mouse out event of


selected elements

mouseover() Triggers, or binds a function to the mouse over event of


selected elements

mouseup() Triggers, or binds a function to the mouse up event of


selected elements

one() Add one or more event handlers to matching elements. This


handler can only be triggered once per element

ready() Binds a function to the ready event of a document


(when an HTML document is ready to use)

resize() Triggers, or binds a function to the resize event of selected


elements

scroll() Triggers, or binds a function to the scroll event of selected


elements

select() Triggers, or binds a function to the select event of selected


elements

submit() Triggers, or binds a function to the submit event of selected


elements

toggle() Binds two or more functions to the toggle between for the
click event for selected elements

trigger() Triggers all events bound to the selected elements

triggerHandler() Triggers all functions bound to a specified event for the


selected elements

unbind() Remove an added event handler from selected elements

undelegate() Remove an event handler to selected elements, now or in


the future

unload() Triggers, or binds a function to the unload event of selected


elements

jQuery Effect Methods

"Animate" a div element, by changing its height:

$("#btn1").click(function(){
$("#div1").animate({height:"300px"});
});

Page 148 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

Method Description

animate() Runs a custom animation (of a set of CSS properties) on selected elements

clearQueue() Removes all queued functions on selected elements

delay() Sets a delay for all queued functions on selected elements

dequeue() Runs the next queued functions on selected elements

fadeIn() Fades in selected elements

fadeOut() Fades out selected elements

fadeTo() Fades in/out selected elements to a given opacity

fadeToggle()

hide() Hides selected elements

queue() Shows the queued functions on selected elements

show() Shows selected elements

slideDown() Slide-down (show) selected elements

slideToggle() Toggles slideUp() and slideDown() on selected elements

slideUp() Slide-up (hide) selected elements

stop() Stops a running animation on selected elements

toggle() Toggles between hide() and show(), or custom functions, on selected elements

Modifying the DOM with jQuery

jQuery HTML Methods

eg: this code will assign hello world! Inner html To all <p> tags

$(document).ready(function(){
$("button").click(function(){
$("p").text("Hello world!");
});
});

Method Description

addClass() Adds one or more classes (for CSS) to selected elements

after() Inserts content after selected elements

append() Inserts content at the end of (but still inside) selected elements

WE-IT TUTORIALS Page 149


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C#
WE-IT Tutorials

appendTo() Inserts content at the end of (but still inside) selected elements

attr() Sets or returns an attribute and value of selected elements

before() Inserts content before selected elements

clone() Makes a copy of selected elements

detach() Removes (but keeps a copy of) selected elements

empty() Removes all child elements and content from selected elements

hasClass() Checks if any of the selected elements have a specified class (for CSS)

html() Sets or returns the content of selected elements

insertAfter() Inserts HTML markup or elements after selected elements

insertBefore() Inserts HTML markup or elements before selected elements

prepend() Inserts content at the beginning of (but still inside) selected elements

prependTo() Inserts content at the beginning of (but still inside) selected elements

remove() Removes selected elements

removeAttr() Removes an attribute from selected elements

removeClass() Removes one or more classes (for CSS) from selected elements

replaceAll() Replaces selected elements with new content

replaceWith() Replaces selected elements with new content

text() Sets or returns the text content of selected elements

toggleClass() Toggles between adding/removing one or more classes (for CSS) from selected
elements

unwrap() Removes the parent element of the selected elements

val() Sets or returns the value attribute of the selected elements (form elements)

wrap() Wraps specified HTML element(s) around each selected element

wrapAll() Wraps specified HTML element(s) around all selected elements

wrapInner() Wraps specified HTML element(s) around the content of each selected element

jQuery CSS Methods

Page 150 WE-IT TUTORIALS


TYBSC(IT) ASP.NET USING C#
8097071144/55
TY Bsc(IT) ASP.NET USING C# WE-IT Tutorials

$("button").click(function(){
$("p").css("color","red");
});

methods used to manipulate CSS properties.

Method Description
addClass() Adds one or more classes to selected elements

css() Sets or returns one or more style properties for selected elements

hasClass() Checks if any of the selected elements have a specified class

height() Sets or returns the height of selected elements

offset() Sets or returns the position (relative to the document) for selected elements

offsetParent() Returns the first parent element that is positioned

position() Returns the position (relative to the parent element) of the first selected element

removeClass() Removes one or more classes from selected elements

scrollLeft() Sets or returns the horizontal position of the scrollbar for the selected elements

scrollTop() Sets or returns the vertical position of the scrollbar for the selected elements

toggleClass() Toggles between adding/removing one or more classes from selected elements

width() Sets or returns the width of selected elements

WE-IT TUTORIALS Page 151


TYBSC(IT) ASP.NET USING C#
8097071144/55

Das könnte Ihnen auch gefallen