Sie sind auf Seite 1von 86

.

Net Framework and C#

1. What is .NET?

It is a platform neutral framework.

It is a layer between the operating system and the programming language.

It supports many programming languages, including VB.NET, C# etc.

.NET provides a common set of class libraries, which can be accessed from any .NET
based programming language. There will not be separate set of classes and libraries for
each language. If you know any one .NET language, you can write code in any .NET
language!!

In future versions of Windows, .NET will be freely distributed as part of operating system
and users will never have to install .NET separately.

2. What is Not?

.NET is not an operating system.

.NET is not a programming language.

3. ".NET is a framework"
Confused with this definition?

We cannot define .NET as a 'single thing'.


It is a new, easy, and extensive programming platform.
It is not a programming language, but it supports several programming languages.
By default .NET comes with few programming languages including C# (C Sharp),
VB.NET, J# and managed C++.
.NET is a common platform for all the supported languages. It gives a common class
library, which can be called from any of the supported languages.
So, developers need not learn many libraries when they switch to a different language.
Only the syntax is different for each language.

When you write code in any language and compile, it will be converted to an
'Intermediate Language' (Microsoft Intermediate Language - MSIL).

So, your compiled executable contains the IL and not really ex ecutable machine
language.

When the .NET application runs, the .NET framework in the target computer take care of
the execution. (To run a .NET application, the target computer should have .NET
framework installed.)

The .NET framework converts the calls to .NET class libraries to the corresponding APIs
of the Operating system.

Whether you write code in C# or VB.NET, you are calling methods in the same .NET
class libraries.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#

The same .NET framework executes the C# and VB.NET applications.


So, there won't be any performance difference based on the language you write code.

3.1 Is it platform independent?


Many people ask this question "Java is platform independent, what about .NET?.
The answer is "Yes" and "No!

The code you write is platform independent, because whatever you write is getting
compiled into MSIL.

There is no native code, which depends on your operating system or CPU. But when you
execute the MSIL, the .NET framework in the target system will convert the MSIL into
native platform code.

So, if you run your .NET exe in a Windows machine, the .NET framework for Windows
will convert it into Windows native code and execute.

If you run your .NET application in Unix or Linux, the .NET framework for Unix/Linux will
convert your code into Unix/Linux native code and execute.

So, your code is purely platform independent and runs anywhere!

But wait, we said it wrong... there is no .NET framework for UNIX or Linux available now.
Microsoft has written the .NET framework only for Windows.

If you or some one else write a .NET framework for other platforms in future, your code
will run there too. So, let us wait until someone write .NET framework for Linux before
you run your .NET code in Linux.

3.2 Major Issues before .NET

Registration of COM components.


Unloading COM components
Versioning Problem (DLL Hell)

The .NET Platform


The .Net platform is a set of technologies. Microsoft .NET platform simplify software development
(Windows or WEB) by building applications of XML Web services.
The .NET platform consists of the following core technologies which are refer as components of
.NET:

The .NET Framework


The .NET Enterprise Servers
Building block services
Visual Studio .NET

A programming model (.NET framework) enables developers to build Ex tensible Markup


Language (XML) Web Services and applications.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#

Application
.NET Framework

Libraries

Developer Tools
.NET
Enterprise
Servers

.NET
Building
Block
Services

Visual Studio .NET

CLR
C#, Visual Basic .NET
Windows OS (Win 32)

The .NET Platform Architecture

3.3 Components of .NET Framework


The .Net Framework consists of:

Common Language Runtime


Class Libraries
Support for Multiple Programming Language

.NET Compliant
Languages
(VC++, VB.NET,
ASP.NET, C# and
other third party
languages)

Windows Forms
Web Forms
Web Services

.NET Framework Base Class Library


(ADO.NET, XML, Threading, Diagnostics, IO,
Security, etc.)
Common Language Runtime
(Memory Management, Common Type
System, Garbage Collector)
Components of .NET Framework

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#


4. Application Development and Execution
.NET is a multilingual platform then any .NET based language can be chosen to develop
applications.
4.1 Choosing a Compiler
According to the language we can choose its run time aware compiler for .NET platform. Because
it is a multilingual execution environment, the runtime supports a wide variety of data types and
language features.
4.2 Compiling to MSIL

Source Code

Compiler

EXE/DLL (IL &


Metadata)

Class Libraries
(IL & Metadata)

Class loader

JIT Compiler
Trusted preJIT code only
Managed
Native Code

Call to an uncompiled
method

Execution

Security
checks

Runtime Engine
Source code to native code and code execution
When compiling source code, the compiler translates it into an intermediate code represented in
MSIL. Before code can be run, MSIL code must be converted to CPU-specific code, usually by a
just-in-time (JIT) compiler. When a compiler produces MSIL, it also produces metadata. Metadata
includes following information: -

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#

Description of the types in your code, including the definition of each type.
The signatures of each types members,
The members that your code references.
Other data that the runtime uses at execution time.

The MSIL and metadata are contained in a portable executable (PE) file that is based on and
extends the published Microsoft PE and Common object file format (COFF) used historically for
executable content. The file format, which accommodates MSIL or native code as well as
metadata, enables the operating system to recognize common language runtime images.
4.3 Compiling MSIL to Native Code
Before you can run Microsoft intermediate language (MSIL), it must be compiled against the
common language runtime to native code for the target machine architecture. The .NET
Framework provides two ways to perform this conversion:
A .NET Framework just-in-time (JIT) compiler.
The .NET Framework Ngen.exe (Native Image Generator).
4.4 Compilation by the JIT Compiler
JIT compilation converts MSIL to native code on demand at application run time, when the
contents of an assembly are loaded and executed. Because the common language runtime
supplies a JIT compiler for each supported CPU architecture, developers can build a set of MSIL
assemblies that can be JIT-compiled and run on different computers with different machine
architectures. However, if your managed code calls platform-specific native APIs or a platformspecific class library, it will run only on that operating system.
JIT compilation takes into account the possibility that some code might never be called during
execution. Instead of using time and memory to convert all the MSIL in a PE file to native code, it
converts the MSIL as needed during execution and stores the resulting native code in memory so
that it is accessible for subsequent calls in the context of that process. The loader creates and
attaches a stub to each method in a type when the type is loaded and initialized. When a method
is called for the first time, the stub passes control to the JIT compiler, which converts the MSIL for
that method into native code and modifies the stub to point directly to the generated native code.
Therefore, subsequent calls to the JIT-compiled method go directly to the native code.
Install-Time Code Generation Using NGen.exe
Because the JIT compiler converts an assembly's MSIL to native code when individual methods
defined in that assembly are called, it affects performance adversely at run time. In most cases,
that diminished performance is acceptable. More importantly, the code generated by the JIT
compiler is bound to the process that triggered the compilation. It cannot be shared across
multiple processes. To allow the generated code to be shared across multiple invocations of an
application or across multiple processes that share a set of assemblies, the common language
runtime supports an ahead-of-time compilation mode. This ahead-of-time compilation mode uses
the Ngen.exe (Native Image Generator) to convert MSIL assemblies to native code much like the
JIT compiler does. However, the operation of Ngen.exe differs from that of the JIT compiler in
three ways:
It performs the conversion from MSIL to native code before running the application instead of
while the application is running.
It compiles an entire assembly at a time, instead of one method at a time.
It persists the generated code in the Native Image Cache as a file on disk.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#

4.5 Summary of Managed Code Execution Process


The process of compiling and executing managed code is given below: 1.

2.

3.
4.
5.

6.

7.

8.
9.

When you compile a program developed in a language that targets the CLR, instead of
compiling the source code into machine-level code, the compiler translates it into
Microsoft Intermediate Language (MSIL) or Intermediate language (IL). This ensures
language interoperability.
In addition to translating the code into IL, the compiler also produces metadata about the
program during the process of compilation. Metadata contains the description of the
program, such as classes and interfaces, the dependencies and the versions of the
components used in the program.
The IL and the metadata are linked in assembly.
The compiler creates the .EXE or .DLL file.
When you execute the .EXE or .DLL file, the code (converted to IL) and all the other
relevant information from the base class library is sent to the class loader. The class
loader loads the code in the memory.
Before the code can be executed, the .NET framework needs to convert the IL into native
or CPU-specific code. The Just-in-time (JIT) compiler translates the code from IL to
managed native code. The CLR supplies a JIT compiler for each supported CPU
architecture. During the process of compilation, the JIT compiler compiles only the code
that is required during execution instead of compiling the complete IL code. When an
uncompiled method is invoked during execution, the JIT compiler converts the IL for that
method into native code. This process saves the time and memory required to convert
the complete IL into native code.
During JIT compilation, the code is also checked for type safety. Type safety ensures that
objects are always accessed in a compatible way. Therefore, if you try to pass an 8-byte
value to a method that accepts a 4-byte value as a parameter, the CLR will detect and
trap such an attempt. Type safety also ensures that objects are safely isolated from each
other and are therefore safe from any malicious corruption.
After translating the IL into native code, the converted code is sent to the .NET runtime
manager.
The .NET runtime manager executes the code. While executing the code, a security
check is performed to ensure that the code has the appropriate permissions for
accessing the available resources.

Common Language Infrastructure (CLI)


The Common Language Infrastructure (CLI) is an open specification developed by Microsoft that
describes the executable code and runtime environment that allows multiple high-level languages
to be used on different computer platforms without being rewritten for specific architectures.
The common language Infrastructure (CLI) is a theoretical model of a development platform that
provides a device and language independent way to express data and behavior of applications.
The CLI specification describes the following four aspects:

The Common Type System (CTS)

The language interoperability and .NET Class Framework are not possible without all the
language sharing the same data type. CTS is an important part of the runtime support for crosslanguage integration. The CTS performs the following functions:

Establishes a framework that enables cross-language integration, type safety and high
performance code execution.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#

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


programming languages.

The CTS supports two general categories of types: 1. Value Types


Value types directly contain their data, and instances of value types are either allocated on the
stack or allocated inline in a structure. Value types can be built-in, user-defined or enumerations
types.
2. Reference Types
Reference types store a reference to the values memory address, and are allocated on the heap.
Reference types can be self-describing types, pointers type or interface types. The type of a
reference type can be determined from values of self-describing types. Self-describing types are
further split into arrays and class types are user-defined classes, boxed value types, and
delegates.
A set of data types and operations that are shared by all CTS-compliant programming
languages.

Metadata

Information about program structure is language-agnostic, so that it can be referenced between


languages and tools, making it easy to work with code written in a language you are not using.

Common Language Specification (CLS)

A set of base rules to which any language targeting the CLI should conform in order to
interoperate with other CLS-compliant languages. The CLS rules define a subset of the Common
Type System.

Virtual Execution System (VES)

The VES loads and executes CLI-compatible programs, using the metadata to combine
separately generated pieces of code at runtime.
The Common Language Runtime
The CLR is one of the most essential components of the .NET framework. The CLR or the
runtime provides functionality such as exception handling, security, debugging, and versioning
support to any language that targets it. The CLR can execute programs written any language.
You can use the compilers to write the code that runs in the managed execution environment
provided by the CLR. The code that is developed with a language compiler that targets the CLR
is managed code. On the other hand, the code that is developed without considering the
conventions and requirements of the common language run time is called unmanaged code.
CLR activates objects, performs security checks, lays them out in memory, executes them and
garbage collects these objects as well.
The CLR is a runtime engine that loads required classes, performs just in time compilations, and
enforces security checks and a bunch of other runtime functions.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#


The CLR executables are either exe or DLL files that consist mostly of metadata and code. These
executables must adhere to a file format called the Portable Executable (PE) file format.
Features Provided by CLR
Some of the features provided by the CLR are as follows:

Automatic Memory Management: The CLR provides the garbage collection feature for
managing the lifetime of an object. This process relieves a programmer of the task of
manual memory management by deallocating the blocks of memory associated with
objects that are no longer being used. The objects whose lifetime is managed by the
garbage collection process are called managed data.

Standard Type System: The CLR implements a formal specification called Common Type
System (CTS). The CTS is an important part of the support provided by the CLR for
cross-language integration because it provides a type system that is common across all
programming languages. It also defines the rules that ensure that objects written in
different languages can interact with each other.

Language Interoperability: Language interoperability is the ability of an application to


interact with another application written in a different programming language. Language
interoperability helps maximize code reuse. For example, you can write a class in Visual
Basic and inherit it in a code written in Visual C++.

Platform Independence: When you compile a program developed in language that targets
the CLR, the compiler translates the code into an intermediate language. This language
is CPU-independent. This means that the code can be executed from any platform that
supports the .NET CLR.

Security Management The traditional operating system security model provides


permissions to access resources, such as memory and data, based on user accounts. In
.NET platform security is achieved through the Code Access Security (CAS) model. The
CAS model specifies what the code can access instead of specifying who can access
resources.

Type Safety: This feature ensures that objects are always accessed in compatible ways.
Therefore the CLR will prohibit a code from assigning a 10-byte value to an object that
occupies 8 bytes.

Advantages of the .NET Framework

Consistent programming model


Multi-platform applications
Multi-Language integration
Automatic Resource Management
Ease of deployment

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#


OOPS & C#
The skeleton of object - oriented programming is of course the concepts of class. The C# on
OOPS explains classes and their importance in implementation of object oriented principles.
Any language can be called object oriented if it has data and method that use data
encapsulated in items named objects. An object oriented programming method has many
advantages; some of them are flexibility and code reusability.
Key Concepts of Object Orientation

Abstraction
Encapsulation
Inheritance
Polymorphism

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 characteristic s, 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.
Classes are blueprints for Object.
Objects are instance of classes.

Object References
When we work with an object we are using a reference to that object. On the other hand, when
we are working with simple data types such as Integer, we are working with the actual value
rather than a reference.
When we create a new object using the New keyword, we store a reference to that object in a
variable. For instance:
Draw MyDraw = new Draw;
This code creates a new instance of Draw. We gain access to this new object via the MyDraw
variable. This variable holds a reference to the object.
Now we have a second variable, which also has a reference to that same object. We can use
either variable interchangeably, since they both reference the exact same object. The thing we
need to remember is that the variable we have is not the object itself but, rather, is just a
reference or pointer to the object itself.
Early binding means that our code directly interacts with the object, by directly calling its
methods. Since the compiler knows the object's data type ahead of time, it can directly compile
code to invoke the methods on the object. Early binding also allows the IDE to use IntelliSense to
aid our development efforts; it allows the compiler to ensure that we are referencing methods that
do exist and that we are providing the proper parameter values.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

.Net Framework and C#


Late binding means that our code interacts with an object dynamically at run-time. This provides
a great deal of flexibility since our code literally doesn't care what type of object it is interacting
with as long as the object supports the methods we want to call. Because the type of the object
isn't known by the IDE or compiler, neither IntelliSense nor compile-time syntax checking is
possible but we get unprecedented flexibility in exchange.
If we enable strict type checking by using Option Strict On at the top of our code modules, then
the IDE and compiler will enforce early binding behavior. By default, Option Strict is turned off and
so we have easy access to the use of late binding within our code.

Access Modifiers
Access Modifiers are keywords used to specify the declared accessibility of a member of a type.

Public is visible to everyone. A public member can be accessed using an instance of a class, by
a class's internal code, and by any descendants of a class.

Private is hidden and usable only by the class itself. No code using a class instance can access
a private member directly and neither can a descendant class.

Protected members are similar to private ones in that they are accessible only by the containing
class. However, protected members also may be used by a descendant class. So members that
are likely to be needed by a descendant class should be marked protected.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

10

.Net Framework and C#

Internal/Friend is public to the entire application but private to any outside applications. Internal
is useful when you want to allow a class to be used by other applications but reserve special
functionality for the application that contains the class. Internal is used by C# and Friend by VB
.NET.

Protected Internal may be accessed only by a descendant class that's contained in the same
application as its base class. You use protected internal in situations where you want to deny
access to parts of a class functionality to any descendant classes found in other applications.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

11

.Net Framework and C#

Composition of an OBJECT
We use an interface to get access to an object's data and behavior. The object's data and
behaviors are contained within the object, so a client application can treat the object like a black
box accessible only through its interface. This is a key object-oriented concept called
Encapsulation. The idea is that any programs that make use of this object won't have direct
access to the behaviors or data-but rather those programs must make use of our object's
interface.
There are three main parts of Object:
1. Interface
2. Implementation or Behavior
3. Member or Instance variables

Interface
The interface is defined as a set of methods (Sub and Function routines), properties (Property
routines), events, and fields (variables or attributes) that are declared Public in scope.

Implementation or Behavior
The code inside of a method is called the implementation. Sometimes it is also called behavior
since it is this code that actually makes the object do useful work.
Client applications can use our object even if we change the implementation-as long as we don't
change the interface. As long as our method name and its parameter list and return data type
remain unchanged, we can change the implementation all we want .
So Method Signature depends on:

Method name

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

12

.Net Framework and C#

Data types of parameters


Either Parameter is passed ByVal or ByRef.
Return type of method

It is important to keep in mind that encapsulation is a syntactic tool-it allows our code to continue
to run without change. However, it is not semantic-meaning that, just because our code continues
to run, doesn't mean it continues to do what we actually wanted it to do.

Member or Instance Variables


The third key part of an object is its data, or state. Every instance of a class is absolutely identical
in terms of its interface and its implementation-the only thing that can vary at all is the data
contained within that particular object.
Member variables are those declared so that they are available to all code within our class.
Typically member variables are Private in scope-available only to the code in our class itself.
They are also sometimes referred to as instance variables or as attributes. The .NET Framework
also refers to them as fields.
We shouldn't confuse instance variables with properties. A Property is a type of method that is
geared around retrieving and setting values, while an instance variable is a variable within the
class that may hold the value exposed by a Property.
Interface looks like a class, but has no implementation.
The only thing it contains is definitions of events, indexers, methods and/or properties. The
reason interfaces only provide definitions is because they are inherited by classes and structs,
which must provide an implementation for each interface member defined.
Defining an Interface: MyInterface.cs
interface IMyInterface
{
void MethodToImplement();

}
Above listing shows defines an interface named IMyInterface.
All the methods of Interface are public by default and no access modifiers (like private, public) are
allowed with any method of Interface.
Using an Interface: InterfaceImplementer.cs
class InterfaceImplementer : IMyInterface
{
public void MethodToImplement ()
{
Console.WriteLine("MethodToImplement() called.");
}
}
The InterfaceImplementer class in above listing implements the IMyInterface interface. Indicating
that a class inherits an interface is the same as inheriting a class. In this case, the following
syntax is used:
class InterfaceImplementer : IMyInterface

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

13

.Net Framework and C#

Note that this class inherits the IMyInterface interface; it must implement its all members. While
implementing interface methods all those needs to be declared public only. It does this by
implementing the MethodToImplement() method. Notice that this method implementation has the
exact same signature, parameters and method name, as defined in the IMyInterface interface.
Any difference will cause a compiler error.

Inheritance is the idea that one class, called a subclass, can be based on another cl ass,
called a base class. Inheritance provides a mechanism for creating hierarchies of objects.
Inheritance is an important object-oriented concept. It allows you to build a hierarchy of related
classes, and to reuse functionality defined in existing clas ses.
Inheritance is the ability to apply another class's interface and code to your own class.
Normal base classes may be instantiated themselves, or inherited. Derived classes can inherit
base class members marked with protected or greater access. The derived class is specialized to
provide more functionality, in addition to what its base class provides. Inheriting base class
members in derived class is not mandatory.
C# supports two types of Inheritance mechanisms: 1) Implementation Inheritance
2) Interface Inheritance

What is Implementation Inheritance?


- When a class (type) is derived from another class(type) such that it inherits all the members of
the base type it is Implementation Inheritance

What is Interface Inheritance?


- When a type (class or a struct) inherits only the signatures of the functions from another type it
is Interface Inheritance
In general, Classes can be derived from another class, hence support Implementation inheritance
At the same time Classes can also be derived from one or more interfaces Hence they support
Interface inheritance Structs can derive from one more interface, hence support Interface
Inheritance Structs cannot be derived from another class they are always derived from
SystemValueType

Types of Inheritance
1.
2.
3.
4.

Single Inheritance
Multilevel Inheritance
Multiple Inheritance
(Implementation is possible through
Hierarchical Inheritance

Interface)

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

14

.Net Framework and C#

Class A

Class B
Single Inheritance

Class A

Class A

Class B

Class D

Class C

Hierarchical Inheritance

Class A

Class B

Class B
Class C
Class C
Multilevel Inheritance

Multiple Inheritance

Example: Single Inheritance: public class A


{ }
public class B : A
{ }

Multiple Inheritance: public class A


{ }
public class B

Multilevel Inheritance: public class A


{ }
public class B : A
{ }
public class C : B
{ }

Hierarchical Inheritance: public class A


{ }
public class B : A
{ }
public class C : A
{ }
public class D : A
{ }

{ }
public class C : A, B

{ }

Polymorphism
Polymorphism is the ability to define a method or property in a set of derived classes with
matching method signatures but provide different implementations and then distinguish the
objects' matching interface from one another at runtime when you call the method on the base
class.
It is a feature to use one name in many forms. It can be achieved in following ways:

Method Overloading
Method Overriding
Method Hiding

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

15

.Net Framework and C#


Method overriding and hiding makes use of the following three method keywords
1.
2.
3.

new
virtual
override

1. When a derived class inherits from a base class, it gains all the methods, fields, properties and
events of the base class. To change the data and behavior of a base class, you have two
choices: you can replace the base member with a new derived member, or you can override a
virtual base member.
Replacing a member of a base class with a new derived member requires the new keyword. If a
base class defines a method, field, or property, the new keyword is used to create a new
definition of that method, field, or property on a derived class. The new keyword is placed before
the return type of a class member that is being replaced. For example:
public class BaseClass
{
public void DoWork() { }
public int WorkField;
public int WorkProperty
{
get { return 0; }
}
}
public class DerivedClass : BaseClass
{
public new void DoWork() { }
public new int WorkField;
public new int WorkProperty
{
get { return 0; }
}
}
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Calls the old method.

2,3. In order for an instance of a derived class to completely take over a class member from a
base class, the base class has to declare that member as virtual. This is accomplished by adding
the virtual keyword before the return type of the member. A derived class then has the option of
using the override keyword, instead of new, to replace the base class implementation with its
own. For example:
public class BaseClass
{
public virtual void DoWork() { }
public virtual int WorkProperty
{
get { return 0; }
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

16

.Net Framework and C#


public class DerivedClass : BaseClass
{
public override void DoWork() { }
public override int WorkProperty
{
get { return 0; }
}
}
DerivedClass B = new DerivedClass();
B.DoWork(); // Calls the new method.
BaseClass A = (BaseClass)B;
A.DoWork(); // Also calls the new method.

Remarks about Virtual

When a virtual method is invoked, the run-time type of the object is checked for an
overriding member. The overriding member in the most derived class is called, whic h
might be the original member, if no derived class has overridden the member.

By default, methods are non-virtual. You cannot override a non-virtual method.

You cannot use the virtual modifier with the static, abstract, private or override modifiers.

Virtual properties behave like abstract methods, except for the differences in declaration
and invocation syntax.

It is an error to use the virtual modifier on a static property.

A virtual inherited property can be overridden in a derived class by including a property


declaration that uses the override modifier.

Remarks about Override

The override modifier is required to extend or modify the abstract or virtual


implementation of an inherited method, property, indexer, or event.

An override method provides a new implementation of a member inherited from a base


class. The method overridden by an override declaration is known as the overridden base
method. The overridden base method must have the same signature as the override
method.

You cannot override a non-virtual or static method. The overridden base method must be
virtual, abstract, or override.

An override declaration cannot change the accessibility of the virtual method. Both the
override method and the virtual method must have the same access level modifier.

You cannot use the modifiers new, static, virtual, or abstract to modify an override
method.

An overriding property declaration must specify the exact same access modifier, type,
and name as the inherited property, and the overridden property must be virtual, abstract,
or override.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

17

.Net Framework and C#


Class and Objects
Classes
A class is a construct that enables you to create your own custom types by grouping together
variables of other types, methods and events. A class is like a blueprint. It defines the data and
behavior of a type. If the class is not declared as static, client code can use it by creating objects
or instances which are assigned to a variable. The variable remains in memory until all references
to it go out of scope. At that time, the CLR marks it as eligible for garbage collection. If the class
is declared as static, then only one copy exists in memory and client code can only access it
through the class itself, not an instance variable.
Declaring Class
public class Customer
{
//Fields, properties, methods and events go here...
}
The class keyword is preceded by the access level. Because public is used in this case, anyone
can create objects from this class. The name of the class follows the class keyword.
Objects
An object is basically a block of memory that has been allocated and configured according to the
blueprint. A program may create many objects of the same class. Objects are also called
instances, and they can be stored in either a named variable or in an array or collection.
Creating Objects
A class and an object are different things. A class defines a type of object, but it is not an object
itself. An object is a concrete entity based on a class, and is sometimes referred to as an instance
of a class.
Objects can be created by using the new keyword followed by the name of the class that the
object will be based on, like this:
Customer object1 = new Customer();
When an instance of a class is created, a reference to the object is passed back to the
programmer. In the previous example, object1 is a reference to an object that is based on
Customer.
Class Modifiers
A class-declaration can optionally include a sequence of class modifiers:
class-modifiers:
class-modifier
class-modifiers class-modifier
class-modifier:
new, public, protected, internal, private, abstract, sealed

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

18

.Net Framework and C#


The new modifier is permitted on nested classes. The new modifier can be used to modify a
nested type if the nested type is hiding another type.
The public, protected, internal, and private modifiers control the accessibility of the class.
Depending on the context in which the class declaration occurs, some of these modifiers may not
be permitted
The abstract modifier is used to indicate that a class is incomplete and that it is intended to be
used only as a base class. An abstract class differs from a non-abstract class in the following
ways:

An abstract class cannot be instantiated directly, and it is a compile-time error to use the
new operator on an abstract class. While it is possible to have variables and values
whose compile-time types are abstract, such variables and values will necessarily either
be null or contain references to instances of non-abstract classes derived from the
abstract types.

An abstract class is permitted (but not required) to contain abstract methods and
members.

An abstract class cannot be sealed.

Features of Abstract Methods:

An abstract method is implicitly a virtual method.


Abstract method declarations are only permitted in abstract classes.
Because an abstract method declaration provides no actual implementation, there is no
method body; the method declaration simply ends with a semicolon and there are no
braces ({ }) following the signature. For example:
Copypublic abstract void MyMethod();

The implementation is provided by an overriding method, which is a member of a nonabstract class.


It is an error to use the static or virtual modifiers in an abstract method declaration.

Abstract properties behave like abstract methods, except for the differences in decl aration and
invocation syntax.

It is an error to use the abstract modifier on a static property.


An abstract inherited property can be overridden in a derived class by including a
property declaration that uses the override modifier.
An abstract class must provide implementation for all interface members.
Example: // abstract_keyword.cs
// Abstract Classes
using System;
abstract class MyBaseC // Abstract class
{
protected int x = 100;
protected int y = 150;
public abstract void MyMethod(); // Abstract method

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

19

.Net Framework and C#


public abstract int GetX // Abstract property
{
get;
}
public abstract int GetY // Abstract property
{
get;
}
}
class MyDerivedC: MyBaseC
{
public override void MyMethod()
{
x++;
y++;
}
public override int GetX // overriding property
{
get
{
return x+10;
}
}
public override int GetY // overriding property
{
get
{
return y+10;
}
}
public static void Main()
{
MyDerivedC mC = new MyDerivedC();
mC.MyMethod();
Console.WriteLine("x = {0}, y = {1}", mC.GetX, mC.GetY);
}
}
The sealed modifier is used to prevent derivation from a class. A compile-time error occurs if a
sealed class is specified as the base class of another class.
A sealed class cannot also be an abstract class.
The sealed modifier is primarily used to prevent unintended derivation, but it also enables certain
run-time optimizations. In particular, because a sealed class is known to never have any derived
classes, it is possible to transform virtual function member invocations on sealed class instances
into non-virtual invocations.
Example: use of Sealed modifier
// cs_sealed_keyword.cs

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

20

.Net Framework and C#


// Sealed classes
using System;
sealed class MyClass
{
public int x;
public int y;
}
class MainClass
{
public static void Main()
{
MyClass mC = new MyClass();
mC.x = 110;
mC.y = 150;
Console.WriteLine("x = {0}, y = {1}", mC.x, mC.y);
}
}
Output: x=110, y=150
Constructors
Whenever a class or struct is created, its constructor is called. A class or struct may have multiple
constructors that take different arguments.
Constructors allow the programmer to set default values, limit instantiation, and write code that is
flexible and easy to read.

Constructor
Constructor
Constructor
Constructor
external).
Constructor

is used to initialize an object (instance) of a class.


is a like a method without any return type.
has same name as class name.
follows the access scope (Can be private, protected, public, Internal and
can be overloaded.

Constructors generally following types:

Default Constructor
Parameterized constructor
Private Constructor
Static Constructor
Copy Constructor

Default Constructor
A constructor that takes no parameters is called a default constructor.
When a class is initiated default constructor is called which provides default values to different
data members of the class.
You need not to define default constructor it is implicitly defined.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

21

.Net Framework and C#


Example: -

class Program
{
class C1
{
int a, b;
public C1()
{
this.a = 10;
this.b = 20;
}
public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);
}
}
static void Main(string[] args)
{
C1 ob1 = new C1();
ob1.display();
Console.ReadLine();
}
}
Output: - Value of a: 10
Value of b: 20

Parameterized constructor
Constructor that accepts arguments is known as parameterized constructor. There may be
situations, where it is necessary to initialize various data members of different objects with
different values when they are created. Parameterized constructors help in doing that task.

class Program
{
class C1
{
int a, b;
public C1(int x, int y)
{
this.a = x;
this.b = y;
}
public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

22

.Net Framework and C#


}
}
static void Main(string[] args)
{ // Here when you create instance of the class
// parameterized constructor will be called
C1 ob1 = new C1(10,20);
ob1.display();
Console.ReadLine();
}
}
Output: - Value of a: 10
Value of b: 20
Private Constructor
Private constructors are used to restrict the instantiation of object using 'new' operator. A private
constructor is a special instance constructor. It is commonly used in classes that contain static
members only.

If you don't want the class to be inherited we declare its constructor private.
We can't initialize the class outside the class or the instance of class can't be created
outside if its constructor is declared private.
We have to take help of nested class (Inner Class) or static method to initialize a class
having private constructor.

Example: class Program


{
class C1
{
int a, b;
public C1(int x, int y)
{
this.a = x;
this.b = y;
}
public static C1 create_instance()
{ return new C1(12, 20); }
public void display()
{
Console.WriteLine("Value of a: {0}", a);
Console.WriteLine("Value of b: {0}", b);
int z = a + b;
Console.WriteLine(z);
}
}
static void Main(string[] args)
{ // Here the class is initiated using a static method of the
class than only you can use private constructor

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

23

.Net Framework and C#


C1 ob1 = C1.create_instance();
ob1.display();
Console.ReadLine();
}
}

Static Constructors
C# supports two types of constructor, a class constructor static constructor and an instance
constructor (non-static constructor).
Static constructors might be convenient, but they are slow. The runtime is not smart enough to
optimize them in the same way it can optimize inline assignments. Non-static constructors are
inline and are faster.
Static constructors are used to initializing class static data members.
Point to be remembered while creating static constructor:
1.
2.
3.
4.

There can be only one static constructor in the class.


The static constructor should be without parameters.
It can only access the static members of the class.
There should be no access modifier in static constructor definition.

Static members are preloaded in the memory. While instance members are post loaded into
memory.
Static methods can only use static data members.
Example:
class Program
{
public class test
{
static string name;
static int age;
static test()
{
Console.WriteLine("Using static constructor to initialize
static data members");
name = "John Sena";
age = 23;
}
public static void display()
{
Console.WriteLine("Using static function");
Console.WriteLine(name);
Console.WriteLine(age);
}
}
static void Main(string[] args)
{
test.display();
Console.ReadLine();
}}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

24

.Net Framework and C#


Output:
Using static constructor to initialize static data members
Using static function
John Sena
23

Copy Constructor
If you create a new object and want to copy the values from an existing object, you use copy
constructor.
This constructor takes a single argument: a reference to the object to be copied.
Example:

class Program
{
class c1
{
int a, b;
public c1(int x, int y)
{
this.a = x;
this.b = y;
}
// Copy construtor
public c1(c1 a)
{
this.a = a.a;
this.b = a.b;
}
public void display()
{
int z = a + b;
Console.WriteLine(z);
}
}
static void Main(string[] args)
{
c1 ob1 = new c1(10, 20);
ob1.display();
// Here we are using copy constructor. Copy
constructor is
using the values already defined with ob1
c1 ob2 = new c1(ob1);
ob2.display();
Console.ReadLine();
}
}
Output:
30
30

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

25

.Net Framework and C#


Destructors
The .NET framework has an in built mechanism called Garbage Collection to de-allocate memory
occupied by the un-used objects. The destructor implements the statements to be executed
during the garbage collection process. A destructor is a function with the same name as the name
of the class but starting with the character ~.
Example:
class Complex
{
public Complex()
{
// constructor
}
~Complex()
{
// Destructor
}
}

Remember that a destructor can't have any modifiers like private, public etc. If we declare
a destructor with a modifier, the compiler will show an error.
Also destructor will come in only one form, without any arguments.
There is no parameterized destructor in C#.

Destructors are invoked automatically and can't be invoked explicitly. An object becomes eligible
for garbage collection, when it is no longer used by the active part of the program. Execution of
destructor may occur at any time after the instance or object becomes eligible for destruction.

Operator Overloading
Operator overloading permits user-defined operator implementations to be specified for
operations where one or both of the operands are of a user-defined class or struct type.
In another way, Operator overloading is a concept in which operator can define to work with the
user defined data types such as structs and classes in the same way as the pre-defined data
types.

There are many operators which can not be overloaded, which are listed below: Conditional Operator
&&, ||
Compound Assignment +=, -=, *=, /=, %=
Other Operators
[], ( ), =, ?:, ->, new, sizeof, typesof.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

26

.Net Framework and C#


public class Item
{
public int i;
public Item(int j)
{ i = j; }
public static Item operator +(Item x, Item y)
{
Console.WriteLine("OPerator +" + x.i + "" + y.i);
Item z = new Item(x.i + y.i);
return z;
}
}
class Program
{
static void Main(string[] args)
{
Item a = new Item(10);
Item b = new Item(5);
Item c;
c = a + b;
Console.WriteLine(c.i);
Console.Read();
}
}
Output: Operator + 10 5
15

In C#, a special function called operator function is used for overloading purpose.
These special function or method must be public and static.
They can take only value arguments.
The ref and out parameters are not allowed as arguments to operator functions.

The general form of an operator function is as follows.

public static return_type operator op (argument list)


Where the op is the operator to be overloaded and operator is the required keyword.
Example: Overloading of Unary operator

class Complex
{
private int x;
private int y;
public Complex()
{}
public Complex(int i, int j)
{

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

27

.Net Framework and C#


x = i;
y = j;
}
public void ShowXY()
{
Console.WriteLine("{0}\t{1}",x,y);
}
public static Complex operator -(Complex c) //PASSING OBJECT
{
Complex temp = new Complex();
temp.x = -c.x;
temp.y = -c.y;
return temp;
}
}
class Program
{
static void Main(string[] args)
{
Complex c1 = new Complex(10, 20);
c1.ShowXY(); // displays 10 & 20
Complex c2 = new Complex();
c2.ShowXY(); // displays 0 & 0
c2 = -c1;
//overloading unary operator
c2.ShowXY(); // diapls -10 & -20
Console.Read();
}
}
Output:
10 20
0 0
-10 -20

Namespace :
Namespaces are C# program elements designed to help you organize your programs. They also
provide assistance in avoiding name clashes between two s ets of code.
In Microsoft .Net, Namespace is like containers of objects. They may contain unions, classes,
structures, interfaces, enumerators and delegates. Main goal of using namespace in .Net is for
creating a hierarchical organization of program. In this case, you need not to worry about the
naming conflicts of classes, functions, variables etc., inside a project.
In Microsoft .Net, every program is created with a default namespace. This default namespace is
called as global namespace. But the program itself can declare any number of namespaces, each
of them with a unique name. The advantage is that every namespace can contain any number of
classes, functions, variables and also namespaces etc., whose names are unique only inside the

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

28

.Net Framework and C#


namespace. The members with the same name can be created in some other namespace
without any compiler complaints from Microsoft .Net.

To declare namespace C# .Net has a reserved keyword namespace. If a new project is created in
Visual Studio .NET it automatically adds some global namespaces. These namespaces can be
different in different projects. But each of them should be placed under the base namespace
System. The names space must be added and used through the using operator, if used in a
different project.
A namespace has the following properties:

They organize large code projects.


They are delimited with the . operator.
The using directive means you do not need to specify the name of the namespace for
every class.
The global namespace is the "root" namespace: global::system will always refer to the
.NET Framework namespace System.

Now have a look at the example of declaring some namespace:


namespace SampleNamespace
{
class SampleClass{}
interface SampleInterface{}
struct SampleStruct{}
enum SampleEnum{a,b}
delegate void SampleDelegate(int i);
namespace SampleNamespace.Nested
{
class SampleClass2{}
}
}
Within a namespace, you can declare one or more of the following types:

another namespace
class
interface
struct
enum
delegate

Namespaces implicitly have public access and this is not modifiable.


It is possible to define a namespace in two or more declarations. For example, the following
example defines two classes as part of the MyCompany namespace:
namespace MyCompany.Proj1
{
class MyClass
{
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

29

.Net Framework and C#

namespace MyCompany.Proj1
{
class MyClass1
{
}
}

Example: The following example shows how to call a static method in a nested
namespace:
using System;
namespace SomeNameSpace
{
public class MyClass
{
static void Main()
{
Nested.NestedNameSpaceClass.SayHello();
}
}
// a nested namespace
namespace Nested
{
public class NestedNameSpaceClass
{
public static void SayHello()
{
Console.WriteLine("Hello");
}
}
}
}
Output
Hello

Example: Calling Nested Namespace Members


// Namespace Declaration
using System;
namespace Ex_nestedNamespace
{
namespace tutorial
{
class example
{
public static void MyPrint1()
{
Console.WriteLine("First Example of calling another namespace member.");
}
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

30

.Net Framework and C#


namespace Ex_NameSpace
{
class Program
{
static void Main(string[] args)
{
tutorial.example.MyPrint1();
tutorial.example1.MyPrint2();
Console.Read();
}
}
}
}
namespace Ex_nestedNamespace.tutorial
{
class example1
{
public static void MyPrint2()
{
Console.WriteLine("Second Example of calling another namespace member.");
}
}
}
Output:
First Example of calling another namespace member.
Second Example of calling another namespace member.

Interface
An Interface is a reference type and it contains only abstract members. Interface's members can
be Events, Methods, Properties and Indexers. But the interface contains only declaration for i ts
members. Any implementation must be placed in class that realizes them. The interface can not
contain constants, data fields, constructors, destructors and static members. All the member
declarations inside interface are implicitly public and they cannot include any access modifiers.
An interface has the following properties:

An interface is like an abstract base class: any non-abstract type that implements the
interface must implement all its members.

An interface cannot be instantiated directly.

Interfaces can contain events, indexers, methods, and properties.

Interfaces contain no implementation of methods.

Classes and structs can implement more than one interface.

An interface itself can inherit from multiple interfaces.

interface IPoint
{

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

31

.Net Framework and C#


int x
{ get; set; }
int y
{ get; set; }
}
namespace Ex_Interface
{
class MyPoint:IPoint
{
private int myX;
private int myY;
public MyPoint(int x, int y)
{
myX= x;
myY=y;
}
public int x
{
get
{
return myX;
}
set
{
myX=value;
}
}
public int y
{
get
{
return myY;
}
set
{
myY=value;
}
}
}
class Program
{
private static void PrintPoint(IPoint P)
{
Console.WriteLine("x={0}, y={1}",P.x,P.y);
}
static void Main(string[] args)
{
MyPoint P = new MyPoint(2, 3);
Console.Write("My Point::");
PrintPoint(P);
Console.Read();
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

32

.Net Framework and C#


}
Output:
My Point::x=2, y=3

Another Example of Interface by Casting Interface methods:


interface add
{ int sum();}
interface Multiply
{ int mul();}
class Calculate : add, Multiply
{
int a, b;
public Calculate(int x, int y)
{
a = x;
b = y;
}
public int sum()
{ return (a + b);}
public int mul()
{ return a * b; }
}
namespace Ex_MultipleInterface
{
class Program
{
static void Main(string[] args)
{
Calculate cal = new Calculate(5, 10);
add A = (add)cal;
Console.WriteLine("Sum::" + A.sum());
Multiply M = (Multiply)cal;
Console.WriteLine("Multiplication::" + M.mul());
Console.Read();
}
}
}
Output:
Sum::15
Multiplication::50

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

33

.Net Framework and C#

Delegates
In .NET, you use delegates to call event procedure. Delegates are objects that you use to call the
methods of other objects. Delegates are said to be object -oriented function pointers since they
allow a function to be invoked indirectly by using a reference to the function.
However, unlike function pointers, the delegates in .NET are reference types, based on the class
System.Delegate. In addition, delegates in .NET can reference both shared and instance
methods.

In another way, a delegate can be defined as a type safe function pointer. You use delegates
to call the methods of other objects. They are object-oriented function pointers since they allow a
function to be invoked indirectly by using a reference to the function.
Where are Delegates used?
The most common example of using delegates is in events.
You define a method that contains code for performing various tasks when an event (such as a
mouse click) takes place.
This method needs to be invoked by the runtime when the event occ urs. Hence this method, that
you defined, is passed as a parameter to a delegate.
Starting Threads/Parallel Processing:
You defined several methods and you wish to execute them simultaneously and in parallel to
whatever else the application is doing. This can be achieved by starting new threads. To start a
new thread for your method you pass your method details to a delegate.
Generic Classes: Delegates are also used for generic class libraries which have generic
functionality defined. However the generic class may need to call certain functions defined by the
end user implementing the generic class. This can be done by passing the user defined functions
to delegates.
Creating and Using Delegates:
Using delegates is a two step process..........1) Define the delegate to be used
..........2) Create one or more instances of the delegate
Syntax for defining a delegate:
delegate string reviewStatusofARegion();
to define a delegate we use a key word delegate followed by the method signature the delegate
represents. In the above example string reviewStatusofARegion(); represents any method that
returns a string and takes no parameters.
Syntax for creating an instance of the delegate:

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

34

.Net Framework and C#


reviewStatusofARegion = new reviewStatusofARegion(my Class.get Europe);
private string getEurope()
{
return Doing Great in Europe;
}
To create an instance of the delegate you call its constructor. The delegate constructor takes one
parameter which is the method name.
The method signature should exactly match the original definition of the delegate. If it does not
match the compiler would raise an Error.

C# provides support for Delegates through the class called Delegate in the System
namespace. Delegates are of two types.

Single-cast delegates

Multi-cast delegates

A Single-cast delegate is one that can refer to a single method whereas a Multi-cast
delegate can refer to and eventually fire off multiple methods that have the same signature.
The signature of a delegate type comprises are the following.

The name of the delegate

The arguments that the delegate would accept as parameters

The return type of the delegate

A delegate is either public or internal if no specifier is included in its signature. Further, you
should instantiate a delegate prior to using the same.
The following is an example of how a delegate is declared.
Listing 1: Declaring a delegate
public delegate void TestDelegate(string message);
The return type of the delegate shown in the above example is "void" and it accepts a string
argument. Note that the keyword "delegate" identifies the above declaration as a delegate to a
method. This delegate can refer to and eventually invoke a method that can accept a string
argument and has a return type of void, i.e., it does not return any value.
Listing 2: Instantiating a delegate
TestDelegate t = new TestDelegate(Display);

Implementing Delegates in C#
This section illustrates how we can implement and use delegates in C#.This section illustrate how
we can implement and use delegates in C#.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

35

.Net Framework and C#


Example 1: Single Cast Delegate
namespace Ex_Delegate
{
delegate int Operation(int x, int y); //declaration
class Metaphor
{
public static int Add(int a, int b)
{ return a + b; }
public static int Sub(int a, int b)
{ return a - b; }
public static int Mul(int a, int b)
{ return a * b; }
}
class Program
{
static void Main(string[] args)
{ // Delegate instances
Operation opr1 = new Operation(Metaphor.Add);
Operation opr2 = new Operation(Metaphor.Sub);
Operation opr3 = new Operation(Metaphor.Mul);
//invoking of delegates
int ans1 = opr1(200, 100);
int ans2 = opr2(200, 100);
int ans3 = opr3(20, 10);
Console.WriteLine("\n Addition:" + ans1);
Console.WriteLine("\n Subtract:" + ans2);
Console.WriteLine("\n Multiplication:" + ans3);
Console.Read();
} }}
Example 2: Single Cast Delegate
namespace Ex_SingleCastDelegate
{
//Declare the delegate
public delegate void TestDelegate(string message);
class Program
{
public static void Display(string message)
{Console.WriteLine("The string entered is : " + message);}
static void Main(string[] args)
{ //Initiate the delegate
TestDelegate t = new TestDelegate(Display);
Console.WriteLine("Please enter a string::");
string message = Console.ReadLine();
t(message);
Console.ReadLine();
}}}

Multicast Delegate
A multi-cast delegate is basically a list of delegates or a list of methods with the same signature.
A multi-cast delegate can call a collection of methods instead of only a single method.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

36

.Net Framework and C#


Example: Multicast Delegate

namespace Ex_MulticastDelegate
{
public delegate void TestDelegate();
class Program
{
public static void Display1()
{
Console.WriteLine("This is first method");
}
public static void Display2()
{
Console.WriteLine("This is second method");
}
static void Main(string[] args)
{
TestDelegate t1 = new TestDelegate(Display1);
TestDelegate t2 = new TestDelegate(Display2);
t1 = t1 + t2; // Make t1 a multi-cast delegate
t1(); //Invoke delegate
Console.Read();
}}}
In another way, You can also assign the references of multiple methods to a delegate and use it
to invoke multiple methods. Such a delegate is called a multi-cast delegate as multiple method
references are cast to it and then the delegate is used to invoke these methods.
What are Attributes?
An Attribute is a declarative tag which can be used to provide information to the compiler about
the behaviour of the C# elements such as classes and assemblies.
C# provides convenient technique that will handle tasks such as performing compile time
operations , changing the behaviour of a method at runtime or maybe even handle unmanaged
code.
C# Provides many Built-in Attributes.
Some Popular ones are

Obsolete
DllImport
Conditional
WebMethod

It is also possible to create new ones by extending the System.Attribute class.


For example:
using System;
[CLSCompliant(true)]
Public class myClass
{ // class code }
Web services also make use of attributes. The attribute [WebMethod] is used to specify that a
particular method is to be exposed as a web service.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

37

.Net Framework and C#

Why Attributes ?
The reason attributes are necessary is because many of the services they provide would be very
difficult to accomplish with normal code. You see, attributes add what is called metadata to your
programs. When your C# program is compiled, it creates a file called an assembly, which is
normally an executable or DLL library. Assemblies are self-describing because they have
metadata written to them when they are compiled. Via a process known as reflection, a program's
attributes can be retrieved from its assembly metadata. Attributes are classes that can be written
in C# and used to decorate your code with declarative information. This is a very powerful
concept because it means that you can extend your language by creating customized declarative
syntax with attributes.
How it is used in C#?
Attributes are elements that allow you to add declarative information to your programs. This
declarative information is used for various purposes during runtime and can be used at design
time by application development tools. For example, there are attributes such as
DllImportAttribute that allow a program to communicate with the Win32 libraries. Another
attribute, ObsoleteAttribute, causes a compile-time warning to appear, letting the developer know
that a method should no longer be used. When building Windows forms applications, there are
several attributes that allow visual components to be drag-n-dropped onto a visual form builder
and have their information appear in the properties grid. Attributes are also used extensively in
securing .NET assemblies, forcing calling code to be evaluated against pre-defined security
constraints. These are just a few descriptions of how attributes are used in C# programs.
Predefined .NET
Attribute
AttributeUsage

Valid Targets
Class

CLSCompliant

All

DllImport

Method

MTAThread

Method (Main)

NonSerialized

Field

Obsolete

All except Assembly, Module,


Parameter, and Return

ParamArray

Parameter

Serializable

Class, struct, enum, delegate

STAThread

Method (Main)

ThreadStatic

Field (static)

Description
Specifies the valid usage of another attribute
class.
Indicates whether a program element is
compliant with the Common Language
Specification (CLS).
Specifies the DLL location that contains the
implementation of an external method.
Indicates that the default threading model for an
application is multithreaded apartment (MTA).
Applies to fields of a class flagged as
Serializable; specifies that these fields wont be
serialized.
Marks an element obsoletein other words, it
informs the user that the element will be
removed in future versions of the product.
Allows a single parameter to be implicitly treated
as a params (array) parameter.
Specifies that all public and private fields of this
type can be serialized.
Indicates that the default threading model for an
application is STA.
Implements thread-local storage (TLS)in other
words, the given static field isnt shared across
multiple threads and each thread has its own
copy of the static field.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

38

.Net Framework and C#

Predefined attributes
Example:
Pre-defined attributes are used to store external information into metadata. For example, consider
the following piece of code:

public class testAttribute {


[DllImport("sampleDLL.dll")]
public static extern sampleFunction(int sampleNo, string sampleString );
public static void Main( ) {
string strVar;
sampleFunction(10, Test Attribute);
}
}
Using the example code above, you can import a method called sampleFunction from
sampleDLL.dll and use it in your program as if its your own method. This is achieved using the
pre-defined attribute DllImport.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

39

.Net Framework and C#


Multi-Threading
Multithreading forms a subset of multitasking. Instead of having switch between programs this
feature switches between different parts of the same program. For example when you are writing
words in Ms-word then spell checking is going on background.
Thread - A thread (or "thread of execution") is a sort of context in which code is running. Any one
thread follows program flow for wherever it is in the code, in the obvious way.
A thread is a unit of processing, and multitasking is t he simultaneous execution of multiple
threads. Multitasking comes in two flavors: cooperative and preemptive. Very early versions of
Microsoft Windows supported cooperative multitasking, which meant that each thread was
responsible for relinquishing control to the processor so that it could process other threads.
However, Microsoft Windows NT-and, later, Windows 95, Windows 98, and Windows 2000support the same preemptive multitasking that OS/2 does. With preemptive multitasking, the
processor is responsible for giving each thread a certain amount of time in which to execute-a
timeslice. The processor then switches among the different threads, giving each its timeslice, and
the programmer doesn't have to worry about how and when to relinquish control so that other
threads can run. .NET will only work only on preemptive multitasking operating systems.
1. Starting Thread
Object thread is obtained from System.Threading namespace. With the use object of this class
we can create a new thread, delete, pause, and resume threads. Simple a new thread is created
by Thread class and started by Thread.Start().
eg. Thread th = new Thread (new ThreadStart (somedata));
th.Start();
2. Pausing Thread
Some time the requirement to pause a thread for certain time of interval; you can attain the same
by using Sleep (n) method. This method takes an integer value to determine how long a thread
should pause or Sleep.
eg. th.Sleep(2000);
Note:
To pause or sleep a thread for an in determine time, just call the sleep () method as: [make sure
you have added System.Threading namespace] Thread.Sleep(TimeOut.Infinite).
To Resume or interrupt this call : Thread.Interrupt () method.
3. Suspending Thread
Of course, there is a Suspend () method which suspends the thread. It is suspended until a
Resume () method called.
eg. if (th.ThreadState = = ThreadState.Running)
th.Suspended();

4. Resuming Thread
To Resume a suspended thread, there is a Resume () method, thread resumes if earlier
suspended if not so then there is no effect of Resume () method on the thread.
eg. if (th.ThreadState = = ThreadState.Suspended)
th.Resume();

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

40

.Net Framework and C#


5. Killing Thread
You can call Abort () method to kill a thread, before calling the same method, make sure thread is
alive.
eg. if (th.IsAlive)
th.Abort();
Suspend and Resume in Threading
It is similar to sleep and Interrupt. Suspend allows you to block a thread until another thread calls
Thread.Resume ().The difference between sleep and suspend is that the later does no
immediately place a thread in the wait state. The thread does not suspend until the .Net runtime
determines that it is in a safe place to suspend it. Sleep will immediately place a thread in a wait
state.
Important:
You can change thread priority for that just supply : th.Priority = ThreadPriority.Highest. [th
Thread name]. Priority sets the sequence of thread in which they are running. You can set the
following priority to thread(s):
1.
2.
3.
4.
5.

ThreadPriority.Highest
ThreadPriority.AboveNormal
ThreadPriority.Normal
ThreadPriority.BelowNormal
ThreadPriority.Lowest

Code Example of Multithreading


using System.Threading;
namespace Ex_ThreadExample
{
class SimpleThread
{
private Thread thread1;
private Thread thread2;
private void Method1()
{
for (int i =0; i<10;i++)
{
Console.WriteLine ("i = " +i);
Thread.Sleep (400); // 200 miliseconds pause
}
}
private void Method2()
{
for (int i =0;i<10;i++)
{
Console.WriteLine ("i = " + 100 * i);
Thread.Sleep (100); // 100 miliseconds pause
}
}
static void Main(string[] args)
{
SimpleThread app = new SimpleThread ();

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

41

.Net Framework and C#


app.thread1 = new Thread (new ThreadStart (app.Method1));
// thread start Delegate Method
app.thread2 = new Thread (new ThreadStart (app.Method2));
app.thread1.Start ();
app.thread2.Start ();
Console.WriteLine ();
Console.ReadLine();
}
}
}
-------------x--------------x--------------x---------------x---------Socket Programming in C#

Network programming in windows is possible with sockets. A socket is like a handle to a file.
Socket programming resembles the file IO as does the Serial Communication. You can use
sockets programming to have two applications communicate with each other. The application are
typically on the different computers but they can be on same computer. For the two applications
to talk to each either on the same or different computers using sockets one application is
generally a server that keeps listening to the incoming requests and the other application acts as
a client and makes the connection to the server application.
The server application can either accept or reject the connection. If the server accepts the
connection, a dialog can begin with between the client and the server. Once the client is done
with whatever it needs to do it can close the connection with the server. Connections are
expensive in the sense that servers allow finite connections to occur. During the time client has
an active connection it can send the data to the server and/or receive the data.
Socket programming in .NET is made possible by Socket class present inside the System.Net.
Sockets namespace.
Socket class has several method and properties and a constructor.

The first step is to create an object of this class. Since there is only one constructor we
have no choice but to use it.

Here is how to create the socket:


m_socListener = new Socket(AddressFamily.InterNetwork,Socket Type.Stream,ProtocolType.IP );
AddressFamily is an enum defined in Sockets namespace.

Next we need to specify socket type: and we would use reliable two way connectionbased sockets (stream) instead of un-reliable Connectionless sockets ( datagrams) . So
we obviously specify stream as the socket type and finally we are using TCP/IP so we
would specify protocol type as TCP.

Once we have created a Socket we need to make a connection to the server since we
are using connection-based communication.
To connect to the remote computer we need to know the IP Address and port at which to
connect.
In .NET there is a class under System.Net namespace called IPEndPoint which
represents a network computer as an IP address and a port number.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

42

.Net Framework and C#

The IPEndPoint has two constructors - one that takes a IP Address and Port number
and one that takes long and port number. Since we have computer IP address we would
use the former
public IPEndPoint(System.Net.IPAddress address, int port);

As you can see the first parameter takes a IPAddress object. If you examine the
IPAddress class you will see that it has a static method called Pars e that returns
IPAddress given a string ( of dot notation ) and second parameter will be the port
number. Once we have endpoint ready we can use Connect method of Socket class to
connect to the end point ( remote server computer ).

Here is the code:


System.Net.IPAddress ipAdd = System.Net.IPAddress.Parse("10.10.101.200" );
System.Net.IPEndPoint remoteEP = new IPEndPoint (ipAdd,8221);
m_socClient.Connect (remoteEP);
Description
These three lines of code will make a connection to the remote host running on computer
with IP 10.10.101.200 and listening at port 8221. If the Server is running and started (
listening ), the connection will succeed. If however the server is not running an exception
called SocketException will be thrown. If you catch the exception and check the Message
property of the exception in this case you see following text:
"No connection could be made because the target machine actively refused it."
Similarly if you already have made a connection and the server somehow dies, you will get
following exception if you try to send data.
"An existing connection was forcibly closed by the remote host"
Assuming that the connection is made, you can send data to other side using the Send method of
the Socket class.
Send method has several overloads. All of them take a byte array. For example if you want to
send "Hello There" to host you can use following call:
try
{
String szData = "Hello There";
byte[] byData = System.Text.Encoding.ASCII.GetBytes(szData);
m_socClient.Send(byData);
}
catch (SocketException se)
{
MessageBox.Show ( se.Message );
}
Note that the Send method is blocking. What it means the call will block till the data has been
sent or an exception has been thrown. There is a non-blocking version of the send which we will
discuss in the next part of this article.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

43

.Net Framework and C#


Similar to send there is a Receive method on the Socket class. You can receive data using
following call:
byte [] buffer = new byte[1024];
int iRx = m_socClient.Receive (buffer);
The Receive method again is blocking. It means that if there is no data available the call will block
until some data arrives or an exception is thrown.
Non-blocking version of Receive method is more useful than the non-blocking version of Send
because if we opt for block Receive, we are effectively doing polling. There is no event about data
arrival. This model does not work well for serious applications. But all that is the subject of our
next part of this article. For now we will settle with the blocking version.

Server Side Code:


using System;
using System.Net.Sockets;
public class AsynchIOServer
{
public static void Main()
{
TCPListener tcpListener = new TCPListener(10);
tcpListener.Start();
Socket socketForClient = tcpListener.Accept();
if (socketForClient.Connected)
{
Console.WriteLine("Client connected");
NetworkStream networkStream = new NetworkStream(socketForClient);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
System.IO.StreamReader streamReader = new System.IO.StreamReader(net workStream);
string theString = "Sending";
streamWriter.WriteLine(theString);
Console.WriteLine(theString);
streamWriter.Flush();
theString = streamReader.ReadLine();
Console.WriteLine(theString);
streamReader.Close();
networkStream.Close();
streamWriter.Close();
}
socketForClient.Close();
Console.WriteLine("Exiting...");
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

44

.Net Framework and C#


Client Code:
using System;
using System.Net.Sockets;
public class Client
{
static public void Main( string[] Args )
{
TCPClient socketForServer;
try
{
socketForServer = new TCPClient("localHost", 10);
}
catch
{
Console.WriteLine(
"Failed to connect to server at {0}:999", "localhost");
return;
}
NetworkStream networkStream = socketForServer.GetStream();
System.IO.StreamReader streamReader = new System.IO.StreamReader(net workStream);
System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(networkStream);
try
{
string outputString;
// read the data from the host and display it
{
outputString = streamReader.ReadLine();
Console.WriteLine(outputString);
streamWriter.WriteLine("Client Message");
Console.WriteLine("Client Message");
streamWriter.Flush();
}
}
catch
{
Console.WriteLine("Exception reading from Server");
}
// tidy up
networkStream.Close();
}
}
-----------x----------------x--------------------------x-------------------------x----------------x---------------x----------

Exception Handling
Overview of Exception Handling
Exceptions are error conditions that arise when the normal flow of a code path-that is, a series of
method calls on the call stack-is impractical. Exception handling is an in built mechanism in .NET
framework to detect and handle run time errors. The exceptions are anomalies that occur during
the execution of a program. They can be because of user, logic or system errors. If a user
(programmer) do not provide a mechanism to handle these anomalies, the .NET run time
environment provide a default mechanism, which terminates the program execution. C# provides
three keywords try, catch and finally to do exception handling. The try encloses the statements

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

45

.Net Framework and C#


that might throw an exception whereas catch handles an exception if one exists. The finally can
be used for doing any clean up process.
The general form try-catch-finally in C# is shown below:
try
{
// Statement which can cause an exception.
}
catch(Type x)
{
// Statements for handling the exception
}
finally
{
//Any cleanup code
}
If any exception occurs inside the try block, the control transfers to the appropriate catch block
and later to the finally block.
But in C#, both catch and finally blocks are optional. The try block can exist either with one or
more catch blocks or a finally block or with both catch and finally blocks.
If there is no exception occurred inside the try block, the control directly transfers to finally block.
We can say that the statements inside the finally block is executed always. Note that it is an error
to transfer control out of a finally block by using break, continue, return or goto.
In C#, exceptions are nothing but objects of the type Exception. The Exception is the ultimate
base class for any exceptions in C#. The C# itself provides couple of standard exceptions. Or
even the user can create their own exception classes, provided that this should inherit from either
Exception class or one of the standard derived classes of Exception class like
DivideByZeroExcpetion ot ArgumentException etc.
The modified form of the above program with exception handling mechanism is as follows : //C#: Exception Handling
using System;
class MyClient
{
public static void Main()
{
int x = 0; int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{ Console.WriteLine("Exception occured"); }
finally
{ Console.WriteLine("Finally Block"); }
Console.WriteLine("Result is {0}",div);
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

46

.Net Framework and C#


Multiple Catch Blocks
A try block can throw multiple exceptions, which can handle by using multiple catch blocks.
Remember that more specialized catch block should come before a generalized one. Otherwise
the compiler will show a compilation error.
//C#: Exception Handling: Multiple catch
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(DivideByZeroException de)
{ Console.WriteLine("DivideBy ZeroException" ); }
catch(Exception ee)
{ Console.WriteLine("Exception" ); }
finally
{ Console.WriteLine("Finally Block"); }
Console.WriteLine("Result is {0}",div);
}
}
Catching All Exception
By providing a catch block without a brackets or arguments, we can catch all exceptions occurred
inside a try block. Even we can use a catch block with an Exception type parameter to catch all
exceptions happened inside the try block since in C#, all exceptions are directly or indirectly
inherited from the Exception class.
//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch
{ Console.WriteLine("oException" );}
Console.WriteLine("Result is {0}",div);
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

47

.Net Framework and C#


The following program handles all exception with Exception object.
//C#: Exception Handling: Handling all exceptions
using System;
class MyClient
{
public static void Main()
{
int x = 0;
int div = 0;
try
{
div = 100/x;
Console.WriteLine("Not executed line");
}
catch(Exception e)
{ Console.WriteLine("oException" );}
Console.WriteLine("Result is {0}",div);
}
}
Throwing an Exception
In C#, it is possible to throw an exception programmatically. The 'throw' keyword is used for this
purpose. The general form of throwing an exception is as follows.
throw exception_obj;
For example the following statement throws an ArgumentException explicitly.
throw new ArgumentException("Exception");
Example
//C#: Exception Handling:
using System;
class MyClient
{
public static void Main()
{
try
{
throw new DivideByZeroException("Invalid Division");}
catch(DivideByZeroException e)
{ Console.WriteLine("Exception" ); }
Console.WriteLine("LAST STATEMENT");
}
}
Standard Exceptions
There are two types of exceptions: exceptions generated by an executing program and
exceptions generated by the common language runtime. System.Exception is the base class for
all exceptions in C#. Several exception classes inherit from this class including
ApplicationException and SystemException. These two classes form the basis for most other
runtime exceptions. Other exceptions that derive directly from System.Exception include
IOException, WebException etc.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

48

.Net Framework and C#

The common language runtime throws SystemException. The ApplicationException is thrown by


a user program rather than the runtime. The SystemException includes the
ExecutionEngineException, StaclOverFlowException etc. It is not recommended that we catch
SystemExceptions nor is it good programming practice to throw SystemExceptions i n our
applications.

System.OutOfMemoryException
System.NullReferenceException
Syste.InvalidCastException
Syste.ArrayTypeMismatchException
System.IndexOutOfRangeException
System.ArithmeticException
System.DevideByZeroException
System.OverFlowException

User-Defined Exceptions
In C#, it is possible to create our own exception class. But Exception must be the ultimate base
class for all exceptions in C#. So the user-defined exception classes must inherit from either
Exception class or one of its standard derived classes.
//C#: Exception Handling: User defined exceptions
using System;
class MyException : Exception
{
public MyException(string str)
{ Console.WriteLine("User defined exception");}
}
class MyClient
{
public static void Main()
{
try
{ throw new MyException("RAJESH"); }
catch(Exception e)
{Console.WriteLine("Exception caught here" + e.ToString()); }
Console.WriteLine("LAST STATEMENT");
}
}

------------------x-------------------------x------------------------------x-------------------------x-----------------------

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

49

.Net Framework and C#

File Handling in C#
File handling is an unmanaged resource in your application system. It is outside your application
domain (unmanaged resource). It is not managed by CLR.
Data is stored in two ways, persistent and non-persistent manner.
When you open a file for reading or writing, it becomes stream.

Stream: Stream is a sequence of bytes traveling from a source to a destination over a


communication path.
The two basic streams are input and output streams. Input stream is used to read and output
stream is used to write.
The System.IO namespace includes various classes for file handling.
The parent class of file processing is stream. Stream is an abstract class, which is used as the
parent of the classes that actually implement the necessary operations.
The primary support of a file as an object is provided by a .NET Framework class called File. This
static class is equipped with various types of (static) methods to create, save, open, copy, move,
delete, or check the existence of a file.

Object
System.IO

System

MarshalByref
Object
System.IO

FileSystemInfo

System.IO

FileInfo

Directoryinfo

File

Path

Directory

DriveInfo

Diagram to represent file-handling class hierarchy

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

50

.Net Framework and C#

The following table describes some commonly used classes in the System.IO namespace: Class Name

Description

FileStream

It is used to read from and write to any location within a file

BinaryReader

It is used to read primitive data types from a binary stream

BinaryWriter

It is used to write primitive data types in binary format

StreamReader

It is used to read characters from a byte Stream

StreamWriter

It is used to write characters to a stream

StringReader

It is used to read from a string buffer

StringWriter

It is used to write into a string buffer

DirectoryInfo

It is used to perform operations on directories

FileInfo

It is used to perform operations on files

Reading and Writing in the text file


StreamWriter Class
The StreamWriter class in inherited from the abstract class TextWriter. The TextWriter class
represents a writer, which can write a series of characters.
The following table describes some of the methods used by StreamWriter class : Methods

Description

Close

Close the current StreamWriter object and underlying stream

Flush

Clears all buffers for the current writer and causes any buffered
data to be written to the underlying stream.

Write

Writes to the Stream

WriteLine

Writes data specified by the overloaded parameters, followed by


end of line.

Program to write user input to a file using StreamWriter Class

using System;
using System.Text;
using System.IO;
namespace FileWriting_SW
{
class Program
{

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

51

.Net Framework and C#

class FileWrite
{
public void WriteData()
{
FileStream fs = new FileStream("c:\\test.txt", FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
Console.WriteLine("Enter the text which you want to write to the file");
string str = Console.ReadLine();
sw.WriteLine(str);
sw.Flush();
sw.Close();
fs.Close();
}
}
static void Main(string[] args)
{
FileWrite wr = new FileWrite();
wr.WriteData();
}
}
}
StreamReader Class
The StreamReader class is inherited from the abstract class TextReader. The TextReader class
represents a reader, which can read series of characters.
The following table describes some methods of the StreamReader class: Methods

Description

Close

Closes the object of StreamReader class and the underlying stream, and
release any system resources associated with the reader

Peek

Returns the next available character but doesn't consume it

Read

Reads the next character or the next set of characters from the stream

ReadLine

Reads a line of characters from the current stream and returns data as a string

Seek

Allows the read/write position to be moved to any position with the file

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

52

.Net Framework and C#

Program to read from a file using StreamReader Class

using System;
using System.IO;
namespace FileReading_SR
{
class Program
{
class FileRead
{
public void ReadData()
{
FileStream fs = new FileStream ("c:\\test.txt", FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader (fs);
Console.WriteLine("Program to show content of test file");
sr.BaseStream.Seek(0, SeekOrigin.Begin);
string str = sr.ReadLine();
while (str != null)
{
Console.WriteLine(str);
str = sr.ReadLine();
}
Console.ReadLine();
sr.Close();
fs.Close();
}
}
static void Main(string[] args)
{
FileRead wr = new FileRead();
wr.ReadData();
}
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

53

.Net Framework and C#

Introduction to Web Services


A Web service exposes a number of methods that provide functionality that can be one or more
application, regardless of the programming languages, operating systems, and hardware
platforms used to develop them. The methods that provide such functionality are called Web
Methods. The functionality exposed by a Web service can be accessed by applications by using
Internet Standards, such as Simple Object Access Protocol (SOAP). SOAP is a protocol that
uses extensible Markup Language (XML) to describe data and HyperText Transfer Protocol
(HTTP) to transmit application data. An application that uses a Web service is called a Web
Service Client.
A Web service is similar to a component that provides a specific functionality. However,
components uses object model-specific protocols, such as Internet Inter-ORB Protocol (IIOP) and
Remote Method Invocation (RMI), for communicating with client applications. This communication
approach requires a similar infrastructure at both client and the server sides. This approach is
acceptable when the use of components is confined to controlled environments. Web services
use Internet Standards, such as HTTP and XML, to communicate with client applications. This
communication approach makes Web services independent of any language or platform. Any
computer that has access to the Internet can easily access a Web service.
Depending on the requirements of a business, different types of Web services can be created
and used in an application.
Enabling Technologies used in Web Services
A web service can be created using any programming language in the .NET suite. There are
certain requirements need to be fulfilled to enable applications to access the functionality
provided by Web services. The requirements are:

A common data representation format in order to ensure the interoperability of the data
exchanged by the client application and the Web service.
A standard method for sending messages from the client application to the Web service
and vice versa.
A standard format for describing the web service.
A mechanism to allow client applications to discover the Web services and their
locations.

To cater these requirements, various standards such as XML, SOAP and Web Services
Description Language (WSDL) are used.
XML
A client passes arguments to a method exposed by a Web service. The method performs some
action on the arguments and returns the results to the client application. The data returned by the
Web service can be used by the client application, regardless of the hardware and software
platform used to develop the application. To enable this kind of data interchange, you require a
standard data representation format that can be understood by any platform. Since XML is a
plain-text format that can be understood by any kind of device.
SOAP
To be able to communicate with each other, a Web service and a client application must agree
upon a common protocol. SOAP is a standard communication protocol for interchanging
information in a structured format in a distributed environment . The information exchanged

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

54

.Net Framework and C#


between the client application and the web service is called a message. When a client application
makes a request for a web method, a SOAP packet is created. This packet contains the name of
the Web method to be invoked and the parameters to be passed to the Web method in an XML
format. This information is used to invoke the Web method with the appropriate parameters.
When the SOAP packet arrives at the Web server on which the Web service resides, the Web
method name and its parameters are extracted from the SOAP packet and the appropriate Web
method is invoked.
WSDL
To be able to use a Web service, the developers of a client application need to know the methods
exposed by the Web service and the parameters to be passed to thes e methods. Therefore, you
need a standard method to describe the methods that are exposed by Web service. This
information should be readily accessible to the Web service clients during the design phase. This
is achieved by using an XML vocabulary called Web Service Description Language (WSDL).
WSDL is a markup language that describes a Web service.
A WSDL document contains the following information:

The
The
The
The
The
The

web services available for a given Web site.


purpose for which these services can be used.
types of parameters that need to passed to a Web service.
type of value that is returned by a Web service.
format used to access these Web services.
URL at which a Web service can be accessed.

UDDI (Universal Description Discovery and Integra tion)


UDDI provides a standard mechanism to register and discover a Web Service. When a Web
service provider wants to make a Web service available to client applications, the provider
describes the web service by using a WSDL document. Then, the provider registers the Web
service in the UDDI Directory. The UDDI directory contains pointers to the Web service and the
WSDL document for the Web service. Client applications can then discover the Web service by
using the UDDI Directory.
WSDL
Document

UDDI
Registry

Locates a Web
Service

Describes

Client
Application

Web
Service
Communication through
SOAP messages

Relation between Enabling Web Service Technologies

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

55

.Net Framework and C#

XML (eXtensible Markup Language)


XML is a text based markup language that enables you to store data in a structured format by
using meaningful tags. The term eXtensible implies that you can extend your ability to describe
a document by defining meaningful tags for your application.
XML is a cross-platform, hardware and software independent markup language. XML allows
computers to store data in a format that can be interpreted by any other computer system and
therefore. XML can be used to transfer structured data between heterogeneous systems. XML is
used as a common data interchange format in a number of applications.
Advantages of XML
Some of the advantages offered by XML are as follows:

It
It
It
It
It

provides a way of creating domain-specific vocabulary.


allows data interchange between different computer systems.
enables smart searches.
provides user-selected view of data.
allows granular updates.

Structure of XML document


Before storing data in XML document, It need to organize. An XML document is composed of a
number of components that can be used for representing information in a hierarchical order.
These components are:

Processing Instruction

An XML document usually begins with the XML declaration statement also called the Processing
Instruction (PI). The PI provides information regarding the way in which the XML file should be
processed. The PI statement can be written as:
<? Xml version=1.0 encoding UTF-8?>
The PI is optional. The PI uses the encoding property to specify the information about the
encoding scheme that is used to create the XML file. The encoding scheme is the standard
character set for a language. UTF-8 is the standard character set that is used to create pages
written in English. This character set uses eight bits of information to represent each character.
Therefore, UTF-8 stands for an 8-bit character set.

Tag

Tags are used to specify a name for a given piece of information. It is a means of identifying data.
Data is marked-up using tags. A tag consists of an opening and a closing angular bracket (<>).
These brackets enclose the name of the tag. Tags usually occur in pairs.
<P> Nick Peter </P>
In this example, <p> is a predefined HTML tag or mark -up. As XML allows you to create your own
tags, the same information can be stored in the following way:
<EMP_NAME> Nick Peter</EMP_NAME>

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

56

.Net Framework and C#


In this example, <EMP_NAME> is a new tag created using XML.

Elements

Elements are the basic units that are used to identify and describe data in XML. They are the
building blocks of an XML document. Elements are represented using tags.
XML allows you to provide meaningful names to elements, whic h helps improve the readability of
the code. For example: <Authorname> Vivek </Authorname>
In the example, the Authorname element is used to store the names of authors. In this case, the
element name provides a description of the content within the tags.
An XML document must always have a root element. A root element contains all other elements
in the document.

Content

The information that is represented by the elements of an XML document is referred to as the
content of that element. For example,
<BOOKNAME> the painted Hose</BOOKNAME>
The name of the book The Painted House is the content of the BOOKNAME element. XML
enables to declare and use elements that can contain different kinds of information. An element
can contain any of the following types of content:

Character or data content


Element content
Combination or mixed content

Examples
Character content
<BOOKNAME> the painted Hose</BOOKNAME>
Element content
<Author>
<Fname> John </Fname>
<Lname> Smith </Lname>
</Author>
Mixed Content
<PRODUCTDESCRIP TION>
The product is available inn four colors.
<COLOR> RED
</COLOR>
<COLOR> BLUE
</COLOR>
<COLOR> GREEN </COLOR>
<COLOR> YELLOW </COLOR>
</PRODUCTDESCRIP TION>

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

57

.Net Framework and C#

Attributes

Attributes provide additional information about the elements for which they are declared. An
attribute consists of a name-value pair. Consider the following example: <PRODUCTNAME PROID=P001> DOLL</PRODUCTNAME>
In this example, the element PRODUCTNAME has an attribute called PROID. The value of this
attribute is set to 001.
Elements can have one or more attributes. Attributes or attribute values can be either mandatory
or optional.
In general, an element is used to represent a definable unit. An attribute is used to represent data
that further qualifies the element. For example, an element called font could have an attribute
called color that is used to specify the color of the font.

Entity

An entity can be described as a shortcut to a set of information. It is name that is associated with
a block of data. This data can be a chunk of text or a reference to an external file that contains
textual or binary information.
<DISPLAY> The price of the this toy is &lt; 20 <DISPLAY>
In the example, &lt; internal entity is used to display a less than (<) symbol.

Comment

Comments are statements that are used to explain the code. They are also used to provide
documentation information about an XML file or even the application to which the file belongs.
When the code is executed, comment entries are ignored by the parser.
Comments are created using an opening angular bracket followed by an exclamation mark and
two hyphens (<!--). This is followed by the text that comprises the comments. The comment entry
can be closed using two hyphens followed by a closing angular bracket (-->).
Example: -

<! -- Productdata is the root element -->

Rules for Creating Well-formed XML document

Every start tag must have an end tag.


Empty tags must be closed using a forward slash (/).
All attribute values must be given in double quotation marks.
Tags must nest correctly.
XML tags are case-sensitive. They must match each other in every implementation.

Declaring Elements in a Document Type Definition


To represent data in a consistent format, it needs to be given a meaningful st ructure. A wellformed document in XML may not necessarily have a meaningful structure. By defining the role of

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

58

.Net Framework and C#


each element in a formal model, known as Document Type Definition (DTD), users of XML can
check that each component of the document appears in a valid place in the XML document.
Document Type Definition (DTD)
DTD defines the structure of the content of an XML document, thereby allowing to store data in a
consistent format. It specifies the elements that can be resent in the XML document, attributes of
these elements, and their arrangement with relation to each other.
Creating a DTD is similar to creating a table in a database. In DTDs you specify the structure of
data by declaring elements to denote the data. This is similar to creating columns in a table.
XML allows you to create your own DTDs for applications. This gives you complete control over
the process of checking the content and structure of XML documents is created for an
application. This checking process is called validation. XML document that conform to a DTD are
considered valid documents.
Declaring Elements in a DTD
In a DTD, elements are described using the following syntax: <! ELEMENT elementname (content-type or content-model/)>
In the given syntax,

Elementname specifies the name of the element.

Content-type or content-model specifies whether the element contains textual data or


other element.

Rule for Naming Elements and Attribute in XML

A name consists of at least one letter: a to z, or A to Z.


An element name may start with an underscore (_).
One or more letters, digits, hyphens, underscores or full stops can follow the initial letter.
Spaces and tabs are not allowed in element names, and the only punctuation signs
allowed.

An element can be empty, unrestricted, or a container element. The following table describes
each type of element:

Element Type
Empty
Unrestricted
Container

Description
Empty elements have no content and are marked up as <empty element/>
The opposite of an empty element is an unrestricted element, which can
contain any element declared elsewhere in the DTD.
Elements can contain character data and other elements

Declaring Container Elements


Consider the following tag structure:

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

59

.Net Framework and C#


<BOOK>
<TITLE> If tomorrow comes </TITLE>
<AUTHOR> Sidney John </AUTHOR>
</BOOK>
For the given XML document to be valid, you need to create a DTD that contains declaration for
three elements: BOOK, TITLE and AUTHOR. The DTD would look as follows:
<! ELEMENT BOOK (TITLE, AUTHOR)>
<! ELEMENT TITLE (#PCDATA)>
<! ELEMENT AUTHOR (#PCDATA)>
PCDATA stands for Parsable Character Data and is used to represent character content.
Declaring Attributes
In addition to declaring elements, attributes too can be declared in a DTD. These declarations are
used during the process of validation. The syntax for declaring attributes in a DTD is: <! ATTLIST elementname attributename valuetype [attributetype] [default]>
You can assign values to attributes. The following table discusses the different value types that
can be specified: -

Value Type
PCDATA
ID
(enumerated)

Description
Used to represent plain text values
Used to assign a unique value to each element in the document. The ID must
begin with an alphabetic character.
Used to assign a specific range of values. These values are specified within
parenthesis

In addition to specifying the value type of an attribute, you also need to specify whether the
attribute is optional or mandatory. Look at the following table for attribute types: Attribute Type
REQUIRED
FIXED
IMPLIED

Description
If the attributes of an element is specified as #REQUIRED, then the value for
that attribute must be specified each time the element is used in the XML
document.
If the attribute of an element is specified as #FIXED, then the value of the
attribute can not be changed in XML document.
If the attribute of an element is specified as #IMPLIED, then the attribute is
optional. An IMPLIED attribute can take text strings as their values.

Method to validate the structure of data


To validate the structure of data stored in an XML document against the DTD, you need to use
parsers. Parsers are software programs that check the syntax used in an XML file. There are two
types of parsers. They are:

Non-validating parsers

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

60

.Net Framework and C#

Validating parsers

Non-validating parsers
A non-validating parser checks if a document follows the XML syntax rules. It builds a tree
structure from the tags used in an XML document and returns an error only when there is a
problem with the syntax of the document. Non-validating parsers process a document faster
because they do not have to check every element against a DTD. The Expat parser is an
example of a non-validating parser.
Validating parsers
A validating parser checks the syntax, builds the tree structure, and compares the structure of the
XML document with the structure specified in the DTD associated with the document. Microsoft
MSXML parser is an example of a validating parser.
XML Tags Examples
para
The para tag works like <br> or <p> in html to structure the text into paragraphs. It can be used to
break a line of continuous text, or to wrap a segment of text into a paragraph.

<para/> or <para>...</para>
/// The <c>para</c> tag works like <![CDATA[<br> or <p>]]> in html to
/// structure the text into paragraphs.<para/>It can be used to break a line
/// of continuous text, <para>or to wrap a segment of text into a paragraph.</para>
param
The param tag is used to describe the parameters of the method. Parameter tags are
automatically inserted into the header template if parameters are in the syntax. The name of the
parameter is automatically inserted into the parameter tag. The parameter description should be
brief.

<param name="...">...</param>
/// <param name="_value">
/// Used to demonstrate the usage of <c>param</c>
/// </param>
see
Assigns a hyperlink to the specified text.

<see href|cref|langword="..."/> or <see href="...">...</see>


/// See <see cref="T:System.Enum">enumeration</see>
/// See <see cref="M:TutorialXmlDocument ationTags.code" >code</see>
/// See <see href="http://www.microsoft.com">Microsoft</see>
///<see langword="null"/>
seealso
Adds a link to the "See Also" section.

<seealso href|cref="..."/> or <seealso href="...">...</seealso>


/// <seealso cref="T:TutorialXmlDoc ument ationTags"/>

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

61

.Net Framework and C#


/// <seealso href="http://microsoft.com"/>
/// <seealso href="http://www.codeplex.com/Sandcastle">Sandc astle on CodePlex</seealso>
Unsafe Mode
When you use the new keyword to create a new instance of a reference type, you are asking the
CLR to set aside enough memory to use for the variable. The CLR allocates enough memory for
the variable and associates the memory with your variable. Under normal conditions, your code is
unaware of the actual location of that memory, as far as a memory address is concerned. After
the new operation succeeds, your code is free to use the allocated memory without knowing or
caring where the memory is actually located on your system.
Occasionally, however, you need to work with a specific memory address in your C# code. Your
code may need that extra ounce of performance, or your C# code may need to work with legacy
code that requires that you provide the address of a specific piece of memory. The C# language
supports a special mode, called unsafe mode, which enables you to work directly with memory
from within your C# code.
This special C# construct is called unsafe mode because your code is no longer safe from the
memory-management protection offered by the CLR. In unsafe mode, your C# code is allowed to
access memory directly, and it can suffer from the same class of memory -related bugs found in C
and C++ code if you're not extremely careful with the way you manage memory.
Generally, When we write any program in C#, we create managed code. Managed code is
executed under the control of CLR. CLR causes that programmer do not need to manage
memory and take care about memorys allocation and deallocation. CLR also allows you to write
what is called unsafe code.
The CLR knows how to manipulate three kinds of pointers:

Managed pointers: These pointers can point to data contained in the object heap
managed by the garbage collector. These pointers are not used explicitly by the C# code.
They are thus used implicitly by the C# compiler when it compiles methods with out and
ref arguments.

Unmanaged function pointers: The pointers are conceptually close to the notion of
delegate.

Unmanaged pointers: These pointers can point to any data contained in the user
addressing space of the process. The C# language allows to use this type of pointers in
zones of code considered unsafe.

Compilation options to allow unsafe code


Unsafe code must be used on purpose and you must also provide the /unsafe option to the
csc.exe compiler to tell it that you are aware that the code you wish to compile contains zones
which will be seen as unverifiable by the JIT compiler. Visual Studio offers the Build Allow unsafe
code project property to indicate that you wish to use this compiler option.
Declaring unsafe code in C#
In C#, the unsafe keyword lets the compiler know when you will use unsafe code. It can be used
in three situations:

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

62

.Net Framework and C#


Before the declaration of a class or structure. In this case, all the methods of the type can use
pointers.
Before the declaration of a method. In this case, the pointers can be used within the body of this
method and in its signature.
Within the body of a method (static or not). In this case, pointers are only allowed within the
marked block of code. For example:
unsafe
{
...
}
Using pointers in C#
Each object, whether it is a value or reference type instance, has a memory address at which it is
physically located in the process. This address is not necessarily constant during the lifetime of
the object as the garbage collector can physically move object s store in the heap.
To create a pointer you can use the following declaration:
Type* variable_name;
As a type may be used each type that is not a reference-type field. It can be only: sbyte, byte,
short, ushort, int, uint, long, ulong, char, float, double etc.
Following examples show different pointers declarations:
int* pi; // declaration a pointer to integer variable
float* pf, pq // two pointers to float variables
char* pz // pointer to char
Advantages of UNSAFE in C#

Performance and flexibility, by using pointer you can access data and manipulate it in the
most efficient way possible.
Compatibility, in most cases we still need to use old windows APIs, which use pointers
extensively, or third parties may supply DLLs that some of its functions need pointer
parameters. Although this can be done by writing the DLLImport declaration in a way that
avoids pointers, but in some cases its just much simpler to use pointer.
Memory Addresses, there is no way to know the memory address of some data without
using pointers.

Disadvantages of UNSAFE in C#

Complex syntax, to use pointers you need to go through more complex syntax than we
used to experience in C#.
Harder to use, you need be more careful and logical while using pointers, miss -using
pointers might lead to the following: Overwrite other variables
Stack Overflow
Access areas of memory that doesnt contain any data as they do.
Overwrite some information of the code for the .net runtime, which will suerly
lead your application to crash.
Your code will be harder to debug. A simple mistake in using pointers might lead your
application to crash randomly and unpredictably.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

63

.Net Framework and C#

Type-safety, using pointers will cause the code to fail in the .net type-safety checks, and
of course if your security police dont allow non type-safety code, then the .net framework
will refuse to execute your application.

Distributed Application in C#
Introduction
Distributed computing is an integral part of almost every software development. Before .Net
Remoting, DCOM was the most used method of developing distributed application on Microsoft
platform. Because of object oriented architecture, .NET Remoting replaces DCOM as .Net
framework replaces COM.
Remoting is a framework built into Common Language Runtime (CLR) in order to provide
developers classes to build distributed applications and wide range of network services.
Remoting provides various features such as Object Passing, Proxy Objects, Activation, Stateless
and Stateful Object, Lease Based LifeTime and Hosting of Objects in IIS.
Benefits of Distributed Application Development:
Fault Tolerance: Fault tolerance means that a system should be resilient when failures within the
system occur.
Scalability: Scalability is the ability of a system to handle increased load with only an incremental
change in performance.
Administration: Managing the system from one place.
In brief, .NET remoting is an architecture which enables communication between different
application domains or processes using different transportation protocols, serialization formats,
object lifetime schemes, and modes of object creation. Remote means any object which executes
outside the application domain. The two processes can exist on the same computer or on two
computers connected by a LAN or the Internet. This is called marshalling (This is the process of
passing parameters from one context to another.), and there are two basic ways to marshal an
object:
Marshal by value: the server creates a copy of the object passes the copy to the client.
Marshal by reference: the client creates a proxy for the object and then uses the proxy to access
the object.
Comparison between .NET Remoting and Web services:
S.No
1
2

3
4

ASP.NET WebService
Easy to develop and deploy
Gives extensibility by allowing us
to intercept the SOAP messages
during the serialization and
deserialization stages.
Accessed only over HTTP
Webservices support only the
data types defined in the XSD
type system, their by limiting the

.NET Remoting
Involves complex programming
Highly extensible by allowing us to
customize the different components of
the .NET remoting framework.
Can be accessed over any of the
protocol like HTTP, SMPT, TCP etc.
By Using binary communication, .NET
Remoting can provide support for rich
type system

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

64

.Net Framework and C#


number of objects that can be
serialized.

Architecture:
Remote objects are accessed through channels. Channels are Transport protocols for passing
the messages between Remote objects. A channel is an object that makes communication
between a client and a remote object, across app domain boundaries. The .NET Framework
implements two default channel classes, as follows:

HttpChannel: Implements a channel that uses the HTTP protocol.


TcpChannel: Implements a channel that uses the TCP protocol (Transmission Control
Protocol).

Channel take stream of data and creates package for a transport protocol and sends to other
machine. A simple architecture of .NET remoting is as in below Figure.

Server Application Domain

Client Application Domain

Server Object

Client Object

Proxy

Remoting
System

Remoting System
Channel

Figure shows, Remoting system creates a proxy for the server object and a reference to the
proxy will be returned to the client. When client calls a method, Remoting system sends request
thro the channel to the server. Then client receives the response sent by the server process thro
the proxy.
Example:
Let us see a simple example which demonstrates .Net Remoting. In This example the Remoting
object will send us the maximum of the two integer numbers sent.
Creating Remote Server and the Service classes on Machine 1:

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

65

.Net Framework and C#

Please note for Remoting support your service (Remote object) should be derived from
MarshalByRefObject.

using System;
using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinks
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http; //For HTTP channel
using System.IO;
namespace ServerApp
{
public class RemotingServer
{
public RemotingServer()
{
//
// TODO: Add constructor logic here
//
}
}
//Service class
public class Service: MarshalByRefObject
{
public void WriteMessage (int num1,int num2)
{
Console.WriteLine (Math.Max(num1,num2));
}
}
//Server Class
public class Server
{
public static void Main ()
{
HttpChannel channel = new HttpChannel(8001);
//Create a new channel
ChannelServices.RegisterChannel (channel);
//Register channel
RemotingConfiguration.RegisterWellKnownServiceType(typeof
Service),"Service",WellKnownObjectMode.Singleton);
Console.WriteLine ("Server ON at port number:8001");
Console.WriteLine ("Please press enter to stop the server.");
Console.ReadLine ();
}
}
}
Save the above file as ServerApp.cs. Create an executable by using Visual Studio.Net command
prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ServerApp.cs
A ServerApp.Exe will be generated in the Class folder.
Run the ServerApp.Exe will give below message on the console
Server ON at port number:8001

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

66

.Net Framework and C#


Please press enter to stop the server.
In order to check whether the HTTP channel is binded to the port, type
http://localhost:8001/Service?WSDL in the browser.
You should see a XML file describing the Service class.
Please note before running above URL on the browser your server (ServerApp.Exe should be
running) should be ON.
Creating Proxy and the Client application on Machine 2
SoapSuds.exe is a utility which can be used for creating a proxy dll.
Type below command on Visual studio.Net command prompt.
soapsuds -url:http://<
oa:Server.dll

Machine

Name

where

service

is

running>:8001/Service?WSDL

This will generates a proxy dll by name Server.dll. This will be used to access remote object.
Client Code:
using System;
using System.Runtime.Remoting.Channels; //To support and handle Channel and channel sinks
using System.Runtime.Remoting;
using System.Runtime.Remoting.Channels.Http; //For HTTP channel
using System.IO;
using ServerApp;
namespace RemotingApp
{
public class ClientApp
{
public ClientApp()
{
}
public static void Main (string[] args)
{
HttpChannel channel = new HttpChannel (8002); //Create a new channel
ChannelServices.RegisterChannel (channel); //Register the channel
//Create Service class object
Service svc = (Service) Activator.GetObject (typeof (Service),"http://<Machine name where
Service running>:8001/Service"); //Localhost can be replaced by
//Pass Message
svc.WriteMessage (10,20);
}
}
}
Save the above file as ClientApp.cs. Create an executable by using Visual Studio.Net command
prompt by,
csc /r:system.runtime.remoting.dll /r:system.dll ClientrApp.cs
A ClientApp.Exe will be generated in the Class folder. Run ClientApp.Exe , we can see the result
on Running ServerApp.EXE command prompt.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

67

.Net Framework and C#

In the same way we can implement it for TCP channel also.

ADO.NET
ADO.NET is a model used by .NET applications to communicate with a database for retrieving,
accessing and updating data.
Features of ADO.NET
Some of the features of ADO.NET are given below:
1.

2.

3.

4.

Disconnected data architecture ADO.NET uses the disconnected data architecture.


Applications connect to the database only while retrieving and updating data. After data is
retrieved, the connection with the databse is closed. When the database needs to be
updated, the connection is re-established. Working with applications that do not follow a
disconnected architecure leads to a wastage of valuable system resources, since the
application connects to the database and keeps the connection open until it stops
running, but does not actually interact with the database except while retrieving and
updating data.
Data Cahed in datasets A dataset is the most common method of accessing data since
it implements a disconnected architecture. Since ADO.NET is based on a disconnected
data structure, it is not possible for the application to interact with the database for
processing each record. Therefore, the data is retrieved and store in datasets. A dataset
is a chached set of database records.You can work with the records stored in a dataset
as you work with real data; the only difference being that the dataset is independent of
data source and you remain disconnected from the data source.
Data transfer in XML format XML is the fundamental format for data transfer in
ADO.NET. Data is transferred from a databse into a dataset and from the dataset to
another component by using XML. You can use XML file as a data source and store data
from it in a dataset. Using XML as the data transfer language is beneficial as XML is an
industry standard for exchanging information between types of applications.
Interaction with the database is done through data commands All operations on the
database are performed by using data commands. A data command can be a SQL
statement or a stored procedure. You can retrieve, insert, delete or modify data from a
database by executing data commands.

The ADO.NET Object Model


ADO.NET uses a structured process flow containing components. The structured process flow or
the object model is shown in following figure:

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

68

.Net Framework and C#

Data Provider

.NET
Application

Accessing
Retrieved data

Establish connection

Connection
Retrieve data in a readonly, forwarded only

Data Reader
Accessing retrieved data

Database
Executes a command
to retrieve data

Command

DataSet

Transfer data to the


dataset and reflects the
changes in dataset

Filling dataset w ith data

Data Adapter

ADO.NET Object Model

Data Access in ADO.NET relies on two components: DataSet and Data Provider.
DataSet
The dataset is a disconnected, in-memory representation of data. It can be considered as a local
copy of the relevant portions of the database. The DataSet is persisted in memory and the data in
it can be manipulated and updated independent of the database. When the use of this DataSet is
finished, changes can be made back to the central database for updating. The data in DataSet
can be loaded from any valid data source like Microsoft SQL server database, an Oracle
database or from a Microsoft Access database.

Data Provider
The Data Provider is responsible for providing and maintaining the connection to the database. A
DataProvider is a set of related components that work together to provide data in an efficient and
performance driven manner.
The .NET Framework currently comes with two DataProviders: the SQL Data Provider which is
designed only to work with Microsoft's SQL Server 7.0 or later and the OleDb DataProvider which
allows us to connect to other types of databases like Access and Oracle. Each DataProvider
consists of the following component classes:

The Connection object which provides a connection to the database


The Command object which is used to execute a command
The DataReader object which provides a forward-only, read only, connected recordset
The DataAdapter object which populates a disconnected DataSet with data and performs
update

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

69

.Net Framework and C#


Component classes that make up the Data Providers
The Connection Object
The Connection object creates the connection to the database. Microsoft Visual Studio .NET
provides two types of Connection classes: the SqlConnection object, which is designed
specifically to connect to Microsoft SQL Server 7.0 or later, and the OleDbConnection object,
which can provide connections to a wide range of database types like Microsoft Access and
Oracle. The Connection object contains all of the information required to open a connection to the
database.
The Command Object
The Command object is represented by two corresponding classes: SqlCommand and
OleDbCommand. Command objects are used to execute commands to a database across a data
connection. The Command objects can be used to execute stored procedures on the database,
SQL commands, or return complete tables directly. Command objects provide three methods that
are used to execute commands on the database:

ExecuteNonQuery: Executes commands that have no return values such as INSERT,


UPDATE or DELETE
ExecuteScalar: Returns a single value from a database query
ExecuteReader: Returns a result set by way of a DataReader object

The DataReader Object


The DataReader object provides a forward-only, read-only, connected stream recordset from a
database. Unlike other components of the Data Provider, DataReader objects cannot be directly
instantiated. Rather, the DataReader is returned as the result of the Command object's
ExecuteReader method. The SqlCommand.ExecuteReader method returns a SqlDataReader
object, and the OleDbCommand.ExecuteReader method returns an OleDbDataReader object.
The DataReader can provide rows of data directly to application logic when you do not need to
keep the data cached in memory. Because only one row is in memory at a time, the DataReader
provides the lowest overhead in terms of system performance but requires the exclusive use of
an open Connection object for the lifetime of the DataReader.
The DataAdapter Object
The DataAdapter is the class at the core of ADO .NET's disconnected data access. It is
essentially the middleman facilitating all communication between the database and a DataSet.
The DataAdapter is used either to fill a DataTable or DataSet with data from the database with it's
Fill method. After the memory-resident data has been manipulated, the DataAdapter can commit
the changes to the database by calling the Update method. The DataAdapter provides four
properties that represent database commands:

SelectCommand
InsertCommand
DeleteCommand
UpdateCommand

When the Update method is called, changes in the DataSet are copied back to the database and
the appropriate InsertCommand, DeleteCommand, or UpdateCommand is executed.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

70

.Net Framework and C#


ADO.NET Archtecture
The following diagram illustrates the relationship between a .NET Framework data provider and a
DataSet

Basic steps involved in data access with ADO.NET in disconnected environment


Data access using ADO.NET involves following steps:

Defining the connection string for the database server.


Defingin the connection to the database using connection string.
Defining the command or command string that contains the query.
Defining the data adapter using the command string and command object.
Creating a new dataset object.
If the command SELECT, filling the dataset object with the result of the query through the
data adapter.
Reading the records from the Data Tables in the datasets us ing the Data Row and Data
Column Objects.
If the command is Update, Insert, or Delete, then updating the dataset through the data
Adapter.
Accepting to save the changes in the data set to the database.

Connection methods:

Open- Opens the connection to our database.


Close- Closes the database connection.
Dispose- Realeses the resources on the connection object, used to force garbage
collecting, ensuring no resources are being held after our connection is used. It
automatically call close method.
State- Tells you what type of connection state your object is in used to check whether
your conection is still using any resources.
If (ConnectionObject.Sate==Connectionstate.Open)

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

71

.Net Framework and C#


Command Object methods:

Execute Reader- Simply executes the SQL query against the database using Read().
ExecuteNonQuery- Used whenever you work with SQL stored procedures with
parameters.
Execute Scalar-Returns a lightining fast signle value as an object from your database.
Ex: - object val = Command.ExecuteScalar();
Prepare- Equivalent to ADOs Command.Prepare= TRUE property. Useful in caching the
SQL command so it runs faster when called more than one.
Ex: - Commad.Prepare();
Dispose- Release the resources on the command object.

Data Reader methods:

Read-Means the record pointer to the first row, which allows the data to be read by
column Name of index position
Ex: - If (Reader.Read()==true);
IsClosed- A method that can determine if the Datareader is closed
If (DataReader.Isclosed==false);
Next Result-Equivalent to ADOs NextRecordset method, where a batch of SQL
statement are executed with this method before advancing to the next set of data results.
Ex: - DataReader.NextResult();
Close- close the Data Reader.

Example of Use of Command Object


It supports a command Type:
1. Text
A SQL command defining the statements to be executed at the data source.
2. Stored Procedure
The name of SP. You can use parameter property of a command to
access input and output parameters and return values.
3. Table Direct the name of a table.
Example Code1: Static void GetSalesByCategory( String ConnectionString, String CategoryName)
{
Using (SqlConnection connection= New SqlConnection(ConnectionString))
{
SqlCommand command = new Sqlcommand();
Command.Connection=connection;
Command.CommandText=SalesByCategory;
Command.CommandType= CommandType.StoredP rocedure;
SqlParameter parameter = New SqlParameter();
parameter.ParameterName= @ CategoryName;
parameter.SqlDbType=S qlDbType. Nvarchar;
parameter.Direction=ParameterDirection.Input;
parameter.Value= CategoryName;
Command.Parameters.Add(parameter);
Connection.Open();
SQLDataReader.reader=Command.ExecuteReader();
If (reader.HasRows)
{
While(reader.Read())

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

72

.Net Framework and C#


{
Console.WriteLine({0}:{1}, reader[0],reader[1]);
}
}
else
{
Console.WriteLine(No rows found);}
reader.Close();
}
}
Example Code2:
//Use of DataTable to Display the content of Database
using System.Data.OleDb;
namespace Ex_DatabaseDemo
{
class Program
{
static void Main(string[] args)
{
OleDbConnection con = new
OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\
\Ex_TestDataBase.mdb");
OleDbDataAdapter adp = new OleDbDataAdapter("Select * from
EMP", con);
DataTable tbl = new DataTable();
adp.Fill(tbl);
DataRow row;
for (int i = 0; i < 5; i++)
{
row = tbl.Rows[i];
for (int j = 0; j < 5; j++)
Console.Write("{0,15}", row[j]);
Console.WriteLine();
}
Console.Read();
}
}
}
Example Code3:
using System.Data.SQLClient;
namespace Ex_DatabaseDemo
{
class Program
{
static void Main(string[] args)
{
String OleDbConnectionString=Provider=SQLOLEDB; Data Source=(local);+
Inegrated Security=SSPI;Initial Catalog=AdventureWorks;;

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

73

.Net Framework and C#


String OleDbSelect = Select * from Sales.SalesOrderHeader Where
TotalDues>?;
OleDbConnection oledbconection = new OleDbConnection(OleDbConnection
String);
OleDbCommand oledbcommand = new OleDbCommand(OleDbSelect,
oledbconection);
OleDbCommand.Parameters.Add(@TotalDue,OleDbType.Currency);
OleDbCommand.Parameters[@TotalDue].Value= 20000;
OleDbDataAdapter OleDbDa = new OleDbDataAdapter(oledbcommand);
DataTable OleDbDt = new DataTable();
OleDbDa.Fill(OleDbDt);
ForEach(DataRow row in OleDbDt.Rows)
{
Console.WriteLine(row[SalesOrderID]);
Console.WriteLine(row[OrderDate]);
Console.WriteLine(row[TotalDue]);
}
Console.Read();
}
}

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

74

.Net Framework and C#


Generics
Generics are a new feature in version 2.0 of the C# language and the common language runtime
(CLR). Generics introduce to the .NET Framework the concept of type parameters, which make it
possible to design classes and methods that defer the specification of one or more types until the
class or method is declared and instantiated by client code. For example, by using a generic type
parameter T you can write a single class that other client code can use without incurring the cost
or risk of runtime casts or boxing operations, as shown here:
Example:
// Declare the generic class
public class GenericList<T>
{
void Add(T input) { }
}
class TestGenericList
{
private class ExampleClass { }
static void Main()
{
// Declare a list of type int
GenericList<int> list1 = new GenericList<int>();
// Declare a list of type string
GenericList<string> list2 = new GenericList<string>();
// Declare a list of type ExampleClass
GenericList<ExampleClass> list3 = new GenericList<ExampleClass>();
}
}

Generics Overview

Use generic types to maximize code reuse, type safety, and performance.

The most common use of generics is to create collection classes.

The .NET Framework class library contains several new generic collection classes in the
System.Collections.Generic namespace. These should be used whenever possible in
place of classes such as ArrayList in the System.Collections namespace.

You can create your own generic interfaces, classes, methods, events and delegates.

Generic classes may be constrained to enable access to methods on particular data


types.

Information on the types used in a generic data type may be obtained at run-time by
means of reflection.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

75

.Net Framework and C#


As the projects get more complicated, programmers increasingly need a means to better reuse
and customize their existing component-based software. To achieve such a high level of code
reuse in other languages, programmers typically employ a feature called Generics.
Using Generics, we can create class templates that support any type. When we instantiate that
class, we specify the type we want to use, and from that point on, our object is "locked in" to the
type we chose.
Let us look at an example of how we can create a generic class using C# 2.0.
public class MyCustomList<MYTYPE>
{
private ArrayList m_list = new ArrayList();
public int Add(myType value)
{
return m_list.Add(value);
}
public void Remove(myType value)
{
m_list.Remove(value);
}
public myType this[int index]
{
get
{
return (myType)m_list[index];
}
set
{
m_list[index] = value;
}
}
}
Here, MyCustomList is built on an ArrayList. But its methods and indexer are strongly typed. Here
<myType> is really just a placeholder for whatever type you choose when you create the class.
This placeholder is defined in angled brackets after the name of the class.
Now, let us look at how to create an instance of the class MyCustomList:
MyCustomList<int> list = new MyCustomList<int>();
// Add two integers to list
list.Add(1);
list.Add(33);
// The next statement will fail and wont compile
list.Add("Emp");
If we want our MyCustomList to store strings, it can be done as follows:
MyCustomList<string> list = new MyCustomList<string>();

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

76

.Net Framework and C#


Generic Methods
Generic methods use a similar syntax to generic types. They allow individual methods to be
created that work with types that are defined only when the method is called. A generic method
includes one or more type parameters in its signature. Those type parameters can then be used
for the return value for the method and in its parameters. This allows the methods to be reused
with many different types.
Code Example: 1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

// GenericMethod.cs
// Using overloaded methods to print arrays of different types.
using System;
using System.Collections.Generic;
class GenericMethod
{
static void Main( string[] args )
{
// create arrays of int, double and char
int[] intArray = { 1, 2, 3, 4, 5, 6 };
double[] doubleArray = { 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7 };
char[] charArray = { 'H', 'E', 'L', 'L', 'O' };
Console.WriteLine( "Array intArray contains:" );
PrintArray( intArray );
// pass an int array argument
Console.WriteLine( "Array doubleArray contains:" );
PrintArray( doubleArray );
// pass a double array argument
Console.WriteLine( "Array charArray contains:" );
PrintArray( charArray );
// pass a char array argument
}
// end Main
// output array of all types
static void PrintArray< E >( E[] inputArray )
{
foreach ( E element in inputArray )
Console.Write( element + " " );
Console.WriteLine( "\n" );
}
}

// end method PrintArray


// end class GenericMethod

Output:
Array intArray contains:
123456
Array doubleArray contains:
1.1 2.2 3.3 4.4 5.5 6.6 7.7
Array charArray contains:H E L L O

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

77

.Net Framework and C#


.NET Assemblies
Assemblies in the .Net platform are a solution to a problem that has been around as long as
libraries. The problem, known as "DLL Hell", can be caused by one application overwriting a
shared library of another application, usually with a different version.
Imagine you write an application with a shared library and then years later create a new
application with an updated library. In order not to break old programs, what do you do with the
new library? You could give it a different name, store it in a different location, or overwrite the old
ones?
Problems can also arise when a DLL is registered on a computer and for some reason the
information is corrupted or modified so that the reference no longer links to the library.
Registering a DLL in the system registry stores information about that library in sucha a way that
other applications can access the data from a central store.
.Net assemblies overcome these issues by storing information about themselves, rather than
having that information stored in a central location. The assembly will hold information about itself
such as version and vendor.
Microsoft has defines an assembly and its role in .NET as:
In the .NET Framework an assembly is the physical unit that can be executed, deployed,
versioned, and secured. All .NET Framework applications contain one or more assemblies.
What is an Assembly?
An assembly is a file that is automatically generated by the compiler upon successful compilation
of every .NET application. It can be either a Dynamic Link Library or an executable file. It is
generated only once for an application and upon each subsequent compilation the assembly gets
updated.
An Assembly contains Intermediate Language (IL) code, which is similar to Java byte code. In the
.NET language, it consists of metadata. Metadata enumerates the features of every "type" inside
the assembly or the binary. In addition to metadata, assemblies also have a special file called
Manifest. It contains information about the current version of the assembly and other related
information.
Assembly is the smallest unit of deployment, it is the collection of various things to perform a
common task or goal. It is also called the logical entity that is collection of information to execute
an application.
Features of assemblies
(1)
(2)
(3)
(4)
(5)
(6)

Assemblies are self-describing.


Version dependencies are recorded inside an assembly manifest.
Assemblies can be loaded side-by-side.
Application isolation is endured using application domains.
Installation can be as easy as copying the files that belong to an assembly.
Assemblies can be private or shared.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

78

.Net Framework and C#


Assembly Structure
An assembly consists of assembly metadata describing the complete assembly, type metadata
describing the exported types and methods, MSIL code, and resources. All these parts can be
inside of one file or spread across several files.
In this example (see Figure), the assembly metadata, type metadata, MSIL code, and resources
are all in one file - Component.dll. The assembly consists of a single file.
Composite File Assembly

Single File Assembly

Type Metadata
Manifest

Manifest

Type Metadata

Type Metadata

MSIL Code

MSIL Code

Resources

Resources

MSIL Code

Type Metadata
MSIL Code

Structure of Assembly

Assembly Metadata or Manifest


This contains information about the assembly. Remember, assemblies in .NET are selfdescribing. They contain all the information that .NET needs to use them. Assembly metadata
contains the following details of an assembly:

Assembly name
Version number of the assembly, which has four numbers in the format
major.minor.revison.build
Culture - language assembly supports
Strong name - required only for global assemblies
List of files in the assembly. An assembly can be made up of multiple files
Type reference information - informs which type is in which file of the assembly
Information about referenced assemblies - Contains list of other assemblies referenced
by this assembly. For each assembly referenced we have assembly name, version,
culture and public key (if assembly is a global assembly)

Type metadata
This section of an assembly contains information about all classes, structure etc. created in the
assembly along with the data types for their parameters and return values .
MSIL Code
MSIL is the CPU-independent instruction set into which .NET Framework programs are compiled.
MSIL include instructions for loading, storing, intitializing and calling methods on objects, as well
as instructions for arithmetic and logical operations, control flow, direct memory access, exception
handling and other operations.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

79

.Net Framework and C#


Resource
This section contains messages and pictures used by assembly.

Types of Assembly
1.Private assembly (.dll and .exe are at same place)
2.Shared assembly (.dll and .exe are at different place)
3.Dynamic assembly (dynamically create )
4.Distributed assembly (in different parts)
5.Satellite assembly (on network)
Private Assembly
A private assembly is an assembly that is deployed with an application and is available for the
exclusive use of that application. That is, other applications do not share the private assembly.
Private assemblies are one of the methods that can be used to create isolated applications.
How to create an assembly in C#
The following are the steps to create a private assembly (by default all assembl ies are private)
using Visual C#.
Step-1 Select File->New Project
Step-2 From Templates, select Class Library
Step-3 Enter name CounterLibrary
A class library is created using a single class Class1
Step-4 Rename class to Counter and add the following code.
namespace CounterLibrary
{
public class Counter
{
protected int v = 0;
public Counter(int v)
{
this.v = v;
}
public int Value
{
get
{
return v;
}
}
}
}
Step-5 Save project using File->Save All. When prompted to enter location for project, select the
folder where you want to save your project. I use c:\csharp. Do not select checkbox for Create
directory for solution
Step-6 Build (not run) the project using Build->Build Solution

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

80

.Net Framework and C#


After
the
above
process,
we
get
CounterLibrary.dll
assembly
placed
in
c:\csharp\counterlibrary\bin\release directory.
Step-7 Use this assembly in a console application. As a matter of fact, once a source program is
converted to MSIL, it can be used anywhere in .NET, irrespective of language and type of
application.
Using a private assembly in a console application developed in C#
Now, let us use the class library created in C# in a console application. Though I am using a
console application in C#, you can use any language supported by .NET.
Start Visual C#
Step-1 Create a new console application using File -> New Project
Step-2 From template select Console Application as type of projec t
Step-3 Give name UseCounter for application.
Step-4 A new application is created with a single class with Main() method.
Step-5 Go to Solution Explorer and select project
Step-6 Right click on it and select Add References from the context menu.
Step-7 From dialog box, select Browse tab and select
c:\csharp\counterlibrary\bin\release\counterlibrary.dll
Solution explorer displays counterlibrary as one of the references under references node in
solution explorer
Step-8 Add the following code in Main() method of Program.cs
using System;
namespace UseCounter
{
class Program
{
static void Main(string[] args)
{
Counterlibrary.Counter c = new Counterlibrary.Counter(100);
Console.WriteLine(c.Value);
}
}
}
As you do the above, you can notice that a copy of counterlibrary.dll is copied into BIN directory
of UseCounter application. This is the case with any private library. Whenever an application
makes a reference to it, a copy of private assembly is copied into it's bin directory.
If you do not see .DLL file that is copied to BIN directory of console application (UseCounter),
close the application and reopen it.
Shared Assembly
For using a shared assembly an application must have a key (token) for authorization and
authority.
When .dll and main file are not in same folder & main file can't direct access the .dll file. It must
take permission for Runtime manager for using that .dll, then the collection to run the file can be
known as shared assembly.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

81

.Net Framework and C#

Steps to create Shared assembly


Step 1: Create a class file
using System;
namespace SharedAssembly
{
public class Bike
{
public void start()
{
Console.WriteLine("kick start ");
}
}
}
Step 2: Generate the token
This token known as strong name key. It is the string that is large collection of alphabet and
numeric value, it is very big-string. It is also so long so that no one can access without any
permission.
--> open command prompt of visual studio
D:\shared assembly> sn -k shrd.snk
This will create a key file having name shrd.snk(128 bit key ).
Note: To generate the key it use RSA2 (Rivest Shamir Alderman) algorithm.
Step 3: Apply the key on our class file by written the code in .dll source file
// add this code to your class file
using System.Reflection;
[assembly:AssemblyKeyFile("shrd.snk")]
Class file
using System;
using System.Reflection;
[assembly:AssemblyKeyFile("shrd.snk")]
namespace SharedAssembly
{
public class Bike
{
public void start()
{
Console.WriteLine("kick start ");
}
}
}
Step 4: Complied the code file & Create a .dll file of Bike class

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

82

.Net Framework and C#


Step 5: Now register/install .dll into GAC. GAC is the database of CLR in case of .NET.After
installing this .dll in GAC, any file can use it with the help of CLR.
To install
D:\shared assembly>gacutil /i SharedAssembly.dll
Step 6: The Client Application are as follow
using System;
using SharedAssembly;
public class MainP
{
public static void Main(string []args)
{
Bike bk=new Bike();
bk.start();
Console.Read();
}
}
Step 7: Compiled the whole application
D:\> csc /r:d:\shared assembly\sharedAss.dll MainP.cs
Step 8: Run your program by using the command given below:
D:\>MainP
Difference between Private Assembly and Shared Assembly
Location and visibility: A private assembly is normally used by a single application, and is
stored in the application's directory, or a subdirectory beneath. A s hared assembly is normally
stored in the global assembly cache, which is a repository of assemblies maintained by the .NET
runtime. Shared assemblies are usually libraries of code which many applications will find useful,
e.g. the .NET framework classes.
Versioning: The runtime enforces versioning constraints only on shared assemblies, not on
private assemblies.
Global Assembly Cache
A shared assembly has version constraints. It is stored in the Global Assembly Cache (GAC).
GAC is a repository of shared assemblies maintained by the .NET runtime. The shared
assemblies may be used by many applications. To make an assembly a shared assembly, it has
to be strongly named.
To know more on how to share an assembly, create a strongly named assembly Click Here
GAC is located at C:\Windows\Assembly
Strong Name
A strong name consists of the assembly's identity its simple text name, version number, and
culture information (if provided) plus a public key and a digital signature. It is generated from
an assembly file (the file that contains the assembly manifest, which in turn contains the names
and hashes of all the files that make up the assembly), using the corresponding private key.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

83

.Net Framework and C#


Satellite Assembly
When you write a multilingual or multi-cultural application in .NET, and want to distribute the core
application separately from the localized modules, the localized assemblies that modify the core
application are called satellite assemblies.
A .NET Framework assembly containing resources specific to a given language. Using satellite
assemblies, you can place the resources for different languages in different assemblies, and the
correct assembly is loaded into memory only if the user elects to view the application in that
language.
ASP.NET
ASP.Net life cycle specifies, how:
ASP.Net processes pages to produce dynamic output
The application and its pages are instantiated and processed
ASP.Net compiles the pages dynamically
The ASP.Net life cycle could be divided into two groups:
Application Life Cycle
Page Life Cycle
ASP.Net Application Life Cycle:
The application life cycle has the following stages:

User makes a request for accessing application resource, a page. Browser sends this
request to the web server.
A unified pipeline receives the first request and the following events take place:

An object of the ApplicationManager class is created.

An object of the HostingEnvironment class is created to provide information regarding


the resources.

Top level items in the application are compiled.

Response objects are created . the application objects: HttpContext, HttpRequest and
HttpResponse are created and initialized.

An instance of the HttpApplication object is created and assigned to the request. The
request is processed by the HttpApplication class. Different events are raised by this
class for processing the request.

When an ASP page is requested, it is loaded into the server memory, processed and sent to the
browser. Then it is unloaded from the memory. At each of this steps, methods and events are
available, which could be overridden according to the need of the application. In other words, you
can write your own code to override the default code.

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

84

.Net Framework and C#


ASP.Net Page Life Cycle
The page life cycle phases are:
Initialization
Instantiation of the controls on the page
Restoration and maintenance of the state
Execution of the event handler codes
Page rendering
Following are the different stages of an ASP.Net page:
Stage
Page Request

Start

Initialization

Load
Postback Event
Handling
Rendering

Unload

Description
The page request occurs before the page life cycle begins. W hen the page is
requested by a user, ASP.NET determines whether the page needs to be
parsed and compiled (therefore beginning the life of a page), or whether a
cached version of the page can be sent in response without running the page.
In the start stage, page properties such as Request and Response are set. At
this stage, the page also determines whether the request is a postback or a
new request and sets the IsPostBack property. The page also sets the
UICulture property.
During page initialization, controls on the page are available and each control's
UniqueID property is set. A master page and themes are also applied to the
page if applicable. If the current request is a postback, the postback data has
not yet been loaded and control property values have not been restored to the
values from view state.
During load, if the current request is a postback, control properties are loaded
with information recovered from view state and control state.
If the request is a postback, control event handlers are called. After that, the
Validate method of all validator controls is called, which sets the IsValid
property of individual validator controls and of the page.
Before rendering, view state is saved for the page and all controls. During the
rendering stage, the page calls the Render method for each control, providing
a text writer that writes its output to the OutputStream object of the page's
Response property.
The Unload event is raised after the page has been fully rendered, sent to the
client, and is ready to be discarded. At this point, page properties such as
Response and Request are unloaded and cleanup is performed.

State Management in ASP.NET


State management means to preserve state of a control, web page, object/data, and user in the
application explicitly because all ASP.NET web applications are stateless, i.e., by default, for
each page posted to the server, the state of controls is lost. Nowadays all web apps demand a
high level of state management from control to application level.
Type of State Management
There are two types of state management:
Client side
Hidden Field
View State
Cookies
Control State
Query Strings

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

85

.Net Framework and C#


Server side

Session
Application

ASP Built-in Objects: In ASP.NET, objects are defined in System.Web namespace.


Objects
Application Object

Request Object

Response Object

Server Object

Session Object

Description
Describes the methods, properties, and collections of the object that stores
information related to the entire Web application, including variables and
objects that exist for the lifetime of the application.
Describes the methods, properties, and collections of the object that stores
information related to the HTTP request. This includes forms, cookies,
server variables, and certificate data.
Describes the methods, properties, and collections of the object that stores
information related to the server's response. This includes displaying
content, manipulating headers, setting locales, and redirecting requests.
Describes the methods and properties of the object that provides methods
for various server tasks. With these methods you can execute code, get
error conditions, encode text strings, create objects for use by the Web
page, and map physical paths.
Describes the methods, properties, and collections of the object that stores
information related to the user's session, including variables and objects
that exist for the lifetime of the session.

Validation Server Control


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:
Validation Server Control
CompareValidator
CustomValidator
RangeValidator
RegularExpressionValidator
RequiredFieldValidator
ValidationSummary

Description
Compares the value of one input control to the value of another
input control or to a fixed value
Allows you to write a method to handle the validation of the value
entered
Checks that the user enters a value that falls between two values
Ensures that the value of an input control matches a specified
pattern
Makes an input control a required field
Displays a report of all validation errors occurred in a Web page

By: Vikas Srivastava, Department of Computer Applications, JSSATEN

86

Das könnte Ihnen auch gefallen