You are on page 1of 328

www.rejinpaul.

com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Introduction

C# (pronounced "C sharp") is a simple, modern, object-oriented, and type-safe


programming language. It will immediately be familiar to C and C++ programmers. C#
combines the high productivity of Rapid Application Development (RAD) languages and
the raw power of C++.

Visual C# .NET is Microsoft's C# development tool. It includes an interactive


development environment, visual designers for building Windows and Web applications,
a compiler, and a debugger. Visual C# .NET is part of a suite of products, called Visual
Studio .NET, that also includes Visual Basic .NET, Visual C++ .NET, and the JScript
scripting language. All of these languages provide access to the Microsoft .NET
Framework, which includes a common execution engine and a rich class library. The
.NET Framework defines a "Common Language Specification" (CLS), a sort of lingua
franca that ensures seamless interoperability between CLS-compliant languages and
class libraries. For C# developers, this means that even though C# is a new language, it
has complete access to the same rich class libraries that are used by seasoned tools
such as Visual Basic .NET and Visual C++ .NET. C# itself does not include a class
library.

Getting started

The canonical "hello, world" program can be written as follows:

using System;

class Hello

static void Main() {

Console.WriteLine("hello, world");

The source code for a C# program is typically stored in one or more text files with a file
extension of .cs, as in hello.cs. Using the command-line compiler provided with Visual
Studio .NET, such a program can be compiled with the command-line directive

csc hello.cs

which produces an application named hello.exe. The output produced by this


application when it is run is:

CS6001 C# and .Net programming Page 1

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

hello, world

Close examination of this program is illuminating:

 The using System; directive references a namespace called System that is


provided by the Microsoft .NET Framework class library. This namespace
contains the Console class referred to in the Main method. Namespaces provide
a hierarchical means of organizing the elements of one or more programs. A
"using" directive enables unqualified use of the types that are members of the
namespace. The "hello, world" program uses Console.WriteLine as shorthand
for System.Console.WriteLine.
 The Main method is a member of the class Hello. It has the static modifier, and
so it is a method on the class Hello rather than on instances of this class.
 The entry point for an application — the method that is called to begin execution
— is always a static method named Main.
 The "hello, world" output is produced using a class library. The language does
not itself provide a class library. Instead, it uses a class library that is also used
by Visual Basic .NET and Visual C++ .NET.

For C and C++ developers, it is interesting to note a few things that do not appear in the
"hello, world" program.

 The program does not use a global method for Main. Methods and variables are
not supported at the global level; such elements are always contained within type
declarations (e.g., class and struct declarations).
 The program does not use either "::" or "->" operators. The "::" is not an operator
at all, and the "->" operator is used in only a small fraction of programs — those
that employ unsafe code (Section A). The separator "." is used in compound
names such asConsole.WriteLine.
 The program does not contain forward declarations. Forward declarations are
never needed, as declaration order is not significant.
 The program does not use #include to import program text. Dependencies
among programs are handled symbolically rather than textually. This approach
eliminates barriers between applications written using multiple languages. For
example, the Console class need not be written in C#.

C# is a simple, modern, general-purpose, object-oriented programming language


developed by Microsoft within its .NET initiative led by Anders Hejlsberg. This tutorial
will teach you basic C# programming and will also take you through various advanced
concepts related to C# programming language.

sample code

using System;

CS6001 C# and .Net programming Page 2

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

namespace HelloWorldApplication
{
class HelloWorld
{
static void Main(string[] args)
{
/* my first program in C# */
Console.WriteLine("Hello World");
Console.ReadKey();
}
}
}

C# is a modern, general-purpose, object-oriented programming language developed by


Microsoft and approved by European Computer Manufacturers Association (ECMA)
and International Standards Organization (ISO).

C# was developed by Anders Hejlsberg and his team during the development of .Net
Framework.

C# is designed for Common Language Infrastructure (CLI), which consists of the


executable code and runtime environment that allows use of various high-level
languages on different computer platforms and architectures.

The following reasons make C# a widely used professional language:

 It is a modern, general-purpose programming language


 It is object oriented.
 It is component oriented.
 It is easy to learn.
 It is a structured language.
 It produces efficient programs.
 It can be compiled on a variety of computer platforms.
 It is a part of .Net Framework.

Strong Programming Features of C#

Although C# constructs closely follow traditional high-level languages, C and C++ and
being an object-oriented programming language. It has strong resemblance with Java,
it has numerous strong programming features that make it endearing to a number of
programmers worldwide.

Following is the list of few important features of C#:

 Boolean Conditions
 Automatic Garbage Collection

CS6001 C# and .Net programming Page 3

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

 Standard Library
 Assembly Versioning
 Properties and Events
 Delegates and Events Management
 Easy-to-use Generics
 Indexers
 Conditional Compilation
 Simple Multithreading
 LINQ and Lambda Expressions
 Integration with Windows

CS6001 C# and .Net programming Page 4

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Literals and Constants

The constants refer to fixed values that the program may not alter during its execution.
These fixed values are also called literals. Constants can be of any of the basic data
types like an integer constant, a floating constant, a character constant, or a string
literal. There are also enumeration constants as well.

The constants are treated just like regular variables except that their values cannot be
modified after their definition.

Integer Literals

An integer literal can be a decimal, octal, or hexadecimal constant. A prefix specifies


the base or radix: 0x or 0X for hexadecimal, 0 for octal, and no prefix id for decimal.

An integer literal can also have a suffix that is a combination of U and L, for unsigned
and long, respectively. The suffix can be uppercase or lowercase and can be in any
order.

Here are some examples of integer literals:

212 /* Legal */
215u /* Legal */
0xFeeL /* Legal */
078 /* Illegal: 8 is not an octal digit */
032UU /* Illegal: cannot repeat a suffix */

Following are other examples of various types of Integer literals:

85 /* decimal */
0213 /* octal */
0x4b /* hexadecimal */
30 /* int */
30u /* unsigned int */
30l /* long */
30ul /* unsigned long */

Floating-point Literals

A floating-point literal has an integer part, a decimal point, a fractional part, and an
exponent part. You can represent floating point literals either in decimal form or
exponential form.

Here are some examples of floating-point literals:

CS6001 C# and .Net programming Page 5

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

3.14159 /* Legal */
314159E-5L /* Legal */
510E /* Illegal: incomplete exponent */
210f /* Illegal: no decimal or exponent */
.e55 /* Illegal: missing integer or fraction */

While representing in decimal form, you must include the decimal point, the exponent,
or both; and while representing using exponential form you must include the integer
part, the fractional part, or both. The signed exponent is introduced by e or E.

Character Constants

Character literals are enclosed in single quotes. For example, 'x' and can be stored in a
simple variable of char type. A character literal can be a plain character (such as 'x'),
an escape sequence (such as '\t'), or a universal character (such as '\u02C0').

There are certain characters in C# when they are preceded by a backslash. The have
special meaning and they are used to represent like newline (\n) or tab (\t). Here, is a
list of some of such escape sequence codes:

Escape sequence Meaning

\\ \ character

\' ' character

\" " character

\? ? character

\a Alert or bell

\b Backspace

\f Form feed

\n Newline

\r Carriage return

\t Horizontal tab

\v Vertical tab

\ooo Octal number of one to three digits

\xhh . . . Hexadecimal number of one or more digits

CS6001 C# and .Net programming Page 6

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Following is the example to show few escape sequence characters:

using System;
namespace EscapeChar
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello\tWorld\n\n");
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Hello World

String Literals

String literals or constants are enclosed in double quotes "" or with @"". A string
contains characters that are similar to character literals: plain characters, escape
sequences, and universal characters.

You can break a long line into multiple lines using string literals and separating the
parts using whitespaces.

Here are some examples of string literals. All the three forms are identical strings.

"hello, dear"
"hello, \
dear"
"hello, " "d" "ear"
@"hello dear"

Defining Constants

Constants are defined using the const keyword. Syntax for defining a constant is:

const <data_type> <constant_name> = value;

The following program demonstrates defining and using a constant in your program:

using System;
namespace DeclaringConstants
{

CS6001 C# and .Net programming Page 7

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class Program
{
static void Main(string[] args)
{
const double pi = 3.14159;

// constant declaration
double r;
Console.WriteLine("Enter Radius: ");
r = Convert.ToDouble(Console.ReadLine());
double areaCircle = pi * r * r;
Console.WriteLine("Radius: {0}, Area: {1}", r, areaCircle);
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Enter Radius:

Radius: 3, Area: 28.27431

CS6001 C# and .Net programming Page 8

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Variables

A variable is nothing but a name given to a storage area that our programs can
manipulate. Each variable in C# has a specific type, which determines the size and
layout of the variable's memory the range of values that can be stored within that
memory and the set of operations that can be applied to the variable.

The basic value types provided in C# can be categorized as:

Type Example

Integral types sbyte, byte, short, ushort, int, uint, long,


ulong, and char

Floating point types float and double

Decimal types decimal

Boolean types true or false values, as assigned

Nullable types Nullable data types

C# also allows defining other value types of variable such as enum and reference
types of variables such as class, which we will cover in subsequent chapters.

Defining Variables

Syntax for variable definition in C# is:

<data_type> <variable_list>;

Here, data_type must be a valid C# data type including char, int, float, double, or any
user-defined data type, and variable_list may consist of one or more identifier names
separated by commas.

Some valid variable definitions are shown here:

int i, j, k;

char c, ch;

float f, salary;

double d;

You can initialize a variable at the time of definition as:

CS6001 C# and .Net programming Page 9

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

int i = 100;

Initializing Variables

Variables are initialized (assigned a value) with an equal sign followed by a constant
expression. The general form of initialization is:

variable_name = value;

Variables can be initialized in their declaration. The initializer consists of an equal sign
followed by a constant expression as:

<data_type> <variable_name> = value;

Some examples are:

int d = 3, f = 5; /* initializing d and f. */


byte z = 22; /* initializes z. */
double pi = 3.14159; /* declares an approximation of pi. */
char x = 'x'; /* the variable x has the value 'x'. */

It is a good programming practice to initialize variables properly, otherwise sometimes


program may produce unexpected result.

The following example uses various types of variables:

using System;
namespace VariableDefinition
{
class Program
{
static void Main(string[] args)
{
short a;
int b ;
double c;

/* actual initialization */
a = 10;
b = 20;
c = a + b;
Console.WriteLine("a = {0}, b = {1}, c = {2}", a, b, c);
Console.ReadLine();
}

CS6001 C# and .Net programming Page 10

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

}
}

When the above code is compiled and executed, it produces the following result:

a = 10, b = 20, c = 30

Accepting Values from User

The Console class in the System namespace provides a function ReadLine()for


accepting input from the user and store it into a variable.

For example,

int num;
num = Convert.ToInt32(Console.ReadLine());

The function Convert.ToInt32() converts the data entered by the user to int data type,
because Console.ReadLine() accepts the data in string format.

Lvalue and Rvalue Expressions in C#:

There are two kinds of expressions in C#:

 lvalue: An expression that is an lvalue may appear as either the left-hand or


right-hand side of an assignment.
 rvalue: An expression that is an rvalue may appear on the right- but not left-
hand side of an assignment.

Variables are lvalues and hence they may appear on the left-hand side of an
assignment. Numeric literals are rvalues and hence they may not be assigned and can
not appear on the left-hand side. Following is a valid C# statement:

int g = 20;

But following is not a valid statement and would generate compile-time error:

10 = 20;

CS6001 C# and .Net programming Page 11

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Data Types

The varibles in C#, are categorized into the following types:

 Value types
 Reference types
 Pointer types

Value Type

Value type variables can be assigned a value directly. They are derived from the
class System.ValueType.

The value types directly contain data. Some examples are int, char, and float, which
stores numbers, alphabets, and floating point numbers, respectively. When you declare
an int type, the system allocates memory to store the value.

The following table lists the available value types in C# 2010:

Type Represents Range Default


Value

bool Boolean value True or False False

byte 8-bit unsigned integer 0 to 255 0

char 16-bit Unicode U +0000 to U +ffff '\0'


character

decimal 128-bit precise decimal (-7.9 x 1028 to 7.9 x 1028) / 100 to 28 0.0M
values with 28-29
significant digits

double 64-bit double-precision (+/-)5.0 x 10-324 to (+/-)1.7 x 10308 0.0D


floating point type

float 32-bit single-precision -3.4 x 1038 to + 3.4 x 1038 0.0F


floating point type

int 32-bit signed integer -2,147,483,648 to 2,147,483,647 0


type

long 64-bit signed integer -9,223,372,036,854,775,808 to 0L


type 9,223,372,036,854,775,807

sbyte 8-bit signed integer -128 to 127 0


type

CS6001 C# and .Net programming Page 12

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

short 16-bit signed integer -32,768 to 32,767 0


type

uint 32-bit unsigned integer 0 to 4,294,967,295 0


type

ulong 64-bit unsigned integer 0 to 18,446,744,073,709,551,615 0


type

ushort 16-bit unsigned integer 0 to 65,535 0


type

To get the exact size of a type or a variable on a particular platform, you can use
the sizeof method. The expression sizeof(type) yields the storage size of the object or
type in bytes. Following is an example to get the size of int type on any machine:

using System;
namespace DataTypeApplication
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Size of int: {0}", sizeof(int));
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Size of int: 4

Reference Type

The reference types do not contain the actual data stored in a variable, but they
contain a reference to the variables.

In other words, they refer to a memory location. Using multiple variables, the reference
types can refer to a memory location. If the data in the memory location is changed by
one of the variables, the other variable automatically reflects this change in value.
Example of built-in reference types are: object,dynamic, and string.

CS6001 C# and .Net programming Page 13

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Object Type

The Object Type is the ultimate base class for all data types in C# Common Type
System (CTS). Object is an alias for System.Object class. The object types can be
assigned values of any other types, value types, reference types, predefined or user-
defined types. However, before assigning values, it needs type conversion.

When a value type is converted to object type, it is called boxing and on the other
hand, when an object type is converted to a value type, it is calledunboxing.

object obj;

obj = 100; // this is boxing

Dynamic Type

You can store any type of value in the dynamic data type variable. Type checking for
these types of variables takes place at run-time.

Syntax for declaring a dynamic type is:

dynamic <variable_name> = value;

For example,

dynamic d = 20;

Dynamic types are similar to object types except that type checking for object type
variables takes place at compile time, whereas that for the dynamic type variables
takes place at run time.

String Type

The String Type allows you to assign any string values to a variable. The string type is
an alias for the System.String class. It is derived from object type. The value for a
string type can be assigned using string literals in two forms: quoted and @quoted.

For example,

String str = "Tutorials Point";

A @quoted string literal looks as follows:

CS6001 C# and .Net programming Page 14

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

@"Tutorials Point";

The user-defined reference types are: class, interface, or delegate. We will discuss
these types in later chapter.

Pointer Type

Pointer type variables store the memory address of another type. Pointers in C# have
the same capabilities as the pointers in C or C++.

Syntax for declaring a pointer type is:

type* identifier;

For example,

char* cptr;

int* iptr;

CS6001 C# and .Net programming Page 15

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Operators

An operator is a symbol that tells the compiler to perform specific mathematical or


logical manipulations. C# has rich set of built-in operators and provides the following
type of operators:

 Arithmetic Operators
 Relational Operators
 Logical Operators
 Bitwise Operators
 Assignment Operators
 Misc Operators

This tutorial explains the arithmetic, relational, logical, bitwise, assignment, and other
operators one by one.

Arithmetic Operators

Following table shows all the arithmetic operators supported by C#. Assume
variable A holds 10 and variable B holds 20 then:

Show Examples

Operator Description Example

+ Adds two operands A + B = 30

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

* Multiplies both operands A * B =


200

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

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

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

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

Relational Operators

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

Show Examples

CS6001 C# and .Net programming Page 16

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Operator Description Example

== Checks if the values of two operands are equal or not, if yes (A == B) is


then condition becomes true. not true.

!= Checks if the values of two operands are equal or not, if (A != B) is


values are not equal then condition becomes true. true.

> Checks if the value of left operand is greater than the value (A > B) is
of right operand, if yes then condition becomes true. not true.

< Checks if the value of left operand is less than the value of (A < B) is
right operand, if yes then condition becomes true. true.

>= Checks if the value of left operand is greater than or equal to (A >= B) is
the value of right operand, if yes then condition becomes not true.
true.

<= Checks if the value of left operand is less than or equal to the (A <= B) is
value of right operand, if yes then condition becomes true. true.

Logical Operators

Following table shows all the logical operators supported by C#. Assume
variable A holds Boolean value true and variable B holds Boolean value false, then:

Show Examples

Operator Description Example

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

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


non zero then condition becomes true. true.

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

Bitwise Operators

Bitwise operator works on bits and perform bit by bit operation. The truth tables for &, |,
and ^ are as follows:

CS6001 C# and .Net programming Page 17

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

p q p&q p|q p^q

0 0 0 0 0

0 1 0 1 1

1 1 1 1 0

1 0 0 1 1

Assume if A = 60; and B = 13; then in the binary format they are as follows:

A = 0011 1100

B = 0000 1101

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

A&B = 0000 1100

A|B = 0011 1101

A^B = 0011 0001

~A = 1100 0011

The Bitwise operators supported by C# are listed in the following table. Assume
variable A holds 60 and variable B holds 13, then:

Show Examples

Operator Description Example

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

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


operand. which is 0011
1101

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


operand but not both. which is 0011
0001

~ Binary Ones Complement Operator is unary and has the (~A ) = 61,

CS6001 C# and .Net programming Page 18

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

effect of 'flipping' bits. which is 1100


0011 in 2's
complement
due to a
signed binary
number.

<< Binary Left Shift Operator. The left operands value is A << 2 = 240,
moved left by the number of bits specified by the right which is 1111
operand. 0000

>> Binary Right Shift Operator. The left operands value is A >> 2 = 15,
moved right by the number of bits specified by the right which is 0000
operand. 1111

Assignment Operators

There are following assignment operators supported by C#:

Show Examples

Operator Description Example

= Simple assignment operator, Assigns values C = A + B assigns value of A + B


from right side operands to left side operand into C

+= Add AND assignment operator, It adds right C += A is equivalent to C = C + A


operand to the left operand and assign the
result to left operand

-= Subtract AND assignment operator, It C -= A is equivalent to C = C - A


subtracts right operand from the left operand
and assign the result to left operand

*= Multiply AND assignment operator, It C *= A is equivalent to C = C * A


multiplies right operand with the left operand
and assign the result to left operand

/= Divide AND assignment operator, It divides C /= A is equivalent to C = C / A


left operand with the right operand and
assign the result to left operand

%= Modulus AND assignment operator, It takes C %= A is equivalent to C = C %


modulus using two operands and assign the A
result to left operand

CS6001 C# and .Net programming Page 19

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

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

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

&= Bitwise AND assignment operator C &= 2 is same as C = C & 2

^= bitwise exclusive OR and assignment C ^= 2 is same as C = C ^ 2


operator

|= bitwise inclusive OR and assignment C |= 2 is same as C = C | 2


operator

Miscellaneous Operators

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

Show Examples

Operator Description Example

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

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

& Returns the address of an variable. &a; returns actual address


of the variable.

* Pointer to a variable. *a; creates pointer named


'a' to a variable.

?: Conditional Expression If Condition is true ? Then


value X : Otherwise value
Y

is Determines whether an object is of a certain If( Ford is Car) // checks if


type. Ford is an object of the
Car class.

as Cast without raising an exception if the cast Object obj = new


fails. StringReader("Hello");

StringReader r = obj as
StringReader;

CS6001 C# and .Net programming Page 20

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Operator Precedence in C#

Operator precedence determines the grouping of terms in an expression. This affects


evaluation of an expression. Certain operators have higher precedence than others; for
example, the multiplication operator has higher precedence than the addition operator.

For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so the first evaluation takes place for 3*2 and then 7 is added into
it.

Here, operators with the highest precedence appear at the top of the table, those with
the lowest appear at the bottom. Within an expression, higher precedence operators
are evaluated first.

Show Examples

Category Operator Associativity

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

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

Multiplicative */% Left to right

Additive +- Left to right

Shift << >> Left to right

Relational < <= > >= Left to right

Equality == != Left to right

Bitwise AND & Left to right

Bitwise XOR ^ Left to right

Bitwise OR | Left to right

Logical AND && Left to right

Logical OR || Left to right

Conditional ?: Right to left

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

Comma , Left to right

CS6001 C# and .Net programming Page 21

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

The checked and unchecked operators

The checked and unchecked operators are used to control the overflow checking
context for integral-type arithmetic operations and conversions.

checked-expression:

checked ( expression )

unchecked-expression:

unchecked ( expression )

The checked operator evaluates the contained expression in a checked context, and
the unchecked operator evaluates the contained expression in an unchecked context. A
checked-expression or unchecked-expression corresponds exactly to a parenthesized-
expression , except that the contained expression is evaluated in the given overflow
checking context.

The overflow checking context can also be controlled through


the checked and unchecked statements .

The following operations are affected by the overflow checking context established by
the checked and unchecked operators and statements:

 The predefined ++ and -- unary operators and, when the operand is of an integral
type.
 The predefined - unary operator, when the operand is of an integral type.
 The predefined +, -, *, and / binary operators, when both operands are of integral
types.
 Explicit numeric conversions from one integral type to another integral type, or
from float or double to an integral type.

When one of the above operations produce a result that is too large to represent in the
destination type, the context in which the operation is performed controls the resulting
behavior:

 In a checked context, if the operation is a constant expression, a compile-time


error occurs. Otherwise, when the operation is performed at run-time,
a System.OverflowException is thrown.
 In an unchecked context, the result is truncated by discarding any high-order bits
that do not fit in the destination type.

For non-constant expressions (expressions that are evaluated at run-time) that are not
enclosed by any checked or unchecked operators or statements, the default overflow

CS6001 C# and .Net programming Page 22

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

checking context is unchecked unless external factors (such as compiler switches and
execution environment configuration) call for checked evaluation.

For constant expressions (expressions that can be fully evaluated at compile-time), the
default overflow checking context is always checked. Unless a constant expression is
explicitly placed in an unchecked context, overflows that occur during the compile-time
evaluation of the expression always cause compile-time errors.

In the example

class Test

static readonly int x = 1000000;

static readonly int y = 1000000;

static int F() {

return checked(x * y); // Throws OverflowException

static int G() {

return unchecked(x * y); // Returns -727379968

static int H() {

return x * y; // Depends on default

no compile-time errors are reported since neither of the expressions can be evaluated
at compile-time. At run-time, the F method throws aSystem.OverflowException, and
the G method returns –727379968 (the lower 32 bits of the out-of-range result). The
behavior of the Hmethod depends on the default overflow checking context for the
compilation, but it is either the same as F or the same as G.

In the example

CS6001 C# and .Net programming Page 23

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class Test

const int x = 1000000;

const int y = 1000000;

static int F() {

return checked(x * y); // Compile error, overflow

static int G() {

return unchecked(x * y); // Returns -727379968

static int H() {

return x * y; // Compile error, overflow

the overflows that occur when evaluating the constant expressions in F and H cause
compile-time errors to be reported because the expressions are evaluated in
a checked context. An overflow also occurs when evaluating the constant expression
in G, but since the evaluation takes place in an unchecked context, the overflow is not
reported.

The checked and unchecked operators only affect the overflow checking context for
those operations that are textually contained within the "(" and ")" tokens. The operators
have no effect on function members that are invoked as a result of evaluating the
contained expression. In the example

class Test

static int Multiply(int x, int y) {

return x * y;

CS6001 C# and .Net programming Page 24

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

static int F() {

return checked(Multiply(1000000, 1000000));

the use of checked in F does not affect the evaluation of x * y in Multiply, so x * y is


evaluated in the default overflow checking context.

The unchecked operator is convenient when writing constants of the signed integral
types in hexadecimal notation. For example:

class Test

public const int AllBits = unchecked((int)0xFFFFFFFF);

public const int HighBit = unchecked((int)0x80000000);

Both of the hexadecimal constants above are of type uint. Because the constants are
outside the int range, without the unchecked operator, the casts to int would produce
compile-time errors.

The checked and unchecked operators and statements allow programmers to control
certain aspects of some numeric calculations. However, the behavior of some numeric
operators depends on their operands' data types. For example, multiplying two decimals
always results in an exception on overflow even within an
explicitly unchecked construct. Similarly, multiplying two floats never results in an
exception on overflow even within an explicitly checked construct. In addition, other
operators are never affected by the mode of checking, whether default or explicit.

CS6001 C# and .Net programming Page 25

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Expressions (C# Programming Guide)

An expression is a sequence of one or more operands and zero or more operators that
can be evaluated to a single value, object, method, or namespace. Expressions can
consist of a literal value, a method invocation, an operator and its operands, or a simple
name. Simple names can be the name of a variable, type member, method parameter,
namespace or type.

Expressions can use operators that in turn use other expressions as parameters, or
method calls whose parameters are in turn other method calls, so expressions can
range from simple to very complex. Following are two examples of expressions:

((x < 10) && ( x > 5)) || ((x > 20) && (x < 25))

System.Convert.ToInt32("35")

Expression Values

In most of the contexts in which expressions are used, for example in statements or
method parameters, the expression is expected to evaluate to some value. If x and y
are integers, the expression x + y evaluates to a numeric value. The expression new
MyClass() evaluates to a reference to a new instance of a MyClass object. The
expression myClass.ToString() evaluates to a string because that is the return type of
the method. However, although a namespace name is classified as an expression, it
does not evaluate to a value and therefore can never be the final result of any
expression. You cannot pass a namespace name to a method parameter, or use it in a
new expression, or assign it to a variable. You can only use it as a sub-expression in a
larger expression. The same is true for types (as distinct from System.Type objects),
method group names (as distinct from specific methods), and
event add and remove accessors.

Every value has an associated type. For example, if x and y are both variables of
type int, the value of the expression x + y is also typed as int. If the value is assigned to
a variable of a different type, or if x and y are different types, the rules of type
conversion are applied. For more information about how such conversions work,
see Casting and Type Conversions (C# Programming Guide).

Overflows

Numeric expressions may cause overflows if the value is larger than the maximum
value of the value's type. For more information, see Checked and Unchecked (C#
Reference) and Explicit Numeric Conversions Table (C# Reference).

CS6001 C# and .Net programming Page 26

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Branching and Looping in C#

Certainly you are familiar with if, switch, while, return and goto statements. These are
famous Branching and Looping statements in many programming languages for
selecting code paths conditionally, looping and jumping to another part of your
application unconditionally. In this article we will discuss what C# offers to us from these
statements. As you will see, the common programming errors that existed in C++ were
eliminated with C# statements.

The if Statement

The if statement gives you the ability to test an expression, then select a statement or a
group of statements to be executed if the expression evaluates to true. If you have the
else part of the statement, you can execute another statement (or statements) if the
expression evaluates to false. The syntax of if statement is as follows:

if(bool expression)
statement 1;

As we will see shortly, the expression must evaluate to bool value (true or false). If you
have more than one statement, you must put the statements in a block using curly
braces:

if(bool expression)
{
statement 1;
statement 2;
statement 3;
}

The same applies to the else statement, so if you have only one statement to execute
with the else statement, you can write it like this:

if(bool expression)
statement 1;
else
statement 1;

But if you have multiple statements in your else part, you can write it as:

if(bool expression)
{
statement 1;
statement 2;
statement 3;
}

CS6001 C# and .Net programming Page 27

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

else
{
statement 1;
statement 2;
statement 3;
}

For consistency, use the curly braces even if you have only one statement with the if
statement or with the else statement. Most programmers prefer this usage.

{mospagebreak title= No Implicit Conversion}

C# eliminates a common source of programming errors that existed in the world of C


and C++, which is the implicit conversion of numeric values to Boolean values (0 to
false and all the other numeric values to true). In C#, the if statement’s expression must
evaluate to a Boolean value, so the next block of code will not compile in C# but it will
compile in C++:

int x = 10;
if(x)
{
Console.WriteLine(x);
}

In C# you will get a compile time error that states “Can’t implicitly convert type ‘int’ to
‘bool'”. You need to write this block as follows:

int x = 10;
if(x > 5)
{
Console.WriteLine(x);
}

This will compile in C# because now it’s a Boolean expression. Let’s look at
an example. The following example takes an input number from the user, tests to see if
it’s an even or odd number (using the module operator), and prints a line in each case.

using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
Console.WriteLine(“Please type a number”);
int x = Convert.ToInt32(Console.ReadLine());

CS6001 C# and .Net programming Page 28

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

if(x % 2 == 0)
{
Console.WriteLine(“this is an EVEN number”);
}
else
{
Console.WriteLine(“this is an ODD number”);
}
Console.ReadLine();
}
}
}

{mospagebreak title=Nesting}

Of course you can nest if statements as much as you want. Let’s take a look:

using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
Console.WriteLine(“Please type a number”);
int x = Convert.ToInt32(Console.ReadLine());
if(x % 2 == 0)
{
if(x < 1000)
{
Console.WriteLine(“this is an EVEN number”);
}
else
{
Console.WriteLine(“this is a big EVEN number”);
}
}
else
{
if(x < 1000)
{
Console.WriteLine(“this is an ODD number”);
}
else
{

CS6001 C# and .Net programming Page 29

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine(“this is a big ODD number”);


}
}
Console.ReadLine();
}
}
}

You can combine else with if in one statement to execute more than one test on the
expression. As you already know, if tests the expression, and if it evaluates to false, the
else block will be executed. Sometimes this is not what we need, however. We may
need to be very specific with the else part. For example, take a look at the following
code:

int x = 5;
if(x != 0)
{
Console.WriteLine(“x != 0″);
}
else
{
Console.WriteLine(“x = 0″);
}

There is nothing special about this code; but notice that with the if statement we test to
see if the x is not equal to zero, and if so, it will execute the if block, and else it will
execute the else block. Now let’s look at the following code:

using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
int x = 5;
if(x == 0)
{
Console.WriteLine(“x != 0″);
}
else if(x == 4)
{
Console.WriteLine(“x == 4″);
}
else if(x == 5)
{

CS6001 C# and .Net programming Page 30

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine(“x == 5″);
}
else
{
Console.WriteLine(“x = 0″);
}
Console.ReadLine();
}
}
}

if you compile and run the application, you will get the following in the console window:

C# features the combination of else with if to further test the Boolean expression (only
when the if statement evaluates to false), so if the if Boolean expression evaluated to
true, the else if statements will never be tested. I will rewrite the above code as follows:

using System;
namespace MyCompany
{
public class IfStatement
{
static void Main(string[] args)
{
int x = 5;
if(x != 0)
{
Console.WriteLine(“x != 0″);
}
else if(x == 4)
{
Console.WriteLine(“x == 4″);
}
else if(x == 5)
{

CS6001 C# and .Net programming Page 31

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine(“x == 5″);
}
else
{
Console.WriteLine(“x = 0″);
}
Console.ReadLine();
}
}
}

You will get the following result:

This is an unexpected result, because x is assigned 5. It is true that x is assigned 5, but


the code was not perfect; the if statement tested to check if x is not equal to 0, and it’s
not equal to zero, so it escaped the next else if statement, and that’s why we got this
value. With this in mind, never use an expression that is misleading while using else if
statements.

{mospagebreak title=The switch Statement}

The switch statement is similar to multiple else if statements, but it accepts only
expressions that will evaluate to constant values. The if/else structure is appropriate for
small groups of Boolean expressions, but it would be very ugly to write 20 else if
statements to test for some values: else if(x ==5) do something else if(x == 6) do
another thing, and so on. This is the syntax of a switch statement:

switch(expression)
{
case constant-value:
statement 1;
statement 2;
jump statement
case constant-value:

CS6001 C# and .Net programming Page 32

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

statement 1;
statement 2;
jump statement
default:
statement 1;
statement 2;
jump statement
}

There are more than three keywords you can use with the switch statement: first, the
switch keyword which, followed by an expression that returns an integral value of type
sbyte, byte, short, ushort, int, uint, long, ulong, char, string, or an Enumeration value.
The switch expression’s value can be returned from a method call, too.

After the switch expression is evaluated, the value will be compared to each case label,
and when the value is found, control is transferred to the first statement in the this case
statement. Each case statement must be ended with a jump statement (unlike C and
C++), such as break or goto. The case keyword is used to define a constant value
(called case label) that will be compared to the value returns from the switch
expression. The constant value of the case label must have a compatible value with the
switch block. This makes sense, because you can’t define an int case label while the
switch expression returns a string value. We will talk about jump statements later in the
article.

The default keyword declares the default statement, which will be executed if none of
the case labels match the switch expression. There can be only one default statement
for each switch statement, and you can write your switch statement without a default
statement, too. Let’s take a look at an example of a switch statement with our famous
Employee class example:

using System;
namespace MyCompany
{
public enum Jobs
{
Programmer = 1,
NetworkAdmin = 2,
Designer = 3,
COMDeveloper = 4
}

public class Employee


{
public Positions EmpJob;

// class constructor

CS6001 C# and .Net programming Page 33

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

public Employee(Jobs EJ)


{
switch(EJ)
{
case Jobs.Programmer:
Console.WriteLine(“You are a programmer”);
break;
case Jobs.NetworkAdmin:
Console.WriteLine(“You are a network administrator”);
break;
case Jobs.Designer:
Console.WriteLine(“You are a designer”);
break;
default:
Console.WriteLine(“You are an employee”);
break;
}
}
}

public class EmployeeTest


{
static void Main(string[] args)
{
Employee Michael = new Employee(Jobs.Designer);
Console.ReadLine();
}
}
}

This is a very simple example. The Employee class constructor accepts a value of type
Positions, and defines a switch case block to print the Employee job title. One very
important issue to notice is that, with the if/else structure you can write as many else if
statements, each with different conditional expressions, as you want — but you can’t do
that with the switch/case structure. Here the case statements just test for the value of
the switch expression, and if the comparison succeeds, the block get executed. If you
have a statement that will be executed with more than one case label, you can combine
case labels in the following way:

switch(EP)
{
case Positions.Programmer:
case Positions.NetworkAdmin:
case Positions.Designer:
Console.WriteLine(“You are an IT Employee”);

CS6001 C# and .Net programming Page 34

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

break;
default:
Console.WriteLine(“You are an employee”);
break;
}

You simply write a case statement followed by the next, until you write them all; then
write the statement you want to be executed, then a jump statement. In C# you must
use jump statements between case statements, because the designers of C# eliminated
the fall though that has been in C and C++. You can still explicitly state that you need
the functionality of fall though by using the goto jump keyword:

switch(EP)
{
case Positions.Programmer:
goto case Positions.Designer;
case Positions.NetworkAdmin:
goto case Positions.Designer;
case Positions.Designer:
Console.WriteLine(“You are an IT Employee”);
break;
default:
Console.WriteLine(“You are an employee”);
break;
}

This is an explicit fall through that is clear for every programmer and in fact this
technique eliminates the common problems associated with fall through.

{mospagebreak title=Looping Statements}

Executing a statement (or a group of statements) a number of times is called looping,


and there are four statements for looping and iteration in C#, so let’s begin with the for
statement.

The for Statement

This is the famous for loop structure that many of you have been using to write your
own algorithms. The for loop is used when the number of loops is known (unlike the
while loop, as we will see later). The syntax of the for loop is:

for (initialization; conditional expression; stepping)


{
statement 1;
statement 2;
}

CS6001 C# and .Net programming Page 35

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

As you can see, the initialization, the expression that controls the loop, and the stepping
parts are all defined in the top of the statement and in one location. The parts are also
separated by semicolons, and you begin the looped statements, or the statements that
will be executed in the loop, using a block ( { } ). The first part of the for statement is the
initialization part; use this part to initialize the variables that will be used in the algorithm
of the for loop. Note that these variables are allocated on the stack, and this part will be
executed only one time, because it doesn’t make any sense to declare and initialize the
same variable with the same value each time in the loop.

The next part is the conditional expression, which determines whether the loop will be
executed again or not. If the condition (something like i < myArray.Length) evaluated to
false, control passes to the first statement after the for statement block. If the condition
evaluated to true, the body of the for block (the controlled statements) will be executed.

The last part is the stepping part. Usually it will be a counter that will increment the
variable that the conditional expression uses, because at some point we need the
conditional expression to evaluate to false and terminate the execution of the for loop.
Note that the stepping part executes after the controlled statements. That is, first the
initialization part executes (one time only) and the variables allocate space on the stack;
second, the conditional expression is evaluated, and if true, the controlled statements
execute, followed by the stepping part execution, and again the conditional expression
is evaluated and the process iterates.

Note that any of the three parts that make the for statement can be empty; although it’s
not common, it can happen. Take a look:

static void Main(string[] args)


{
int x = 10;
for(; x < 100; x += 10)
{
Console.WriteLine(x);
}
Console.ReadLine();
}

Compile the method into a class and run the application; you will get the following result:

CS6001 C# and .Net programming Page 36

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

As you can see, we omit the initialization part and we just put in the semicolon. Also
note that the counter can increment or decrement, and it’s up to you to define the
algorithm.

The for loop can be used to define very complex algorithms; this happens as a result of
nesting the for loops. Let’s take a very simple example which extends the above loop
example. It will simply write the same numbers, but this time with a little difference.

public class Loops


{
static void Main(string[] args)
{

for(int x = 10; x < 100; x += 10)


{
Console.WriteLine();
Console.WriteLine(x);
for(int y = x – 1, temp = x – 10; y > temp; y–)
{
Console.Write(“{0}, “, y);
}
}
Console.ReadLine();
}
}

Compile the class and run it, and you will get the following result:

CS6001 C# and .Net programming Page 37

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

I have used a nest for loop to print all the numbers between two iterations from the outer
for loop. The ability to use for loops actually makes great programmers

CS6001 C# and .Net programming Page 38

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Methods

A method is a group of statements that together perform a task. Every C# program


has at least one class with a method named Main.

To use a method, you need to:

 Define the method


 Call the method

Defining Methods in C#

When you define a method, you basically declare the elements of its structure. The
syntax for defining a method in C# is as follows:

<Access Specifier> <Return Type> <Method Name>(Parameter List)

Method Body

Following are the various elements of a method:

 Access Specifier: This determines the visibility of a variable or a method from


another class.
 Return type: A method may return a value. The return type is the data type of
the value the method returns. If the method is not returning any values, then the
return type is void.
 Method name: Method name is a unique identifier and it is case sensitive. It
cannot be same as any other identifier declared in the class.
 Parameter list: Enclosed between parentheses, the parameters are used to
pass and receive data from a method. The parameter list refers to the type,
order, and number of the parameters of a method. Parameters are optional; that
is, a method may contain no parameters.
 Method body: This contains the set of instructions needed to complete the
required activity.

Example

Following code snippet shows a function FindMax that takes two integer values and
returns the larger of the two. It has public access specifier, so it can be accessed from
outside the class using an instance of the class.

CS6001 C# and .Net programming Page 39

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;

return result;
}
...
}

Calling Methods in C#

You can call a method using the name of the method. The following example illustrates
this:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

if (num1 > num2)


result = num1;
else
result = num2;
return result;
}
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;
NumberManipulator n = new NumberManipulator();

CS6001 C# and .Net programming Page 40

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

//calling the FindMax method


ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Max value is : 200

You can also call public method from other classes by using the instance of the class.
For example, the method FindMax belongs to the NumberManipulatorclass, you can
call it from another class Test.

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int FindMax(int num1, int num2)
{
/* local variable declaration */
int result;

if(num1 > num2)


result = num1;
else
result = num2;

return result;
}
}

class Test
{
static void Main(string[] args)
{
/* local variable definition */
int a = 100;
int b = 200;
int ret;

CS6001 C# and .Net programming Page 41

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

NumberManipulator n = new NumberManipulator();

//calling the FindMax method


ret = n.FindMax(a, b);
Console.WriteLine("Max value is : {0}", ret );
Console.ReadLine();
}
}

When the above code is compiled and executed, it produces the following result:

Max value is : 200

Recursive Method Call

A method can call itself. This is known as recursion. Following is an example that
calculates factorial for a given number using a recursive function:

using System;
namespace CalculatorApplication
{
class NumberManipulator
{
public int factorial(int num)
{
/* local variable declaration */
int result;
if (num == 1)
{
return 1;
}
else
{
result = factorial(num - 1) * num;
return result;
}
}

static void Main(string[] args)


{
NumberManipulator n = new NumberManipulator();
//calling the factorial method
CS6001 C# and .Net programming Page 42

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine("Factorial of 6 is : {0}", n.factorial(6));


Console.WriteLine("Factorial of 7 is : {0}", n.factorial(7));
Console.WriteLine("Factorial of 8 is : {0}", n.factorial(8));
Console.ReadLine();
}
}
}

When the above code is compiled and executed, it produces the following result:

Factorial of 6 is: 720

Factorial of 7 is: 5040

Factorial of 8 is: 40320

Passing Parameters to a Method

When method with parameters is called, you need to pass the parameters to the
method. There are three ways that parameters can be passed to a method:

Mechanism Description

Value parameters This method copies the actual value of an argument into the
formal parameter of the function. In this case, changes
made to the parameter inside the function have no effect on
the argument.

Reference This method copies the reference to the memory location of


parameters an argument into the formal parameter. This means that
changes made to the parameter affect the argument.

Output parameters This method helps in returning more than one value.

CS6001 C# and .Net programming Page 43

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Casting and Type Conversions

Because C# is statically-typed at compile time, after a variable is declared, it cannot be


declared again or used to store values of another type unless that type is convertible to
the variable's type. For example, there is no conversion from an integer to any arbitrary
string. Therefore, after you declare i as an integer, you cannot assign the string "Hello"
to it, as is shown in the following code.

C#

int i;

i = "Hello"; // Error: "Cannot implicitly convert type 'string' to 'int'"

However, you might sometimes need to copy a value into a variable or method
parameter of another type. For example, you might have an integer variable that you
need to pass to a method whose parameter is typed as double. Or you might need to
assign a class variable to a variable of an interface type. These kinds of operations are
called type conversions. In C#, you can perform the following kinds of conversions:

 Implicit conversions: No special syntax is required because the conversion is


type safe and no data will be lost. Examples include conversions from smaller to
larger integral types, and conversions from derived classes to base classes.
 Explicit conversions (casts): Explicit conversions require a cast operator.
Casting is required when information might be lost in the conversion, or when the
conversion might not succeed for other reasons. Typical examples include
numeric conversion to a type that has less precision or a smaller range, and
conversion of a base-class instance to a derived class.
 User-defined conversions: User-defined conversions are performed by special
methods that you can define to enable explicit and implicit conversions between
custom types that do not have a base class–derived class relationship. For more
information, see Conversion Operators (C# Programming Guide).
 Conversions with helper classes: To convert between non-compatible types,
such as integers and System.DateTime objects, or hexadecimal strings and byte
arrays, you can use the System.BitConverter class, the System.Convert class,
and the Parse methods of the built-in numeric types, such as Int32.Parse. For
more information, see How to: Convert a byte Array to an int (C# Programming
Guide), How to: Convert a String to a Number (C# Programming Guide),
and How to: Convert Between Hexadecimal Strings and Numeric Types (C#
Programming Guide).

Implicit Conversions

For built-in numeric types, an implicit conversion can be made when the value to be
stored can fit into the variable without being truncated or rounded off. For example, a
variable of type long (8 byte integer) can store any value that an int (4 bytes on a 32-bit

CS6001 C# and .Net programming Page 44

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

computer) can store. In the following example, the compiler implicitly converts the value
on the right to a type long before assigning it to bigNum.

C#

// Implicit conversion. num long can

// hold any value an int can hold, and more!

int num = 2147483647;

long bigNum = num;

For a complete list of all implicit numeric conversions, see Implicit Numeric Conversions
Table (C# Reference).

For reference types, an implicit conversion always exists from a class to any one of its
direct or indirect base classes or interfaces. No special syntax is necessary because a
derived class always contains all the members of a base class.

Derived d = new Derived();

Base b = d; // Always OK.

Explicit Conversions

However, if a conversion cannot be made without a risk of losing information, the


compiler requires that you perform an explicit conversion, which is called a cast. A cast
is a way of explicitly informing the compiler that you intend to make the conversion and
that you are aware that data loss might occur. To perform a cast, specify the type that
you are casting to in parentheses in front of the value or variable to be converted. The
following program casts a double to an int. The program will not compile without the
cast.

class Test
{
static void Main()
{
double x = 1234.7;
int a;
// Cast double to int.
a = (int)x;
System.Console.WriteLine(a);
}
}

CS6001 C# and .Net programming Page 45

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// Output: 1234

For a list of the explicit numeric conversions that are allowed, see Explicit Numeric
Conversions Table (C# Reference).

For reference types, an explicit cast is required if you need to convert from a base type
to a derived type:

C#

// Create a new derived type.

Giraffe g = new Giraffe();

// Implicit conversion to base type is safe.

Animal a = g;

// Explicit conversion is required to cast back

// to derived type. Note: This will compile but will

// throw an exception at run time if the right-side

// object is not in fact a Giraffe.

Giraffe g2 = (Giraffe) a;

A cast operation between reference types does not change the run-time type of the
underlying object; it only changes the type of the value that is being used as a reference
to that object. For more information, see Polymorphism (C# Programming Guide).

Type Conversion Exceptions at Run Time

In some reference type conversions, the compiler cannot determine whether a cast will
be valid. It is possible for a cast operation that compiles correctly to fail at run time. As
shown in the following example, a type cast that fails at run time will cause
an InvalidCastException to be thrown.

using System;

class Animal

CS6001 C# and .Net programming Page 46

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

{
public void Eat() { Console.WriteLine("Eating."); }
public override string ToString()
{
return "I am an animal.";
}
}
class Reptile : Animal { }
class Mammal : Animal { }

class UnSafeCast
{
static void Main()
{
Test(new Mammal());

// Keep the console window open in debug mode.


System.Console.WriteLine("Press any key to exit.");
System.Console.ReadKey();
}

static void Test(Animal a)


{
// Cause InvalidCastException at run time
// because Mammal is not convertible to Reptile.
Reptile r = (Reptile)a;
}

CS6001 C# and .Net programming Page 47

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Arrays

An array stores a fixed-size sequential collection of elements of the same type. An


array is used to store a collection of data, but it is often more useful to think of an array
as a collection of variables of the same type stored at contiguous memory locations.

Instead of declaring individual variables, such as number0, number1, ..., and


number99, you declare one array variable such as numbers and use numbers[0],
numbers[1], and ..., numbers[99] to represent individual variables. A specific element in
an array is accessed by an index.

All arrays consist of contiguous memory locations. The lowest address corresponds to
the first element and the highest address to the last element.

Declaring Arrays

To declare an array in C#, you can use the following syntax:

datatype[] arrayName;

where,

 datatype is used to specify the type of elements in the array.


 [ ] specifies the rank of the array. The rank specifies the size of the array.
 arrayName specifies the name of the array.

For example,

double[] balance;

Initializing an Array

Declaring an array does not initialize the array in the memory. When the array variable
is initialized, you can assign values to the array.

CS6001 C# and .Net programming Page 48

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Array is a reference type, so you need to use the new keyword to create an instance of
the array. For example,

double[] balance = new double[10];

Assigning Values to an Array

You can assign values to individual array elements, by using the index number, like:

double[] balance = new double[10];

balance[0] = 4500.0;

You can assign values to the array at the time of declaration, as shown:

double[] balance = { 2340.0, 4523.69, 3421.0};

You can also create and initialize an array, as shown:

int [] marks = new int[5] { 99, 98, 92, 97, 95};

You may also omit the size of the array, as shown:

int [] marks = new int[] { 99, 98, 92, 97, 95};

You can copy an array variable into another target array variable. In such case, both
the target and source point to the same memory location:

int [] marks = new int[] { 99, 98, 92, 97, 95};

int[] score = marks;

CS6001 C# and .Net programming Page 49

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

When you create an array, C# compiler implicitly initializes each array element to a
default value depending on the array type. For example, for an int array all elements
are initialized to 0.

Accessing Array Elements

An element is accessed by indexing the array name. This is done by placing the index
of the element within square brackets after the name of the array. For example,

double salary = balance[9];

The following example, demonstrates the above-mentioned concepts declaration,


assignment, and accessing arrays:

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */
int i,j;

/* initialize elements of array n */


for ( i = 0; i < 10; i++ )
{
n[ i ] = i + 100;
}

/* output each array element's value */


for (j = 0; j < 10; j++ )
{
Console.WriteLine("Element[{0}] = {1}", j, n[j]);
}
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

CS6001 C# and .Net programming Page 50

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

UsingtheforeachLoop

In the previous example, we used a for loop for accessing each array element. You can
also use a foreach statement to iterate through an array.

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int [] n = new int[10]; /* n is an array of 10 integers */

/* initialize elements of array n */


for ( int i = 0; i < 10; i++ )
{
n[i] = i + 100;
}

/* output each array element's value */


foreach (int j in n )
{
int i = j-100;
Console.WriteLine("Element[{0}] = {1}", i, j);
i++;
}
Console.ReadKey();
}
}
}

CS6001 C# and .Net programming Page 51

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

When the above code is compiled and executed, it produces the following result:

Element[0] = 100
Element[1] = 101
Element[2] = 102
Element[3] = 103
Element[4] = 104
Element[5] = 105
Element[6] = 106
Element[7] = 107
Element[8] = 108
Element[9] = 109

C#Arrays

There are following few important concepts related to array which should be clear to a
C# programmer:

Concept Description

Multi-dimensional arrays C# supports multidimensional arrays. The


simplest form of the multidimensional array is
the two-dimensional array.

Jagged arrays C# supports multidimensional arrays, which are


arrays of arrays.

Passing arrays to functions You can pass to the function a pointer to an


array by specifying the array's name without an
index.

Param arrays This is used for passing unknown number of

CS6001 C# and .Net programming Page 52

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

parameters to a function.

The Array Class Defined in System namespace, it is the base


class to all arrays, and provides various
properties and methods for working with arrays.

CS6001 C# and .Net programming Page 53

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Array Class

The Array class is the base class for all the arrays in C#. It is defined in the System
namespace. The Array class provides various properties and methods to work with
arrays.

Properties of the Array Class

The following table describes some of the most commonly used properties of the Array
class:

Sr.No Property

1 IsFixedSize
Gets a value indicating whether the Array has a fixed size.

2 IsReadOnly
Gets a value indicating whether the Array is read-only.

3 Length
Gets a 32-bit integer that represents the total number of elements in all the
dimensions of the Array.

4 LongLength
Gets a 64-bit integer that represents the total number of elements in all the
dimensions of the Array.

5 Rank
Gets the rank (number of dimensions) of the Array.

Methodsof theArrayClass

The following table describes some of the most commonly used methods of the Array
class:

Sr.No Methods

CS6001 C# and .Net programming Page 54

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

1 Clear
Sets a range of elements in the Array to zero, to false, or to null, depending
on the element type.

2 Copy(Array, Array, Int32)


Copies a range of elements from an Array starting at the first element and
pastes them into another Array starting at the first element. The length is
specified as a 32-bit integer.

3 CopyTo(Array, Int32)
Copies all the elements of the current one-dimensional Array to the specified
one-dimensional Array starting at the specified destination Array index. The
index is specified as a 32-bit integer.

4 GetLength
Gets a 32-bit integer that represents the number of elements in the specified
dimension of the Array.

5 GetLongLength
Gets a 64-bit integer that represents the number of elements in the specified
dimension of the Array.

6 GetLowerBound
Gets the lower bound of the specified dimension in the Array.

7 GetType
Gets the Type of the current instance. (Inherited from Object.)

8 GetUpperBound
Gets the upper bound of the specified dimension in the Array.

9 GetValue(Int32)
Gets the value at the specified position in the one-dimensional Array. The
index is specified as a 32-bit integer.

10 IndexOf(Array, Object)
Searches for the specified object and returns the index of the first

CS6001 C# and .Net programming Page 55

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

occurrence within the entire one-dimensional Array.

11 Reverse(Array)
Reverses the sequence of the elements in the entire one-dimensional Array.

12 SetValue(Object, Int32)
Sets a value to the element at the specified position in the one-dimensional
Array. The index is specified as a 32-bit integer.

13 Sort(Array)
Sorts the elements in an entire one-dimensional Array using the
IComparable implementation of each element of the Array.

14 ToStringk
Returns a string that represents the current object. (Inherited from Object.)

For complete list of Array class properties and methods, please consult Microsoft
documentation on C#.

Example

The following program demonstrates use of some of the methods of the Array class:

using System;
namespace ArrayApplication
{
class MyArray
{
static void Main(string[] args)
{
int[] list = { 34, 72, 13, 44, 25, 30, 10 };
int[] temp = list;
Console.Write("Original Array: ");

foreach (int i in list)


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

CS6001 C# and .Net programming Page 56

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// reverse the array


Array.Reverse(temp);
Console.Write("Reversed Array: ");

foreach (int i in temp)


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

//sort the array


Array.Sort(list);
Console.Write("Sorted Array: ");

foreach (int i in list)


{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

Original Array: 34 72 13 44 25 30 10
Reversed Array: 10 30 25 44 13 72 34
Sorted Array: 10 13 25 30 34 44 72

CS6001 C# and .Net programming Page 57

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - ArrayList Class

It represents an ordered collection of an object that can be indexed individually. It is


basically an alternative to an array. However, unlike array you can add and remove
items from a list at a specified position using an index and the array resizes itself
automatically. It also allows dynamic memory allocation, adding, searching and sorting
items in the list.

Methods and Properties of ArrayList Class

The following table lists some of the commonly used properties of theArrayList class:

Property Description

Capacity Gets or sets the number of elements that the ArrayList can
contain.

Count Gets the number of elements actually contained in the ArrayList.

IsFixedSize Gets a value indicating whether the ArrayList has a fixed size.

IsReadOnly Gets a value indicating whether the ArrayList is read-only.

Item Gets or sets the element at the specified index.

The following table lists some of the commonly used methods of the ArrayListclass:

Sr.No. Methods

1 public virtual int Add(object value);


Adds an object to the end of the ArrayList.

2 public virtual void AddRange(ICollection c);


Adds the elements of an ICollection to the end of the ArrayList.

3 public virtual void Clear();

CS6001 C# and .Net programming Page 58

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Removes all elements from the ArrayList.

4 public virtual bool Contains(object item);


Determines whether an element is in the ArrayList.

5 public virtual ArrayList GetRange(int index, int count);


Returns an ArrayList which represents a subset of the elements in the
source ArrayList.

6 public virtual int IndexOf(object);


Returns the zero-based index of the first occurrence of a value in the
ArrayList or in a portion of it.

7 public virtual void Insert(int index, object value);


Inserts an element into the ArrayList at the specified index.

8 public virtual void InsertRange(int index, ICollection c);


Inserts the elements of a collection into the ArrayList at the specified index.

9 public virtual void Remove(object obj);


Removes the first occurrence of a specific object from the ArrayList.

10 public virtual void RemoveAt(int index);


Removes the element at the specified index of the ArrayList.

11 public virtual void RemoveRange(int index, int count);


Removes a range of elements from the ArrayList.

12 public virtual void Reverse();


Reverses the order of the elements in the ArrayList.

13 public virtual void SetRange(int index, ICollection c);


Copies the elements of a collection over a range of elements in the
ArrayList.

CS6001 C# and .Net programming Page 59

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

14 public virtual void Sort();


Sorts the elements in the ArrayList.

15 public virtual void TrimToSize();


Sets the capacity to the actual number of elements in the ArrayList.

Example

The following example demonstrates the concept:

using System;
using System.Collections;

namespace CollectionApplication
{
class Program
{
static void Main(string[] args)
{
ArrayList al = new ArrayList();

Console.WriteLine("Adding some numbers:");


al.Add(45);
al.Add(78);
al.Add(33);
al.Add(56);
al.Add(12);
al.Add(23);
al.Add(9);

Console.WriteLine("Capacity: {0} ", al.Capacity);


Console.WriteLine("Count: {0}", al.Count);

Console.Write("Content: ");
foreach (int i in al)
{
Console.Write(i + " ");
}

Console.WriteLine();
Console.Write("Sorted Content: ");
al.Sort();
foreach (int i in al)

CS6001 C# and .Net programming Page 60

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

{
Console.Write(i + " ");
}
Console.WriteLine();
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

Adding some numbers:


Capacity: 8
Count: 7
Content: 45 78 33 56 12 23 9
Content: 9 12 23 33 45 56 78

CS6001 C# and .Net programming Page 61

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Strings

In C#, you can use strings as array of characters, However, more common practice is
to use the string keyword to declare a string variable. The string keyword is an alias
for the System.String class.

Creating a String Object

You can create string object using one of the following methods:

 By assigning a string literal to a String variable


 By using a String class constructor
 By using the string concatenation operator (+)
 By retrieving a property or calling a method that returns a string
 By calling a formatting method to convert a value or an object to its string
representation

The following example demonstrates this:

using System;
namespace StringApplication
{
class Program
{
static void Main(string[] args)
{
//from string literal and string concatenation
string fname, lname;
fname = "Rowan";
lname = "Atkinson";

string fullname = fname + lname;


Console.WriteLine("Full Name: {0}", fullname);

//by using string constructor


char[] letters = { 'H', 'e', 'l', 'l','o' };
string greetings = new string(letters);
Console.WriteLine("Greetings: {0}", greetings);

//methods returning string


string[] sarray = { "Hello", "From", "Tutorials", "Point" };
string message = String.Join(" ", sarray);
Console.WriteLine("Message: {0}", message);

//formatting method to convert a value


DateTime waiting = new DateTime(2012, 10, 10, 17, 58, 1);
CS6001 C# and .Net programming Page 62

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

string chat = String.Format("Message sent at {0:t} on {0:D}", waiting);


Console.WriteLine("Message: {0}", chat);
}
}
}

When the above code is compiled and executed, it produces the following result:

Full Name: Rowan Atkinson


Greetings: Hello
Message: Hello From Tutorials Point
Message: Message sent at 5:58 PM on Wednesday, October 10, 2012

Propertiesof the StringClass

The String class has the following two properties:

Sr.No Property

1 Chars

Gets the Char object at a specified position in the current Stringobject.

2 Length

Gets the number of characters in the current String object.

Methodsof theStringClass

The String class has numerous methods that help you in working with the string
objects. The following table provides some of the most commonly used methods:

Sr.No Methods

1 public static int Compare(string strA, string strB)


Compares two specified string objects and returns an integer that indicates
their relative position in the sort order.

CS6001 C# and .Net programming Page 63

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

2 public static int Compare(string strA, string strB, bool ignoreCase )


Compares two specified string objects and returns an integer that indicates
their relative position in the sort order. However, it ignores case if the
Boolean parameter is true.

3 public static string Concat(string str0, string str1)


Concatenates two string objects.

4 public static string Concat(string str0, string str1, string str2)


Concatenates three string objects.

5 public static string Concat(string str0, string str1, string str2, string
str3)
Concatenates four string objects.

6 public bool Contains(string value)


Returns a value indicating whether the specified String object occurs within
this string.

7 public static string Copy(string str)


Creates a new String object with the same value as the specified string.

8 public void CopyTo(int sourceIndex, char[] destination, int


destinationIndex, int count)
Copies a specified number of characters from a specified position of the
String object to a specified position in an array of Unicode characters.

9 public bool EndsWith(string value)


Determines whether the end of the string object matches the specified
string.

10 public bool Equals(string value)


Determines whether the current String object and the specified String object
have the same value.

11 public static bool Equals(string a, string b)


Determines whether two specified String objects have the same value.

CS6001 C# and .Net programming Page 64

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

12 public static string Format(string format, Object arg0)


Replaces one or more format items in a specified string with the string
representation of a specified object.

13 public int IndexOf(char value)


Returns the zero-based index of the first occurrence of the specified
Unicode character in the current string.

14 public int IndexOf(string value)


Returns the zero-based index of the first occurrence of the specified string in
this instance.

15 public int IndexOf(char value, int startIndex)


Returns the zero-based index of the first occurrence of the specified
Unicode character in this string, starting search at the specified character
position.

16 public int IndexOf(string value, int startIndex)


Returns the zero-based index of the first occurrence of the specified string in
this instance, starting search at the specified character position.

17 public int IndexOfAny(char[] anyOf)


Returns the zero-based index of the first occurrence in this instance of any
character in a specified array of Unicode characters.

18 public int IndexOfAny(char[] anyOf, int startIndex)


Returns the zero-based index of the first occurrence in this instance of any
character in a specified array of Unicode characters, starting search at the
specified character position.

19 public string Insert(int startIndex, string value)


Returns a new string in which a specified string is inserted at a specified
index position in the current string object.

20 public static bool IsNullOrEmpty(string value)


Indicates whether the specified string is null or an Empty string.

CS6001 C# and .Net programming Page 65

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

21 public static string Join(string separator, params string[] value)


Concatenates all the elements of a string array, using the specified
separator between each element.

22 public static string Join(string separator, string[] value, int startIndex,


int count)
Concatenates the specified elements of a string array, using the specified
separator between each element.

23 public int LastIndexOf(char value)


Returns the zero-based index position of the last occurrence of the specified
Unicode character within the current string object.

24 public int LastIndexOf(string value)


Returns the zero-based index position of the last occurrence of a specified
string within the current string object.

25 public string Remove(int startIndex)


Removes all the characters in the current instance, beginning at a specified
position and continuing through the last position, and returns the string.

26 public string Remove(int startIndex, int count)


Removes the specified number of characters in the current string beginning
at a specified position and returns the string.

27 public string Replace(char oldChar, char newChar)


Replaces all occurrences of a specified Unicode character in the current
string object with the specified Unicode character and returns the new string.

28 public string Replace(string oldValue, string newValue)


Replaces all occurrences of a specified string in the current string object with
the specified string and returns the new string.

29 public string[] Split(params char[] separator)


Returns a string array that contains the substrings in the current string
object, delimited by elements of a specified Unicode character array.

CS6001 C# and .Net programming Page 66

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

30 public string[] Split(char[] separator, int count)


Returns a string array that contains the substrings in the current string
object, delimited by elements of a specified Unicode character array. The int
parameter specifies the maximum number of substrings to return.

31 public bool StartsWith(string value)


Determines whether the beginning of this string instance matches the
specified string.

32 public char[] ToCharArray()


Returns a Unicode character array with all the characters in the current
string object.

33 public char[] ToCharArray(int startIndex, int length)


Returns a Unicode character array with all the characters in the current
string object, starting from the specified index and up to the specified length.

34 public string ToLower()


Returns a copy of this string converted to lowercase.

35 public string ToUpper()


Returns a copy of this string converted to uppercase.

36 public string Trim()


Removes all leading and trailing white-space characters from the current
String object.

You can visit MSDN library for the complete list of methods and String class
constructors.

Examples

The following example demonstrates some of the methods mentioned above:

Comparing Strings:

using System;
CS6001 C# and .Net programming Page 67

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str1 = "This is test";
string str2 = "This is text";

if (String.Compare(str1, str2) == 0)
{
Console.WriteLine(str1 + " and " + str2 + " are equal.");
}
else
{
Console.WriteLine(str1 + " and " + str2 + " are not equal.");
}
Console.ReadKey() ;
}
}
}

When the above code is compiled and executed, it produces the following result:

This is test and This is text are not equal.

String Contains String:

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "This is test";
if (str.Contains("test"))
{
Console.WriteLine("The sequence 'test' was found.");
}
Console.ReadKey() ;
}
}

CS6001 C# and .Net programming Page 68

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

When the above code is compiled and executed, it produces the following result:

The sequence 'test' was found.

Getting a Substring:

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string str = "Last night I dreamt of San Pedro";
Console.WriteLine(str);
string substr = str.Substring(23);
Console.WriteLine(substr);
}
}
}

When the above code is compiled and executed, it produces the following result:

San Pedro

Joining Strings:

using System;
namespace StringApplication
{
class StringProg
{
static void Main(string[] args)
{
string[] starray = new string[]{"Down the way nights are dark",
"And the sun shines daily on the mountain top",
"I took a trip on a sailing ship",
"And when I reached Jamaica",

CS6001 C# and .Net programming Page 69

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

"I made a stop"};

string str = String.Join("\n", starray);


Console.WriteLine(str);
}
}
}

When the above code is compiled and executed, it produces the following result:

Down the way nights are dark


And the sun shines daily on the mountain top
I took a trip on a sailing ship
And when I reached Jamaica
I made a stop

CS6001 C# and .Net programming Page 70

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Using the StringBuilder Class in the .NET Framework

The String object is immutable. Every time you use one of the methods in
the System.String class, you create a new string object in memory, which requires a
new allocation of space for that new object. In situations where you need to perform
repeated modifications to a string, the overhead associated with creating a
new String object can be costly. The System.Text.StringBuilder class can be used when
you want to modify a string without creating a new object. For example, using
the StringBuilder class can boost performance when concatenating many strings
together in a loop.

Instantiating a StringBuilder Object

You can create a new instance of the StringBuilder class by initializing your variable
with one of the overloaded constructor methods, as illustrated in the following example.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

Setting the Capacity and Length

Although the StringBuilder is a dynamic object that allows you to expand the number of
characters in the string that it encapsulates, you can specify a value for the maximum
number of characters that it can hold. This value is called the capacity of the object and
should not be confused with the length of the string that the current StringBuilder holds.
For example, you might create a new instance of the StringBuilder class with the string
"Hello", which has a length of 5, and you might specify that the object has a maximum
capacity of 25. When you modify the StringBuilder, it does not reallocate size for itself
until the capacity is reached. When this occurs, the new space is allocated automatically
and the capacity is doubled. You can specify the capacity of the StringBuilder class
using one of the overloaded constructors. The following example specifies that
the MyStringBuilder object can be expanded to a maximum of 25 spaces.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!", 25);

Additionally, you can use the read/write Capacity property to set the maximum length of
your object. The following example uses the Capacityproperty to define the maximum
object length.

MyStringBuilder.Capacity = 25;

The EnsureCapacity method can be used to check the capacity of the


current StringBuilder. If the capacity is greater than the passed value, no change is
made; however, if the capacity is smaller than the passed value, the current capacity is
changed to match the passed value.

CS6001 C# and .Net programming Page 71

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

The Length property can also be viewed or set. If you set the Length property to a
value that is greater than the Capacity property, theCapacity property is automatically
changed to the same value as the Length property. Setting the Length property to a
value that is less than the length of the string within the current StringBuilder shortens
the string.

Modifying the StringBuilder String

The following table lists the methods you can use to modify the contents of
a StringBuilder.

Method name Use

StringBuilder.Append Appends information to the end of the


current StringBuilder.

StringBuilder.AppendFormat Replaces a format specifier passed in a string with


formatted text.

StringBuilder.Insert Inserts a string or object into the specified index of the


current StringBuilder.

StringBuilder.Remove Removes a specified number of characters from the


current StringBuilder.

StringBuilder.Replace Replaces a specified character at a specified index.

Append

The Append method can be used to add text or a string representation of an object to
the end of a string represented by the currentStringBuilder. The following example
initializes a StringBuilder to "Hello World" and then appends some text to the end of
the object. Space is allocated automatically as needed.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

MyStringBuilder.Append(" What a beautiful day.");

CS6001 C# and .Net programming Page 72

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine(MyStringBuilder);

// The example displays the following output:

// Hello World! What a beautiful day.

AppendFormat

The StringBuilder.AppendFormat method adds text to the end of


the StringBuilder object. It supports the composite formatting feature (for more
information, see Composite Formatting) by calling the IFormattable implementation of
the object or objects to be formatted. Therefore, it accepts the standard format strings
for numeric, date and time, and enumeration values, the custom format strings for
numeric and date and time values, and the format strings defined for custom types. (For
information about formatting, see Formatting Types in the .NET Framework.) You can
use this method to customize the format of variables and append those values to
a StringBuilder. The following example uses the AppendFormat method to place an
integer value formatted as a currency value at the end of a StringBuilder object.

int MyInt = 25;

StringBuilder MyStringBuilder = new StringBuilder("Your total is ");

MyStringBuilder.AppendFormat("{0:C} ", MyInt);

Console.WriteLine(MyStringBuilder);

// The example displays the following output:

// Your total is $25.00

Insert

The Insert method adds a string or object to a specified position in the


current StringBuilder object. The following example uses this method to insert a word
into the sixth position of a StringBuilder object.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

MyStringBuilder.Insert(6,"Beautiful ");

Console.WriteLine(MyStringBuilder);

// The example displays the following output:

// Hello Beautiful World!

CS6001 C# and .Net programming Page 73

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Remove

You can use the Remove method to remove a specified number of characters from the
current StringBuilder object, beginning at a specified zero-based index. The following
example uses the Remove method to shorten a StringBuilder object.

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

MyStringBuilder.Remove(5,7);

Console.WriteLine(MyStringBuilder);

// The example displays the following output:

// Hello

Replace

The Replace method can be used to replace characters within the StringBuilder object
with another specified character. The following example uses the Replace method to
search a StringBuilder object for all instances of the exclamation point character (!) and
replace them with the question mark character (?).

StringBuilder MyStringBuilder = new StringBuilder("Hello World!");

MyStringBuilder.Replace('!', '?');

Console.WriteLine(MyStringBuilder);

// The example displays the following output:

// Hello World?

Converting a StringBuilder Object to a String

You must convert the StringBuilder object to a String object before you can pass the
string represented by the StringBuilder object to a method that has a String parameter
or display it in the user interface. You do this conversion by calling
the StringBuilder.ToString method. The following example calls a number
of StringBuilder methods and then calls the StringBuilder.ToString() method to display
the string.

using System;
using System.Text;

public class Example

CS6001 C# and .Net programming Page 74

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

{
public static void Main()
{
StringBuilder sb = new StringBuilder();
bool flag = true;
string[] spellings = { "recieve", "receeve", "receive" };
sb.AppendFormat("Which of the following spellings is {0}:", flag);
sb.AppendLine();
for (int ctr = 0; ctr <= spellings.GetUpperBound(0); ctr++) {
sb.AppendFormat(" {0}. {1}", ctr, spellings[ctr]);
sb.AppendLine();
}
sb.AppendLine();
Console.WriteLine(sb.ToString());
}
}
// The example displays the following output:
// Which of the following spellings is True:
// 0. recieve
// 1. receeve
// 2. receive

CS6001 C# and .Net programming Page 75

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Structures

In C#, a structure is a value type data type. It helps you to make a single variable hold
related data of various data types. The struct keyword is used for creating a structure.

Structures are used to represent a record. Suppose you want to keep track of your
books in a library. You might want to track the following attributes about each book:

 Title
 Author
 Subject
 Book ID

Defining a Structure

To define a structure, you must use the struct statement. The struct statement defines
a new data type, with more than one member for your program.

For example, here is the way you can declare the Book structure:

struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

The following program shows the use of the structure:

using System;
struct Books
{
public string title;
public string author;
public string subject;
public int book_id;
};

public class testStructure


{
public static void Main(string[] args)
{

Books Book1; /* Declare Book1 of type Book */

CS6001 C# and .Net programming Page 76

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Books Book2; /* Declare Book2 of type Book */

/* book 1 specification */
Book1.title = "C Programming";
Book1.author = "Nuha Ali";
Book1.subject = "C Programming Tutorial";
Book1.book_id = 6495407;

/* book 2 specification */
Book2.title = "Telecom Billing";
Book2.author = "Zara Ali";
Book2.subject = "Telecom Billing Tutorial";
Book2.book_id = 6495700;

/* print Book1 info */


Console.WriteLine( "Book 1 title : {0}", Book1.title);
Console.WriteLine("Book 1 author : {0}", Book1.author);
Console.WriteLine("Book 1 subject : {0}", Book1.subject);
Console.WriteLine("Book 1 book_id :{0}", Book1.book_id);

/* print Book2 info */


Console.WriteLine("Book 2 title : {0}", Book2.title);
Console.WriteLine("Book 2 author : {0}", Book2.author);
Console.WriteLine("Book 2 subject : {0}", Book2.subject);
Console.WriteLine("Book 2 book_id : {0}", Book2.book_id);

Console.ReadKey();

}
}

When the above code is compiled and executed, it produces the following result:

Book 1 title : C Programming


Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700

CS6001 C# and .Net programming Page 77

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Features of C# Structures

You have already used a simple structure named Books. Structures in C# are quite
different from that in traditional C or C++. The C# structures have the following
features:

 Structures can have methods, fields, indexers, properties, operator methods,


and events.
 Structures can have defined constructors, but not destructors. However, you
cannot define a default constructor for a structure. The default constructor is
automatically defined and cannot be changed.
 Unlike classes, structures cannot inherit other structures or classes.
 Structures cannot be used as a base for other structures or classes.
 A structure can implement one or more interfaces.
 Structure members cannot be specified as abstract, virtual, or protected.
 When you create a struct object using the New operator, it gets created and the
appropriate constructor is called. Unlike classes, structs can be instantiated
without using the New operator.
 If the New operator is not used, the fields remain unassigned and the object
cannot be used until all the fields are initialized.

Class versus Structure

Classes and Structures have the following basic differences:

 classes are reference types and structs are value types


 structures do not support inheritance
 structures cannot have default constructor

In the light of the above discussions, let us rewrite the previous example:

using System;
struct Books
{
private string title;
private string author;
private string subject;
private int book_id;
public void getValues(string t, string a, string s, int id)
{
title = t;
author = a;
subject = s;
book_id = id;
}
public void display()

CS6001 C# and .Net programming Page 78

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

{
Console.WriteLine("Title : {0}", title);
Console.WriteLine("Author : {0}", author);
Console.WriteLine("Subject : {0}", subject);
Console.WriteLine("Book_id :{0}", book_id);
}
};

public class testStructure


{
public static void Main(string[] args)
{

Books Book1 = new Books(); /* Declare Book1 of type Book */


Books Book2 = new Books(); /* Declare Book2 of type Book */

/* book 1 specification */
Book1.getValues("C Programming",
"Nuha Ali", "C Programming Tutorial",6495407);
/* book 2 specification */
Book2.getValues("Telecom Billing",
"Zara Ali", "Telecom Billing Tutorial", 6495700);
/* print Book1 info */
Book1.display();
/* print Book2 info */
Book2.display();

Console.ReadKey();

}
}

When the above code is compiled and executed, it produces the following result:

Title : C Programming
Author : Nuha Ali
Subject : C Programming Tutorial
Book_id : 6495407
Title : Telecom Billing
Author : Zara Ali
Subject : Telecom Billing Tutorial
Book_id : 6495700

CS6001 C# and .Net programming Page 79

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Enums

An enumeration is a set of named integer constants. An enumerated type is declared


using the enum keyword.

C# enumerations are value data type. In other words, enumeration contains its own
values and cannot inherit or cannot pass inheritance.

Declaring enum Variable

The general syntax for declaring an enumeration is:

enum <enum_name>

enumeration list

};

Where,

 The enum_name specifies the enumeration type name.


 The enumeration list is a comma-separated list of identifiers.

Each of the symbols in the enumeration list stands for an integer value, one greater
than the symbol that precedes it. By default, the value of the first enumeration symbol
is 0. For example:

enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

Example

The following example demonstrates use of enum variable:

using System;
namespace EnumApplication
{
class EnumProgram
{
enum Days { Sun, Mon, tue, Wed, thu, Fri, Sat };

static void Main(string[] args)


{

CS6001 C# and .Net programming Page 80

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

int WeekdayStart = (int)Days.Mon;


int WeekdayEnd = (int)Days.Fri;
Console.WriteLine("Monday: {0}", WeekdayStart);
Console.WriteLine("Friday: {0}", WeekdayEnd);
Console.ReadKey();
}
}
}

When the above code is compiled and executed, it produces the following result:

Monday: 1

Friday: 5

CS6001 C# and .Net programming Page 81

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Boxing and Unboxing

Boxing is the process of converting a value type to the type object or to any interface
type implemented by this value type. When the CLR boxes a value type, it wraps the
value inside a System.Object and stores it on the managed heap. Unboxing extracts the
value type from the object. Boxing is implicit; unboxing is explicit. The concept of boxing
and unboxing underlies the C# unified view of the type system in which a value of any
type can be treated as an object.

In the following example, the integer variable i is boxed and assigned to object o.

int i = 123;

// The following line boxes i.

object o = i;

The object o can then be unboxed and assigned to integer variable i:

o = 123;

i = (int)o; // unboxing

The following examples illustrate how boxing is used in C#.

// String.Concat example.
// String.Concat has many versions. Rest the mouse pointer on
// Concat in the following statement to verify that the version
// that is used here takes three object arguments. Both 42 and
// true must be boxed.
Console.WriteLine(String.Concat("Answer", 42, true));
// List example.
// Create a list of objects to hold a heterogeneous collection
// of elements.
List<object> mixedList = new List<object>();

// Add a string element to the list.


mixedList.Add("First Group:");
// Add some integers to the list.
for (int j = 1; j < 5; j++)
{
// Rest the mouse pointer over j to verify that you are adding
// an int to a list of objects. Each element j is boxed when
// you add j to mixedList.
mixedList.Add(j);
}

CS6001 C# and .Net programming Page 82

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// Add another string and more integers.


mixedList.Add("Second Group:");
for (int j = 5; j < 10; j++)
{
mixedList.Add(j);
}
// Display the elements in the list. Declare the loop variable by
// using var, so that the compiler assigns its type.
foreach (var item in mixedList)
{
// Rest the mouse pointer over item to verify that the elements
// of mixedList are objects.
Console.WriteLine(item);
}

// The following loop sums the squares of the first group of boxed
// integers in mixedList. The list elements are objects, and cannot
// be multiplied or added to the sum until they are unboxed. The
// unboxing must be done explicitly.
var sum = 0;
for (var j = 1; j < 5; j++)
{
// The following statement causes a compiler error: Operator
// '*' cannot be applied to operands of type 'object' and
// 'object'.
//sum += mixedList[j] * mixedList[j]);

// After the list elements are unboxed, the computation does


// not cause a compiler error.
sum += (int)mixedList[j] * (int)mixedList[j];
}

// The sum displayed is 30, the sum of 1 + 4 + 9 + 16.


Console.WriteLine("Sum: " + sum);

// Output:
// Answer42True
// First Group:
// 1
// 2
// 3
// 4
// Second Group:
// 5
// 6
// 7

CS6001 C# and .Net programming Page 83

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// 8
// 9
// Sum: 30

Performance

In relation to simple assignments, boxing and unboxing are computationally expensive


processes. When a value type is boxed, a new object must be allocated and
constructed. To a lesser degree, the cast required for unboxing is also expensive
computationally. For more information, see Performance.

Boxing

Boxing is used to store value types in the garbage-collected heap. Boxing is an implicit
conversion of a value type to the type object or to any interface type implemented by
this value type. Boxing a value type allocates an object instance on the heap and copies
the value into the new object.

Consider the following declaration of a value-type variable:

int i = 123;

The following statement implicitly applies the boxing operation on the variable i:

// Boxing copies the value of i into object o.

object o = i;

The result of this statement is creating an object reference o, on the stack, that
references a value of the type int, on the heap. This value is a copy of the value-type
value assigned to the variable i. The difference between the two variables, i and o, is
illustrated in the following figure.

Boxing Conversion

It is also possible to perform the boxing explicitly as in the following example, but explicit
boxing is never required:

CS6001 C# and .Net programming Page 84

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

int i = 123;

object o = (object)i; // explicit boxing

Description

This example converts an integer variable i to an object o by using boxing. Then, the
value stored in the variable i is changed from 123 to 456. The example shows that the
original value type and the boxed object use separate memory locations, and therefore
can store different values.

class TestBoxing
{
static void Main()
{
int i = 123;

// Boxing copies the value of i into object o.


object o = i;

// Change the value of i.


i = 456;

// The change in i does not effect the value stored in o.


System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}
/* Output:
The value-type value = 456
The object-type value = 123
*/

Unboxing

Unboxing is an explicit conversion from the type object to a value type or from an
interface type to a value type that implements the interface. An unboxing operation
consists of:

 Checking the object instance to make sure that it is a boxed value of the given
value type.
 Copying the value from the instance into the value-type variable.

The following statements demonstrate both boxing and unboxing operations:

int i = 123; // a value type

CS6001 C# and .Net programming Page 85

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

object o = i; // boxing

int j = (int)o; // unboxing

The following figure demonstrates the result of the previous statements.

Unboxing Conversion

For the unboxing of value types to succeed at run time, the item being unboxed must be
a reference to an object that was previously created by boxing an instance of that value
type. Attempting to unbox null causes a NullReferenceException. Attempting to unbox a
reference to an incompatible value type causes an InvalidCastException.

The following example demonstrates a case of invalid unboxing and the


resulting InvalidCastException. Using try and catch, an error message is displayed
when the error occurs.

class TestUnboxing
{
static void Main()
{
int i = 123;
object o = i; // implicit boxing

try
{
int j = (short)o; // attempt to unbox

System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.", e.Message);
}
CS6001 C# and .Net programming Page 86

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

}
}

This program outputs:

Specified cast is not valid. Error: Incorrect unboxing.

If you change the statement:

int j = (short) o;

to:

int j = (int) o;

the conversion will be performed, and you will get the output:

Unboxing OK.

Ref: http://www.tutorialspoint.com/

https://msdn.microsoft.com

http://www.aspfree.com/c/a/c-sharp/branching-and-looping-in-c-part-1

CS6001 C# and .Net programming Page 87

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Unit II

OBJECT ORIENTED ASPECTS OF C#

Key Concepts of Object Orientation

 Abstraction
 Encapsulation
 Polymorphism
 Inheritance.

Abstraction is the ability to generalize an object as


a data type that has a specific set of characteristics
and is able to perform a set of actions.

Object-oriented languages provide abstraction via


classes. Classes define the properties and methods
of an object type.

Examples:

 You can create an abstraction of a dog with


characteristics, such as color, height, and
weight, and actions such as run and bite. The
characteristics are called properties, and the
actions are called methods.
 A Recordset object is an abstract representation
of a set of data.

CS6001 C# and .Net programming Page 1

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Classes
When you define a class, you define a blueprint for a data type. This does
not actually define any data, but it does define what the class name means.
That is, what an object of the class consists of and what operations can be
performed on that object. Objects are instances of a class. The methods
and variables that constitute a class are called members of the class.

Defining a Class
A class definition starts with the keyword class followed by the class name;
and the class body enclosed by a pair of curly braces. Following is the
general form of a class definition:

<access specifier> class class_name

// member variables

<access specifier> <data type> variable1;

<access specifier> <data type> variable2;

...

<access specifier> <data type> variableN;

// member methods

<access specifier> <return type> method1(parameter_list)

// method body

<access specifier> <return type> method2(parameter_list)

// method body

...

<access specifier> <return type> methodN(parameter_list)

// method body

CS6001 C# and .Net programming Page 2

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Note:

 Access specifiers specify the access rules for the members as well as the class
itself. If not mentioned, then the default access specifier for a class type
is internal. Default access for the members is private.

 Data type specifies the type of variable, and return type specifies the data type
of the data the method returns, if any.

 To access the class members, you use the dot (.) operator.

 The dot operator links the name of an object with the name of a member.

The following example illustrates the concepts discussed so far:

using System;

namespace BoxApplication

class Box

public double length; // Length of a box

public double breadth; // Breadth of a box

public double height; // Height of a box

class Boxtester

static void Main(string[] args)

Box Box1 = new Box(); // Declare Box1 of type Box

Box Box2 = new Box(); // Declare Box2 of type Box

double volume = 0.0; // Store the volume of a box here

// box 1 specification

Box1.height = 5.0;

CS6001 C# and .Net programming Page 3

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Box1.length = 6.0;

Box1.breadth = 7.0;

// box 2 specification

Box2.height = 10.0;

Box2.length = 12.0;

Box2.breadth = 13.0;

// volume of box 1

volume = Box1.height * Box1.length * Box1.breadth;

Console.WriteLine("Volume of Box1 : {0}", volume);

// volume of box 2

volume = Box2.height * Box2.length * Box2.breadth;

Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Volume of Box1 : 210


Volume of Box2 : 1560

Member Functions and Encapsulation


A member function of a class is a function that has its definition or its
prototype within the class definition similar to any other variable. It
operates on any object of the class of which it is a member, and has access
to all the members of a class for that object.

Member variables are the attributes of an object (from design perspective)


and they are kept private to implement encapsulation. These variables can
only be accessed using the public member functions.

CS6001 C# and .Net programming Page 4

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Let us put above concepts to set and get the value of different class
members in a class:

using System;

namespace BoxApplication

class Box

private double length; // Length of a box

private double breadth; // Breadth of a box

private double height; // Height of a box

public void setLength( double len )

length = len;

public void setBreadth( double bre )

breadth = bre;

public void setHeight( double hei )

height = hei;

public double getVolume()

return length * breadth * height;

class Boxtester

static void Main(string[] args)

CS6001 C# and .Net programming Page 5

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Box Box1 = new Box(); // Declare Box1 of type Box

Box Box2 = new Box();

double volume;

// Declare Box2 of type Box

// box 1 specification

Box1.setLength(6.0);

Box1.setBreadth(7.0);

Box1.setHeight(5.0);

// box 2 specification

Box2.setLength(12.0);

Box2.setBreadth(13.0);

Box2.setHeight(10.0);

// volume of box 1

volume = Box1.getVolume();

Console.WriteLine("Volume of Box1 : {0}" ,volume);

// volume of box 2

volume = Box2.getVolume();

Console.WriteLine("Volume of Box2 : {0}", volume);

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Volume of Box1 : 210


Volume of Box2 : 1560

CS6001 C# and .Net programming Page 6

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# Constructors
A class constructor is a special member function of a class that is executed
whenever we create new objects of that class.

A constructor has exactly the same name as that of class and it does not
have any return type. Following example explains the concept of
constructor:

using System;

namespace LineApplication

class Line

private double length; // Length of a line

public Line()

Console.WriteLine("Object is being created");

public void setLength( double len )

length = len;

public double getLength()

return length;

static void Main(string[] args)

Line line = new Line();

// set line length

CS6001 C# and .Net programming Page 7

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Object is being created


Length of line : 6

A default constructor does not have any parameter but if you need, a
constructor can have parameters. Such constructors are
called parameterized constructors. This technique helps you to assign
initial value to an object at the time of its creation as shown in the following
example:

using System;

namespace LineApplication

class Line

private double length; // Length of a line

public Line(double len) //Parameterized constructor

Console.WriteLine("Object is being created, length = {0}", len);

length = len;

public void setLength( double len )

length = len;

public double getLength()

CS6001 C# and .Net programming Page 8

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

return length;

static void Main(string[] args)

Line line = new Line(10.0);

Console.WriteLine("Length of line : {0}", line.getLength());

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Object is being created, length = 10


Length of line : 10
Length of line : 6

C# Destructors
A destructor is a special member function of a class that is executed
whenever an object of its class goes out of scope. A destructor has exactly
the same name as that of the class with a prefixed tilde (~) and it can
neither return a value nor can it take any parameters.

Destructor can be very useful for releasing memory resources before exiting
the program. Destructors cannot be inherited or overloaded.

Following example explains the concept of destructor:

using System;

CS6001 C# and .Net programming Page 9

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

namespace LineApplication

class Line

private double length; // Length of a line

public Line() // constructor

Console.WriteLine("Object is being created");

~Line() //destructor

Console.WriteLine("Object is being deleted");

public void setLength( double len )

length = len;

public double getLength()

return length;

static void Main(string[] args)

Line line = new Line();

// set line length

line.setLength(6.0);

Console.WriteLine("Length of line : {0}", line.getLength());

CS6001 C# and .Net programming Page 10

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

When the above code is compiled and executed, it produces the following
result:

Object is being created


Length of line : 6
Object is being deleted

Static Members of a C# Class


We can define class members as static using the static keyword. When we
declare a member of a class as static, it means no matter how many
objects of the class are created, there is only one copy of the static
member.

The keyword static implies that only one instance of the member exists for
a class. Static variables are used for defining constants because their values
can be retrieved by invoking the class without creating an instance of it.
Static variables can be initialized outside the member function or class
definition. You can also initialize static variables inside the class definition.

The following example demonstrates the use of static variables:

using System;

namespace StaticVarApplication

class StaticVar

public static int num;

public void count()

num++;

public int getNum()

return num;

CS6001 C# and .Net programming Page 11

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class StaticTester

static void Main(string[] args)

StaticVar s1 = new StaticVar();

StaticVar s2 = new StaticVar();

s1.count();

s1.count();

s1.count();

s2.count();

s2.count();

s2.count();

Console.WriteLine("Variable num for s1: {0}", s1.getNum());

Console.WriteLine("Variable num for s2: {0}", s2.getNum());

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Variable num for s1: 6


Variable num for s2: 6

You can also declare a member function as static. Such functions can
access only static variables. The static functions exist even before the
object is created. The following example demonstrates the use of static
functions:

using System;

namespace StaticVarApplication

CS6001 C# and .Net programming Page 12

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class StaticVar

public static int num;

public void count()

num++;

public static int getNum()

return num;

class StaticTester

static void Main(string[] args)

StaticVar s = new StaticVar();

s.count();

s.count();

s.count();

Console.WriteLine("Variable num: {0}", StaticVar.getNum());

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Variable num: 3

CS6001 C# and .Net programming Page 13

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Inheritance
One of the most important concepts in object-oriented programming is
inheritance. Inheritance allows us to define a class in terms of another
class, which makes it easier to create and maintain an application. This also
provides an opportunity to reuse the code functionality and speeds up
implementation time.

When creating a class, instead of writing completely new data members and
member functions, the programmer can designate that the new class should
inherit the members of an existing class. This existing class is called
the baseclass, and the new class is referred to as the derived class.

The idea of inheritance implements the IS-A relationship. For example,


mammalIS A animal, dog IS-A mammal hence dog IS-A animal as well,
and so on.

Base and Derived Classes


A class can be derived from more than one class or interface, which means
that it can inherit data and functions from multiple base classes or
interfaces.

The syntax used in C# for creating derived classes is as follows:

<acess-specifier> class <base_class>

...

class <derived_class> : <base_class>

...

Consider a base class Shape and its derived class Rectangle:

using System;

namespace InheritanceApplication

CS6001 C# and .Net programming Page 14

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class Shape

public void setWidth(int w)

width = w;

public void setHeight(int h)

height = h;

protected int width;

protected int height;

// Derived class

class Rectangle: Shape

public int getArea()

return (width * height);

class RectangleTester

static void Main(string[] args)

Rectangle Rect = new Rectangle();

Rect.setWidth(5);

Rect.setHeight(7);

CS6001 C# and .Net programming Page 15

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// Print the area of the object.

Console.WriteLine("Total area: {0}", Rect.getArea());

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Total area: 35

Initializing Base Class


The derived class inherits the base class member variables and member
methods. Therefore the super class object should be created before the
subclass is created. You can give instructions for superclass initialization in
the member initialization list.

The following program demonstrates this:

using System;

namespace RectangleApplication

class Rectangle

//member variables

protected double length;

protected double width;

public Rectangle(double l, double w)

length = l;

width = w;

public double GetArea()

CS6001 C# and .Net programming Page 16

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

return length * width;

public void Display()

Console.WriteLine("Length: {0}", length);

Console.WriteLine("Width: {0}", width);

Console.WriteLine("Area: {0}", GetArea());

}//end class Rectangle

class Tabletop : Rectangle

private double cost;

public Tabletop(double l, double w) : base(l, w)

{ }

public double GetCost()

double cost;

cost = GetArea() * 70;

return cost;

public void Display()

base.Display();

Console.WriteLine("Cost: {0}", GetCost());

class ExecuteRectangle

static void Main(string[] args)

CS6001 C# and .Net programming Page 17

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Tabletop t = new Tabletop(4.5, 7.5);

t.Display();

Console.ReadLine();

When the above code is compiled and executed, it produces the following
result:

Length: 4.5
Width: 7.5
Area: 33.75
Cost: 2362.5

Multiple Inheritance in C#
C# does not support multiple inheritance. However, you can use
interfaces to implement multiple inheritance. The following program
demonstrates this:

using System;

namespace InheritanceApplication

class Shape

public void setWidth(int w)

width = w;

public void setHeight(int h)

height = h;

protected int width;

protected int height;

CS6001 C# and .Net programming Page 18

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// Base class PaintCost

public interface PaintCost

int getCost(int area);

// Derived class

class Rectangle : Shape, PaintCost

public int getArea()

return (width * height);

public int getCost(int area)

return area * 70;

class RectangleTester

static void Main(string[] args)

Rectangle Rect = new Rectangle();

int area;

Rect.setWidth(5);

Rect.setHeight(7);

area = Rect.getArea();

// Print the area of the object.

Console.WriteLine("Total area: {0}", Rect.getArea());

CS6001 C# and .Net programming Page 19

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine("Total paint cost: ${0}" , Rect.getCost(area));

Console.ReadKey();

When the above code is compiled and executed, it produces the following
result:

Total area: 35
Total paint cost: $2450

CS6001 C# and .Net programming Page 20

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Understanding Properties in C#
In C#, properties are nothing but natural extension of data fields. They are

usually known as 'smart fields' in C# community. We know that data

encapsulation and hiding are the two fundamental characteristics of any

object oriented programming language.In C#, data encapsulation is possible

through either classes or structures. By using various access modifiers like

private, public, protected, internal etc it is possible to control the

accessibility of the class members.

Usually inside a class, we declare a data field as private and will provide a

set of public SET and GET methods to access the data fields. This is a good

programming practice, since the data fields are not directly accessible out

side the class. We must use the set/get methods to access the data fields.

An example, which uses a set of set/get methods, is shown below.

//SET/GET methods

//Author: rajeshvs@msn.com

using System;

class MyClass

private int x;

public void SetX(int i)

CS6001 C# and .Net programming Page 21

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

x = i;

public int GetX()

return x;

class MyClient

public static void Main()

MyClass mc = new MyClass();

mc.SetX(10);

int xVal = mc.GetX();

Console.WriteLine(xVal);//Displays 10

But C# provides a built in mechanism called properties to do the above. In

C#, properties are defined using the property declaration syntax. The

general form of declaring a property is as follows.

<acces_modifier> <return_type> <property_name>

get

CS6001 C# and .Net programming Page 22

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

set

Where <access_modifier> can be private, public, protected or internal. The

<return_type> can be any valid C# type. Note that the first part of the

syntax looks quite similar to a field declaration and second part consists of a

get accessor and a set accessor.

For example the above program can be modifies with a property X as

follows.

class MyClass

private int x;

public int X

get

return x;

set

CS6001 C# and .Net programming Page 23

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

x = value;

The object of the class MyClass can access the property X as follows.

MyClass mc = new MyClass();

mc.X = 10; // calls set accessor of the property X, and pass 10 as value of

the standard field 'value'.

This is used for setting value for the data member x.

Console.WriteLine(mc.X);// displays 10. Calls the get accessor of the

property X.

The complete program is shown below.

//C#: Property

//Author: rajeshvs@msn.com

using System;

class MyClass

private int x;

public int X

CS6001 C# and .Net programming Page 24

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

get

return x;

set

x = value;

class MyClient

public static void Main()

MyClass mc = new MyClass();

mc.X = 10;

int xVal = mc.X;

Console.WriteLine(xVal);//Displays 10

Remember that a property should have at least one accessor, either set or

get. The set accessor has a free variable available in it called value, which

CS6001 C# and .Net programming Page 25

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

gets created automatically by the compiler. We can't declare any variable

with the name value inside the set accessor.

We can do very complicated calculations inside the set or get accessor. Even

they can throw exceptions.

Since normal data fields and properties are stored in the same memory

space, in C#, it is not possible to declare a field and property with the same

name.

Static Properties

C# also supports static properties, which belongs to the class rather than to

the objects of the class. All the rules applicable to a static member are

applicable to static properties also.

The following program shows a class with a static property.

//C# : static Property

//Author: rajeshvs@msn.com

using System;

class MyClass

private static int x;

public static int X

get

CS6001 C# and .Net programming Page 26

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

return x;

set

x = value;

class MyClient

public static void Main()

MyClass.X = 10;

int xVal = MyClass.X;

Console.WriteLine(xVal);//Displays 10

Remember that set/get accessor of static property can access only other

static members of the class. Also static properties are invoking by using the

class name.

Properties & Inheritance

CS6001 C# and .Net programming Page 27

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

The properties of a Base class can be inherited to a Derived class.

//C# : Property : Inheritance

//Author: rajeshvs@msn.com

using System;

class Base

public int X

get

Console.Write("Base GET");

return 10;

set

Console.Write("Base SET");

class Derived : Base

class MyClient

CS6001 C# and .Net programming Page 28

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

public static void Main()

Derived d1 = new Derived();

d1.X = 10;

Console.WriteLine(d1.X);//Displays 'Base SET Base GET 10'

The above program is very straightforward. The inheritance of properties is

just like inheritance any other member.

Properties & Polymorphism

A Base class property can be polymorphicaly overridden in a Derived class.

But remember that the modifiers like virtual, override etc are using at

property level, not at accessor level.

//C# : Property : Polymorphism

//Author: rajeshvs@msn.com

using System;

class Base

public virtual int X

CS6001 C# and .Net programming Page 29

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

get

Console.Write("Base GET");

return 10;

set

Console.Write("Base SET");

class Derived : Base

public override int X

get

Console.Write("Derived GET");

return 10;

set

Console.Write("Derived SET");

CS6001 C# and .Net programming Page 30

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class MyClient

public static void Main()

Base b1 = new Derived();

b1.X = 10;

Console.WriteLine(b1.X);//Displays 'Derived SET Derived GET 10'

Abstract Properties

A property inside a class can be declared as abstract by using the keyword

abstract. Remember that an abstract property in a class carries no code at

all. The get/set accessors are simply represented with a semicolon. In the

derived class we must implement both set and get assessors.

If the abstract class contains only set accessor, we can implement only set in

the derived class.

The following program shows an abstract property in action.

//C# : Property : Abstract

CS6001 C# and .Net programming Page 31

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

//Author: rajeshvs@msn.com

using System;

abstract class Abstract

public abstract int X

get;

set;

class Concrete : Abstract

public override int X

get

Console.Write(" GET");

return 10;

set

Console.Write(" SET");

CS6001 C# and .Net programming Page 32

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class MyClient

public static void Main()

Concrete c1 = new Concrete();

c1.X = 10;

Console.WriteLine(c1.X);//Displays 'SET GET 10'

The properties are an important features added in language level inside C#.

They are very useful in GUI programming. Remember that the compiler

actually generates the appropriate getter and setter methods when it parses

the C# property syntax.

CS6001 C# and .Net programming Page 33

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Indexers

An indexer allows an object to be indexed such as an array. When you

define an indexer for a class, this class behaves similar to a virtual array.

You can then access the instance of this class using the array access

operator ([ ]).

Syntax
A one dimensional indexer has the following syntax:

element-type this[int index]

// The get accessor.

get

// return the value specified by index

// The set accessor.

set

// set the value specified by index

CS6001 C# and .Net programming Page 34

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Use of Indexers
Declaration of behavior of an indexer is to some extent similar to a

property. similar to the properties, you use get and set accessors for

defining an indexer. However, properties return or set a specific data

member, whereas indexers returns or sets a particular value from the

object instance. In other words, it breaks the instance data into smaller

parts and indexes each part, gets or sets each part.

Defining a property involves providing a property name. Indexers are not

defined with names, but with the this keyword, which refers to the object

instance. The following example demonstrates the concept:

using System;

namespace IndexerApplication

class IndexedNames

private string[] namelist = new string[size];

static public int size = 10;

CS6001 C# and .Net programming Page 35

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

public IndexedNames()

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

namelist[i] = "N. A.";

public string this[int index]

get

string tmp;

if( index >= 0 && index <= size-1 )

tmp = namelist[index];

else

tmp = "";

CS6001 C# and .Net programming Page 36

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

return ( tmp );

set

if( index >= 0 && index <= size-1 )

namelist[index] = value;

static void Main(string[] args)

IndexedNames names = new IndexedNames();

names[0] = "Zara";

names[1] = "Riz";

names[2] = "Nuha";

names[3] = "Asif";

names[4] = "Davinder";

CS6001 C# and .Net programming Page 37

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

names[5] = "Sunil";

names[6] = "Rubic";

for ( int i = 0; i < IndexedNames.size; i++ )

Console.WriteLine(names[i]);

Console.ReadKey();

When the above code is compiled and executed, it produces the following

result:

Zara
Riz
Nuha
Asif
Davinder
Sunil
Rubic

CS6001 C# and .Net programming Page 38

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

N. A.
N. A.
N. A.

Overloaded Indexers
Indexers can be overloaded. Indexers can also be declared with multiple

parameters and each parameter may be a different type. It is not necessary

that the indexes have to be integers. C# allows indexes to be of other

types, for example, a string.

The following example demonstrates overloaded indexers:

using System;

namespace IndexerApplication

class IndexedNames

private string[] namelist = new string[size];

static public int size = 10;

public IndexedNames()

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

CS6001 C# and .Net programming Page 39

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

namelist[i] = "N. A.";

public string this[int index]

get

string tmp;

if( index >= 0 && index <= size-1 )

tmp = namelist[index];

else

tmp = "";

CS6001 C# and .Net programming Page 40

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

return ( tmp );

set

if( index >= 0 && index <= size-1 )

namelist[index] = value;

public int this[string name]

get

int index = 0;

while(index < size)

if (namelist[index] == name)

return index;

CS6001 C# and .Net programming Page 41

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

index++;

return index;

static void Main(string[] args)

IndexedNames names = new IndexedNames();

names[0] = "Zara";

names[1] = "Riz";

names[2] = "Nuha";

names[3] = "Asif";

names[4] = "Davinder";

names[5] = "Sunil";

names[6] = "Rubic";

//using the first indexer with int parameter

CS6001 C# and .Net programming Page 42

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

for (int i = 0; i < IndexedNames.size; i++)

Console.WriteLine(names[i]);

//using the second indexer with the string


parameter

Console.WriteLine(names["Nuha"]);

Console.ReadKey();

When the above code is compiled and executed, it produces the following

result:

Zara
Riz
Nuha
Asif
Davinder
Sunil

CS6001 C# and .Net programming Page 43

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Rubic
N. A.
N. A.
N. A.
2

CS6001 C# and .Net programming Page 44

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Polymorphism

The word polymorphism means having many forms. In object-oriented

programming paradigm, polymorphism is often expressed as 'one interface,

multiple functions'.

Polymorphism can be static or dynamic. In static polymorphism, the

response to a function is determined at the compile time. In dynamic

polymorphism, it is decided at run-time.

Static Polymorphism
The mechanism of linking a function with an object during compile time is

called early binding. It is also called static binding. C# provides two

techniques to implement static polymorphism. They are:

 Function overloading

 Operator overloading

We discuss operator overloading in next chapter.

Function Overloading
You can have multiple definitions for the same function name in the same

scope. The definition of the function must differ from each other by the

types and/or the number of arguments in the argument list. You cannot

overload function declarations that differ only by return type.

CS6001 C# and .Net programming Page 45

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

The following example shows using function print() to print different data

types:

using System;

namespace PolymorphismApplication

class Printdata

void print(int i)

Console.WriteLine("Printing int: {0}", i );

void print(double f)

Console.WriteLine("Printing float: {0}" , f);

void print(string s)

Console.WriteLine("Printing string: {0}", s);


CS6001 C# and .Net programming Page 46

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

static void Main(string[] args)

Printdata p = new Printdata();

// Call print to print integer

p.print(5);

// Call print to print float

p.print(500.263);

// Call print to print string

p.print("Hello C++");

Console.ReadKey();

When the above code is compiled and executed, it produces the following

result:

CS6001 C# and .Net programming Page 47

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Printing int: 5
Printing float: 500.263
Printing string: Hello C++

Dynamic Polymorphism
C# allows you to create abstract classes that are used to provide partial

class implementation of an interface. Implementation is completed when a

derived class inherits from it. Abstract classes contain abstract methods,

which are implemented by the derived class. The derived classes have more

specialized functionality.

Here are the rules about abstract classes:

 You cannot create an instance of an abstract


class

 You cannot declare an abstract method outside


an abstract class

 When a class is declared sealed, it cannot be


inherited, abstract classes cannot be declared
sealed.

The following program demonstrates an abstract class:

using System;
CS6001 C# and .Net programming Page 48

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

namespace PolymorphismApplication

abstract class Shape

public abstract int area();

class Rectangle: Shape

private int length;

private int width;

public Rectangle( int a=0, int b=0)

length = a;

width = b;

public override int area ()

Console.WriteLine("Rectangle class area :");

return (width * length);

CS6001 C# and .Net programming Page 49

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

class RectangleTester

static void Main(string[] args)

Rectangle r = new Rectangle(10, 7);

double a = r.area();

Console.WriteLine("Area: {0}",a);

Console.ReadKey();

When the above code is compiled and executed, it produces the following

result:

Rectangle class area :


Area: 70

When you have a function defined in a class that you want to be

implemented in an inherited class(es), you use virtual functions. The

CS6001 C# and .Net programming Page 50

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

virtual functions could be implemented differently in different inherited class

and the call to these functions will be decided at runtime.

Dynamic polymorphism is implemented by abstract classes and virtual

functions.

The following program demonstrates this:

using System;

namespace PolymorphismApplication

class Shape

protected int width, height;

public Shape( int a=0, int b=0)

width = a;

height = b;

public virtual int area()

Console.WriteLine("Parent class area :");

CS6001 C# and .Net programming Page 51

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

return 0;

class Rectangle: Shape

public Rectangle( int a=0, int b=0): base(a, b)

public override int area ()

Console.WriteLine("Rectangle class area :");

return (width * height);

class Triangle: Shape

public Triangle(int a = 0, int b = 0): base(a, b)

CS6001 C# and .Net programming Page 52

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

public override int area()

Console.WriteLine("Triangle class area :");

return (width * height / 2);

class Caller

public void CallArea(Shape sh)

int a;

a = sh.area();

Console.WriteLine("Area: {0}", a);

class Tester

static void Main(string[] args)

CS6001 C# and .Net programming Page 53

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Caller c = new Caller();

Rectangle r = new Rectangle(10, 7);

Triangle t = new Triangle(10, 5);

c.CallArea(r);

c.CallArea(t);

Console.ReadKey();

When the above code is compiled and executed, it produces the following

result:

Rectangle class area:


Area: 70
Triangle class area:
Area: 25

CS6001 C# and .Net programming Page 54

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

C# - Interfaces

An interface is defined as a syntactical contract that all the classes

inheriting the interface should follow. The interface defines the 'what' part

of the syntactical contract and the deriving classes define the 'how' part of

the syntactical contract.

Interfaces define properties, methods, and events, which are the members

of the interface. Interfaces contain only the declaration of the members. It

is the responsibility of the deriving class to define the members. It often

helps in providing a standard structure that the deriving classes would

follow.

Abstract classes to some extent serve the same purpose, however, they are

mostly used when only few methods are to be declared by the base class

and the deriving class implements the functionalities.

Declaring Interfaces
Interfaces are declared using the interface keyword. It is similar to class

declaration. Interface statements are public by default. Following is an

example of an interface declaration:

public interface ITransactions

CS6001 C# and .Net programming Page 55

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

// interface members

void showTransaction();

double getAmount();

Example
The following example demonstrates implementation of the above interface:

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System;

namespace InterfaceApplication

public interface ITransactions

// interface members

void showTransaction();

double getAmount();

CS6001 C# and .Net programming Page 56

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

public class Transaction : ITransactions

private string tCode;

private string date;

private double amount;

public Transaction()

tCode = " ";

date = " ";

amount = 0.0;

public Transaction(string c, string d, double a)

tCode = c;

date = d;

amount = a;

CS6001 C# and .Net programming Page 57

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

public double getAmount()

return amount;

public void showTransaction()

Console.WriteLine("Transaction: {0}", tCode);

Console.WriteLine("Date: {0}", date);

Console.WriteLine("Amount: {0}", getAmount());

class Tester

static void Main(string[] args)

Transaction t1 = new Transaction("001",


"8/10/2012", 78900.00);

Transaction t2 = new Transaction("002",


"9/10/2012", 451900.00);

t1.showTransaction();
CS6001 C# and .Net programming Page 58

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

t2.showTransaction();

Console.ReadKey();

When the above code is compiled and executed, it produces the following

result:

Transaction: 001
Date: 8/10/2012
Amount: 78900
Transaction: 002
Date: 9/10/2012
Amount: 451900

CS6001 C# and .Net programming Page 59

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Abstract classes

Abstract classes, marked by the keyword abstract in the class


definition, are typically used to define a base class in the
hierarchy. What's special about them, is that you can't create an
instance of them - if you try, you will get a compile error. Instead,
you have to subclass them, as taught in the chapter on
inheritance, and create an instance of your subclass. So when do
you need an abstract class? It really depends on what you do.

To be honest, you can go a long way without needing an abstract


class, but they are great for specific things, like frameworks,
which is why you will find quite a bit of abstract classes within the
.NET framework it self. A good rule of thumb is that the name
actually makes really good sense - abstract classes are very
often, if not always, used to describe something abstract,
something that is more of a concept than a real thing.

In this example, we will create a base class for four legged


animals and then create a Dog class, which inherits from it, like
this:

namespace AbstractClasses
{
class Program
{
static void Main(string[] args)
{
Dog dog = new Dog();

CS6001 C# and .Net programming Page 60

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Console.WriteLine(dog.Describe());
Console.ReadKey();
}
}

abstract class FourLeggedAnimal


{
public virtual string Describe()
{
return "Not much is known about this
four legged animal!";
}
}

class Dog : FourLeggedAnimal


{

}
}
If you compare it with the examples in the chapter about
inheritance, you won't see a big difference. In fact, the abstract
keyword in front of the FourLeggedAnimal definition is the biggest
difference. As you can see, we create a new instance of the Dog
class and then call the inherited Describe() method from the
FourLeggedAnimal class. Now try creating an instance of the
FourLeggedAnimal class instead:

CS6001 C# and .Net programming Page 61

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

FourLeggedAnimal someAnimal = new


FourLeggedAnimal();
You will get this fine compiler error:

Cannot create an instance of the abstract class or interface


'AbstractClasses.FourLeggedAnimal'

Now, as you can see, we just inherited the Describe() method, but
it isn't very useful in it's current form, for our Dog class. Let's
override it:

class Dog : FourLeggedAnimal


{
public override string Describe()
{
return "This four legged animal is a
Dog!";
}
}
In this case, we do a complete override, but in some cases, you
might want to use the behavior from the base class in addition to
new functionality. This can be done by using the base keyword,
which refers to the class we inherit from:

abstract class FourLeggedAnimal


{
public virtual string Describe()
{
return "This animal has four legs.";

CS6001 C# and .Net programming Page 62

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

}
}

class Dog : FourLeggedAnimal


{
public override string Describe()
{
string result = base.Describe();
result += " In fact, it's a dog!";
return result;
}
}

CS6001 C# and .Net programming Page 63

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
SRI VIDYA COLLEGE OF ENGINEERING & TECHNOLOGY,VIRUDHUNAGRA COURSE MATERIAL (LECTURE NOTES)

Ref :

http://www.tutorialspoint.com/

http://www.c-sharpcorner.com/UploadFile/tusharkantagarwal/objectorientedcsharp11162005070743AM/objectorientedcsharp.aspx

CS6001 C# and .Net programming Page 64

Get useful study materials from www.rejinpaul.com


www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Web application development


The DOT NET (.NET) created by Microsoft is a software development platform focused on rapid application development (RAD), platform
independence and network transparency. DOT NET (.NET) is Microsoft's strategic initiative for server and desktop development for the next
decade. According to Microsoft, DOT NET (.NET) includes many technologies designed to facilitate rapid development of Internet and
intranet applications.

DOT NET (.NET) has brought new functionalities and tools to the application programming interface (API). These innovations allow
development of applications for both Windows and the web as well as components and services (web services). .NET provides a new
reflective, object-oriented API. .NET is designed to be sufficiently generic so that many different high-level languages can be compiled.

Shrigen Technologies has Expertise in .NET


Shrigen provides design, development and integration business solutions based on the DOT NET (.NET) platform. Our team of experienced
Microsoft certified DOT NET (.NET) architects, analysts and developers delivers a wide range of comprehensive solutions in the following
key areas.

 DOT NET (.NET) Desktop Application Development


 ASP.NET (Web) Application Development
 DOT NET (.NET) Software Product Development
 Migration of Web and Desktop Applications to DOT NET (.NET)
 Web Services Based DOT NET (.NET) Application Development
 Mobile applications based on DOT NET (.NET) Compact Framework

ASP.NET Web Forms


ASP.NET is a development framework for building web pages and web sites with HTML, CSS,
JavaScript and server scripting.

ASP.NET supports three different development models:


Web Pages, MVC (Model View Controller), and Web Forms.

What is Web Forms?


Web Forms is one of the 3 programming models for creating ASP.NET web sites and web
applications.

The other two programming models are Web Pages and MVC (Model, View, Controller).

Web Forms is the oldest ASP.NET programming model, with event driven web pages written as a
combination of HTML, server controls, and server code.

Web Forms are compiled and executed on the server, which generates the HTML that displays
the web pages.

Web Forms comes with hundreds of different web controls and web components to build user-
driven web sites with data access.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Visual Studio Express 2012/2010


Visual Studio Express is a free version of Microsoft Visual Studio.

Visual Studio Express is a development tool tailor made for Web Forms (and MVC).

Visual Studio Express contains:

 MVC and Web Forms


 Drag-and-drop web controls and web components
 A web server language (Razor using VB or C#)
 A web server (IIS Express)
 A database server (SQL Server Compact)
 A full web development framework (ASP.NET)

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Working With XML File in ASP.NET


Introduction

Extensible Markup Language (XML) strores and transports data. If we use a XML file to store
the data then we can do operations with the XML file directly without using the database.
The XML format is supported for all applications. It is independent of all software
applications and it is accessible by all applications. Here is an example that shows how to
insert the data into the XML file and how to retrieve the data from the XML file; also how to
bind the data into tha DataList using ASP.NET. For this the following procedure can be used.

Step 1: First start Visual Studio 2010 by clicking "File" -> "New" -> "Web Site..." then click
on "ASP.NET Web Site". Now write the following inline code that will design your web page.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<style type="text/css">
.style1
{
width: 40%;
border-style: solid;
border-width: 1px;
background-color:Silver;
height: 152px;
}
.style2
{
width: 295px;
}
.style3
{
width: 754px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<div>
<table class="style1">
<tr>
<td class="style2">
&nbsp;</td>
<td class="style3">
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Employee_Info
rmation</td>
</tr>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<tr>
<td class="style2">
Name:</td>
<td class="style3">
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Emp_Id:</td>
<td class="style3">
<asp:TextBox ID="TextBox2"runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td class="style2">
Qualification:</td>
<td class="style3">
<asp:DropDownList ID="DropDownList1" runat="server" Height="22px" Width
="132px">
<asp:ListItem>--SELECT--</asp:ListItem>
<asp:ListItem>MCA</asp:ListItem>
<asp:ListItem>BCA</asp:ListItem>
<asp:ListItem>MBA</asp:ListItem>
<asp:ListItem>BBA</asp:ListItem>
<asp:ListItem>BTech</asp:ListItem>
<asp:ListItem>MTech</asp:ListItem>
</asp:DropDownList>
</td>
</tr>
<tr>
<td class="style2">
&nbsp;</td>
<td class="style3">
<asp:Button ID="Button1" runat="server" Text="Submit" onclick="Button1_Cl
ick"/>
<asp:Button ID="Button2" runat="server" onclick="Button2_Click" Text="Sho
w"/>
</td>
</tr>
</table>
<asp:DataList ID="DataList1" runat="server" BackColor="#DEBA84" BorderColor="#D
EBA84"

BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2" GridLines="Both"


RepeatDirection="Horizontal"
style="margin-right: 32px">
<FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510"/>
<HeaderStyle BackColor="#A55129" Font-Bold="True"ForeColor="White"/>
<ItemStyle BackColor="#FFF7E7" ForeColor="#8C4510"/>
<SelectedItemStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White"/>
<ItemTemplate>
<hrsize=0 />

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Name:<%#DataBinder.Eval(Container.DataItem,"name")%><br/>

Emp_id:<%#DataBinder.Eval(Container.DataItem,"Emp_id")%></a><br/>
Qualification:<%#DataBinder.Eval(Container.DataItem,"Qualification")%><br/>
</ItemTemplate>
</asp:DataList>
<br />
</div>
</form>
</body>
</html>

The design will look as in the following image:

Step 2: Add a XML file by clicking "File" -> "Add new item" then click on "XML file". Name
this XML file Sample.xml. Put the following code in the XML file:

<?xml version="1.0"encoding="utf-8"?>
<EmployeeInformation>
</EmployeeInformation>

Step 3: After that add the following namespaces in the code behind:

using System.Data;
using System.Xml;

Step 4: Now write the following code in the code behind file:

public partial classDefault2 : System.Web.UI.Page


{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

{
//Bind xml data to datalist
BindDatalist();
}
}
private void BindDatalist()
{
XmlTextReader xmlreader =new XmlTextReader(Server.MapPath("Employee.xml"));
DataSet ds = newDataSet();
ds.ReadXml(xmlreader);
xmlreader.Close();
if (ds.Tables.Count != 0)
{
DataList1.DataSource = ds;
DataList1.DataBind();
}
else
{
DataList1.DataSource = null;
DataList1.DataBind();
}
}
}

Step 5: Write the following code in the click event of the submit button, so that the data
that is entered is stored in the XML File:

protected void Button1_Click(object sender, EventArgs e)


{
XmlDocument xmldoc =new XmlDocument();
xmldoc.Load(Server.MapPath("Employee.xml"));
BindDatalist();
}

Step 6: Write the following code in the click event of the show button. Now the data stored
in the XML file can be shown.

protected void Button2_Click(object sender, EventArgs e)


{
XmlDocument xmldoc =new XmlDocument();
xmldoc.Load(Server.MapPath("Employee.xml"));
XmlElement parentelement = xmldoc.CreateElement("Details");
XmlElement name = xmldoc.CreateElement("Name");
name.InnerText = TextBox1.Text;
XmlElement Emp_id = xmldoc.CreateElement("Emp_id");
Emp_id.InnerText = TextBox2.Text;
XmlElement Qualification = xmldoc.CreateElement("Qualification");
Qualification.InnerText = DropDownList1.SelectedItem.Text;
parentelement.AppendChild(name);
parentelement.AppendChild(Emp_id);
parentelement.AppendChild(Qualification);

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

xmldoc.DocumentElement.AppendChild(parentelement);
xmldoc.Save(Server.MapPath("Employee.xml"));
BindDatalist();
}

Step 7: Run your application by pressing F5. The output is:

Step 8 : See your sample.xml file, it will include the data that I entered at the run time like
this:

<?xmlversion="1.0"encoding="utf-8"?>
<EmployeeInformation>
<Details>
<Name>Richa</Name>
<Emp_id>1</Emp_id>
<Qualification>MCA</Qualification>
</Details>
</EmployeeInformation>

Summary: In this article I use a XML file so that the data is stored and retrieved in XML
using the Datalist in ASP.NET.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Parsing XML Files in .NET Using C#


Parsing XML files is an unglamorous task that can be time consuming and tricky. In the days
before .NET, programmers were forced to read XML as a text file line by line and then use string
functions and possibly regular expressions. This is a time-consuming and error-prone process,
and just not very much fun.

While I was writing .NET test automation that had test case data stored in XML files, I discovered
that the .NET Framework provides powerful new ways of parsing XML. But in conversations with
colleagues, I also discovered that there are a variety of opinions on which way of parsing XML
files is the best.

I set out to determine how many different ways there are to parse XML using .NET and to
understand the pros and cons of each technique. After some experimentation, I learned that
there are five fundamentally different ways to parse XML, and that the "best" method depends
both on the particular development situation you are in and on the style of programming you
prefer.

In the sections that follow, I will demonstrate how to parse a testCases.xml file using five
different techniques. Each technique is based on a different .NET Framework class and its
associated methods:

 XmlTextReader
 XmlDocument
 XPathDocument
 XmlSerializer
 DataSet

After I explain each technique so you can modify my examples to suit your needs, I will give you
guidance on which technique should be used in which situation. Knowing these five methods for
parsing XML files will be a valuable addition to your .NET skill set. I'm assuming that you're
familiar with C#, VS.NET, the creation and use of class libraries, and have a working knowledge
of XML files.

The XML File to Parse and the Goal

Let's examine the testCases.xml file that we will use for all five parsing examples. The file
contents are shown in Listing One.

Listing One: XML file to parse

?
1 <?xml version="1.0" encoding="utf-8" ?>

2 <suite>

4 <testcase id="001" kind="bvt">

5 <inputs>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

6 <arg1>4</arg1>

7 <arg2>7</arg2>

8 </inputs>

9 <expected>11.00</expected>

10 </testcase>

11

12 <testcase id="002" kind="drt">

13 <inputs>

14 <arg1>9</arg1>

15 <arg2>6</arg2>

16 </inputs>

17 <expected>15.00</expected>

18 </testcase>

19

20 <testcase id="003" kind="bvt">

21 <inputs>

22
<arg1>5</arg1>

<arg2>8</arg2>
23
</inputs>
24
<expected>13.00</expected>
25
</testcase>
26
<
27
/suite>
28

Note that each of the three test cases has five data items: id, kind, arg1,
arg2, andexpected. Some of the data is stored as XML attributes (id and kind),
and arg1 and arg2are stored as XML elements two levels deep relative to the root node
(suite). Extracting attribute data and dealing with nested elements are key tasks regardless of
which parsing strategy we use.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

The goal is to parse our XML test cases file and extract the data into memory in a form that we
can use easily. The memory structure we will use for four of the five parsing methods is shown in
Listing Two. (The method that employs an XmlSerializer object requires a slightly
different memory structure and will be presented later.)

Listing Two: CommonLib.dll definitions

?
1
using System;
2
using System.Collections;
3

4
namespace CommonLib
5
{
6
public class TestCase
7
{
8
public string id;
9
public string kind;
10
public string arg1;
11
public string arg2;
12 public string expected;
13 }
14

15 public class Suite


16 {
17 public ArrayList items = new ArrayList();

18 public void Display()

19 {

20 foreach (TestCase tc in items)

21 {

22 Console.Write(tc.id + " " + tc.kind + " " + tc.arg1 +


" ");
23

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

24 Console.WriteLine(tc.arg2 + " " + tc.expected);

25 }

26 }

27 } // class Suite

} // ns

Because four of the five techniques will use these definitions, for convenience we can put the
code in a .NET class library named "CommonLib." A TestCase object will hold the five data
parts of each test case, and a Suite object will hold a collection of TestCase objects and
provide a way to display it.

Once the XML data is parsed and stored, the result can be represented as shown in >Figure 1.
The data can now be easily accessed and manipulated.

Figure 1 XML data stored in memory

Parsing XML with XmlTextReader

Of the five ways to parse an XML file, the most traditional technique is to use
theXmlTextReader class. The example code is shown in Listing Three.

Listing Three: Parsing XML using XmlTextReader

?
1 using System;

2 using System.Xml;

3 using CommonLib;

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

5 namespace Run

6 {

7 class Class1

8 {

9 [STAThread]

10 static void Main(string[] args)

11 {

12 CommonLib.Suite s = new CommonLib.Suite();

13

14 XmlTextReader xtr = new


XmlTextReader("..\\..\\..\\..\\testCases.xml");
15
xtr.WhitespaceHandling = WhitespaceHandling.None;
16
xtr.Read(); // read the XML declaration node, advance to <suite> tag
17

18
while (!xtr.EOF) //load loop
19
{
20
if (xtr.Name == "suite" && !xtr.IsStartElement()) break;
21

22
while (xtr.Name != "testcase" || !xtr.IsStartElement() )
23
xtr.Read(); // advance to <testcase> tag
24

25
CommonLib.TestCase tc = new CommonLib.TestCase();
26
tc.id = xtr.GetAttribute("id");
27
tc.kind = xtr.GetAttribute("kind");
28
xtr.Read(); // advance to <inputs> tag
29
xtr.Read(); // advance to <arg1> tag
30
tc.arg1 = xtr.ReadElementString("arg1"); // consumes the </arg1> tag
31
tc.arg2 = xtr.ReadElementString("arg2"); // consumes the </arg2> tag

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

32 xtr.Read(); // advance to <expected> tag

33 tc.expected = xtr.ReadElementString("expected"); // consumes the


</expected> tag
34
// we are now at an </testcase> tag
35
s.items.Add(tc);
36
xtr.Read(); // and now either at <testcase> tag or </suite> tag
37
} // load loop
38

39
xtr.Close();
40
s.Display(); // show the suite of TestCases
41

42
} // Main()
43
} // class Class1
44
} // ns Run

After creating a new C# Console Application Project in Visual Studio .NET, we add a Project
Reference to the CommonLib.dll file that contains definitions
for TestCase and Suite classes. We start by creating a Suite object to hold the XML data
and an XmlTextReader object to parse the XML file.

The key to understanding this technique is to understand


the Read() andReadElementString() methods of XmlTextReader. To
an XmlTextReader object, an XML file is a sequence of nodes. For example,

?
1 <?xml version="1.0" ?>

2 <foo>

3 <bar>99</bar>

4 </foo>

has 6 nodes: the XML declaration, <foo>, <bar>, 99, </bar>, and </foo>.

The Read() method advances one node at a time. Unlike many Read() methods in other
classes, the System.XmlTextReader.Read() does not return significant data.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

TheReadElementString() method, on the other hand, returns the data between the
begin and end tags of its argument, and advances to the next node after the end tag. Because
XML attributes are not nodes, we have to extract attribute data using
the GetAttribute()method.

Figure 2 shows the output of running this program. You can see that we have successfully parsed
the data from testCases.xml into memory.

Figure 2 Output from the XmlTextReader technique

The statement xtr.WhitespaceHandling = WhitespaceHandling.None; is


important because without it you would have to Read() over newline characters and blank
lines.

The main loop control structure that I used is not elegant but is more readable than the
alternatives:

?
while (!xtr.EOF) //load loop
1
{
2
if (xtr.Name == "suite" && !xtr.IsStartElement())
3
break;

It exits when we are at EOF or an </suite> tag.

When marching through the XML file, you can either Read() your way one node at a time or
get a bit more sophisticated with code like the following:

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

?
1 while (xtr.Name != "testcase" || !xtr.IsStartElement() )

2 xtr.Read(); // advance to <testcase> tag

The choice of technique you use is purely a matter of style.

Parsing an XML file with XmlTextReader has a traditional, pre-.NET feel. You walk
sequentially through the file using Read(), and extract data
with ReadElementString() andGetAttribute(). Using XmlTextReader is
straightforward and effective and is appropriate when the structure of your XML file is relatively
simple and consistent. Compared to other techniques we will see in this
article, XmlTextReader operates at a lower level of abstraction, meaning it is up to you as a
programmer to keep track of where you are in the XML file andRead() correctly.

Parsing XML with XmlDocument

The second of five ways to parse an XML file is to use the XmlDocument class.
The example code is shown in Listing Four.

Listing Four: Parsing XML using XmlDocument


?
1 using System;

2 using System.Xml;

3 using CommonLib;

5 namespace Run

6 {

7 class Class1

8 {

9 [STAThread]

10 static void Main(string[] args)

11 {

12 CommonLib.Suite s = new CommonLib.Suite();

13

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

14 XmlDocument xd = new XmlDocument();

15 xd.Load("..\\..\\..\\..\\testCases.xml");

16

17 XmlNodeList nodelist = xd.SelectNodes("/suite/testcase"); // get all <testcase> nodes

18

19 foreach (XmlNode node in nodelist) // for each <testcase> node

20 {

21 CommonLib.TestCase tc = new CommonLib.TestCase();

22

23 tc.id = node.Attributes.GetNamedItem("id").Value;

24 tc.kind = node.Attributes.GetNamedItem("kind").Value;

25

26 XmlNode n = node.SelectSingleNode("inputs"); // get the one <input> node

27 tc.arg1 = n.ChildNodes.Item(0).InnerText;

28 tc.arg2 = n.ChildNodes.Item(1).InnerText;

29

30 tc.expected = node.ChildNodes.Item(1).InnerText;

31

32 s.items.Add(tc);

33 } // foreach <testcase> node

34

35 s.Display();

36

37 } // Main()

38 } // class Class1

39

40 } // ns Run

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

XmlDocument objects are based on the notion of XML nodes and child nodes.
Instead of sequentially navigating through a file, we select sets of nodes with
the SelectNodes()method or individual nodes with
the SelectSingleNode() method. Notice that because XML attributes are
not nodes, we must get their data with
an Attributes.GetNamedItem()method applied to a node.

After loading the XmlDocument, we fetch all the test case nodes at once with:

?
1 XmlNodeList nodelist = xd.SelectNodes("/suite/testcase");

Then we iterate through this list of nodes and fetch each <input> node with:

?
1 XmlNode n = node.SelectSingleNode("inputs");

and then extract the arg1 (and similarly arg2) value using:

?
1 tc.arg1 = n.ChildNodes.Item(0).InnerText;

In this statement, n is the <inputs> node; ChildNodes.Item(0) is the first


element of<inputs>, i.e., <arg1> and InnerText is the value
between <arg1> and </arg1>.

The output from running this program is shown in Figure 3. Notice it is identical to
the output from running the XmlTextReader technique and, in fact, all the
other techniques presented in this article.

Figure 3 Output from the XmlDocument technique

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

The XmlDocument class is modeled on the W3C XML Document Object Model
and has a different feel to it than many .NET Framework classes that you are
familiar with. Using theXmlDocument class is appropriate if you need to extract
data in a nonsequential manner, or if you are already
using XmlDocument objects and want to maintain a consistent look and feel to
your application's code.

Let me note that in discussions with my colleagues, there was often some confusion
about the role of the XmlDataDocument class. It is derived from
the XmlDocument class and is intended for use in conjunction
with DataSet objects. So, in this example, you could use
theXmlDataDocument class but would not gain anything.

Parsing XML with XPathDocument

The third technique to parse an XML file is to use the XPathDocument class.
The example code is shown in Listing Five.

Listing Five: Parsing XML using XPathDocument


1 using System;

2 using System.Xml.XPath;

3 using CommonLib;

5 namespace Run

6 {

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

7 class Class1

8 {

9 [STAThread]

10 static void Main(string[] args)

11 {

12 CommonLib.Suite s = new CommonLib.Suite();

13

14 XPathDocument xpd = new XPathDocument("..\\..\\..\\..\\testCases.xml");

15 XPathNavigator xpn = xpd.CreateNavigator();

16 XPathNodeIterator xpi = xpn.Select("/suite/testcase");

17

18 while (xpi.MoveNext()) // each testcase node

19 {

20 CommonLib.TestCase tc = new CommonLib.TestCase();

21 tc.id = xpi.Current.GetAttribute("id", xpn.NamespaceURI);

22 tc.kind = xpi.Current.GetAttribute("kind", xpn.NamespaceURI);

23

24 XPathNodeIterator tcChild =
xpi.Current.SelectChildren(XPathNodeType.Element);
25
while (tcChild.MoveNext()) // each part (<inputs> and <expected>) of <testcase>

26
{
27
if (tcChild.Current.Name == "inputs")
28
{
29
XPathNodeIterator tcSubChild =
30 tcChild.Current.SelectChildren(XPathNodeType.Element);

31 while (tcSubChild.MoveNext()) // each part (<arg1>, <arg2>) of <inputs>

32 {

33 if (tcSubChild.Current.Name == "arg1")

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

34 tc.arg1 = tcSubChild.Current.Value;

35 else if (tcSubChild.Current.Name == "arg2")

36 tc.arg2 = tcSubChild.Current.Value;

37 }

38 }

39 else if (tcChild.Current.Name == "expected")

40 tc.expected = tcChild.Current.Value;

41 }

42 s.items.Add(tc);

43

44 } // each testcase node

45

46 s.Display();

47

48 } // Main()

49 } // class Class1

50

} // ns Run

Using an XPathDocument object to parse XML has a hybrid feel that is part
procedural (as inXmlTextReader) and part functional (as in XmlDocument).
You can select parts of the document using the Select() method of
an XPathNavigator object and also move through the document using
the MoveNext() method of an XPathNodeIterator object.

After loading the XPathDocument object, we get what is in essence a reference


to the first <testcase> node into an XPathNodeIterator object with:

?
1 XPathNavigator xpn = xpd.CreateNavigator();

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

2 XPathNodeIterator xpi = xpn.Select("/suite/testcase");

Because XPathDocument does not maintain "node identity," we must iterate


through each<testcase> node with this loop:

?
1 while (xpi.MoveNext())

Similarly, we have to iterate through the children with:

?
1 while (tcChild.MoveNext())

The XPathDocument class is optimized for XPath data model queries. So using
it is particularly appropriate when the XML file to parse is deeply nested or has a
complex structure. You might also consider using XPathDocument if other parts
of your application code use that class so that you maintain a consistent coding look
and feel.

Parsing XML with XmlSerializer

The fourth technique we will use to parse an XML file is


the XmlSerializer object. The example code is shown in Listing Six.

Listing Six: Parsing XML using XmlSerializer


?
1 using System;

2 using System.Xml.Serialization;

3 using System.IO;

4 using SerializerLib; // defines a Suite class compatible with testCases.xml

6 namespace Run

7 {

8 class Class1

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

9 {

10 [STAThread]

11 static void Main(string[] args)

12 {

13 XmlSerializer xs = new XmlSerializer(typeof(Suite));

14 StreamReader sr = new
StreamReader("..\\..\\..\\..\\testCases.xml");
15
SerializerLib.Suite s =
16 (SerializerLib.Suite)xs.Deserialize(sr);

17 sr.Close();

18 s.Display();

19 }

20 } // class Class1

} // ns Run

Using the XmlSerializer class is significantly different from using any of the
other classes because the in-memory data store is different from the
CommonLib.Suite we used for all other examples. In fact, observe that pulling the
XML data into memory is accomplished in a single statement:

?
SerializerLib.Suite s =
1
(SerializerLib.Suite)xs.Deserialize(sr);

I created a class library named "SerializerLib" to hold the definition for


a Suite class that corresponds to the testCases.xml file so that
the XmlSerializer object can store the XML data into it. The trick, of course,
is to set up this Suite class.

Creating the Suite class is done with the help of the xsd.exe command-line tool.
You will find it in your Program Files\Microsoft Visual Studio
.NET\FrameworkSDK\bin folder. I used xsd.exe to generate a Suite class and
then modified it slightly by changing some names and adding
aDisplay() method.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

The screen shot in Figure 4 shows how I generated the file testCases.cs, which
contains aSuite definition that you can use directly or modify as I did. Listings
Seven and Eight show the classes generated by XSD and my modified classes in the
SerializerLib library.

Figure 4 Generating testCases.cs definitions using XSD

Listing Seven: XSD-generated suite definition


?
// This source code was auto-generated by xsd, Version=1.0.3705.288.
1
//
2
using System.Xml.Serialization;
3

4
[System.Xml.Serialization.XmlRootAttribute("suite", Namespace="",
5 IsNullable=false)]

6 public class suite {

7 [System.Xml.Serialization.XmlElementAttribute("testcase")]

8 public suiteTestcase[] Items;

9 }

10

11 public class suiteTestcase {

12 public string expected;

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

13 [System.Xml.Serialization.XmlElementAttribute("inputs")]

14 public suiteTestcaseInputs[] inputs;

15 [System.Xml.Serialization.XmlAttributeAttribute()]

16 public string id;

17 [System.Xml.Serialization.XmlAttributeAttribute()]

18 public string kind;

19 }

20

21 public class suiteTestcaseInputs {

22 public string arg1;

23 public string arg2;

24 }

Listing Eight: Modified suite definition


?
1 using System;

2 using System.Xml.Serialization;

4 namespace SerializerLib

5 {

6 [XmlRootAttribute("suite")]

7 public class Suite

8 {

9 [XmlElementAttribute("testcase")]

10 public TestCase[] items; // changed name from xsd-generated code

11 public void Display() // added to xsd-generated code

12 {

13 foreach (TestCase tc in items)

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

14 {

15 Console.Write(tc.id + " " + tc.kind + " " + tc.inputs.arg1


+ " ");
16
Console.WriteLine(tc.inputs.arg2 + " " + tc.expected);
17
}
18
}
19
}
20

21
public class TestCase // changed name from xsd-generated code

22
{
23
[XmlAttributeAttribute()]
24
public string id;
25
[XmlAttributeAttribute()]
26
public string kind;
27
[XmlElementAttribute("inputs")]
28
public Inputs inputs; // change from xsd-generated code: no array

29
public string expected;
30
}
31

32
public class Inputs // changed name from xsd-generated code

33
{
34
public string arg1;
35
public string arg2;
36
}
37
}

Using the XmlSerializer class gives a very elegant solution to the problem of
parsing an XML file. Compared with the other four techniques in this
article, XmlSerializer operates at the highest level of abstraction, meaning

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

that the algorithmic details are largely hidden from you. But this gives you less
control over the parsing and lends an air of magic to the process.

Most of the code I write is test automation, and using XmlSerializer is my


default technique for parsing XML. XmlSerializer is most appropriate for
situations not covered by the other four techniques in this article: fine-grained
control is not required, the application program does not use
other XmlDocument objects, the XML file is not deeply nested, and the
application is not primarily an ADO .NET application (as we will see in our next
example).

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

How To Create a Virtual Directory in


Internet Information Services (IIS)

Create Virtual Directories in IIS 5.0

1. Click Start, point to Programs, click to select Administrative Tools, and then click Internet Services Manager.
2. Expand the server name.

3. In the left pane, right-click Default Web Site, point to New, and then click Virtual Directory.
4. In the first screen of the Virtual Directory Creation Wizard, type an alias, or name, for the virtual directory (such
as MyWebData), and then click Next.
5. In the second screen, click Browse. Locate the content folder that you created to hold the content. Click Next.
6. In the third screen, click to select Read and Run scripts (such as ASP). Make sure that the other check boxes
are cleared. Click Finish to complete the wizard.
7. For ASP content, you may want to confirm that an application was created. To do this, right-click the new virtual
directory, and then click Properties.
8. On the Virtual Directory tab, make sure that the virtual directory name is listed in the Application Name box
under Application Settings. If it is not, click Create. Note that the application name does not have to match
the virtual directory alias.
9. Close the Properties dialog box.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Creating virtual directories and application pools


in IIS 7.5 and 7.0
To create a virtual directory:

1. Open IIS Manager

 On Windows 7: Open Start -> Control Panel -> System and Security category -> Administrative
Tools -> Internet Information Services (IIS) Manager.
 On Windows Server 2008 or Windows Vista: Open Start -> Control Panel -> System and
Maintenance category -> Administrative Tools ->Internet Information Services (IIS) Manager.

2. Expand local computer -> Sites -> right-click on Default Web Site (or other website if you're
running multiple websites on the same computer) and choose Add Virtual Directory...

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 An Add Virtual Directory dialog appears.

3. Enter the Virtual Directory Alias. If you want the website to run
as http://localhost/KenticoCMSDemo, enter alias KenticoCMSDemo.

4. Type a path or browse to the physical directory that contains the chosen directory.

5. Click OK.

 The system creates a new virtual directory.

6. Right-click the virtual directory and choose Convert to Application.

 An Add Application dialog appears.

7.Click Select... and choose the ASP.NET v4.0 application pool from the drop-down menu.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

8. Click OK.

The system converts the virtual directory to an application.

Alternatively, you can create an application in one step by right-clicking a web site and
choosing Add Application... and filling the required information in the Add Application dialog as
mentioned above.

Configuring application pools in IIS 7 and IIS 7.5


Application Pools provide you with additional level of website management. They are supported only
by Windows Server 2003/2008/Vista/7. You can configure them in the Internet Information
Services (IIS) Manager under local computer -> Application Pools.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

You can check and change the assigned application pool by right-clicking an application under local
computer -> Sites -> Default Web Site (or other web site) and selecting Manage Application ->
Advanced Settings...

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

You can set the Recycling and other options by right-clicking on an application pool under local
computer -> Application Pools and selecting Advanced Settings....

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Recommended Application Pool Configuration

 It's highly recommended that you run Kentico in a separate application pool. If you share the pool
with other websites, the system may behave unpredictably.
 We do not recommend to run multiple websites in a single pool.
 It's recommended that you specify some value in the Recycle worker processes on
the Recycling tab. This value shouldn't be too short (less than60 minutes) or too long (more
than 1440 minutes/1 day). Setting this value ensures that the memory is recycled and the
application is automatically recovered from failures by regular restart. If your website
freezes time to time, you can temporarily set the value to 30 minutes to ensure that the website is
restarted automatically. Short intervals may lead to high server load and slow response since after
each recycling, the application needs to be restarted and data reloaded to the cache.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 It's recommended that you do not limit the maximum virtual or used memory. If you need to use
some value, use at least 100 MB. If your website is being restarted too often, it may be caused by
low maximum memory limit. You can check the frequency of application restarts in KenticoEvent log.
 The Maximum number of worker processes on the Performance tab must be set to 1. If you set a
higher value, the worker processes will not be synchronized and Kentico website will not work
correctly. This may lead to unexpected caching of content and system objects.
 You can configure the user account under which the application runs on the Identity tab. This
information is useful if you need to troubleshoot issues with permissions, such as disk write
permissions.
 Kentico does not support Web garden. Therefore, the Maximum number of worker
processes has to be set to 1.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Understanding Session Management


Techniques in ASP.NET

Introduction
In this article we will try to see what are the different ways we can manage
sessions in an ASP.NET application. When should we use which techniques and
what are the pros and cons of using each technique.

Background
The basic stateless nature of web sites and web applications are rather very
confusing to anyone who is starting with web development. ASP.NET provides
various ways of handling the states. The basic overview of all the state
management techniques can be found here.

In this article we will specifically be discussing the Session management


techniques. Session are the server side method of managing the state of an
application i.e. all the web applications' state related info will be stored on server
side if we use this technique. The benefit of having this technique is that since we
are keeping all the state related information on server, the request and response
becomes lightweight. Also, the chances of someone intercepting or changing this
data is also reduced. But this technique does involve more resource usage on the
server.

The advantages of using Session State are

 Better security
 Reduced bandwidth

The disadvantages of using Session state are

 More resource consumption of server.


 Extra code/care if a Web farm is used(we will discuss this shortly)

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Let us start looking into how we can use the Session state in our application and
see how we can configure it to use various techniques.

Getting to know the Players


Using Session State

ASP.NET allows us to save values using Session state. It is a global storage


mechanism that is accessible from all pages in the Web application. Session state
is stored in the Session key/value dictionary. This information will be user
specific i.e. for each user separate dictionary will be created and no one can
access other session information. below is the Example usage of sessions.

Hide Copy Code

//global.asax
void Session_Start(object sender, EventArgs e)
{
// Code that runs when a new session is started
Session["number"] = 0;
}

// Web forms
Session["number"] = Convert.ToInt32(Session["number"]) + 1;

Label6.Text = Session["number"].ToString();s

Enumerating Session Management Techniques

Before we proceed, let us see what all session management techniques are
present in the ASP.NET framework.

 In-Proc.
 SQLServer.
 StateServer.

How to configure Sessions


To configure the session management we need to specify the settings in
the web.config file. Typical settings inweb.config looks like:

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Hide Copy Code

<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>

Let us see what each of these attributes mean.

This specifies the type of session management we want


mode
to use. it could be InProc,SQLServer, and StateServer

If we use StateServer as session management technique


stateConnectionStringthen this specifies the location of the server that is
handling the session data.

If we use SQLServer as session management technique


sqlConnectionString then this specifies the databaseconnectionstring that will
store the session data.

This specifies whether we will be using cookies to identify


cookieless sessions or we want session info appended in URL. It
could be true or false.

This specifies the time for which the session should be


timeout active. after this much time of inactivity the session will
expire.

Single server vs Web Farm

Website require a hosting server. If we have a high traffic website then to


improve the performance we might choose to have multiple web servers. In case
we want multiple web servers(Web Farm), We need to have all the requests
handled at a single point i.e. a Load Balancer. The Load Balancer will accept all the
requests and forward it to appropriate server(based on load on server and some
other criteria)

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Single server

Setup with a Load Balancer

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Note: Why is this relevant will become clear in some time.

Configuring the Session Modes


Using In-Proc Session Mode

If we are using In-Proc session handling then all the session information will be
stored in the server memory. This is the default session state in ASP.NET.

This approach works fine as long as we are keeping small session information.
Since the memory location was handled by the ASP.NET worker thread only it
involves a considerable overhead for the worker thread to manage these. Also,
since this is in the memory of server, chances are that large session information
would lead to more memory usage and thus lowering the performance.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Let us try to visualize this session management technique.

To configure the In-Proc session management we need to specify


the sessionState element in theweb.config file. let us see how to configure
the in-proc sessions

Hide Copy Code

<sessionState mode="InProc"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>

The only relevant options for In_proc session mode in this configuration elements
are the mode(which specifies that we are using In_proc sessions), the cookieless(if
true, will use to manage sessions otherwise append session management data in
the URL) and timeout(the time after which the session should expire.

It is advisable to use the In-Proc sessions when we want very small amount of
information in the sessions. Since the session data is stored in the memory of
computer which is directly accessible by ASP.NET worker thread nothing extra
needs to be done.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

The problem with In-Proc mode session mode is that if the size of session data
becomes large then it effects performance. Also, since the session data is in
memory of server the application restart(ASP.NET) will effectively flush all the
data.

In-Proc sessions in Web Farm scenario

As we have discussed above the web farm will have a load balancer accepting all
the requests. It will then forward the request to any server based on some criteria.
Lets try to see a scenario which could create problems for us if we are using In-
Proc sessions.

Problem Scenario

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

1. The request from Computer1 reaches the load balancer and load balancer forwards
it to server1.
2. The In-Proc session led the session data created in the server1's memory.
3. The next request comes from Computer1 and this time load balancer pushes it
to Server2.
4. Since the server1 had this user specific data in its memory server2 will not be able
to recognize this request leading to failure of our application logic.

So what should we do to tackle this situation. The whole problem was because
each server in our web form was keeping the session data in their own memory. If
we could somehow move this data from each server memory to a centralized
location then we will not face this problem. And that is where
the SQLServer and stateServercomes to rescue. using these two approaches we
can easily configure a central repository to store session data.

Note: There could still be some reasons(explained below) which will force you to
use In-Proc sessions in a Web farm scenario. If this is the case then the load
balancer should be configured to maintain connection affinity or sticky
sessions so that the requests coming from a particular client will always be
forwarded to the same server so that the session information can always be
found.

Using SQLServer Session Mode

If we use the SqlServer mode of session management then the session data will
be stored in the SqlServer. The benefit of having this scenario is that the data is
stored in a centralized database rather than the server memory. Let us see how
this can be configured from web.config

Hide Copy Code

<sessionState mode="SQLServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>

Apart from this the SQLServer also needs to be configured to store the session
data. To do that simply typeaspnet_regsql on Visual studio command prompt and

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

a configuration wizard will open. Here we can configure the SqlServer to cater
the session data. The demo project has sqlexpress in local machine configured
for this. To run the application, you will have to configure the sqlserver on local
machine and perhaps change the web.config of the website.

Note: I have given cursory step by step guide to configure SqlServer because I
want to keep this article at conceptual level rather than becoming a "How
To" guide.

This way the server memory is not affected by the size of session data. Also, if we
have a web farm then we can don't find any problem in using session data as the
session data is in a central location. lets try to visualize this scenario

Using this mode will only involve the overhead of additional database access to
retrieve the session data. But there is one important aspect to remember when
we are planning to use this technique. We need to send and receive the data to
a SqlServer database, which will be a separate server. To successfully send and

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

receive the data toSqlServer all the data that is being kept in the Session has to
be serializable. This sometimes becomes a very big issue when an application is
being ported to web farm from a single server. That is where the load balancer's
connection affinity will come in picture with In-Proc sessions.

Using StateServer Session Mode

If we use the StateServer mode of session management then the session data
will be stored in a separate computer(server) and the session data will be handled
by a windows service. The benefit of having this scenario is that the data is stored
in a centralized location i.e. a state server rather than the individual server
memory. Let us see how this can be configured from web.config

Hide Copy Code

<sessionState mode="StateServer"
stateConnectionString="tcpip=127.0.0.1:42424"
sqlConnectionString="Data Source=.\SQLEXPRESS;Trusted_Connection=Yes;"
cookieless="false"
timeout="100"/>

Apart from this the Server that will be used as state server also needs to be
configured to store the session data. To do that simply run the service
named ASP.NET state service to enable the desired Server to cater the session
data. The demo project does the same on local machine configured for this. To
run the application, you will have to run the service on local machine and perhaps
change the web.config of the website.

Note: I have given cursory step by step guide to configure state server on local
machine because I want to keep this article at conceptual level rather than
becoming a "How To" guide.

This way the server memory is not affected by the size of session data. Also, if we
have a web farm then we can don't find any problem in using session data as the
session data is in a central location. lets try to visualize this scenario

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Using this mode will only involve the overhead of network latency to retrieve the
session data. But there is one important aspect to remember when we are
planning to use this technique. We need to send and receive the data to a state
server. To successfully send and receive the data to the state server all the data
that is being kept in the Session has to be serializable. This sometimes becomes
a very big issue when an application is being ported to web farm from a single
server. That is where the load balancer's connection affinity will come in picture
with In-Proc sessions.

Using the code


The test application contains 3 web sites with single page each. functionality wise
all the web sites are doing the same thing but each of then is using a different
session management technique.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

To run all three websites the Sqlserver on local machine has to be configured to
store session specific data(details above in the respective category) and the
ASP.NET state service should be running on local machine. Also,
the connectionstring will have to be modified accordingly to use the database on
the running computer.

Note: Please refer the web.config of each website to get the subtle difference.

The application while running will look like:

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

WHAT IS A WEB.CONFIG FILE?


A web.config file lets you customize the way your site or a specific
directory on your site behaves. For example, if you place a web.config
file in your root directory, it will affect your entire site
(www.coolexample.com). If you place it in a /content directory, it will
only affect that directory (www.coolexample.com/content). However, in
order for a web.config file to register in a specific directory, there must
be a web.config file in the root directory.

web.config files work on our Windows servers.

Using a web.config file, you can control:

 Database connection strings.

 Error behavior.

 Security.

ASP.NET - Configuration
The behavior of an ASP.NET application is affected by different settings in
the configuration files:

 machine.config

 web.config

The machine.config file contains default and the machine-specific value for
all supported settings. The machine settings are controlled by the system
administrator and applications are generally not given access to this file.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

An application however, can override the default values by creating


web.config files in its roots folder. The web.config file is a subset of the
machine.config file.

If the application contains child directories, it can define a web.config file for
each folder. Scope of each configuration file is determined in a hierarchical
top-down manner.

Any web.config file can locally extend, restrict, or override any settings
defined on the upper level.

Visual Studio generates a default web.config file for each project. An


application can execute without a web.config file, however, you cannot
debug an application without a web.config file.

The following figure shows the Solution Explorer for the sample example
used in the web services tutorial:

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

In this application, there are two web.config files for two projects i.e., the
web service and the web site calling the web service.

The web.config file has the configuration element as the root node.
Information inside this element is grouped into two main areas: the
configuration section-handler declaration area, and the configuration section
settings area.

The following code snippet shows the basic syntax of a configuration file:

<configuration>

<!-- Configuration section-handler declaration area. -->

<configSections>

<section name="section1" type="section1Handler" />

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<section name="section2" type="section2Handler" />

</configSections>

<!-- Configuration section settings area. -->

<section1>

<s1Setting1 attribute1="attr1" />

</section1>

<section2>

<s2Setting1 attribute1="attr1" />

</section2>

<system.web>

<authentication mode="Windows" />

</system.web>

</configuration>

Configuration Section Handler declarations


The configuration section handlers are contained within the
<configSections> tags. Each configuration handler specifies name of a
configuration section, contained within the file, which provides some
configuration data. It has the following basic syntax:

<configSections>

<section />

<sectionGroup />

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<remove />

<clear/>

</configSections>

It has the following elements:

 Clear - It removes all references to inherited sections and


section groups.

 Remove - It removes a reference to an inherited section and


section group.

 Section - It defines an association between a configuration


section handler and a configuration element.

 Section group - It defines an association between a


configuration section handler and a configuration section.

Application Settings
The application settings allow storing application-wide name-value pairs for
read-only access. For example, you can define a custom application setting
as:

<configuration>

<appSettings>

<add key="Application Name" value="MyApplication" />

</appSettings>

</configuration>

For example, you can also store the name of a book and its ISBN number:

<configuration>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<appSettings>

<add key="appISBN" value="0-273-68726-3" />

<add key="appBook" value="Corporate Finance" />

</appSettings>

</configuration>

Connection Strings
The connection strings show which database connection strings are
available to the website. For example:

<connectionStrings>

<add name="ASPDotNetStepByStepConnectionString"

connectionString="Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=E:\\projects\datacaching\ /

datacaching\App_Data\ASPDotNetStepByStep.mdb"

providerName="System.Data.OleDb" />

<add name="booksConnectionString"

connectionString="Provider=Microsoft.Jet.OLEDB.4.0;

Data Source=C:\ \databinding\App_Data\books.mdb"

providerName="System.Data.OleDb" />

</connectionStrings>

System.Web Element
The system.web element specifies the root element for the ASP.NET
configuration section and contains configuration elements that configure
ASP.NET Web applications and control how the applications behave.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

It holds most of the configuration elements needed to be adjusted in


common applications. The basic syntax for the element is as given:

<system.web>

<anonymousIdentification>

<authentication>

<authorization>

<browserCaps>

<caching>

<clientTarget>

<compilation>

<customErrors>

<deployment>

<deviceFilters>

<globalization>

<healthMonitoring>

<hostingEnvironment>

<httpCookies>

<httpHandlers>

<httpModules>

<httpRuntime>

<identity>

<machineKey>

<membership>

<mobileControls>

<pages>

<processModel>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<profile>

<roleManager>

<securityPolicy>

<sessionPageState>

<sessionState>

<siteMap>

<trace>

<trust>

<urlMappings>

<webControls>

<webParts>

<webServices>

<xhtmlConformance>

</system.web>

The following table provides brief description of some of common sub


elements of the system.web element:

AnonymousIdentification
This is required to identify users who are not authenticated when
authorization is required.

Authentication
It configures the authentication support. The basic syntax is as given:

<authentication mode="[Windows|Forms|Passport|None]">

<forms>...</forms>

<passport/>

</authentication>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Authorization
It configures the authorization support. The basic syntax is as given:

<authorization>

<allow .../>

<deny .../>

</authorization>

Caching
It Configures the cache settings. The basic syntax is as given:

<caching>

<cache>...</cache>

<outputCache>...</outputCache>

<outputCacheSettings>...</outputCacheSettings>

<sqlCacheDependency>...</sqlCacheDependency>

</caching>

CustomErrors
It defines custom error messages. The basic syntax is as given:

<customErrors defaultRedirect="url" mode="On|Off|RemoteOnly">

<error. . ./>

</customErrors>

Deployment
It defines configuration settings used for deployment. The basic syntax is as
follows:

<deployment retail="true|false" />

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

HostingEnvironment
It defines configuration settings for hosting environment. The basic syntax
is as follows:

<hostingEnvironment idleTimeout="HH:MM:SS"
shadowCopyBinAssemblies="true|false"

shutdownTimeout="number" urlMetadataSlidingExpiration="HH:MM:SS" />

Identity
It configures the identity of the application. The basic syntax is as given:

<identity impersonate="true|false" userName="domain\username"

password="<secure password>"/>

MachineKey
It configures keys to use for encryption and decryption of Forms
authentication cookie data.

It also allows configuring a validation key that performs message


authentication checks on view-state data and forms authentication tickets.
The basic syntax is:

<machineKey validationKey="AutoGenerate,IsolateApps" [String]

decryptionKey="AutoGenerate,IsolateApps" [String]

validation="HMACSHA256" [SHA1 | MD5 | 3DES | AES | HMACSHA256 |

HMACSHA384 | HMACSHA512 | alg:algorithm_name]

decryption="Auto" [Auto | DES | 3DES | AES | alg:algorithm_name]

/>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Membership
This configures parameters of managing and authenticating user accounts.
The basic syntax is:

<membership defaultProvider="provider name"

userIsOnlineTimeWindow="number of minutes" hashAlgorithmType="SHA1">

<providers>...</providers>

</membership>

Pages
It provides page-specific configurations. The basic syntax is:

<pages asyncTimeout="number" autoEventWireup="[True|False]"

buffer="[True|False]" clientIDMode="[AutoID|Predictable|Static]"

compilationMode="[Always|Auto|Never]"

controlRenderingCompatibilityVersion="[3.5|4.0]"

enableEventValidation="[True|False]"

enableSessionState="[True|False|ReadOnly]"

enableViewState="[True|False]"

enableViewStateMac="[True|False]"

maintainScrollPositionOnPostBack="[True|False]"

masterPageFile="file path"

maxPageStateFieldLength="number"

pageBaseType="typename, assembly"

pageParserFilterType="string"

smartNavigation="[True|False]"

styleSheetTheme="string"

theme="string"

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

userControlBaseType="typename"

validateRequest="[True|False]"

viewStateEncryptionMode="[Always|Auto|Never]" >

<controls>...</controls>

<namespaces>...</namespaces>

<tagMapping>...</tagMapping>

<ignoreDeviceFilters>...</ignoreDeviceFilters>

</pages>

Profile
It configures user profile parameters. The basic syntax is:

<profile enabled="true|false" inherits="fully qualified type reference"

automaticSaveEnabled="true|false" defaultProvider="provider name">

<properties>...</properties>

<providers>...</providers>

</profile>

RoleManager
It configures settings for user roles. The basic syntax is:

<roleManager cacheRolesInCookie="true|false" cookieName="name"

cookiePath="/" cookieProtection="All|Encryption|Validation|None"

cookieRequireSSL="true|false " cookieSlidingExpiration="true|false "

cookieTimeout="number of minutes" createPersistentCookie="true|false"

defaultProvider="provider name" domain="cookie domain">

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

enabled="true|false"

maxCachedResults="maximum number of role names cached"

<providers>...</providers>

</roleManager>

SecurityPolicy
It configures the security policy. The basic syntax is:

<securityPolicy>

<trustLevel />

</securityPolicy>

UrlMappings
It defines mappings to hide the original URL and provide a more user
friendly URL. The basic syntax is:

<urlMappings enabled="true|false">

<add.../>

<clear />

<remove.../>

</urlMappings>

WebControls
It provides the name of shared location for client scripts. The basic syntax
is:

<webControls clientScriptsLocation="String" />

WebServices
This configures the web services.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Web Services Tutorial


Web services are open standard (XML, SOAP, HTTP etc.) based Web
applications that interact with other web applications for the purpose of
exchanging data.

Web Services can convert your existing applications into Web-applications.

In this tutorial you will learn what exactly Web Services are and Why and
How to use them.

Audience
This tutorial will be useful for all those readers inclined to learn the basics of
web services and implement them in practice.

Prerequisites
This is an elementary tutorial that introduces the concepts of web services.
It does not require the readers to have a prior knowledge of any technology
in particular, however it would certainly make you comfortable if you have a
basic understanding of XML, HTTP, TCP/IP concepts.

What are Web Services?


Different books and different organizations provide different definitions to
Web Services. Some of them are listed here.

 A web service is any piece of software that makes itself available


over the internet and uses a standardized XML messaging
system. XML is used to encode all communications to a web
service. For example, a client invokes a web service by sending
an XML message, then waits for a corresponding XML response.
As all communication is in XML, web services are not tied to any

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

one operating system or programming language--Java can talk


with Perl; Windows applications can talk with Unix applications.

 Web services are self-contained, modular, distributed, dynamic


applications that can be described, published, located, or
invoked over the network to create products, processes, and
supply chains. These applications can be local, distributed, or
web-based. Web services are built on top of open standards
such as TCP/IP, HTTP, Java, HTML, and XML.

 Web services are XML-based information exchange systems that


use the Internet for direct application-to-application interaction.
These systems can include programs, objects, messages, or
documents.

 A web service is a collection of open protocols and standards


used for exchanging data between applications or systems.
Software applications written in various programming languages
and running on various platforms can use web services to
exchange data over computer networks like the Internet in a
manner similar to inter-process communication on a single
computer. This interoperability (e.g., between Java and Python,
or Windows and Linux applications) is due to the use of open
standards.

To summarize, a complete web service is, therefore, any service that:

 Is available over the Internet or private (intranet) networks

 Uses a standardized XML messaging system

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 Is not tied to any one operating system or programming


language

 Is self-describing via a common XML grammar

 Is discoverable via a simple find mechanism

Components of Web Services


The basic web services platform is XML + HTTP. All the standard web
services work using the following components

 SOAP (Simple Object Access Protocol)

 UDDI (Universal Description, Discovery and Integration)

 WSDL (Web Services Description Language)

All these components have been discussed in the Web Services


Architecturechapter.

How Does a Web Service Work?


A web service enables communication among various applications by using
open standards such as HTML, XML, WSDL, and SOAP. A web service takes
the help of:

 XML to tag the data

 SOAP to transfer a message

 WSDL to describe the availability of service.

You can build a Java-based web service on Solaris that is accessible from
your Visual Basic program that runs on Windows.

You can also use C# to build new web services on Windows that can be
invoked from your web application that is based on JavaServer Pages (JSP)
and runs on Linux.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Example
Consider a simple account-management and order processing system. The
accounting personnel use a client application built with Visual Basic or JSP
to create new accounts and enter new customer orders.

The processing logic for this system is written in Java and resides on a
Solaris machine, which also interacts with a database to store information.

The steps to perform this operation are as follows:

 The client program bundles the account registration information


into a SOAP message.

 This SOAP message is sent to the web service as the body of an


HTTP POST request.

 The web service unpacks the SOAP request and converts it into a
command that the application can understand.

 The application processes the information as required and


responds with a new unique account number for that customer.

 Next, the web service packages the response into another SOAP
message, which it sends back to the client program in response
to its HTTP request.

 The client program unpacks the SOAP message to obtain the


results of the account registration process.

Why Web Services?


Here are the benefits of using Web Services:

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Exposing the Existing Function on the network


A web service is a unit of managed code that can be remotely invoked using
HTTP, that is, it can be activated using HTTP requests. Web services allows
you to expose the functionality of your existing code over the network.
Once it is exposed on the network, other application can use the
functionality of your program.

Interoperability
Web services allow various applications to talk to each other and share data
and services among themselves. Other applications can also use the web
services. For example, a VB or .NET application can talk to Java web
services and vice versa. Web services are used to make the application
platform and technology independent.

Standardized Protocol
Web services use standardized industry standard protocol for the
communication. All the four layers (Service Transport, XML Messaging,
Service Description, and Service Discovery layers) use well-defined
protocols in the web services protocol stack. This standardization of protocol
stack gives the business many advantages such as a wide range of choices,
reduction in the cost due to competition, and increase in the quality.

Low Cost of Communication


Web services use SOAP over HTTP protocol, so you can use your existing
low-cost internet for implementing web services. This solution is much less
costly compared to proprietary solutions like EDI/B2B. Besides SOAP over
HTTP, web services can also be implemented on other reliable transport
mechanisms like FTP.

Web Services - Characteristics


Web services have the following special behavioral characteristics:

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

XML-Based
Web Services uses XML at data representation and data transportation
layers. Using XML eliminates any networking, operating system, or platform
binding. Web Services based applications are highly interoperable
application at their core level.

Loosely Coupled
A consumer of a web service is not tied to that web service directly. The
web service interface can change over time without compromising the
client's ability to interact with the service. A tightly coupled system implies
that the client and server logic are closely tied to one another, implying that
if one interface changes, the other must be updated. Adopting a loosely
coupled architecture tends to make software systems more manageable and
allows simpler integration between different systems.

Coarse-Grained
Object-oriented technologies such as Java expose their services through
individual methods. An individual method is too fine an operation to provide
any useful capability at a corporate level. Building a Java program from
scratch requires the creation of several fine-grained methods that are then
composed into a coarse-grained service that is consumed by either a client
or another service.

Businesses and the interfaces that they expose should be coarse-grained.


Web services technology provides a natural way of defining coarse-grained
services that access the right amount of business logic.

Ability to be Synchronous or Asynchronous


Synchronicity refers to the binding of the client to the execution of the
service. In synchronous invocations, the client blocks and waits for the
service to complete its operation before continuing. Asynchronous
operations allow a client to invoke a service and then execute other
functions.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Asynchronous clients retrieve their result at a later point in time, while


synchronous clients receive their result when the service has completed.
Asynchronous capability is a key factor in enabling loosely coupled systems.

Supports Remote Procedure Calls(RPCs)


Web services allow clients to invoke procedures, functions, and methods on
remote objects using an XML-based protocol. Remote procedures expose
input and output parameters that a web service must support.

Component development through Enterprise JavaBeans (EJBs) and .NET


Components has increasingly become a part of architectures and enterprise
deployments over the past couple of years. Both technologies are
distributed and accessible through a variety of RPC mechanisms.

A web service supports RPC by providing services of its own, equivalent to


those of a traditional component, or by translating incoming invocations
into an invocation of an EJB or a .NET component.

Supports Document Exchange


One of the key advantages of XML is its generic way of representing not
only data, but also complex documents. These documents can be as simple
as representing a current address, or they can be as complex as
representing an entire book or Request for Quotation (RFQ). Web services
support the transparent exchange of documents to facilitate business
integration.

Web Services - Architecture


There are two ways to view the web service architecture:

 The first is to examine the individual roles of each web service


actor.

 The second is to examine the emerging web service protocol


stack.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Web Service Roles


There are three major roles within the web service architecture:

Service Provider
This is the provider of the web service. The service provider implements the
service and makes it available on the Internet.

Service Requestor
This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML request.

Service Registry
This is a logically centralized directory of services. The registry provides a
central place where developers can publish new services or find existing
ones. It therefore serves as a centralized clearing house for companies and
their services.

Web Service Protocol Stack


A second option for viewing the web service architecture is to examine the
emerging web service protocol stack. The stack is still evolving, but
currently has four main layers.

Service Transport
This layer is responsible for transporting messages between applications.
Currently, this layer includes Hyper Text Transport Protocol (HTTP), Simple
Mail Transfer Protocol (SMTP), File Transfer Protocol (FTP), and newer
protocols such as Blocks Extensible Exchange Protocol (BEEP).

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

XML Messaging
This layer is responsible for encoding messages in a common XML format so
that messages can be understood at either end. Currently, this layer
includes XML-RPC and SOAP.

Service Description
This layer is responsible for describing the public interface to a specific web
service. Currently, service description is handled via the Web Service
Description Language (WSDL).

Service Discovery
This layer is responsible for centralizing services into a common registry
and providing easy publish/find functionality. Currently, service discovery is
handled via Universal Description, Discovery, and Integration (UDDI).

As web services evolve, additional layers may be added and additional


technologies may be added to each layer.

The next chapter explains the components of web services.

Few Words about Service Transport


The bottom of the web service protocol stack is service transport. This layer
is responsible for actually transporting XML messages between two
computers.

Hyper Text Transfer Protocol (HTTP)


Currently, HTTP is the most popular option for service transport. HTTP is
simple, stable, and widely deployed. Furthermore, most firewalls allow HTTP
traffic. This allows XML-RPC or SOAP messages to masquerade as HTTP
messages. This is good if you want to integrate remote applications, but it
does raise a number of security concerns.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Blocks Extensible Exchange Protocol (BEEP)


This is a promising alternative to HTTP. BEEP is a new Internet Engineering
Task Force (IETF) framework for building new protocols. BEEP is layered
directly on TCP and includes a number of built-in features, including an
initial handshake protocol, authentication, security, and error handling.
Using BEEP, one can create new protocols for a variety of applications,
including instant messaging, file transfer, content syndication, and network
management.

SOAP is not tied to any specific transport protocol. In fact, you can use
SOAP via HTTP, SMTP, or FTP. One promising idea is therefore to use SOAP
over BEEP.

Web Services - Components


Over the past few years, three primary technologies have emerged as
worldwide standards that make up the core of today's web services
technology. These technologies are discussed below.

XML-RPC
This is the simplest XML-based protocol for exchanging information between
computers.

 XML-RPC is a simple protocol that uses XML messages to perform


RPCs.

 Requests are encoded in XML and sent via HTTP POST.

 XML responses are embedded in the body of the HTTP response.

 XML-RPC is platform-independent.

 XML-RPC allows diverse applications to communicate.

 A Java client can speak XML-RPC to a Perl server.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 XML-RPC is the easiest way to get started with web services.

To learn more about XML-RPC, visit our XML-RPC Tutorial .

SOAP
SOAP is an XML-based protocol for exchanging information between
computers.

 SOAP is a communication protocol.

 SOAP is for communication between applications.

 SOAP is a format for sending messages.

 SOAP is designed to communicate via Internet.

 SOAP is platform independent.

 SOAP is language independent.

 SOAP is simple and extensible.

 SOAP allows you to get around firewalls.

 SOAP will be developed as a W3C standard.

To learn more about SOAP, visit our SOAP Tutorial.

WSDL
WSDL is an XML-based language for describing web services and how to
access them.

 WSDL stands for Web Services Description Language.

 WSDL was developed jointly by Microsoft and IBM.

 WSDL is an XML based protocol for information exchange in


decentralized and distributed environments.

 WSDL is the standard format for describing a web service.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 WSDL definition describes how to access a web service and what


operations it will perform.

 WSDL is a language for describing how to interface with XML-


based services.

 WSDL is an integral part of UDDI, an XML-based worldwide


business registry.

 WSDL is the language that UDDI uses.

 WSDL is pronounced as 'wiz-dull' and spelled out as 'W-S-D-L'.

To learn more about WSDL, visit our WSDL Tutorial.

UDDI
UDDI is an XML-based standard for describing, publishing, and finding web
services.

 UDDI stands for Universal Description, Discovery, and


Integration.

 UDDI is a specification for a distributed registry of web services.

 UDDI is platform independent, open framework.

 UDDI can communicate via SOAP, CORBA, and Java RMI


Protocol.

 UDDI uses WSDL to describe interfaces to web services.

 UDDI is seen with SOAP and WSDL as one of the three


foundation standards of web services.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 UDDI is an open industry initiative enabling businesses to


discover each other and define how they interact over the
Internet.

Web Services - Examples


Based on the web service architecture, we create the following two
components as a part of web services implementation:

Service Provider or Publisher


This is the provider of the web service. The service provider implements the
service and makes it available on the Internet or intranet.

We will write and publish a simple web service using .NET SDK.

Service Requestor or Consumer


This is any consumer of the web service. The requestor utilizes an existing
web service by opening a network connection and sending an XML request.

We will also write two web service requestors: one web-based consumer
(ASP.NET application) and another Windows application-based consumer.

Given below is our first web service example which works as a service
provider and exposes two methods (add and SayHello) as the web services
to be used by applications. This is a standard template for a web service.
.NET web services use the .asmx extension. Note that a method exposed as
a web service has the WebMethod attribute. Save this file as
FirstService.asmx in the IIS virtual directory (as explained in configuring
IIS; for example, c:\MyWebSerces).

FirstService.asmx

<%@ WebService language = "C" class = "FirstService" %>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

using System;

using System.Web.Services;

using System.Xml.Serialization;

[WebService(Namespace="http://localhost/MyWebServices/")]

public class FirstService : WebService

[WebMethod]

public int Add(int a, int b)

return a + b;

[WebMethod]

public String SayHello()

return "Hello World";

To test a web service, it must be published. A web service can be published


either on an intranet or the Internet. We will publish this web service on IIS
running on a local machine. Let us start with configuring the IIS.

 Open Start → Settings → Control Panel → Administrative tools →


Internet Services Manager.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

 Expand and right-click on the default web site; select New →


Virtual Directory. The Virtual Directory Creation Wizard opens.
Click Next.

 The "Virtual Directory Alias" screen opens. Type the virtual


directory name. For example, MyWebServices. and click Next.

 The "Web Site Content Directory" screen opens.

 Enter the directory path name for the virtual directory. For
example, c:\MyWebServices Click Next.

 The "Access Permission" screen opens. Change the settings as


per your requirements. Let us keep the default settings for this
exercise.

 Click the Next button. It completes the IIS configuration.

 Click Finish to complete the configuration.

To test whether the IIS has been configured properly, copy an HTML file
(For example, x.html) in the virtual directory (C:\MyWebServices) created
above. Now, open Internet Explorer and type
http://localhost/MyWebServices/x.html. It should open the x.html file.

Note: If it does not work, try replacing the localhost with the IP address of
your machine. If it still does not work, check whether IIS is running; you
may need to reconfigure the IIS and the Virtual Directory.

To test this web service, copy FirstService.asmx in the IIS virtual directory
created above (C:\MyWebServices). Open the web service in Internet
Explorer (http://localhost/MyWebServices/FirstService.asmx). It should
open your web service page. The page should have links to two methods

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

exposed as web services by our application. Congratulations! You have


written your first web service!

Testing the Web Service


As we have just seen, writing web services is easy in the .NET Framework.
Writing web service consumers is also easy in the .NET framework;
however, it is a bit more involved. As said earlier, we will write two types of
service consumers, one web-based and another Windows application-based
consumer. Let us write our first web service consumer.

Web-Based Service Consumer


Write a web-based consumer as given below. Call it WebApp.aspx. Note
that it is an ASP.NET application. Save this in the virtual directory of the
web service (c:\MyWebServices\WebApp.axpx).

This application has two text fields that are used to get numbers from the
user to be added. It has one button, Execute, that when clicked gets the
Add and SayHello web services.

WebApp.axpx

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

<script runat="server">

void runSrvice_Click(Object sender, EventArgs e){

FirstService mySvc = new FirstService();

Label1.Text = mySvc.SayHello();

Label2.Text = mySvc.Add(Int32.Parse(txtNum1.Text),
Int32.Parse(txtNum2.Text)).ToString();

</script>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<html>

<head> </head>

<body>

<form runat="server">

<p>

<em>First Number to Add </em>:

<asp:TextBox id="txtNum1" runat="server" Width="43px">4<


/asp:TextBox>

</p>

<p>

<em>Second Number To Add </em>:

<asp:TextBox id="txtNum2" runat="server"


Width="44px">5</asp:TextBox>

</p>

<p>

<strong><u>Web Service Result -</u></strong>

</p>

<p>

<em>Hello world Service</em> :

<asp:Label id="Label1" runat="server" Font-


Underline="True">Label< /asp:Label>

</p>

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

<p>

<em>Add Service</em> :

& <asp:Label id="Label2" runat="server" Font-


Underline="True">Label</asp:Label>

</p>

<p align="left">

<asp:Button id="runSrvice" onclick="runSrvice_Click"


runat="server" Text="Execute"></asp:Button>

</p>

</form>

</body>

</html>

After the consumer is created, we need to create a proxy for the web
service to be consumed. This work is done automatically by Visual Studio
.NET for us when referencing a web service that has been added. Here are
the steps to be followed:

 Create a proxy for the Web Service to be consumed. The proxy is


created using the WSDL utility supplied with the .NET SDK. This
utility extracts information from the Web Service and creates a
proxy. The proxy is valid only for a particular Web Service. If
you need to consume other Web Services, you need to create a
proxy for this service as well. Visual Studio .NET creates a proxy
automatically for you when the Web Service reference is added.
Create a proxy for the Web Service using the WSDL utility

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

supplied with the .NET SDK. It will create FirstSevice.cs file in


the current directory. We need to compile it to create
FirstService.dll (proxy) for the Web Service.

 c:> WSDL http://localhost/MyWebServices/FirstService.asmx?WSDL

 c:> csc /t:library FirstService.cs

 Put the compiled proxy in the bin directory of the virtual directory
of the Web Service (c:\MyWebServices\bin). Internet Information
Services IIS looks for the proxy in this directory.

 Create the service consumer, in the same way we already did.


Note that an object of the Web Service proxy is instantiated in
the consumer. This proxy takes care of interacting with the
service.

 Type the URL of the consumer in IE to test it (for example,


http://localhost/MyWebServices/WebApp.aspx).
Windows Application-Based Web Service Consumer
Writing a Windows application-based web service consumer is the same as
writing any other Windows application. You only need to create the proxy
(which we have already done) and reference this proxy when compiling the
application. Following is our Windows application that uses the web service.
This application creates a web service object (of course, proxy) and calls
the SayHello, and Add methods on it.

WinApp.cs

using System;

using System.IO;

namespace SvcConsumer {

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

class SvcEater {

public static void Main(String[] args) {

FirstService mySvc = new FirstService();

Console.WriteLine("Calling Hello World Service: " +


mySvc.SayHello());

Console.WriteLine("Calling Add(2, 3) Service: " + mySvc.Add(2,


3).ToString());

Compile it using c:\>csc /r:FirstService.dll WinApp.cs. It will create


WinApp.exe. Run it to test the application and the web service.

Now, the question arises: How can you be sure that this application is
actually calling the web service?

It is simple to test. Stop your Web server so that the Web Service cannot
be contacted. Now, run the WinApp application. It will fire a run-time
exception. Now, start the web server again. It should work.

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [Lecture Notes]

Ref:

http://www.codeproject.com/Articles/416137/Understanding-Session-Management-Techniques-in-ASP

http://www.tutorialspoint.com/asp.net/asp.net_configuration.htm

https://in.godaddy.com/help/what-is-a-webconfig-file-5445

http://www.tutorialspoint.com/webservices/

https://documentation.progress.com/output/ua/OpenEdge_latest/index.html#page/dvnet/passing-
dataset-and-dataset-handle-parameters.html

CS6001 C# AND .NET PROGRAMMING Unit IV


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

.NET Framework
.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large class library known as Framework Class
Library (FCL) and provides language interoperability(each language can use code written in other
languages) across several programming languages. Programs written for .NET Framework execute
in a software environment (as contrasted to hardware environment), known as Common Language
Runtime (CLR), an application virtual machine that provides services such as security, memory
management, and exception handling. FCL and CLR together constitute .NET Framework.

FCL provides user interface, data access, database connectivity, cryptography, web
application development, numericalgorithms, and network communications. Programmers produce
software by combining their own source code with .NET Framework and other libraries. .NET
Framework is intended to be used by most new applications created for the Windows platform.
Microsoft also produces an integrated development environment largely for .NET software
called Visual Studio.

.NET Framework started out as a proprietary framework, although the company worked
to standardize the software stack almost immediately, even before its first release. Despite the
standardization efforts, developers—particularly those in the free and open-source
software communities—expressed their uneasiness with the selected terms and the prospects of
any free and open-source implementation, especially with regard to software patents. Since then,
Microsoft has changed .NET development to more closely follow a contemporary model of a
community-developed software project, including issuing an update to its patent that promises to
address the concerns.

.NET Framework family also includes two versions for mobile or embedded device use. A reduced
version of the framework,.NET Compact Framework, is available on Windows CE platforms,
including Windows Mobile devices such as smartphones. Additionally, .NET Micro Framework is
targeted at severely resource-constrained devices.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Creating Your First C#


Windows Application
Introduction
C# appears to be the new language of choice around the development community, or at least the
most talked about new language. Microsoft has introduced a language that will (hopefully) bring
together both Visual Basic developers and Visual C++ developers alike. It is important to remember
that, this application is only to show you some of the most basic components in C#. Here we will
design a form that will allow a user to populate a listbox with customer names they type above.

This article is based on the ideas that Dr.Asad Altimeemy posed in the article he wrote titled: A
Beginners Guide To Dialog Based Applications written in Visual C++. This article covers essentially
the same methods only converted to run in .NET and written in C#. This code is unfortunately based
on Visual Studio .NET Beta 2; please make any comments regarding the changes to the final release
version.

Creating A New Project


To create a new project you need to first load Visual Studio .NET and select under the Visual C#
Projects, “Windows Application” as in Figure 1. Type the name of the project below along with
selecting the desired location to store your files.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Figure 1. Creating a C# Project.

Designing The Interface


You will need to add the following items onto your form.

Item Quantity

GroupBox 1

Label 3

ComboBox 1

Textbox 2

Button 3

ListBox 1

Arrange your items onto the form so that they look something like this. I would suggest that you
place the GroupBox on the form first, otherwise you will need to re-drag all item inside the box once
they are on the form. Arrange the items as you see below in Figure 2.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Figure 2 Design Layouts For Application.

Labels, Labels, Labels…..


You will want to add the value ‘Title’ to the Text property of label1. The Text property for label2
should be set to ‘First Name’ and the Text property of label3 should be…….’Last Name’, big surprise
huh? Text properties of button1 should be ‘OK’, button2 should be ‘Clear List’ and button3 will be
‘Close’. I have set the Text Property of groupBox1 to ‘Customers’ and Form1 to ‘Customers’ as well.
You may also wish to set the Text value of the listBox and comboBox to blank also.

Adding The Code


To begin, when this form loads we need to populate the ComboBox with the appropriate values. Add
the following code by clicking on the form on the outside of the groupBox. You should see
something like this:

Hide Copy Code

private void Form1_Load(object sender, System.EventArgs e)


{
//Add the following code
//to fill the comboBox when
//form loads.

comboBox1.Items.Add("Dr.");
comboBox1.Items.Add("Mr.");

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

comboBox1.Items.Add("Mrs.");
comboBox1.Items.Add("Ms.");
comboBox1.Focus();
}

We now need to handle what happens when the user hits the OK button after populating the text
boxes. To do this simply click on the Form1.cs[Design]* tab at the top left to switch from code-view
to the form object designer. Double-click on the OK button and add the following code:

Hide Copy Code

private void button1_Click(object sender, System.EventArgs e)


{
listBox1.Items.Add(comboBox1.Text + " " +
textBox1.Text + " " + textBox2.Text);
textBox1.Text = "";
textBox2.Text = "";
comboBox1.Text = "";
comboBox1.Focus();
}

When we want to allow the user to clear all fields entered into the listBox, we will need to go back
like we did above to the visual designer and double-click on the Clear List button, this should again
switch to a code view and allow you to add the following code:

Hide Copy Code

private void button2_Click(object sender, System.EventArgs e)


{
listBox1.Items.Clear();
comboBox1.Focus();
}

And finally we want to allow the user to be able to close the application when they want. To show
you another way to allow the user to close the program aside from that catchy X in the upper right-
hand corner, I have provided a button entitled……Close. I know, you were looking for some complex
name, weren’t you? Anyway, before I get off on a tangent, double-click the Close button and add the
following code below:

Hide Copy Code

private void button3_Click(object sender, System.EventArgs e)


{
this.Dispose();
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Conclusion
Again this small sample application was made to show you how some of the basic components of a
Windows application are controlled in C#. Hopefully, you have a better understanding of how the
new C# language works within a Windows application. Here is a view of what you might see when
running the application.

Figure 3 Final Visual C# Application.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Creating our own window application

S imple Windows Forms Applications


At a minimum, a Windows Forms application consists of the following elements:
 One or more classes that derive from System.Windows.Forms.Form.
 A Main method that invokes the static (shared in Visual Basic) Run method and passes
a Form instance to it. The Run method processes messages from the operating system to
the application.
The following code example shows the essential elements of a Windows Forms application
C#

using System;

using System.Windows.Forms;

public class MyForm : Form {

public MyForm() {

this.Text = "Hello World";

[STAThread]

public static void Main(string[] args) {

MyForm aform = new MyForm();

// The Application.Run method processes messages from the operating system

// to your application. If you comment out the next line of code,

// your application will compile and execute, but because it is not in the //

message loop, it will exit after an instance of the form is created.

Application.Run(aform);

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Using Controls in a Windows Forms


Application
The following code example shows a simple application that
illustrates how Windows Forms applications use controls and
handle events. The example consists of three buttons on a form;
each button changes the background color when clicked.
C#

using System;

using System.ComponentModel;

using System.Windows.Forms;

using System.Resources;

using System.Drawing;

public class MyForm : Form {

private Button red;

private Button blue;

private Button green;

public MyForm() : base() {

InitializeComponent();

protected override void Dispose(bool disposing) {

base.Dispose(disposing);

// InitializeComponent is a helper method for the constructor.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

// It is included for consistency with code that is

// auto-generated by the Windows Forms designer in Visual Studio.

private void InitializeComponent() {

// A delegate for the click event of a button. The argument to

// the constructor contains a reference to the method that performs the

// event handling logic.

EventHandler handler = new EventHandler(button_Click);

// Creates three buttons, sets their properties, and attaches

// an event handler to each button.

red = new Button();

red.Text = "Red";

red.Location = new Point(100, 50);

red.Size = new Size(50, 50);

red.Click +=handler;

Controls.Add(red);

blue = new Button();

blue.Text = "Blue";

blue.Location = new Point(100, 100);

blue.Size = new Size(50, 50);

blue.Click += handler;

Controls.Add(blue);

green = new Button();

green.Text = "Green";

green.Location = new Point(100, 150);

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

green.Size = new Size(50, 50);

green.Click += handler;

Controls.Add(green);

// Event handler.

private void button_Click(object sender, EventArgs e) {

if (sender == red) this.BackColor = Color.Red ;

else if (sender == blue) this.BackColor = Color.Blue;

else this.BackColor = Color.Green;

// The STAThreadAttribute informs the common language runtime that

// Windows Forms uses the single-threaded apartment model.

[STAThread]

public static void Main(string[] args) {

Application.Run(new MyForm());

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Menu Creation
Defining a Property in Windows
Forms Controls
One common aspect of Web sites of any complexity is a
navigational menu. You can use the Menu control in ASP.NET to
easily set up a complex navigational menu without writing code.
The Menu control allows for multiple display options, including a
static display where the menu is fully exposed and a dynamic
display where portions of the menu appear as the mouse pointer
moves over the parent menu item. The control also provides a
combination of static and dynamic display modes that allow a
series of root items that are static, but with child menu items that
appear dynamically.
You can configure the ASP.NET Menu control in the designer with
static links to your pages or you can bind it automatically to a
hierarchical data source such as an XmlDataSource or
a SiteMapDataSource control.
Tasks illustrated in this walkthrough include:
 Creating a basic menu and configuring it statically to link to

your pages.
 Creating a more complex menu that is bound to a

Web.sitemap XML file.


 Adjusting the orientation of a menu.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

 Configuring multiple levels of static display versus dynamic


display.

Walkthrough: Displaying a
Menu on Web Pages
.NET Framework 4

Other Versions

This walkthrough illustrates how to place and configure an ASP.NET Menu control on a Web
page.
One common aspect of Web sites of any complexity is a navigational menu. You can use
the Menu control in ASP.NET to easily set up a complex navigational menu without writing code.
The Menu control allows for multiple display options, including a static display where the menu
is fully exposed and a dynamic display where portions of the menu appear as the mouse pointer
moves over the parent menu item. The control also provides a combination of static and
dynamic display modes that allow a series of root items that are static, but with child menu
items that appear dynamically.
You can configure the ASP.NET Menu control in the designer with static links to your pages or
you can bind it automatically to a hierarchical data source such as an XmlDataSource or
a SiteMapDataSource control.
Tasks illustrated in this walkthrough include:
 Creating a basic menu and configuring it statically to link to your pages.
 Creating a more complex menu that is bound to a Web.sitemap XML file.
 Adjusting the orientation of a menu.
 Configuring multiple levels of static display versus dynamic display.

Prerequisites
In order to complete this walkthrough, you will need:
 Visual Studio or Visual Web Developer Express installed on your computer.

Note

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

If you are using Visual Studio, the walkthrough assumes that you selected the Web
Development collection of settings when you started Visual Studio the first time. For
more information, see How to: Select Web Development Environment Settings.

Creating the Web Site


For this walkthrough, you will create an empty Web site project and add a page to it.
This walkthrough uses a Web site project. You could use a Web application project instead. For
information about the difference between these Web project types, see Web Application
Projects versus Web Site Projects.
To create a file system Web site
1. Open Visual Studio or Visual Web Developer Express.
2. In the File menu, click New Web Site.
The New Web Site dialog box is displayed.
3. Under Installed Templates, click Visual Basic or Visual C# and then select ASP.NET
Empty Web Site.
4. In the Web location box, select File System, and then enter the name of the folder
where you want to keep the pages for your Web site.
For example, type the folder name C:\WebSites.
5. Click OK.
Visual Studio creates a Web site project that includes a Web.config file.
6. In Solution Explorer, right-click the root of your Web site, and then click Add New
Item.
7. Select Web Form, name the file Default.aspx, and then click Add.

Creating a Basic Menu


Although the master page within the ASP.NET Web site template
includes a menu, you can add an additional menu specifically for
the Default.aspx page for the purpose of this walkthrough. The
first step in creating a menu for your page is the placement of
a Menu control.
To add a Menu control to the page
1. Switch to or open Default.aspx, and then switch
to Design view.
2. From the Navigation control group in the Toolbox, drag
a Menu control onto the page.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

For this example, you will orient the menu horizontally rather than
vertically.
To position the Menu control horizontally
 Right-click the Menu control, click Properties, and then
set Orientation to Horizontal.

C onfiguring a Basic Menu


In this section, you will define the menu items by using the Menu Item Editor.
To edit Menu control items
1. Right-click the Menu control, and then click Edit Menu Items.
The Menu Item Editor appears.
2. Under Items, click the Add a root item icon.
3. Under Properties for the new item,
set Text to Home and NavigateURL to Default.aspx.
4. Under Items, click the Add a root item icon.
5. Under Properties, set Text to Products and NavigateURL to Products.aspx.
6. Under Items, click the Add a root item icon.
7. Under Properties, set Text to Services and NavigateURL to Services.aspx.
8. Click OK.
If you look at the source for Default.aspx, you will see that the menu items and links are stated
declaratively in the control.
To create the target pages
1. In Solution Explorer, right-click the root of your Web site,
and then click Add New Item.
2. Click Web Form, name the file Products.aspx, and then
click Add.
3. Repeat the preceding steps and create a file
named Services.aspx.

Testing the Menu


With your pages and menu in place, you can try it out.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

To test the Menu control


1. Click Default.aspx in Solution Explorer and then press
CTRL+F5 to run the Default.aspx page.
2. Move the pointer over the items; the browser's status bar at
the bottom of the page (if visible) will show what page is
linked.
3. Click a link to jump to the page.

Creating a Menu Bound to a Site


Map
In the last section, you created a simple static menu configured
declaratively within the page. In this section, you skip editing
the Menu control items directly, and instead bind the control to a
Web.sitemap file as an XML data source. This allows
the Menu control's structure to be maintained within a separate
XML file that can be easily updated without modifying the page or
using the designer.
For this example you will use a second Menu control.
To create a second Menu control
 From the Navigation group of the Toolbox, drag a
second Menu control onto the Default.aspx page.
Next, you will need a Web.sitemap file to bind to.
To create a site map file
1. In Solution Explorer, right-click the root of your Web site,
and then click Add New Item.
2. In the Add New Item dialog box, click Site Map.
3. Click Add.
4. Place the following XML code in the Web.sitemap file.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

The XML represents the structure of the menu. Nested nodes


become child menu items of parent node menu items.
<siteMap>
<siteMapNode title="Home" description="Home"
url="default.aspx" >
<siteMapNode title="Products"
description="Our products"
url="Products.aspx">
<siteMapNode title="Hardware"
description="Hardware choices"
url="Hardware.aspx" />
<siteMapNode title="Software"
description="Software choices"
url="Software.aspx" />
</siteMapNode>
<siteMapNode title="Services"
description="Services we offer"
url="Services.aspx">
<siteMapNode title="Training"
description="Training classes"
url="Training.aspx" />
<siteMapNode title="Consulting"
description="Consulting services"
url="Consulting.aspx" />
<siteMapNode title="Support"
description="Support plans"
url="Support.aspx" />
</siteMapNode>
</siteMapNode>

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

</siteMap>
5.Save the file.

Binding to a Site Map


Now you can create a navigation data source that points to your
Web.sitemap file and bind your Menu control to it.
To bind to a Menu control to a site map
1. Open the Default.aspx file, and then switch to Design view.
2. Click the smart tag of the new Menu control to display
the Menu Tasks dialog box.
3. In the Menu Tasks dialog box, in the Choose Data
Source drop-down list, click New Data Source.
The Data Source Configuration Wizard dialog box appears.
4. Click Site Map.
Under Specify an ID for the data source, the default
name, SiteMapDataSource1, appears.
5. Click OK.

Testing Site Map Binding


With your pages and menu in place, you can try it out.
To test the site map binding
1. Press CTRL+F5 to run the Default.aspx page.
2. Move the pointer over the Home menu item of the second,
vertical menu.
Products and Services appear.
3. Move the pointer over Products.
Hardware and Software appear.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

If you look at the source code for Default.aspx, you will


notice that unlike the first menu item, the items are not
specified declaratively; instead, the data source is referenced
by the Menu control.
4. Close the Browser window.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

How to: Inherit Windows Forms


Creating new Windows Forms by inheriting from base forms is a
handy way to duplicate your best efforts without going through
the process of entirely recreating a form every time you require it.
For more information about inheriting forms at design time using
the Inheritance Picker dialog box and how to visually distinguish
between security levels of inherited controls, see How to: Inherit
Forms Using the Inheritance Picker Dialog Box.
Note In order to inherit from a form, the file or namespace
containing that form must have been built into an executable file
or DLL. To build the project, choose Build from the Build menu.
Also, a reference to the namespace must be added to the class
inheriting the form. The dialog boxes and menu commands you
see might differ from those described in Help depending on your
active settings or edition. To change your settings, choose Import
and Export Settings on the Tools menu. For more information,
see Customizing Development Settings in Visual Studio.

To inherit a form programmatically


1. In your class, add a reference to the namespace containing
the form you wish to inherit from.
2. In the class definition, add a reference to the form to inherit
from. The reference should include the namespace that
contains the form, followed by a period, then the name of
the base form itself.

C#

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

public class Form2 : Namespace1.Form1

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

SDI and MDI


Single document interface
SDI applications allow only one open document frame window at a time. It's made up of one
or more independent windows, which appears separately on the windows desktop. An
example of this would be a simple text document(Notepad).

MDI applications allow multiple document frame windows to be open in the same instance
of an application. An MDI application has a window within which multiple MDI child
windows, which are frame windows themselves, can be opened, each containing a separate
document. In some applications, the child windows can be of different types, such as chart
windows and spreadsheet windows. In that case, the menu bar can change as MDI child
windows of different types are activated.

Multiple document interface


A multiple document interface (MDI) is a graphical user interface in which multiple
windows reside under a single parent window. Such systems often allow child windows to
embed other windows inside them as well, creating complex nested hierarchies. This
contrasts withsingle document interfaces (SDI) where all windows are independent of each
other.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Comparison with single document interface

In the usability community, there has been much debate about whether the multiple
document or single document interface is preferable. Software companies have used both
interfaces with mixed responses. For example, Microsoft changed its Office applications
from SDI to MDI mode and then back to SDI, although the degree of implementation varies
from one component to another. SDI can be more useful in cases where users switch more
often between separate applications than among the windows of one application.

The disadvantage of MDI usually cited is its lack of information about the currently opened
windows: In MDI applications, the application developer must provide a way to switch
between documents or view a list of open windows, and the user might have to use an
application-specific menu ("window list" or something similar) to switch between open
documents. This is in contrast to SDI applications, where the window manager's task
bar or task manager displays the currently opened windows. However, in recent years it has
become increasingly common for MDI applications to use "tabs" to display the currently
opened windows, which has made this criticism somewhat obsolete. An interface in which
tabs are used to manage open documents is referred to as a "tabbed document interface"
(TDI).

Another option is "tiled" panes or windows, which make it easier to prevent content from
overlapping.

Some applications allow the user to switch between these modes at their choosing,
depending on personal preference or the task at hand.

Nearly all graphical user interface toolkits to date provide at least one solution for designing
MDIs, with an exception being Apple's Cocoa API. The Java GUI toolkit, Swing, for
instance, provides the class javax.swing.JDesktopPane which serves as a container for
individual frames (class javax.swing.JInternalFrame ). GTK+ lacks any standardized
support for MDI.
Advantages[edit]

 With multiple document interfaces (and also tabbed document interfaces), a single
menu bar and/or toolbar is shared between all child windows, reducing clutter and
increasing efficient use of screen space. This argument is less relevant on an operating
system which uses a common menu bar.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

 An application's child windows can be hidden/shown/minimized/maximized as a whole.


 Features such as "Tile" and "Cascade" can be implemented for the child windows.
 Authors of cross-platform applications can provide their users with consistent application
behaviour between platforms.
 If the windowing environment and OS lack good window management, the application
author can implement it themselves.
 Modularity: An advanced window manager can be upgraded independently of the
applications
Disadvantages[edit]

 Can be tricky to implement on desktops using multiple monitors as the parent window
may need to span two or more monitors, hiding sections.
 Virtual desktops cannot be spanned by children of the MDI. However, in some cases,
this is solveable by initiating another parent window; this is the case
in Opera andChrome, for example, which allows tabs/child windows to be dragged
outside of the parent window to start their own parent window. In other cases, each child
window is also a parent window, forming a new, "virtual" MDI [1].
 MDI can make it more difficult to work with several applications at once, by restricting
the ways in which windows from multiple applications can be arranged together without
obscuring each other.
 The shared menu might change, which may cause confusion to some users.
 MDI child windows behave differently from those in single document
interface applications, requiring users to learn two subtly different windowing concepts.
Similarly, the MDI parent window behaves like the desktop in many respects, but has
enough differences to confuse some users.
 Deeply nested, branching hierarchies of child windows can be confusing.
 Many window managers have built-in support for manipulating groups of separate
windows, which is typically more flexible than MDI in that windows can be grouped and
ungrouped arbitrarily. A typical policy is to group automatically windows that belong to
the same application. This arguably makes MDI redundant by providing a solution to the
same problem.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

 Controls and hotkeys learned for the MDI application may not apply to others, whereas
with an advanced Window Manager, more behavior and user preference settings are
shared across client applications on the same system
 Without an MDI frame window, floating toolbars from one application can clutter the
workspace of other applications, potentially confusing users with the jumble of
interfaces.

SDI and MDI


MFC makes it easy to work with both single-document interface (SDI) and multiple-document
interface (MDI) applications.
SDI applications allow only one open document frame window at a time. MDI applications allow
multiple document frame windows to be open in the same instance of an application. An MDI
application has a window within which multiple MDI child windows, which are frame windows
themselves, can be opened, each containing a separate document. In some applications, the
child windows can be of different types, such as chart windows and spreadsheet windows. In
that case, the menu bar can change as MDI child windows of different types are activated.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Dialog box modal and


modeless
A modal from is one that has to be dealt with before a user can continue. An example is
the Change Case dialogue box in Microsoft Word. If you try to click away from the
dialogue box, you'll here a beep to indicate an error. Until you click either the Cancel or
OK buttons, the programme won't let you click anywhere else.

The second form you've just created is called a Modeless form. These are forms than
can be hidden or sent to the taskbar. You can then return to the main form or
programme and do things with it.

A Modal form is sometimes called a dialogue box. And we'll see how to create one of
these now.

Add a second button to your Form1. Change the Name property of the new button
tobtnDialogueBox. Double click the new button and add the following code:

Dim frmDialogue As New frmSecond

frmDialogue.ShowDialog()

To display a form as a Modal dialogue box, you use the ShowDialog method. If you
use the Show method, the form is displayed as a Modeless form.

Run your programme. Click your new button, and the second form should display. Move
it out the way and try to click a button on Form1. You won't be able to. The second form
has to be dealt with before you can access Form1.

When the form is a Modal dialogue box, you can create OK and Cancel buttons for it.
VB.NET then has a trick up its sleeve for these types of buttons. We'll see that trick
now.

OK and Cancel Buttons

In the design environment, Click the Tab for your frmSecond. When the form is
displayed in the design window, add two buttons to it (Make sure you're adding the
buttons to the second form and NOT Form1). Change the Name property of the first

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

button to btnOK, and the Name property of the second to btnCancel. Double click your
OK button and add the following code to it:

Me.DialogResult = DialogResult.OK

The Me keyword refers to the current form. When you type a full stop,
select DialogResult from the pop up list that appears. DialogResult is a property of the
Form. It can accept a range of values. As soon as you type a space after the equals
sign, you'll see a list with these values on it (VB NET 2008 only. In VB 2010, you have
to type the DialogResult):

As you can see, one of these values is DialogResult.OK. This indicates that you want to
use this button as an OK button. When the button is clicked, VB.NET will return a result
of OK for this button.

Access the code for your Cancel button and add the following line:

Me.DialogResult = DialogResult.Cancel

For the Cancel button, we're just selecting DialogResult.Cancel from the list. When the
button is clicked, VB.NET will return a result of Cancel for this button.

You can test to see what value is stored in Me.DialogResult. But you do that from the
button that displays the form, Form1 for us.

So access your Form1 code, and locate the lines that display the second form. The two
lines should be these:

Dim frmDialogue As New frmSecond

frmDialogue.ShowDialog()

Change the second line to this:

If frmDialogue.ShowDialog() = DialogResult.OK Then

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

MessageBox.Show("OK Button Clicked")

End If

To get at the value of the button clicked, you test to see what result
the ShowDialog property is. If theShowDialog property of frmDialogue is OK then you
can execute the code that needs executing. If the Cancel button was clicked, however,
you don't have to do anything: VB.NET will take of closing your Modal dialogue box for
you!

Run your programme and test it out. Click your button to bring up your Modal dialogue
box. Click the OK button, and you should see the message box display. Bring the Modal
dialogue box up a second time and then click the Cancel button. The form will just close
down.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Modal Dialog Boxe


There are two types of dialog boxes: modal and modeless.
A Modal dialog box is one that the user must first close in order to have access to any other
framed window or dialog box of the same application. One of the scenarios in which you use
a dialog box is to create an application that is centered around one. In this case, if either
there is no other form or dialog box in your application or all the other forms or dialog boxes
depend on this central dialog box, it must be created as modal. Such an application is
referred to as dialog-based.

Some applications require various dialog boxes to complete their functionality. When in
case, you may need to call one dialog box from another and display it as modal. Here is
an example:

The Date and Time dialog box of WordPad is modal: when it is displaying, the user cannot
use any other part of WordPad unless he or she closes th

is object first

After creating a dialog used as an addition to an existing form or an existing dialog box, to
call it as modal, use the ShowDialog() method.

Modeless Dialog Boxes


A dialog box is referred to as modeless if the user does not have to close it in order to
continue using the application that owns the dialog box. A modeless dialog box has the
following characteristics

 It has a thin border


 It can be neither minimized nor maximized. This means that it is not equipped with
the Minimize or the Maximize buttons

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

 It is not represented on the taskbar with a button


 It must provide a way for the user to close it

Here is an example:

The Find (and the Replace) dialog box of WordPad (also the Find and the Replace dialog
boxes of most applications) is an example of a modeless dialog box. If it is opened, the
user does not have to close it in order to use the application or the document in the
background.

Since the modeless dialog box does not display its button on the task bar, the user should
know that the dialog box is opened. To make the presence of a modeless dialog box
obvious to the user, it typically displays on top of its host application until the user closes
it.

A modeless dialog box is created from a form but it should look like a regular dialog box
or a tool window. Therefore, to create a modeless dialog box, set
the FormBorderStyle property to an appropriate value such
as FixedSingle, FixedToolWindow, Sizable or SizableToolWindow. Also, set
its ShowInTaskbar property to False.

After creating the dialog box, to display it as modeless, call the Show() method. The
fundamental difference between the ShowDialog() and the Show() methods is that the
former displays a modal dialog box, which makes sure that the called dialog box cannot
go in the background of the main application. By contrast, the Show() method only calls
the dialog box every time it is requested. For this reason, it is up to you to make sure that
the modeless dialog box always remains on top of the application. This is easily taken care
of by setting the BooleanTopMost property of the form to True.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

There are two main ways a normal modeless dialog box can be dismissed:

 If the user has finished using it, he or she can close it and recall it at will
 When the form or application that owns the modeless dialog box is closed, the form
or application closes the modeless dialog if it is opened; this means that you don't
need to find out whether a modeless dialog box is still opened when the application
is being destroyed: either the user or the application itself will take care of closing it

An Application With Various Forms or Dialog boxes


When you create a Windows Forms Application, the starting
form is made available to you. If one form is not enough for
your application, you can add as many as necessary. To add
(or to create) a (new) form, you have various options:
 On the main menu, you can click Project -> Add New
Item...
 On the main menu, you can click File -> Add New Item...
 In Solution Explorer, you can right-click the name of the
project, position the mouse on Add, and click Add New
Item...
In the Add New Item dialog box and in the Templates section,
click Window Form (.NET), provide a name in the Name edit
box then click Open.

If your application is using various forms and you want to


display a particular one at design time:

 In the Forms Designer, you can click the tab that


corresponds to the desired form and that has [Design]
 On the main menu, you can click Window and click the
name of the form in the list under Close All Documents
 In Solution Explorer, expand the Header Files node if
necessary and double-click the name of the desired form
that has the .h extension

If you visually add two (or more) forms to your application, you
may need to link them, allow one to call the other. To do this,
in the top section of the file, type #include followed by the
name of the header file in which the form was defined. In the
section where you want to access the form, declare a handle to
the class of the form and use the new operator to allocate
memory for it. To display the other form, you can call
its Show() method.

Practical Learning: Using Various Forms


1. Display the first form
2. Double-click the New Property... button and implement the event as follows:

private void btnNewProperty_Click(object sender, EventArgs e)


{
Random rnd = new Random();

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

PropertyEditor dlgEditor = new PropertyEditor();

if (dlgEditor.ShowDialog() == DialogResult.OK)
{
ListViewItem lvi = lvwProperties.Items.Add(
rnd.Next(100000, 999999).ToString());
lvi.SubItems.Add(dlgEditor.txtPropertyType.Text);
lvi.SubItems.Add(dlgEditor.txtBedrooms.Text);
lvi.SubItems.Add(dlgEditor.txtBathrooms.Text);
lvi.SubItems.Add(dlgEditor.txtMonthlyRent.Text);
}
}
3. Execute the application and click the New Property... button
4. Create a property

5. Press Enter
6. Create a few more properties and press Enter each time

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

7. Close it and return to your programming environment

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

ADO.NET
Introduction
This article aims at understanding the various concepts and classes available for data access in
ADO.NET. This article is meant for absolute beginners and discusses various techniques of data
access using ADO.NET.

Background
ADO.NET is a set of classes that comes with the Microsoft .NET framework to facilitate data access
from managed languages. ADO.NET has been in existence for a long time and it provides a
comprehensive and complete set of libraries for data access. The strength of ADO.NET is firstly that it
lets applications access various types of data using the same methodology. If I know how to use
ADO.NET to access a SQL Server database then the same methodology can be used to access any
other type of database (like Oracle or MS Access) by just using a different set of classes. Secondly,
ADO.NET provides two models for data access: a connected model where I can keep the connection
with the database and perform data access, and another way is to get all the data in ADO.NET
objects that let us perform data access on disconnected objects.

Note: Many developers and development houses are now using ORMs to perform data access
instead of using ADO.NET. ORMs provide a lot of data access functionality out of the box and
relieves users from writing mundane data access code again and again. Still, I think that knowing and
understanding ADO.NET is crucial as a .NET developer as it gives a better understanding of the data
access methodologies. Also, there are many development houses that are still using ADO.NET.

Let us try to visualize ADO.NET data access using the following diagram:

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

The diagram above shows that ADO.NET can be used with any kind of application, i.e., it can be used
from a Windows Forms application, an ASP.NET application, or from a WPF and/or Silverlight
application. Also, the data store underneath can be any data store, SQL Server, Access, or Oracle. It is
just a matter of using the right set of classes specific to that data store and the methodology will
remain the same.

Using the code


Let us try to understand a few ADO.NET classes and methodologies by writing a small web
application. This application uses a sample database from Microsoft (subset of the Pubs database)
and we will use this database for understanding the various classes and methods of ADO.NET. We
will be using ADO.NET classes specific to SQL Server but once it is understood, the basic philosophy
remains the same and can be applied with any data store.

Before jumping into the code, we will have to understand some of the important objects of
ADO.NET. In a typical scenario requiring data access, we need to perform four major tasks:

1. Connecting to the database


2. Passing the request to the database, i.e., a command like select, insert, or update.
3. Getting back the results, i.e., rows and/or the number of rows effected.
4. Storing the result and displaying it to the user.

This can be visualized as:

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

So now we need to understand how we can achieve these functionalities using ADO.NET.

The Connection

The ADO.NET Connection class is used to establish a connection to the database. The Connection
class uses a ConnectionString to identify the database server location, authentication parameters,
and other information to connect to the database. This ConnectionString is typically stored in
the web.config.

Hide Copy Code

<connectionStrings>
<add name="MyConnectionString"
connectionString ="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\PUBS.MDF;
Integrated Security=True;User Instance=True" />
</connectionStrings>

Let us see how we can use the SqlConnection class to establish a connection with a database.

Hide Copy Code

private SqlConnection con = null;


con = new
SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);

Now we have a connection ready with our database. Whenever we want to retrieve data, we just
need to open the connection, perform the operation, and close the connection.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Storing the Result

Before we can jump to understanding how we can execute commands on a database, we first need
to understand how we can store the results and these results can be displayed to the user. To get the
hang of how we can store the results, we need to understand a few ADO.NET objects.

 DataReader - A DataReader is an object that can be used to access the results sequentially from a
database. The DataReader is used to get forward only sequential results as the query executes. This
is used with the Command object (we will see the usage shortly).
 Dataset - The Dataset can be thought of as an in-memory representation of a database.
A DataSet is a disconnected data access object. The result of the query can be stored in a Dataset.
The DataSet containsDataTables. The DataTables contain DataRow and DataColumns.
A DataSet or a DataTable can be used with a Command and a DataAdapter object to store
query results.
 DataAdapter - A DataAdapter object is used to fill a DataSet/DataTable with query results. This
can be thought of as the adapter between the connected and disconnected data models. A
Command object will be used to execute the query and a DataAdapter will use this Command
object and fill the query results coming from the database into a DataSet/DataTable.

Note:

1. There are more objects that can/are used to store results but we will mainly be using these in this
article.
2. The usage and implentation of these objects are in the next section, as understanding the Command
object is required before that.

The Command

Once we have the connection ready, the next step would be to tell the database about what
operation we need to perform on the database. This can be done using the Command object. We will
be using SqlCommand to tell the database about the operation we need to perform. The typical
commands on a database will be:

1. Select Command - This will return a set of rows to the application.


2. Insert Command - This will return the number of rows inserted.
3. Delete Command - This will return the number of rows deleted.
4. Update Command - This will return the number of rows updated.

Note: We are only talking about data manipulation commands in this article.

All these commands expect SQL syntax. This SQL can either be passed from the application or can be
written in the form of Stored Procedures and executed using a SqlCommand.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Using a Stored Procedure with a Command

If we want to use a Stored Procedure with a Command object then we need to specify it as:

Hide Copy Code

cmd = con.CreateCommand();
// This will specify that we are passing the stored procedures name
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandName; // This will be the stored procedures name

If the Stored Procedure is expecting some parameters then we can pass these parameters by
creating instances ofSqlParameter objects as:

Hide Copy Code

SqlCommand cmd = con.CreateCommand();


// This will specify that we are passing the stored procedures name
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = CommandName; // This will be the stored procedures name
SqlParameter param = new SqlParameter("@id", txtSearch.Text);
cmd.Parameters.Add(param);

Passing a SQL query from an application using a Command

If we want to pass a SQL query from our application then we can use the SqlCommand as:

Hide Copy Code

SqlCommand cmd = con.CreateCommand();


cmd.CommandType = CommandType.Text; //This will specify that we are passing query from
application
string query = "select * from Authors";
cmd.CommandText = query;

There is one important thing to understand here and that is SqlParameters. Many a times we will
need to pass parameters in our SQL query. This can be done in two ways: we can create a query
using string concatenation like:

Hide Copy Code

SqlCommand cmd = con.CreateCommand();


//This will specify that we are passing query from application
cmd.CommandType = CommandType.Text;
string query = "select * from Authors where authorId = '" + txtSearch.Text + "'";
cmd.CommandText = query;

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

This is not recommended as this approach is error prone and is vulnerable to SQL Injection attacks.
So whenever we need to pass parameters to a query the preferred way is using SqlParameters. The
same query can be written as:

Hide Copy Code

SqlCommand cmd = con.CreateCommand();


//This will specify that we are passing query from application
cmd.CommandType = CommandType.Text;
string query = "select * from Authors where authorId = @id";
cmd.CommandText = query;

SqlParameter param = new SqlParameter("@id", txtSearch.Text);


cmd.Parameters.Add(param);

Using SqlParameters gives a cleaner, less error prone and SQL injection safe (comparative) code.

Executing the Select Command

Now let us see how we can retrieve the result of a Select command in the form of a DataTable.

Hide Shrink Copy Code

public DataTable ExecuteSelectCommand(string CommandName, CommandType cmdType)


{
SqlCommand cmd = null;
DataTable table = new DataTable();

cmd = con.CreateCommand();

cmd.CommandType = cmdType;
cmd.CommandText = CommandName;

try
{
con.Open();

SqlDataAdapter da = null;
using (da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

return table;
}

public DataTable ExecuteParamerizedSelectCommand(string CommandName,


CommandType cmdType, SqlParameter[] param)
{
SqlCommand cmd = null;
DataTable table = new DataTable();

cmd = con.CreateCommand();

cmd.CommandType = cmdType;
cmd.CommandText = CommandName;
cmd.Parameters.AddRange(param);

try
{
con.Open();

SqlDataAdapter da = null;
using (da = new SqlDataAdapter(cmd))
{
da.Fill(table);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}

return table;
}

Executing Update, Delete, and Insert Commands

Commands like insert, update, delete are executed by calling the ExecuteNonQuery method
of SqlCommand. Let us see how we can write a simple function that will execute these commands.
These commands can be used by passing a query from the application or by invoking Stored
Procedures (same as we saw above).

Hide Shrink Copy Code

public bool ExecuteNonQuery(string CommandName, CommandType cmdType, SqlParameter[] pars)


{
SqlCommand cmd = null;
int res = 0;

cmd = con.CreateCommand();

cmd.CommandType = cmdType;

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

cmd.CommandText = CommandName;
cmd.Parameters.AddRange(pars);

try
{
con.Open();

res = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
cmd.Dispose();
cmd = null;
con.Close();
}

if (res >= 1)
{
return true;
}
return false;
}

Using the sample application

The first thing to notice in the application is that it contains a class that is responsible for all the
ADO.NET logic. The class DataAccess (file: DataAccess.cs) contains all the ADO.NET classes and
methods. All the pages use this class. This class can be reused in any application with some minor
application specific changes. The class diagram for the class is:

The sample application contains four pages:

 Authors.aspx
 Titles.aspx
 AddAuthors.aspx
 AddTitles.aspx

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

The author pages, i.e., Authors.aspx and AddAuthors.aspx, use Stored Procedures to perform the
operations whereas the title pages pass all the queries from the application to the database. We have
mainly implemented Select and Insert commands but Update and Delete can be implemented on the
same lines as Insert.

Some things worth mentioning about the application are:

 This should in no way be treated as a design reference for the data access layer. This is only to
demonstrate ADO.NET logic.
 The code is written in such a way as to provide a clear understanding from a beginner's perspective,
i.e., experienced programmers will find a lot of possible optimizations in the code.
 No client side or server side validations have been provided as that was not the scope of this article.
 There is no design (architecture wise and look wise) in this application.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

DataSet
Keyword Array Dictionary List String Sub ArrayList Cast
Class Console Dates DataTable DateTime Enum File For Form
at If IndexOf Lambda LINQ Nothing Parse Process Property R
egex Replace Select Sort Split StringBuilder Substring
DataSet stores many DataTables in VB.NET programs. A DataSet is
conceptually a set of DataTables and other information about those
tables. It is an abstraction that makes programs simpler to develop.

Info: This is a container for multiple DataTables. You can use it to


create XML. It is a useful abstraction for simplifying programs.

Example. This example shows how to add multiple DataTables to a


DataSet collection. You should have some DataTables instantiated.
Then, create a new DataSet with the constructor. Next, add tables
with the Tables.Add subroutine invocation.

Finally:We demonstrate that the GetXml() function will print


formatted XML that represents the data.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

VB.NET program that uses DataSet

Module Module1
Sub Main()
' Two DataTables.
Dim table1 As DataTable = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)
table1.Rows.Add("mark", 2)

Dim table2 As DataTable = New


DataTable("medications")
table2.Columns.Add("id")
table2.Columns.Add("medication")
table2.Rows.Add(1, "atenolol")
table2.Rows.Add(2, "amoxicillin")

' Create a DataSet. Put both tables in it.


Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Tables.Add(table2)

' Visualize DataSet.


Console.WriteLine(set1.GetXml())
End Sub
End Module

Output

<office>
<patients>
<name>sam</name>
<id>1</id>
</patients>
<patients>
<name>mark</name>
<id>2</id>
</patients>
<medications>

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

<id>1</id>
<medication>atenolol</medication>
</medications>
<medications>
<id>2</id>
<medication>amoxicillin</medication>
</medications>
</office>
Using. The Using resource acquisition statement can be used
with the DataSet. This sometimes alleviates memory usage
problems in programs. The following example demonstrates
the correct syntax for the Using statement and a DataSet
instance.
VB.NET program that shows Using statement with DataSet

Module Module1
Sub Main()
Using set1 As DataSet = New DataSet("office")
' Use set1 here.
End Using
End Sub
End Module
Namespace, Prefix. One of the uses of DataSet is that it
allows you to get XML data for its contents. This can
generate complete XML files. With the Namespace and Prefix
properties, you can form correct XML for your specific
application's requirements.

Here:Look at how the


Namespace "y" and the
Prefix "x" appear in the
output of this program.
VB.NET program that uses Namespace and Prefix

Module Module1
Sub Main()
' Create DataTable.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Dim table1 As DataTable = New DataTable("patients")


table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)

' Create DataSet.


Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Namespace = "y"
set1.Prefix = "x"

' Visualize it.


Console.WriteLine(set1.GetXml())
End Sub
End Module

Output

<x:office xmlns:x="y">
<patients xmlns="y">
<name>sam</name>
<id>1</id>
</patients>
</x:office>
DataSetName. It is possible to change the name of your
DataSet. When you call the DataSet constructor with a String
argument, that sets the initial name. You can also modify or
read the name by using the DataSetName String property.
VB.NET program that uses DataSetName

Module Module1
Sub Main()
' Initialize DataSet.
Dim set1 As DataSet = New DataSet("office")

' Display, set, then display DataSetName.


Console.WriteLine(set1.DataSetName)
set1.DataSetName = "unknown"
Console.WriteLine(set1.DataSetName)
End Sub

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

End Module

Output

office
unknown
Copy, Clear. The DataSet provides ways for you to copy the
entire contents of it into another object. You can use the
Copy function for this purpose. We also show the Clear
subroutine here, which scrubs the contents of the enclosed
DataTables.

Tip:When we call Clear,


the copied DataSet is
not changed. The two
objects are in separate
memory.
VB.NET program that uses Copy and Clear

Module Module1
Sub Main()
Dim table1 = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)

Dim table2 = New DataTable("medications")


table2.Columns.Add("id")
table2.Columns.Add("medication")
table2.Rows.Add(1, "atenolol")

' Create a DataSet instance.


Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Tables.Add(table2)

' Copy.
Dim copy As DataSet = set1.Copy()

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

' Clear original DataSet instance.


set1.Clear()

Console.WriteLine("set: {0}", set1.GetXml())


Console.WriteLine("copy: {0}", copy.GetXml())
End Sub
End Module

Output

set: <office />


copy: <office>
<patients>
<name>sam</name>
<id>1</id>
</patients>
<medications>
<id>1</id>
<medication>atenolol</medication>
</medications>
</office>
Loop through DataTables. Sometimes it is useful to loop
through the DataTable instances stored in the enclosing
DataSet. With a For-loop, we loop from 0 to the Count of the
Tables collection minus one. Then we get each collection
from the index value.
VB.NET program that loops through tables

Module Module1
Sub Main()
Dim table1 As DataTable = New DataTable("patients")
table1.Columns.Add("name")
table1.Columns.Add("id")
table1.Rows.Add("sam", 1)

Dim table2 As DataTable = New


DataTable("medications")
table2.Columns.Add("id")
table2.Columns.Add("medication")

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

table2.Rows.Add(1, "atenolol")
table2.Rows.Add(6, "trifluoperazine")

' Create the DataSet.


Dim set1 As DataSet = New DataSet("office")
set1.Tables.Add(table1)
set1.Tables.Add(table2)

' Loop over tables in the DataSet.


Dim collection As DataTableCollection = set1.Tables
For i As Integer = 0 To collection.Count - 1
' Get table.
Dim table As DataTable = collection(i)
Console.WriteLine("{0}: {1}", i,
table.TableName)
Next

' First table.


Console.WriteLine("x: {0}",
set1.Tables(0).TableName)

' Row count of medications table.


Console.WriteLine("y: {0}",
set1.Tables("medications").Rows.Count)
End Sub
End Module

Output

0: patients
1: medications
x: patients
y: 2

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Typed DataSets in .NET


Introduction

As all of we know, we can specify the Data type when we create a


DataColumn for a DataTable. This is to enforce the runtime Type-safety for
the column so that only data of specified data type can be stored in the
column. In the same way, in most of the cases we prefer to make a DataSet
itself as Type-safe so as to protect it from runtime mismatch. Hence Typed
DataSets generate classes that expose each object the in the DataSet in
Type-safe manner. These classes inherits directly from DataSet class.

Let us look into a small example which explain the Typed DataSet,

1. Using DataSet:

//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno,empname,empaddress
FROM EMPLOYEE",conn);
//Create a DataSet Object
DataSet dsEmp = new DataSet();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.Tables["EMPLOYEE"].Rows[0][0].ToString());
//Assign a value to the first column
dsEmp.Tables["EMPLOYEE"].Rows[0][0] = "12345";//This will generate runtime error as
empno column is integer

If we observe above code we will get a runtime error when this code gets
executed as the value assigned to the column (empno) does not take string
value. Also any misspell of the column will generate a runtime error. And
also we need to go thro the hierarchy to get the final value.

2. Using Typed DataSet:

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

//Create DataAdapter
SqlDataAdapter daEmp = new SqlDataAdapter("SELECT empno,empname,empaddress
FROM EMPLOYEE",conn);
//Create a DataSet Object
EmployeeDS dsEmp = new EmployeeDS ();
//Fill the DataSet
daEmp.Fill(dsEmp,"EMPLOYEE");
//Let us print first row and first column of the table
Console.Write(dsEmp.EMPLOYEE[0].empno.ToString());
//Assign a value to the first column
dsEmp.EMPLOYEE[0].empno = "12345";//This will generate compile time error.

If we see above code, a typed dataset is very much similar to a normal


dataset. But the only difference is that the sehema is already present for the
same. Hence any mismatch in the column will generate compile time errors
rather than runtime error as in the case of normal dataset. Also accessing
the column value is much easier than the normal dataset as the column
definition will be available in the schema.

How to Generate Typed DataSet?

A Typed DataSet can be generated in two ways,

1. Using Visual Studio .NET IDE.


2. Using XSD.exe (Using VS.Net command prompt)
Open VS.Net command prompt and Type XSD /? For the help on this exe.

Creating a Typed DataSet using Visual Studio .NET IDE

Let me explain a step by step procedure to create a Typed DataSet,

1. Open VS .Net IDE and Click on File -> New -> Project and Select Console
Application.
2. Enter name for the project. Say TypedDataSetTest.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

3. Right click on the solution and click on Add-> Add New Item will show a
dialog box.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Select DataSet from templates pane, give the name (Say TypedDs.xsd) and
click on Open. This will add file by name TypedDs.xsd to the solution.

4. Click on the Server Explorer browse to the database and drop the table on
the TypedDs.xsd file.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

If we check the xml file for the same then we can see the schema for the
table.

This dataset can be used in the same manner as the normal dataset to get
the data.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

C# ADO.NET DataAdapter
DataAdapter is a part of the ADO.NET Data Provider. DataAdapter
provides the communication between the Datasetand the
Datasource. We can use the DataAdapter in combination with the
DataSet Object. DataAdapter provides this combination by mapping
Fill method, which changes the data in the DataSet to match the
data in the data source, and Update, which changes the data in the
data source to match the data in the DataSet. That is, these two
objects combine to enable both data access and data manipulation
capabilities.

The DataAdapter can perform Select , Insert , Update and Delete


SQL operations in the Data Source. The Insert , Update and Delete
SQL operations , we are using the continuation of the Select
command perform by the DataAdapter.
TheSelectCommand property of the DataAdapter is a Command
Object that retrieves data from the data source.
TheInsertCommand , UpdateCommand ,
and DeleteCommandproperties of the DataAdapter are Command
objects that manage updates to the data in the data source
according to modifications made to the data in the DataSet. From
the following links describes how to use SqlDataAdapter
and OleDbDataAdapter in detail.

C# ADO.NET SqlDataAdapter
CS6001 C# AND .NET PROGRAMMING Unit III
Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

SqlDataAdapter Class is a part of the C# ADO.NET Data Provider


and it resides in the System.Data.SqlClient namespace.
SqlDataAdapter provides the communication between the Dataset
and the SQL database. We can use SqlDataAdapter Object in
combination with Dataset Object. DataAdapter provides this
combination by mapping Fill method, which changes the data in the
DataSet to match the data in the data source, and Update, which
changes the data in the data source to match the data in the
DataSet.
SqlDataAdapter adapter = new SqlDataAdapter();

adapter.Fill(ds);

The SqlDataAdapter Object and DataSet objects are combine to


perform both data access and data manipulation operations in
theSQL Server Database. When the user perform the SQL
operations like Select , Insert etc. in the data containing in
the DatasetObject , it won't directly affect the Database, until the
user invoke the Update method in the SqlDataAdapter.

using System;
using System.Windows.Forms;
using System.Data;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection sqlCnn ;
SqlCommand sqlCmd ;
SqlDataAdapter adapter = new SqlDataAdapter();
DataSet ds = new DataSet();
int i = 0;
string sql = null;

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

connetionString = "Data Source=ServerName;Initial


Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Select * from product";

sqlCnn = new SqlConnection(connetionString);


try
{
sqlCnn.Open();
sqlCmd = new SqlCommand(sql, sqlCnn);
adapter.SelectCommand = sqlCmd;
adapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " --
" + ds.Tables[0].Rows[i].ItemArray[1]);
}
adapter.Dispose();
sqlCmd.Dispose();
sqlCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ADO.NET OleDbDataAdapter
The OleDbDataAdapter is a part of the C# ADO.NET Data Provider
and it resides in the System.Data.OleDb namespace. The
OleDbDataAdapter provides the communication between the
Dataset and the OleDb Data Sources. We can use
OleDbDataAdapter Object in combination with Dataset Object.
DataAdapter provides this combination by mapping Fill method,
which changes the data in the DataSet to match the data in the
data source, and Update, which changes the data in the data source
to match the data in the DataSet.
OleDbDataAdapter oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);

oledbAdapter.Fill(ds);

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

The OleDbDataAdapter Object and DataSet objects are combine


to perform both Data Access and Data Manipulation operations in
the OleDb Data Sources. When the user perform the SQL operations
like Select , Insert etc. in the data containing in theDataset
Object , it won't directly affect the Database, until the user invoke
the Update method in the OleDbDataAdapter.
using System;
using System.Windows.Forms;
using System.Data;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection oledbCnn ;
OleDbDataAdapter oledbAdapter ;
DataSet ds = new DataSet();
string sql = null;
int i = 0;

connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=Your mdb filename;";
sql = "Your SQL Statement Here like Select * from product";

oledbCnn = new OleDbConnection(connetionString);


try
{
oledbCnn.Open();
oledbAdapter = new OleDbDataAdapter(sql, oledbCnn);
oledbAdapter.Fill(ds);
for (i = 0; i <= ds.Tables[0].Rows.Count - 1; i++)
{
MessageBox.Show(ds.Tables[0].Rows[i].ItemArray[0] + " --
" + ds.Tables[0].Rows[i].ItemArray[1]);
}
oledbAdapter.Dispose();
oledbCnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Insert, Delete, and Update using Stored


Procedure in ASP.NET
A stored procedure is nothing more than a prepared SQL code that you save so
you can reuse the code over and over again. So if you think about a query that you
write over and over again, instead of having to write that query each time you would
save it as a stored procedure and then just call the stored procedure to execute the
SQL code that you saved as part of the stored procedure.

“ SP is pre-define and pre-compiled set of souce code.”

Basic Difference between Stored Procedure and Functions

1. Function must return a value, but in Stored Procedure it is optional (procedure


can return zero or n values).

2. Functions can have only input parameters for it, whereas procedures can
have input/output parameters.

3. Functions can be called from procedure, whereas procedures cannot be


called from function.

4. Procedure allows SELECT as well as DML (INSERT/UPDATE/DELETE)


statement in it whereas function allows only SELECT statement in it.

5. Stored procedure is precompiled execution plan whereas functions are not.

Note: Sometimes we face a question, why we can't execute stored procedure inside
a function?

Answer:

1. Stored Procedure may contain DML statements.


2. Function can't contain DML statements.

So executing function inside stored procedure will never break rule 1, but executing
stored procedure inside function may break rule 2.

So ultimately strict rule is made that we can't execute stored procedures inside
function.

First we have to create one Table. E.g. Registration

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

1. CREATE TABLE UserRegistration (


2. C_Id int IDENTITY(1, 1) NOT NULL,
3. C_Name varchar(100) NULL,
4. C_Age varchar(100) NULL,
5. C_Country varchar(100) NULL
6. );

After that we have to create one stored procedure. E.g. SpMyProcedure.

1. Create procedure SpMyProcedure (


2. @Id int = null,
3. @Name varchar(100)= null,
4. @Age varchar(100)= null,
5. @Country varchar(100)= null,
6. @Action varchar(100)= null
7. ) As begin if @Action = 'Insert' Insert into UserRegistration(C_Name, C_Age, C
_Country)
8. values
9. (@Name, @Age, @Country) if @Action = 'Update'
10. Update
11. UserRegistration
12. set
13. C_Name = @Name,
14. C_Age = @Age,
15. C_Country = @Countrywhere C_Id = @Id if @Action = 'Delete'
16. Delete from
17. UserRegistration
18. where
19. C_Id = @Id end

Now we can call stored procedure from our code like the following for Insert
operation.

1. protected void btnSave_Click(object sender, EventArgs e)


2. {
3. string str = "server=Your Server Name; Initial Catalog=Your Database Name;
User ID=User Id; Password=Your Password";
4. SqlConnection cn = new SqlConnection(str);
5. SqlCommand cmd = new SqlCommand("SpMyProcedure", cn);
6. cmd.CommandType = CommandType.StoredProcedure;
7. cmd.Parameters.AddWithValue("@Action", "Insert");
8. cmd.Parameters.AddWithValue("@Name", txtName.Text);
9. cmd.Parameters.AddWithValue("@Age", txtAge.Text);
10. cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
11. cn.Open();
12. cmd.ExecuteNonQuery();
13. cn.Close();
14. }

We can call stored procedure from our code like the following for Delete operation.

1. protected void btnDelete_Click(object sender, EventArgs e)


2. {

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

3. string str = "server=Your Server Name; Initial Catalog=Your Database Name;


User ID=User Id; Password=Your Password";
4. SqlConnection cn = new SqlConnection(str);
5. SqlCommand cmd = new SqlCommand("SpMyProcedure", cn);
6. cmd.CommandType = CommandType.StoredProcedure;
7. cmd.Parameters.AddWithValue("@Action", "Delete");
8. cmd.Parameters.AddWithValue("@Id", txtId.Text);
9. cn.Open();
10. cmd.ExecuteNonQuery();
11. cn.Close();
12. }

We can call stored procedure from our code like the following for Update operation.

1. protected void btnUpdate_Click(object sender, EventArgs e)


2. {
3. string str = "server=Your Server Name; Initial Catalog=Your Database Name;
User ID=User Id; Password=Your Password";
4. SqlConnection cn = new SqlConnection(str);
5. SqlCommand cmd = new SqlCommand("SpMyProcedure", cn);
6. cmd.CommandType = CommandType.StoredProcedure;
7. cmd.Parameters.AddWithValue("@Action", "Update");
8. cmd.Parameters.AddWithValue("@Name", txtName.Text);
9. cmd.Parameters.AddWithValue("@Age", txtAge.Text);
10. cmd.Parameters.AddWithValue("@Country", txtCountry.Text);
11. cmd.Parameters.AddWithValue("@Id", txtId.Text);
12. cn.Open();
13. cmd.ExecuteNonQuery();
14. cn.Close();
15. }

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

C# SQL Server Connection


You can connect your C# application to data in a SQL Server
database using the .NET Framework Data Provider for SQL Server.
The first step in a C# application is to create an instance of the
Server object and to establish its connection to an instance of
Microsoft SQL Server.

The SqlConnection Object is Handling the part of physical


communication between the C# application and the SQL Server
Database . An instance of the SqlConnection class in C# is
supported the Data Provider for SQL Server Database. The
SqlConnection instance takes Connection String as argument and
pass the value to the Constructor statement.

Sql Server connection string

connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;User ID=UserName;Password=Password"

If you have a named instance of SQL Server, you'll need to add that
as well.

"Server=localhost\sqlexpress"

When the connection is established , SQL Commands will execute


with the help of the Connection Object and retrieve or manipulate
the data in the database. Once the Database activities is over ,
Connection should be closed and release the Data Source resources
.

cnn.Close();

The Close() method in SqlConnection Class is used to close the


Database Connection. The Close method rolls back any pending
transactions and releases the Connection from the SQL Server
Database.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

A Sample C# Program that connect SQL Server using connection


string.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

Connect via an IP address

connetionString="Data Source=IP_ADDRESS,PORT;
Network Library=DBMSSOCN;Initial Catalog=DatabaseName;
User ID=UserName;Password=Password"

1433 is the default port for SQL Server.

Trusted Connection from a CE device

connetionString="Data Source=ServerName;
Initial Catalog=DatabaseName;Integrated Security=SSPI;
User ID=myDomain\UserName;Password=Password;

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

This will only work on a CE device

Connecting to SQL Server using windows authentication

"Server= localhost; Database= employeedetails;


Integrated Security=SSPI;"

A sample c# program that demonstrate how to execute sql


statement and read data from SQL server.

using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
string sql = null;
SqlDataReader dataReader ;
connetionString = "Data Source=ServerName;Initial
Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statement Here , like Select * from product";
connection = new SqlConnection(connetionString);
try
{
connection.Open();
command = new SqlCommand(sql, connection);
dataReader = command.ExecuteReader();
while (dataReader.Read())
{
MessageBox.Show(dataReader.GetValue(0) + " - " +
dataReader.GetValue(1) + " - " + dataReader.GetValue(2));
}
dataReader.Close();
command.Dispose();
connection.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

A sample C# program that perform Data Manipulation tasks like


Insert , Update , Delete etc. also perform by the ExecuteNonQuery()
of SqlCommand Object.

C# OLEDB Connection
The C# OleDbConnection instance takes Connection String as
argument and pass the value to the Constructor statement. An
instance of the C# OleDbConnection class is supported theOLEDB
Data Provider .
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=yourdatabasename.mdb;";

cnn = new OleDbConnection(connetionString);

When the connection is established between C# application and the


specified Data Source, SQL Commands will execute with the help of
the Connection Object and retrieve or manipulate data in the
database. Once the Database activities is over Connection should be
closed and release from the data source resources .
cnn.Close();

The Close() method in the OleDbConnection class is used to close


the Database Connection. The Close method Rolls Back any
pending transactions and releases the Connection from the
Database connected by the OLEDB Data Provider.
using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

string connetionString = null;


OleDbConnection cnn ;
connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=yourdatabasename.mdb;";
cnn = new OleDbConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

C# ODBC Connection
An instance of the OdbcConnection Class in C# is supported the
ODBC Data Provider. The OdbcConnection instance takes
Connection String as argument and pass the value to the
Constructor statement. When the connection is established between
C# application and the Data Source the SQL Commands will execute
with the help of the Connection Object and retrieve or manipulate
data in the database.
connetionString = "Driver={Microsoft Access Driver (*.mdb)};
DBQ=yourdatabasename.mdb;";

cnn = new OdbcConnection(connetionString);

Once the Database activities is over you should be closed the


Connection and release the Data Source resources . The Close()
method in OdbcConnection Class is used to close the Database
Connection.
cnn.Close();

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

The Close method rolls back any pending transactions and releases
the Connection from the Database connected by theODBC Data
Provider .
using System;
using System.Windows.Forms;
using System.Data.Odbc;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OdbcConnection cnn ;
connetionString = "Driver={Microsoft Access Driver
(*.mdb)};DBQ=yourdatabasename.mdb;";
cnn = new OdbcConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

C# ADO.NET Command
The Command Object in ADO.NET executes SQL statements and
Stored Procedures against the data source specified in the C#
Connection Object. The Command Object requires an instance of a
C# Connection Object for executing the SQL statements .

In order to retrieve a resultset or execute an SQL statement against


a Data Source , first you have to create a Connection Object and
open a connection to the Data Source specified in the connection
string. Next step is to assign the open connection to the connection
property of the Command Object . Then the Command Object can
execute the SQL statements. After the execution of the SQl
statement, the Command Object will return a result set . We can
retrieve the result set using a Data Reader.

The Command Object has a property called CommandText ,


which contains a String value that represents the command that will
be executed against the Data Source. When
theCommandType property is set to StoredProcedure, the
CommandText property should be set to the name of the stored
procedure.

Click the following links to see some important built in methods uses
in the Command Object to execute the SQL statements.

C# ExecuteNonQuery

C# ExecuteReader

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

C# ExecuteScalar

C# ADO.NET SqlCommand -
ExecuteNonQuery
The ExecuteNonQuery() is one of the most frequently used
method in SqlCommand Object, and is used for executing
statements that do not return result sets (ie. statements like insert
data , update data etc.) .
Command.ExecuteNonQuery();

The ExecuteNonQuery() performs Data Definition tasks as well as


Data Manipulation tasks also. The Data Definition tasks like creating
Stored Procedures ,Views etc. perform by
theExecuteNonQuery() . Also Data Manipulation tasks like Insert ,
Update , Delete etc. also perform by the ExecuteNonQuery() of
SqlCommand Object.

The following C# example shows how to use the method


ExecuteNonQuery() through SqlCommand Object.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial


Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";

cnn = new SqlConnection(connetionString);

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed
!!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

How to C# ADO.NET OleDbCommand -


ExecuteNonQuery
The ExecuteNonQuery() is one of the most frequently used
method in OleDbCommand Object and is used for executing
statements that do not returns result sets. The ExecuteNonQuery()
performs Data Definition tasks as well as Data Manipulation tasks
also.
cmd.ExecuteNonQuery();

The Data Definition tasks like creating Stored Procedures, Views etc.
perform by the ExecuteNonQuery() . Also Data Manipulation tasks
like Insert , Update , Delete etc. perform by the
ExecuteNonQuery().

The following C# example shows how to use the method


ExecuteNonQuery() through OleDbCommand Object.
using System;
using System.Windows.Forms;
using System.Data.OleDb;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
OleDbConnection cnn ;
OleDbCommand cmd ;
string sql = null;

connetionString =
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Your mdb filename;"
sql = "Your SQL Statement Here"

cnn = new OleDbConnection(connetionString);


try
{
cnn.Open();
MessageBox.Show("Connection Opened ");
cmd = new OleDbCommand(sql, cnn);
cmd.ExecuteNonQuery();
cmd.Dispose();
cnn.Close();
MessageBox.Show (" ExecuteNonQuery in OleDbConnection
executed !!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! " +
ex.ToString());
}
}
}
}

C# ADO.NET SqlCommand - ExecuteScalar


The ExecuteScalar() in C# SqlCommand Object is using for
retrieve a single value from Database after the execution of the SQL
Statement. The ExecuteScalar() executes SQL statements as well as
Stored Procedure and returned a scalar value on first column of first
row in the returned Result Set.

If the Result Set contains more than one columns or rows , it will
take only the value of first column of the first row, and all other
values will ignore. If the Result Set is empty it will return
a NULLreference.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

It is very useful to use with aggregate functions


like Count(*) orSum() etc. When compare to ExecuteReader() ,
ExecuteScalar() uses fewer System resources.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection cnn ;
SqlCommand cmd ;
string sql = null;

connetionString = "Data Source=ServerName;Initial


Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statement Here like Select Count(*) from
product";

cnn = new SqlConnection(connetionString);


try
{
cnn.Open();
cmd = new SqlCommand(sql, cnn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
cmd.Dispose();
cnn.Close();
MessageBox.Show (" No. of Rows " + count);
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

using System;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

private void button1_Click(object sender, EventArgs e)


{
string connetionString = null;
SqlConnection connection ;
SqlCommand command ;
string sql = null;

connetionString = "Data Source=ServerName;Initial


Catalog=DatabaseName;User ID=UserName;Password=Password";
sql = "Your SQL Statemnt Here";

connection = new SqlConnection(connetionString);


try
{
connection.Open();
command = new SqlCommand(sql, connection);
command.ExecuteNonQuery();
command.Dispose();
connection.Close();
MessageBox.Show (" ExecuteNonQuery in SqlCommand executed
!!");
}
catch (Exception ex)
{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

VB.Net - Exception Handling


An exception is a problem that arises during the execution of a program.
An exception is a response to an exceptional circumstance that arises while
a program is running, such as an attempt to divide by zero.

Exceptions provide a way to transfer control from one part of a program to


another. VB.Net exception handling is built upon four
keywords: Try, Catch,Finally and Throw.

 Try: A Try block identifies a block of code for which particular exceptions
will be activated. It's followed by one or more Catch blocks.

 Catch: A program catches an exception with an exception handler at the


place in a program where you want to handle the problem. The Catch
keyword indicates the catching of an exception.

 Finally: The Finally block is used to execute a given set of statements,


whether an exception is thrown or not thrown. For example, if you open
a file, it must be closed whether an exception is raised or not.

 Throw: A program throws an exception when a problem shows up. This


is done using a Throw keyword.

Syntax
Assuming a block will raise an exception, a method catches an exception
using a combination of the Try and Catch keywords. A Try/Catch block is
placed around the code that might generate an exception. Code within a
Try/Catch block is referred to as protected code, and the syntax for using
Try/Catch looks like the following:

Try

[ tryStatements ]

[ Exit Try ]

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

[ Catch [ exception [ As type ] ] [ When expression ]

[ catchStatements ]

[ Exit Try ] ]

[ Catch ... ]

[ Finally

[ finallyStatements ] ]

End Try

You can list down multiple catch statements to catch different type of
exceptions in case your try block raises more than one exception in
different situations.

Exception Classes in .Net Framework


In the .Net Framework, exceptions are represented by classes. The
exception classes in .Net Framework are mainly directly or indirectly derived
from theSystem.Exception class. Some of the exception classes derived
from the System.Exception class are
the System.ApplicationException andSystem.SystemException classes
.

The System.ApplicationException class supports exceptions generated


by application programs. So the exceptions defined by the programmers
should derive from this class.

The System.SystemException class is the base class for all predefined


system exception.

The following table provides some of the predefined exception classes


derived from the Sytem.SystemException class:

Exception Class Description

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

System.IO.IOException Handles I/O errors.

System.IndexOutOfRangeException Handles errors generated when a method


refers to an array index out of range.

System.ArrayTypeMismatchException Handles errors generated when type is


mismatched with the array type.

System.NullReferenceException Handles errors generated from deferencing


a null object.

System.DivideByZeroException Handles errors generated from dividing a


dividend with zero.

System.InvalidCastException Handles errors generated during


typecasting.

System.OutOfMemoryException Handles errors generated from insufficient


free memory.

System.StackOverflowException Handles errors generated from stack


overflow.

Handling Exceptions
VB.Net provides a structured solution to the exception handling problems in
the form of try and catch blocks. Using these blocks the core program
statements are separated from the error-handling statements.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

These error handling blocks are implemented using


the Try, Catch and Finallykeywords. Following is an example of throwing
an exception when dividing by zero condition occurs:

Module exceptionProg

Sub division(ByVal num1 As Integer, ByVal num2 As Integer)

Dim result As Integer

Try

result = num1 \ num2

Catch e As DivideByZeroException

Console.WriteLine("Exception caught: {0}", e)

Finally

Console.WriteLine("Result: {0}", result)

End Try

End Sub

Sub Main()

division(25, 0)

Console.ReadKey()

End Sub

End Module

When the above code is compiled and executed, it produces the following
result:

Exception caught: System.DivideByZeroException: Attempted to divide by zero.

at ...

Result: 0

Creating User-Defined Exceptions


You can also define your own exception. User-defined exception classes are
derived from the ApplicationException class. The following example
demonstrates this:

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Module exceptionProg

Public Class TempIsZeroException : Inherits ApplicationException

Public Sub New(ByVal message As String)

MyBase.New(message)

End Sub

End Class

Public Class Temperature

Dim temperature As Integer = 0

Sub showTemp()

If (temperature = 0) Then

Throw (New TempIsZeroException("Zero Temperature found"))

Else

Console.WriteLine("Temperature: {0}", temperature)

End If

End Sub

End Class

Sub Main()

Dim temp As Temperature = New Temperature()

Try

temp.showTemp()

Catch e As TempIsZeroException

Console.WriteLine("TempIsZeroException: {0}", e.Message)

End Try

Console.ReadKey()

End Sub

End Module

When the above code is compiled and executed, it produces the following
result:

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

TempIsZeroException: Zero Temperature found

Throwing Objects
You can throw an object if it is either directly or indirectly derived from the
System.Exception class.

You can use a throw statement in the catch block to throw the present
object as:

Throw [ expression ]

The following program demonstrates this:

Module exceptionProg

Sub Main()

Try

Throw New ApplicationException("A custom exception _

is being thrown here...")

Catch e As Exception

Console.WriteLine(e.Message)

Finally

Console.WriteLine("Now inside the Finally Block")

End Try

Console.ReadKey()

End Sub

End Module

When the above code is compiled and executed, it produces the following
result:

A custom exception is being thrown here...

Now inside the Finally Block

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

ASP.NET - Validators
ASP.NET validation controls validate the user input data to ensure that
useless, unauthenticated, or contradictory data don't get stored.

ASP.NET provides the following validation controls:

 RequiredFieldValidator

 RangeValidator

 CompareValidator

 RegularExpressionValidator

 CustomValidator

 ValidationSummary

BaseValidator Class
The validation control classes are inherited from the BaseValidator class
hence they inherit its properties and methods. Therefore, it would help to
take a look at the properties and the methods of this base class, which are
common for all the validation controls:

Members Description

ControlToValidate Indicates the input control to validate.

Display Indicates how the error message is shown.

EnableClientScript Indicates whether client side validation will take.

Enabled Enables or disables the validator.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

ErrorMessage Indicates error string.

Text Error text to be shown if validation fails.

IsValid Indicates whether the value of the control is valid.

SetFocusOnError It indicates whether in case of an invalid control, the focus


should switch to the related input control.

ValidationGroup The logical group of multiple validators, where this control


belongs.

Validate() This method revalidates the control and updates the


IsValid property.

RequiredFieldValidator Control
The RequiredFieldValidator control ensures that the required field is not
empty. It is generally tied to a text box to force input into the text box.

The syntax of the control is as given:

<asp:RequiredFieldValidator ID="rfvcandidate"

runat="server" ControlToValidate ="ddlcandidate"

ErrorMessage="Please choose a candidate"

InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

RangeValidator Control
The RangeValidator control verifies that the input value falls within a
predetermined range.

It has three specific properties:

Properties Description

Type It defines the type of the data. The available values are:
Currency, Date, Double, Integer, and String.

MinimumValue It specifies the minimum value of the range.

MaximumValue It specifies the maximum value of the range.

The syntax of the control is as given:

<asp:RangeValidator ID="rvclass" runat="server" ControlToValidate="txtclass"

ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"

MinimumValue="6" Type="Integer">

</asp:RangeValidator>

CompareValidator Control
The CompareValidator control compares a value in one control with a fixed
value or a value in another control.

It has the following specific properties:

Properties Description

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Type It specifies the data type.

ControlToCompare It specifies the value of the input control to compare with.

ValueToCompare It specifies the constant value to compare with.

Operator It specifies the comparison operator, the available values


are: Equal, NotEqual, GreaterThan, GreaterThanEqual,
LessThan, LessThanEqual, and DataTypeCheck.

The basic syntax of the control is as follows:

<asp:CompareValidator ID="CompareValidator1" runat="server"

ErrorMessage="CompareValidator">

</asp:CompareValidator>

RegularExpressionValidator
The RegularExpressionValidator allows validating the input text by matching
against a pattern of a regular expression. The regular expression is set in
the ValidationExpression property.

The following table summarizes the commonly used syntax constructs for
regular expressions:

Character Escapes Description

\b Matches a backspace.

\t Matches a tab.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

\r Matches a carriage return.

\v Matches a vertical tab.

\f Matches a form feed.

\n Matches a new line.

\ Escape character.

Apart from single character match, a class of characters could be specified


that can be matched, called the metacharacters.

Metacharacters Description

. Matches any character except \n.

[abcd] Matches any character in the set.

[^abcd] Excludes any character in the set.

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

\w Matches any alphanumeric character and underscore.

\W Matches any non-word character.

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

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


etc.

\S Matches any non-whitespace character.

\d Matches any decimal character.

\D Matches any non-decimal character.

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


appear.

Quantifier Description

* Zero or more matches.

+ One or more matches.

? Zero or one matches.

{N} N matches.

{N,} N or more matches.

{N,M} Between N and M matches.

The syntax of the control is as given:

<asp:RegularExpressionValidator ID="string" runat="server" ErrorMessage="string"

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

ValidationExpression="string" ValidationGroup="string">

</asp:RegularExpressionValidator>

CustomValidator
The CustomValidator control allows writing application specific custom
validation routines for both the client side and the server side validation.

The client side validation is accomplished through the


ClientValidationFunction property. The client side validation routine should
be written in a scripting language, such as JavaScript or VBScript, which the
browser can understand.

The server side validation routine must be called from the control's
ServerValidate event handler. The server side validation routine should be
written in any .Net language, like C# or VB.Net.

The basic syntax for the control is as given:

<asp:CustomValidator ID="CustomValidator1" runat="server"

ClientValidationFunction=.cvf_func. ErrorMessage="CustomValidator">

</asp:CustomValidator>

ValidationSummary
The ValidationSummary control does not perform any validation but shows
a summary of all errors in the page. The summary displays the values of
the ErrorMessage property of all validation controls that failed validation.

The following two mutually inclusive properties list out the error message:

 ShowSummary : shows the error messages in specified format.

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

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

The syntax for the control is as given:

<asp:ValidationSummary ID="ValidationSummary1" runat="server"

DisplayMode = "BulletList" ShowSummary = "true" HeaderText="Errors:" />

Validation Groups
Complex pages have different groups of information provided in different
panels. In such situation, a need might arise for performing validation
separately for separate group. This kind of situation is handled using
validation groups.

To create a validation group, you should put the input controls and the
validation controls into the same logical group by setting
their ValidationGroupproperty.

Example
The following example describes a form to be filled up by all the students of
a school, divided into four houses, for electing the school president. Here,
we use the validation controls to validate the user input.

This is the form in design view:

The content file code is as given:

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

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

<table style="width: 66%;">

<tr>

<td class="style1" colspan="3" align="center">

<asp:Label ID="lblmsg"

Text="President Election Form : Choose your president"

runat="server" />

</td>

</tr>

<tr>

<td class="style3">

Candidate:

</td>

<td class="style2">

<asp:DropDownList ID="ddlcandidate" runat="server" style="width:239px">

<asp:ListItem>Please Choose a Candidate</asp:ListItem>

<asp:ListItem>M H Kabir</asp:ListItem>

<asp:ListItem>Steve Taylor</asp:ListItem>

<asp:ListItem>John Abraham</asp:ListItem>

<asp:ListItem>Venus Williams</asp:ListItem>

</asp:DropDownList>

</td>

<td>

<asp:RequiredFieldValidator ID="rfvcandidate"

runat="server" ControlToValidate ="ddlcandidate"

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

ErrorMessage="Please choose a candidate"

InitialValue="Please choose a candidate">

</asp:RequiredFieldValidator>

</td>

</tr>

<tr>

<td class="style3">

House:

</td>

<td class="style2">

<asp:RadioButtonList ID="rblhouse" runat="server" RepeatLayout="Flow">

<asp:ListItem>Red</asp:ListItem>

<asp:ListItem>Blue</asp:ListItem>

<asp:ListItem>Yellow</asp:ListItem>

<asp:ListItem>Green</asp:ListItem>

</asp:RadioButtonList>

</td>

<td>

<asp:RequiredFieldValidator ID="rfvhouse" runat="server"

ControlToValidate="rblhouse" ErrorMessage="Enter your house name" >

</asp:RequiredFieldValidator>

<br />

</td>

</tr>

<tr>

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

<td class="style3">

Class:

</td>

<td class="style2">

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

</td>

<td>

<asp:RangeValidator ID="rvclass"

runat="server" ControlToValidate="txtclass"

ErrorMessage="Enter your class (6 - 12)" MaximumValue="12"

MinimumValue="6" Type="Integer">

</asp:RangeValidator>

</td>

</tr>

<tr>

<td class="style3">

Email:

</td>

<td class="style2">

<asp:TextBox ID="txtemail" runat="server" style="width:250px">

</asp:TextBox>

</td>

<td>

<asp:RegularExpressionValidator ID="remail" runat="server"

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

ControlToValidate="txtemail" ErrorMessage="Enter your email"

ValidationExpression="\w+([-+.']\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*">

</asp:RegularExpressionValidator>

</td>

</tr>

<tr>

<td class="style3" align="center" colspan="3">

<asp:Button ID="btnsubmit" runat="server" onclick="btnsubmit_Click"

style="text-align: center" Text="Submit" style="width:140px" />

</td>

</tr>

</table>

<asp:ValidationSummary ID="ValidationSummary1" runat="server"

DisplayMode ="BulletList" ShowSummary ="true" HeaderText="Errors:" />

</form>

The code behind the submit button:

protected void btnsubmit_Click(object sender, EventArgs e)

if (Page.IsValid)

lblmsg.Text = "Thank You";

else

lblmsg.Text = "Fill up all the fields";

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

Simplest way to have a configuration file in a


Windows Forms C# Application
1) Add a new file to your project (Add->New Item->Application Configuration File)

2) The new config file will appear in Solution Explorer as App.Config.

3) Add your settings into this file using the following as a template
<configuration>
<appSettings>
<add key="setting1" value="key"/>
</appSettings>
<connectionStrings>
<add name="prod" connectionString="YourConnectionString"/>
</connectionStrings>
</configuration>
4)Retrieve them like this :
private void Form1_Load(object sender, EventArgs e)
{
string setting = ConfigurationManager.AppSettings["setting1"];
string conn =
ConfigurationManager.ConnectionStrings["prod"].ConnectionString;
}
5) When built, your output folder will contain a file called
<assemblyname>.exe.config This will be a copy of the App.Config file. No further
work should need to be done by the developer to create this file.

Ref :
https://msdn.microsoft.com/libr
ary

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com
www.rejinpaul.com
Sri Vidya College of Engineering & Technology Course Material [ Lecture Notes]

https://en.wikipedia.org
http://www.functionx.com/vcsharp2008/form/dialogboxes3.htm

http://www.dotnetperls.com/dataset-vbnet

http://www.c-
sharpcorner.com/UploadFile/rupadhyaya/TypedDataSets12032005021013AM/TypedDataSets.aspx

http://www.c-sharpcorner.com/blogs/insert-delete-and-update-using-stored-procedure-in-asp-net1

CS6001 C# AND .NET PROGRAMMING Unit III


Get useful study materials from www.rejinpaul.com

You might also like