0% found this document useful (0 votes)
22 views74 pages

DOT NET Technology

Uploaded by

sdpatil3742
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views74 pages

DOT NET Technology

Uploaded by

sdpatil3742
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

DOT NET Technology

CHAPTER 1: INTRODUCTION to DOT NET Framework

Introduction

.NET Framework (pronounced dot net) is a software framework developed by Microsoft that runs
primarily on Microsoft Windows. It includes a large class library known as Framework Class Library (FCL)
and provides language interoperability (each language can use code written in other languages) across
several programming languages. Programs written for .NET Framework execute in a software environment
(as contrasted to hardware environment), known as Common Language Runtime (CLR), an application
virtual machine that provides services such as security, memory management, and exception handling. FCL
and CLR together constitute .NET Framework. FCL provides user interface, data access, database
connectivity, cryptography, web application development, numeric algorithms, and network
communications. Programmers produce software by combining their own source code with .NET
Framework and other libraries. .NET Framework is intended to be used by most new applications created for
Windows platform. Microsoft also produces an integrated development environment largely for .NET
software called Visual Studio.
.NET Framework is an integral part of many applications running on Windows and provides
common functionality for those applications to run. This download is for people who need .NET to run an
application on their computer. For developers, the .NET Framework provides a comprehensive and
consistent programming model for building applications that have visually stunning user experiences and
seamless and secure communication. .NET Framework is a technology that supports building and running
the next generation of applications and XML Web services. The .NET Framework is designed to fulfill the
following objectives:
 To provide a consistent object-oriented programming environment whether object code is stored and
executed locally, executed locally but Internet-distributed, or executed remotely.
 To provide a code-execution environment that minimizes software deployment and versioning conflicts.
 To provide a code-execution environment that promotes safe execution of code, including code created by
an unknown or semi-trusted third party.
 To provide a code-execution environment that eliminates the performance problems of scripted or
interpreted environments.
 To make the developer experience consistent across widely varying types of applications, such as
Windows-based applications and Web-based applications.
 To build all communication on industry standards to ensure that code based on the .NET Framework can
integrate with any other code.

Features of .NET

Interoperability: Computer systems commonly require interaction between newer and older applications,
hence .NET Framework provides means to access functionality implemented in newer and older programs
that execute outside .NET environment. Access to COM components is provided
in System.Runtime.InteropServices and System.EnterpriseServices namespaces of the framework; access to
other functionality is achieved using the invoke feature.

Common Language Runtime engine: Common Language Runtime (CLR) serves as the execution engine
of .NET Framework. All .NET programs execute under the supervision of CLR, guaranteeing certain
properties and behaviors in the areas of memory management, security and exception handling.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 1


DOT NET Technology

Language independence: .NET Framework introduces a Common Type System (CTS).


CTS specification defines all possible data types and programming constructs supported by CLR and how
they may or may not interact with each other conforming to Common Language Infrastructure (CLI)
specification. Because of this feature, .NET Framework supports the exchange of types and object instances
between libraries and applications written using any conforming .NET language.

Framework Class Library: Framework Class Library (FCL) is a library of functionality available to all
languages using .NET Framework. FCL provides classes that encapsulate a number of common functions,
including file reading and writing, graphic rendering, database interaction, XML document manipulation,
and so on. It consists of classes, interfaces of reusable types that integrates CLR.

Simplified deployment: .NET Framework includes design features and tools which help manage
the installation of computer software to ensure that it does not interfere with previously installed software,
and that it conforms to security requirements.

Security: The design addresses some of the vulnerabilities, such as buffer overflows, which have been
exploited by malicious software. Additionally, .NET provides a common security model for all applications

Portability: While Microsoft has never implemented the full framework on any system except Microsoft
Windows, it has engineered the framework to be platform-agnostic, and cross-platform implementations are
available for other operating systems. Microsoft submitted the specifications for CLI (which includes the
core class libraries, CTS, and the Common Intermediate Language), C# and C++/CLI to
both ECMA and ISO, making them available as official standards. This makes it possible for third parties to
create compatible implementations of the framework and its languages on other platforms.

ARCHITECTURE OF .NET

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 2


DOT NET Technology

.NET framework is multitier, modular, and hierarchal in nature. Each tier of the .NET Framework is
a layer of abstraction. .NET languages are the top tier and the most abstracted level. The common language
runtime is the bottom tier, the least abstracted, and closest to the native environment (i.e. OS). The .NET
Framework is partitioned into modules, each with its own distinct responsibility. Finally, since higher tiers
request services only from the lower tiers, .NET is hierarchal. .NET Framework is a managed environment.
Language interoperability is one goal of .NET.

Common Language Specification (Managed Languages)


Common Language Specification (CLS) is a set of specifications or guidelines defining a .NET
language. Shared specifications promote language interoperability. CLS defines the common types of
managed languages, which is a subset of the Common Type System (CTS). .NET supports managed and
unmanaged programming languages. There are several differences between a compiled managed application
and an unmanaged program. Managed applications have more exposure than unmanaged applications. .NET
has considerable flexibility. For those determined to use unmanaged code, there are interoperability services
Managed applications compile to Microsoft Intermediate Language (MSIL) and metadata. MSIL is a
low-level language that all managed languages compile to instead of native binary. Using just-in-time
compilation, at code execution, MSIL is converted into binary optimized both to the environment and the
hardware. All managed languages ultimately become MSIL; so high degree of language interoperability in
.NET can be achived.
In .NET, a managed application is called an assembly. An assembly adheres to the traditional
Portable Executable (PE) format but contains additional headers and sections specific to .NET. MSIL and
metadata are the most important new additions to the .NET PE. When the .NET Framework is installed, a
new program loader recognizes and interprets the .NET PE format.

Common Type System


The Common Type System (CTS) is a catalog of .NET datatypes. System.Int32, System.Decimal,
System.Boolean, and so on. Developers are not required to use these types directly. These types are the
underlying objects of the specific data types provided in each managed language. User should use the syntax
of the language and not the underlying object type, leaving .NET the flexibility to select the most
appropriate type and size for the operating environment.
The CTS is a pyramid with System.Object at the apex. .NET types are separated into value and
reference types. Value types, which are mainly primitive types, inherit from System.ValueType and then
System.Object. Reference types—anything not a value type—is derived from System.Object, either directly
or indirectly. Value types are short-term objects and are allocated on the stack. Reference types are
essentially pointers and allocated on the managed heap. The lifetime of reference types is controlled by the
Garbage Collector.
Value types can be converted to reference types, and vice versa, through processes called boxing and
unboxing, respectively. Boxing is helpful when a developer needs to change the memory model of an object.
CTS help with type safeness, enhances language interoperability, helps in segregating application domains,
and more. CTS provide a shared type substratum for .NET, enhancing language interoperability. Finally,
.NET introduces lightweight processes called application domains which are processes within a process.
CTS play a role in code verification, type safeness, and guaranteeing that application domains are safe.

Framework Class Library


The .NET Framework Class Library (FCL) is a set of managed classes that provide access to system
services. File input/output, sockets, database access, remoting and XML are just some of the services
available in the FCL. The same classes, methods, parameters, and types are used for system services
regardless of the language. This is one of the most important contributions of FCL. Both versions of the

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 3


DOT NET Technology

program are nearly identical. The primary difference is that C# uses semicolons at the end of statements,
while VB.NET does not.
FCL includes some 600 managed classes. Microsoft partitioned the managed classes of FCL into
separate namespaces based on functionality. For example, classes pertaining to local input/output can be
found in the namespace System. IO. To further refine the hierarchy, FCL namespaces are often nested; the
tiers of namespaces are delimited with dots. The root namespace is System, which provides classes for
console input/output, management of application domains, delegates, garbage collection, and more.

CLR- (Common Language Runtime)


The .NET Framework provides a run-time environment called the common language runtime, which
runs the code and provides services that make the development process easier. Compilers and tools expose
the common language runtime's functionality and enable you to write code that benefits from this managed
execution environment. Code that you develop with a language compiler that targets the runtime is called
managed code; it benefits from features such as cross-language integration, cross-language exception
handling, enhanced security, versioning and deployment support, a simplified model for component
interaction, and debugging and profiling services.
CLR provides the following benefits:
Performance improvements: As part of their metadata, all managed components carry information about
the components and resources they were built against. The runtime uses this information to ensure that your
component or application has the specified versions of everything it needs, which makes your code less
likely to break because of some unmet dependency. Registration information and state data are no longer
stored in the registry where they can be difficult to establish and maintain. Instead, information about the
types you define (and their dependencies) is stored with the code as metadata, making the tasks of
component replication and removal much less complicated.

Easy Deployment: The ability to easily use components developed in other languages. CLR language
runtime makes it easy to design components and applications whose objects interact across languages.
Objects written in different languages can communicate with each other, and their behaviors can be tightly
integrated. For example, you can define a class and then use a different language to derive a class from your
original class or call a method on the original class. You can also pass an instance of a class to a method of a
class written in a different language. This cross-language integration is possible because language compilers
and tools that target the runtime use CTS defined by the runtime, and they follow the runtime's rules for
defining new types, as well as for creating, using, persisting, and binding to types.

Code Manager: CLR manages code. When we compile a .NET application you don't generate code that can
actually execute on your machine. You actually generate Microsoft Intermediate Language (MSIL or just
IL). All .NET code is IL code. IL code is also called Managed Code, because the .NET Common Language
Runtime manages it. Extensible types provided by a class library. Language features such as inheritance,
interfaces, and overloading for object-oriented programming. Support for explicit free threading that allows
creation of multithreaded, scalable applications.

Debug Engine: CLR allows us to perform debugging an application during runtime. It supports for custom
attributes. It enable the runtime to provide services to managed code, language compilers must emit
metadata that describes the types, members, and references in your code. Metadata is stored with the code;
every loadable common language runtime portable executable (PE) file contains metadata. The runtime uses
metadata to locate and load classes, lay out instances in memory, resolve method invocations, generate
native code, enforce security, and set run-time context boundaries.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 4


DOT NET Technology

Garbage Collector: It handles automatic memory management and it will release memory of unused
objects in an application, this provides automatic memory management. The runtime automatically handles
object layout and manages references to objects, releasing them when they are no longer being used. Objects
whose lifetimes are managed in this way are called managed data. Garbage collection eliminates memory
leaks as well as some other common programming errors. If your code is managed, you can use managed
data, unmanaged data, or both managed and unmanaged data in your .NET Framework application. Because
language compilers supply their own types, such as primitive types, you might not always know (or need to
know) whether your data is being managed.

Exception Manager: Exception Manager will handle exceptions thrown by application by while executing
Try-catch block provided by an exception.In "Try" block used where a part of code expects an error. In
"Catch" block throws an exception caught from "try" block, if there is no catch block, it will terminate
application. It supports for structured exception handling.

JIT Compilers: Language compilers and tools expose the runtime's functionality in ways that are intended
to be useful and native to developers. This means that some features of the runtime might be more
noticeable in one environment than in another. It is experienced that the runtime depends on which language
compilers or tools you use.

Security Engine: It enforces security permissions at code level security, folder level security, and machine
level security using Dot Net Framework setting and tools provided by Dot Net. Use of delegates instead of
function pointers for increased type safety and security

MSIL (Microsoft Intermediate Language)

“It is a set of CPU independent instructions that are generated by the language compiler when the
project is compiled. MSIL code is not executable but further processed by CLR/other runtime
environments before it becomes executable. MSIL is contained in the assembly of the .NET application.”

MSIL stands for Microsoft Intermediate Language. We can call it as Intermediate Language (IL) or
Common Intermediate Language (CIL). During the compile time, the compiler converts the source code into
MSIL which is a CPU-independent set of instructions that can be efficiently converted to the native code.
During the runtime the CLR's JIT compiler converts the MSIL code into native code to the Operating
System. When a compiler produces MSIL, it also produces Metadata, both are contained in a portable
executable (PE) file. MSIL includes instructions for loading, storing, initializing, and calling methods on
objects, as well as instructions for arithmetic and logical operations, control flow, direct memory access,
exception handling, and other operations. MSIL provides language interoperability as the code in any .NET
language is compiled into MSIL. Benefits of MSIL are-
 Same performance for all the .NET Languages
 Support for different runtime environments
 CLR can understand MSIL.
 Non .NET environments also support MSIL.

Metadata

Metadata is binary information describing your program that is stored either in a common language
runtime portable executable (PE) file or in memory. When you compile your code into a PE file, metadata is
inserted into one portion of the file, and your code is converted to Microsoft intermediate language (MSIL)

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 5


DOT NET Technology

and inserted into another portion of the file. Every type and member that is defined and referenced in a
module or assembly is described within metadata. When code is executed, the runtime loads metadata into
memory and references it to discover information about your code's classes, members, inheritance, and so
on. Metadata describes every type and member defined in your code in a language-neutral manner. Metadata
stores the following information:
 Description of the assembly.
o Identity (name, version, culture, public key).
o The types that are exported.
o Other assemblies that this assembly depends on.
o Security permissions needed to run.
 Description of types.
o Name, visibility, base class, and interfaces implemented.
o Members (methods, fields, properties, events, nested types).
 Attributes.
o Additional descriptive elements that modify types and members.

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

 Self-describing files.
CLR modules and assemblies are self-describing. A module's metadata contains everything needed to
interact with another module. Metadata automatically provides the functionality of IDL in COM, so you can
use one file for both definition and implementation. Runtime modules and assemblies do not even require
registration with the operating system. As a result, the descriptions used by the runtime always reflect the
actual code in your compiled file, which increases application reliability.

 Language interoperability and easier component-based design.


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

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

Managed Code

Managed code is code that is written to target the services of the managed runtime execution
environment (like Common Language Runtime in .NET Framework). The managed code is always executed
by a managed runtime execution environment rather than the operating system directly. Managed refers to a
method of exchanging information between the program and the runtime environment. Because the

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 6


DOT NET Technology

execution of code is governed by the runtime environment, the environment can guarantee what the code is
going to do and provide the necessary security checks before executing any piece of code. Because of the
same reason the managed code also gets different services from the runtime environment like Garbage
Collection, type checking, exception handling, bounds checking, etc. This way managed code does not have
to worry about memory allocations, type safety, etc. Applications written in Java, C#, VB.NET, etc target a
runtime environment which manages the execution and the code written using these types of languages is
known as Managed Code. Managed code is always compiled into an Intermediate Language (MSIL in case
of .NET Framework). The compiler used by .NET framework to compile managed code compiles it into
Intermediate Language and generates the necessary metadata, symbolic information that describes all of the
entry points and the constructs exposed in the Intermediate Language (e.g., methods, properties) and their
characteristics. The Common Language Infrastructure (CLI) Standard describes how the information is to be
encoded, and programming languages that target the runtime emit the correct encoding.
In .NET Framework Managed Code runs within the .Net Framework’s CLR and benefits from the
services provided by the CLR. When we compile the managed code, the code gets compiled to an
intermediate language (MSIL) and an executable is created. When a user runs the executable the Just In
Time Compiler of CLR compiles the intermediate language into native code specific to the underlying
architecture. Since this translation happens by the managed execution environment (CLR), the managed
execution environment can make guarantees about what the code is going to do, because it can actually
reason about it. It can insert traps and sort of protection around, if it's running in a sandboxed environment,
it can insert all the appropriate garbage collection hooks, exception handling, type safety, array bounce,
index checking and so forth. Managed code also provides platform independence. As the managed code is
first compiled to intermediate language, the CLR’s JIT Compiler takes care of compiling this intermediate
language into the architecture specific instructions.

Unmanaged Code

Code that is directly executed by the Operating System is known as un-managed code. Typically
applications written in VB 6.0, C++, C, etc are all examples of unmanaged code. Unmanaged code typically
targets the processor architecture and is always dependent on the computer architecture. Unmanaged code is
always compiled to target a specific architecture and will only run on the intended platform. This means that
if you want to run the same code on different architecture then you will have to recompile the code using
that particular architecture. Unmanaged code is always compiled to the native code which is architecture
specific. When we compile unmanaged code it gets compiled into a binary X86 image. And this image
always depends on the platform on which the code was compiled and cannot be executed on the other
platforms that are different that the one on which the code was compiled. Unmanaged code does not get any
services from the managed execution environment.In unmanaged code the memory allocation, type safety,
security, etc needs to be taken care of by the developer. This makes unmanaged code prone to memory leaks
like buffer overruns and pointer overrides and so forth.Unmanaged executable files are basically a binary
image, x86 code, loaded into memory. The program counter gets put there and that’s the last the Operating
System knows. There are protections in place around memory management and port I/O and so forth, but the
system doesn’t actually know what the application is doing.

JIT (Just-In-Time) Compilers

Modern software programming languages (like C# and VB.NET) utilize a human-friendly syntax
that is not directly understandable by computers. Software commands in this human-friendly syntax are
referred to as Source Code. Before a computer can execute the source code, special programs called

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 7


DOT NET Technology

compilers must rewrite it into machine instructions, also known as object code. This process (commonly
referred to simply as “compilation”) can be done explicitly or implicitly.

Explicit Compilation
Explicit compilation converts the upper level language into object code prior to program execution. Ahead
of time (AOT) compilers are designed to ensure that, the CPU can understand every line in the code before
any interaction takes place.

Implicit Compilation
Implicit compilation is a two-step process.
 The first step is converting the source code to intermediate language (IL) by a language-specific
compiler.
 The second step is converting the IL to machine instructions. The main difference with the explicit
compilers is that only executed fragments of IL code are compiled into machine instructions, at
runtime. The .NET framework calls this compiler the JIT (Just-In-Time) compiler.

Portability
Delivering portability is a key aspect when developing a program targeting a wide range of platforms. A
couple of questions need answers to enable execution on multiple platforms:
 What kind of CPU is used?
 What Operating System (OS) will the program be running on?
To enable maximum reach of the software, the source code has to be compiled with a wide range of explicit
compilers.

The implicit way delivers portability quite more effortlessly, because the first step of the process is much
more platform agnostic. Each target platform has a JIT compiler deployed and as long as the IL can be
interpreted the program can execute. The initial compiler does not need to know all of the places where the
software might run.

Just-In-Time Compilation
A Web Service or Web Forms file must be compiled to run within the CLR. Compilation can be
implicit or explicit. Although you could explicitly call the appropriate compiler to compile your Web
Service or Web Forms files, it is easier to allow the file to be complied implicitly. Implicit compilation
occurs when you request the .aspx via HTTP-SOAP, HTTP-GET, or HTTP-POST. The parser (xsp.exe)
determines whether a current version of the assembly resides in memory or in the disk. If it cannot use an
existing version, the parser makes the appropriate call to the respective compiler (as you designated in the
Class property of the .aspx page).
When the Web Service (or Web Forms page) is implicitly compiled, it is actually compiled twice. On
the first pass, it is compiled into IL. On the second pass, the Web Service (now an assembly in IL) is
compiled into machine language. This process is called Just-In-Time JIT compilation because it does not
occurs until the assembly is on the target machine. The reason you do not compile it ahead of time is so that
the specific JIT for your OS and processor type can be used. As a result, the assembly is compiled into the
fastest possible machine language code, optimized and enhanced for your specific configuration. It also
enables you to compile once and then run on any number of operating systems.

Working of JIT
Before MSIL(MS Intermediate Language) can be executed, it must converted by .net Framework
Just in time (JIT) compiler to native code, which is CPU specific code that run on some computer

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 8


DOT NET Technology

architecture as the JIT compiler. Rather than using time and memory to convert all the MSIL in portable
executable (PE) file to native code, it converts the MSIL as it is needed during execution and stored in
resulting native code so it is accessible for subsequent calls. The runtime supplies another mode of
compilation called install-time code generation. The install-time code generation mode converts MSIL to
native code just as the regular JIT compiler does, but it converts larger units of code at a time, storing the
resulting native code for use when the assembly is subsequently loaded and executed. As part of compiling
MSIL to native code, code must pass a verification process unless an administrator has established a security
policy that allows code to bypass verification. Verification examines MSIL and metadata to find out whether
the code can be determined to be type safe, which means that it is known to access only the memory
locations it is authorized to access.
CLR class loader lodes MSIL code and metadata are loaded into memory; the code manager calls the
entry point method which is WinMain or DLLMain method. The JIT compiler compiles the method to
before its execution of the entry point method. The code manager places the objects in memory and controls
the execution of the code. The garbage collector performs periodic checks on the managed heap to identify
the objects which is not in use for the application.
At the time of program execution the type checker ensures that all objects and values, and the
references of objects and values has its valid type. The type checker also makes sure that only valid
operations are performed on the code otherwise the exception will be thrown. The code is controlled by CLR
at run time. CLR enforces security in following manner.
 To control and access the system recourses like hard disk
 To control and access the network connections
 To control and access the other hard ware resources.

The JIT compiler is part of the Common Language Runtime (CLR). The CLR manages the execution of all
.NET applications. In addition to JIT compilation at runtime, the CLR is also responsible for garbage
collection, type safety and for exception handling.

Figure 1

Different machine configurations use different machine level instructions. The source code is
compiled to exe or dll by the .NET compiler. Common Intermediate Language (CIL) consists of instructions
that any environment supporting .NET can execute and includes metadata describing structures of both data
and code. The JIT Compiler processes the CIL instructions into machine code specific for an environment.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 9


DOT NET Technology

Program portability is ensured by utilizing CIL instructions in the source code. The JIT compiler compiles
only those methods called at runtime. It also keeps track of any variable or parameter passed through
methods and enforces type-safety in the runtime environment of the .NET Framework.

Types of JIT Compilers


There are three types of JIT compilation in the .NET framework:

Normal JIT Compilation


With the Normal JIT Compiler methods are compiled when called at runtime. After execution this method is
stored in the memory and it is commonly referred as “jitted”. No further compilation is required for the same
method. Subsequent method calls are accessible directly from the memory cache.

Econo JIT Compilation


The Econo JIT Compiler is displayed in following figure. It compiles methods when called at runtime and
removes them from memory after execution.

Pre-JIT Compilation
Another form of compilation in .NET is called Pre-JIT compilation. It compiles the entire assembly instead
of used methods. In .NET languages, this is implemented in Ngen.exe (Native Image Generator). All CIL
instructions are compiled to native code before startup, as shown in figure. This way the runtime can use
native images from the cache instead of invoking the JIT Compiler.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 10


DOT NET Technology

Both implicit and explicit compilations have advantages and disadvantages.


 Ahead of time (AOT) delivers faster start-up time, especially in large applications where much code
executes on startup. But it requires more disk space and more memory/virtual address space to keep
both the IL and precompiled images. In this case the JIT Compiler has to do a lot of disk I/O actions,
which are quite expensive.
 JIT can generate faster code, because it targets the current platform of execution. AOT compilation
must target the lowest common denominator among all possible execution platforms.
 JIT can profile the application while it runs, and dynamically re-compile the code to deliver better
performance in the hot path (the most used functions).

JustTrace and Compilation


JustTrace’s performance profiler uses the JIT Compiler in .NET to collect data. The tracing profiler tracks
every time the runtime enters or leaves methods. It also shows method hit counts, own time and total time
spent by methods. All Methods view which gives information on how much time is spent by different
methods.

JustMock and Compilation


JustMock instruments static and non-virtual functions before they are jitted. JustMock replaces the desired
method with its mocked instance and its behavior at runtime. This achieves a great degree of flexibility.
Machines cannot run MSIL directly. JIT compiler turns MSIL into native code, which is CPU specific code
that runs on the same computer architecture as the JIT compiler. Because the common. Language runtime
supplies a JIT compiler for each supported CPU architecture, developers can write a set of MSIL that can be
JIT-compiled and run on computers with different architectures. However, your managed code will run only
on a specific operating system if it calls platform specific native APIs, or a platform-specific class library.
JIT compilation takes into account the fact that some code might never get called during execution.
Rather than using time and memory to convert all the MSIL in a portable executable (PE) file to native code,
it converts the MSIL as needed during execution and stores the resulting native code so that it is accessible
for subsequent calls.
The loader creates and attaches a stub to each of a type's methods when the type is loaded. On the
initial call to the method, the stub passes control to the JIT compiler, which converts the MSIL for that
method into native code and modifies the stub to direct execution· to the location of the native code.
Subsequent calls of the JIT -compiled method proceed directly to the native code that was previously
generated; reducing the time it takes to JIT-compile and run the code.
In the .NET Framework, all the Microsoft .NET languages use a Common Language Runtime, which
solves the problem of installing separate runtimes for each of the programming languages. When the
Microsoft .NET Common Language Runtime is installed on a computer then it can run any language that is
Microsoft .NET compatible. Before the Microsoft Intermediate Language (MSIL) can be executed, it must
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 11
DOT NET Technology

be converted by a .NET Framework Just-In-Time (JIT) compiler to native code, which is CPU-specific code
that runs on the same computer architecture as the JIT compiler.

Introduction to Visual Studio .NET IDE

An integrated development environment (IDE), also known as integrated design environment and integrated
debugging environment, is a type of computer software that assists computer programmers to develop
software. In the case of Visual Basic .NET, that IDE is Visual Studio. When you start a new project in
Visual Studio .NET, you will see a group of windows opened within the environment. The following
sections in this document describe each of the windows.

Toolbox Window: This window holds a list of controls that you can drag onto your forms. There are
different sets of controls available, depending on the type of designer that is active in the editor. If you are
designing Windows Forms, you will get a specific set of tools that work with Windows Forms. If you are
designing a Web Form, you will get a specific set of tools for working with Web Controls. If you are
designing an XML document, there will be other options you can choose. To view the Toolbox window,
from the View menu in Visual Studio .NET, click Toolbox.

Customizing the Toolbox: If you wish to customize which tools are displayed in the toolbox, or if you wish
to add any additional .NET components, Microsoft® ActiveX® controls, or third-party controls to the
toolbox, click Tools and then Customize Toolbox to display the Customize Toolbox dialog box, as shown in
Figures 5 and 6. Figure 5 shows the ActiveX (COM) components that you can add to the toolbox, and
Figure 6 shows the .NET controls you can add to the toolbox.
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 12
DOT NET Technology

Solution Explorer Window: A set of projects that are part of the same application in Visual Studio .NET is
called a Solution. The Solution Explorer window shows you a tree view list of each project, each project's
references, and each project's components. If this window is closed, you can open it from the View menu by
clicking Solution Explorer. Components may be made up of forms, classes, modules, and any other file
types it takes to create your application. Double-click on an item in order to edit that item within the IDE.

Class View Window: When you start creating a large number of classes, you may want to see a list of all of
the properties and methods that are available in those classes. You can use the Class View window. To bring
up this window, on the View menu, click Class View. Once the window is displayed, you can expand each
item in the list to see the properties and methods. If you choose any of these properties or methods, you can
right-click and you'll see a menu of actions that apply directly to the definition of that method or property.
Once you see the classes in this window, you can double-click on any one of them to have them displayed in
the editor.

Server Explorer Window: The Server Explorer window allows you to view the various services that are
available on a particular server. These services include Crystal Reports Services, Event Logging, Message
Queues, Performance Counters, Other Services, and Database services like SQL Server. For most of these
services, user can drill into each one, see a list of existing items or even add new items. user can drag a
service from this window onto a design surface, so user can interact with this element programmatically in
your application. For example, user can drag a performance counter onto a Windows Form and use that
component to increment or decrement that counter. user could also drag a database table onto a form, and it
will automatically create a connection and a DataAdapter component that you can use to retrieve data from
that table.

Properties Window: When working with classes such as text boxes and forms, you will most likely need to
change certain attributes about those classes. To bring up the Properties window, on the View menu click
Properties Window. Once this window is up, user can either view the list alphabetically or categorized by
attribute. Properties within this window can be selected either from a list or by clicking a button to bring up
a dialog box. There may be others user type some text into, like the Text property that is used to change the
title of a form.

Object Browser Window: Similar to the Class View window, the Object Browser dialog box shows you a
list of classes and their respective properties and methods. The main difference between these two tools is
the Object Browser allows you to browse all referenced components, not just the components for the current
project like the Class View window does. A nice feature of the Object Browser is that it also shows you the
full declaration for the method or property. To bring up the Object Browser, on the View menu, click Other
Windows and then Object Browser. If you wish to see components that are not referenced by your projects,
you can add them using the "customize" button on the toolbar. They will not be added as references, only
shown in the Object Browser for your convenience.

Task List Window: There is a Task List window that is the central location for you to peruse user tasks,
build errors, or issues in your code (comment tasks). To bring up the Task List window, on the View menu,
click Other Windows and then Task List. You will then see a window appear in your design environment
that looks like Figure 10. To add a new task, you can click where the window says, "Click here to add a new
task," or you can add comments in a specific format right in the code of your project. The default comment
that adds to the Task List looks like this:

Types of Windows: There are two types of windows in the Visual Studio .NET IDE: Tool windows and
Document windows. Tool windows are listed in the View menu and other menus such as the Debugger.
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 13
DOT NET Technology

These menus can change based on the current application and the various add-ins you may have installed.
Document windows are those windows that you open for editing some item in your project.

Tool Windows: The windows you have learned about in this document, including the Toolbox, Solution
Explorer, Properties, and Server Explorer, are tool windows. You can manipulate and arrange Tool windows
in the IDE in various ways. You can make these windows automatically hide or show. You can have a group
of them display in a tabbed format. You can dock them against the edges of the IDE, or have them free-
floating, by selecting or clearing the Dockable option on the Window menu. You can even display these
windows on a second monitor if you have a dual monitor capability. To place Tool windows on different
monitors, use the Display settings in the Control Panel to set up your multiple monitor configurations. You
can then drag the Tool window to the other monitor. Only tool windows in a floating mode can be moved
outside of the application frame. You can move a dockable window without snapping it into place by
pressing the CTRL key while dragging it within the IDE.

Features of Tool Windows: You can have multiple instances of certain Tool windows. For example, you
can have more than one Web Browser window open at one time. To create new instances of windows, on
the Window menu, click New Window.Tool windows can be set to auto hide when you highlight another
window. When they auto-hide, they slide to one of the sides of the IDE and only display their icon and
name. You just click them or hover over their icon/label to un-hide them. Once a window is open, you can
click the pushpin icon on the title bar of the window to keep it docked on the IDE.

Document Windows: Document windows are those windows that you use for editing an item from your
project. Any window that is not dockable and is unique to a specific project is a Document window. How
Document windows appear in the IDE will depend on the interface mode you have set in Visual Studio
.NET. You may tile windows when you are in the Tabbed Documents mode. This is accomplished by
dragging a document's tab to the bottom or the right side of the IDE and a frame for tiling will show up. To
cancel this tiling, you simply drag the tab back to its original location.

Interface Modes: Visual Studio .NET supports two different interface modes for document windows:
Multiple Document Interface (MDI) and Tabbed Documents. You can change modes using the General pane
under the Environment options in the Options dialog box. You can get to this dialog box by clicking Tools,
then Options, and then General under the Environment tree. In MDI mode, the IDE provides a parent
window that serves as a visual and logical container for all Tool and Document windows. Tabbed
Documents mode displays all document windows maximized, and a tab strip on top shows the names of the
open documents for quick navigation.

IntelliSense: When using objects such as ADO.NET objects or any data type, after typing the name of the
variable and a dot (.), you will see a list of methods and/or properties that you can use with that object.
When entering a method call, you can see the signature of the method with the types of its parameters and
scroll through the various overloaded signatures. The technology behind this is Microsoft® IntelliSense®; it
allows you to auto-complete the syntax just by hitting the space bar or the tab key once the command that
you wish to use is highlighted.

Split the Editing Window: You can split the editing window by grabbing the upper right corner of the
editing window and dragging it downward. You can also double-click the same area to have it split or un-
split automatically. If you need a full-height split of a document window, on the Window menu, click New
Window to create a second window and position it how you'd like.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 14


DOT NET Technology

Chapter 2: C# Basics

Introduction to C#

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


Microsoft within its .NET initiative led by Anders Hejlsberg. C# programming is very much based on C
and C++ programming languages, so if you have a basic understanding of C or C++ programming, then it
will be easier to learn C#.

Simple C# Program
using System;
class TestClass
{
static void Main(string[] args)
{
System.Console.Write(“Hello Students”);
System.Console.Write(“Welcome to CIMDR”);
System.Console.WriteLine(“Its BCA-III Sem-V”);
System.Console.WriteLine(“We are studying Visual
Programming");
}
}

OUTPUT:
Hello Students Welcome to CIMDR
Its BCA-III Sem-V
We are studying Visual Programming

Compiling a C# program using command line utility


CSC.exe is the C# compiler included in the .NET Framework and can be used to compile from the
command prompt. To compile and execute a program in C#, you just need to click the Run button or press
F5 key to execute the project in Microsoft Visual Studio IDE. Compile a C# program by using the
command-line instead of the Microsoft Visual Studio IDE −

 Open a text editor and add the code.


 Save the file as <file_name>.cs
 Open the command prompt tool and go to the directory where you saved the file.
 Type csc <file_name>.cs and press enter to compile code.
 If there are no errors in code, the command prompt takes you to the next line and
generates <file_name>.exe executable file.
 Type <file_name> to execute program.
 You can see the output printed on the screen.

Entry point method


The Main method is the entry point of a C# console application or windows application. (Libraries
and services do not require a Main method as an entry point.). When the application is started,
the Main method is the first method that is invoked.There can only be one entry point in a C# program. If
you have more than one class that has a Main method, you must compile your program with
the /main compiler option to specify which Main method to use as the entry point
The Main method is the entry point of an .exe program; it is where the program control starts and
ends. Main is declared inside a class or struct. Main must be static and it should not be public. (In the earlier
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 15
DOT NET Technology

example, it receives the default access of private.) The enclosing class or Struct is not required to be static.
Main can either have a void or int return type. The Main method can be declared with or without
a string[] parameter that contains command-line arguments. When using Visual Studio to create Windows
Forms applications, you can add the parameter manually or else use the Environment class to obtain the
command-line arguments. Parameters are read as zero-indexed command-line arguments. Unlike C and
C++, the name of the program is not treated as the first command-line argument.Validforms of Main() are :
static void Main() {...}
static int Main() {...}
static void Main(string[] a) {...}
static int Main(string[] args) {...}

Different valid forms of main


We can use more than on Main Method in C# program, But there will only one Main Method which
will act as entry point for the program. We can pass the value to the main method while running the program
by specifying string array type parameter.
C# has a strong feature in which we can define more than one class with the Main method. Since
Main is the entry point for the program execution, there are now more than one entry points. In fact, there
should be only one entry point. Which will be resolved by specifying which Main is to be used to the
compiler at the time of compilation as shown below:
csc filename.cs/main : class name
Where filename is the name of file where code is stored and classname is the name of class containing the
Main which we would like to be the entry point. To understand the concept let’s see an example.
Program with multiple Main Methods
using System;
class First
{
public static void Main()
{Console.WriteLine("This is First Class"); }
}
class second
{
public static void Main()
{Console.WriteLine("This is second class"); }
}
c1ass Third
{
public static void Main()
{Console.WriteLine ("This is Third Class"); }
}

Compilation and Execution of Program


(suppose the name of file is multiple.cs)
c:\>csc/main : Second multiple.cs
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 16
DOT NET Technology

c:\> multiple
This is second class

C:\>csc/main : First multiple.cs


C:\>multiple
This is First class

Command line arguments


Parameter(s) can be passed to a Main() method in C# and it is called command line
argument. Main() method is where program stars execution. Main method doesn’t accept
parameter from any method. It accept parameter through command line. It is an array type
parameter that can accept n numb er of parameter in runtime. In Main (string [] args), args is a
string type of array that can hold numerous parameter.

using System;
class CIMDR
{
static void Main(string[] args)
{
if(args.Length > 0)
{
Console.WriteLine("Arguments Passed by the Programmer:");
foreach(Object obj in args)
{
Console.WriteLine(obj);
}
}
else
{
Console.WriteLine("No command line arguments found.");
}
}
}

Compile: csc CIMDR.cs


Execute: Geeks.exe Welcome To CIMDR!
OUTPUT : Arguments Passed by the Programmer:
Welcome
To
CIMDR!

Stack and Heap memory

Stack Memory
A stack is a special area of computer's memory which stores temporary variables created by a
function. In stack, variables are declared, stored and initialized during runtime. It is a temporary storage
memory. When the computing task is complete, the memory of the variable will be automatically erased.
The stack section mostly contains methods, local variable, and reference variables. The stack is an array of
memory which works as Last-in, First-out (LIFO) data structure. Data can be added to and deleted only from

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 17


DOT NET Technology

the top of the stack. Placing a data item at the top of the stack is called pushing the item onto the stack.
Deleting an item from the top of the stack is called popping the item from the stack.
Stack stores various types of data:
o The values of certain types of variables
o The program’s current execution environment
o Parameters passed to methods

Advantages of using Stack


 Helps user to manage the data in a Last in First out (LIFO) method which is not possible with Linked
list and array.
 When a function is called the local variables are stored in a stack, and it is automatically destroyed
once returned.
 A stack is used when a variable is not used outside that function.
 It allows you to control how memory is allocated and deallocated.
 Stack automatically cleans up the object.
 Not easily corrupted
 Variables cannot be resized.

Disadvantages of using Stack


 Stack memory is very limited.
 Creating too many objects on the stack can increase the risk of stack overflow.
 Random access is not possible.
 Variable storage will be overwritten, which sometimes leads to undefined behavior of the function or
program.
 The stack will fall outside of the memory area, which might lead to an abnormal termination.

Heap Memory
The heap is a memory used by programming languages to store global variables. By default, all
global variables are stored in heap memory space. It supports dynamic memory allocation. The heap is not
managed automatically for you and is not as tightly managed by the CPU. It is more like a free-floating
region of memory. The heap is an area of memory where chunks are allocated to store certain kinds of data
objects. Data can be stored and removed from the heap in any order. The program can store items in the
heap, it cannot explicitly delete them. Instead, the CLR’s garbage collector (GC) automatically cleans up
orphaned heap objects when it determines that your code can no longer access them.

Advantages of using Heap


 Heap helps user to find the greatest and minimum number
 Garbage collection runs on the heap memory to free the memory used by the object.
 Heap method also used in the Priority Queue.
 It allows user to access variables globally.
 Heap doesn't have any limit on memory size.

Disadvantages of using Heap


 It can provide the maximum memory an OS can provide
 It takes more time to compute.
 Memory management is more complicated in heap memory as it is used globally.
 It takes too much time in execution compared to the stack.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 18


DOT NET Technology

KEY DIFFERENCES
 Stack is a linear data structure whereas Heap is a hierarchical data structure.
 Stack memory will never become fragmented whereas Heap memory can become fragmented as
blocks of memory are first allocated and then freed.
 Stack accesses local variables only while Heap allows you to access variables globally.
 Stack variables can’t be resized whereas Heap variables can be resized.
 Stack memory is allocated in a contiguous block whereas Heap memory is allocated in any random
order.
 Stack doesn’t require de-allocating variables whereas in Heap de-allocation is needed.
 Stack allocation and deallocation are done by compiler instructions whereas Heap allocation and
deallocation is done by the programmer.

Key Differences between Stack and Heap

Parameter Stack Heap


Type of data
A stack is a linear data structure. Heap is a hierarchical data structure.
structures
Access speed High-speed access Slower compared to stack
Heap Space not used as efficiently. Memory
Space Space managed efficiently by OS so
can become fragmented as blocks of
management memory will never become fragmented.
memory first allocated and then freed.
Access Local variables only It allows you to access variables globally.
Limit of space Does not have a specific limit on memory
Limit on stack size dependent on OS.
size size.
Resize Variables cannot be resized Variables can be resized.
Memory Memory is allocated in a contiguous
Memory is allocated in any random order.
Allocation block.
Deallocation Does not require de-allocating variables. Explicit de-allocation is needed.
Cost Less More
A stack can be implemented in 3 ways
Heap can be implemented using array and
Implementation simple array based, using dynamic
trees.
memory, and Linked list based.
Main Issue Shortage of memory Memory fragmentation
Locality of
Automatic compile time instructions. Adequate
reference
Flexibility Fixed size Resizing is possible
Access time Faster Slower
Example Classroom Campus

When to use the Heap or stack?


You should use heap when you require allocating a large block of memory. For example, you want to create
a large size array or big structure to keep that variable around a long time then you should allocate it on the
heap. However, if you are working with relatively small variables that are only required until the function
using them is alive. Then you need to use the stack, which is faster and easier.

Data Types in C#

There are two kinds of datatypes in C#: value types and reference types
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 19
DOT NET Technology

In C#, a Value Type if it holds the value of variable directly on its own memory space and Value Types will
use Stack memory to store the values of the variables. A value type if it holds a data value within its own
memory space. It means the variables of these data types directly contain values.
The following data types are all of value type: bool , byte , char, decimal, double , enum , float, int, long
,sbyte, short, struct, uint, ulong, ushort, etc.

using System;
class Program
{
static void Square(int a, int b)
{
a = a * a;
b = b * b;
Console.WriteLine(a + " " + b);
}

static void Main(string[] args)


{
int num1 = 5;
int num2 = 10;
Console.WriteLine(num1 + " " + num2);
Square(num1, num2);
Console.WriteLine(num1 + " " + num2);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}
}

In c#, Reference Types will contain a pointer which points to other memory location that holds the data.
The Reference Types won’t store the variable value directly in its memory instead; it will store the memory
address of the variable value to indicate where the value is being stored. A reference type doesn't store its
value directly. Instead, it stores the address where the value is being stored. In other words, a reference type
contains a pointer to another memory location that holds the data.
The followings are reference type data types: String, Arrays, Class, Delegate, etc.

using System;
class Person
{
public int age;
}
class Program
{
static void Square(Person a, Person b)
{
a.age = a.age * a.age;
b.age = b.age * b.age;
Console.WriteLine(a.age + " " + b.age);
}
static void Main(string[] args)
{
Person p1 = new Person();
Person p2 = new Person();
p1.age = 5;
p2.age = 10;
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 20
DOT NET Technology

Console.WriteLine(p1.age + " " + p2.age);


Square(p1, p2);
Console.WriteLine(p1.age + " " + p2.age);
Console.WriteLine("Press Any Key to Exit..");
Console.ReadLine();
}
}

Type Casting or Conversion (Implicit and Explicit casting)

The meaning of Type Casting is to change one data type into another data type. Developers change
data type according to their need. C# is statically-typed at compile time, after a variable is declared, it
cannot be declared again or used to store values of another type unless that type is convertible to the
variable's type.
For example, there is no conversion from an integer to any arbitrary string. Therefore, after you
declare i as an integer, you cannot assign the string "Hello" to it, as is shown in the following code.
Explicit and implicit type casting is a common programming topic for almost any imperative
programming language. Most C, C++, or Pascal programmers care about efficiency and speed of their code;
but those who use managed programming environments, such as Java, Visual Basic, or C# rely all the
optimizing tasks on the compiler and the runtime environment. This can be a good approach in many cases,
but managed languages are becoming more and more popular also for high-performance applications where
the knowledge of the language, compiler, and runtime environment can enhance a program's quality and
speed.
C# language contains a great feature which allows defining implicit and explicit conversion
operators. The efficiency of these casting methods depends on the casting method implementation. Anyway,
these functions are always static and have only one parameter, so the procedure call overhead is small (no
"this" parameter should be passed). Anyway, it seems to be that the Microsoft C# compiler doesn't inline
those methods, so arranging parameters and return addresses in the stack may slow your code execution
speed.
int i;
i = "Hello"; // Error: "Cannot implicitly convert type 'string' to
'int'"

 Implicit casting or conversion


Implicit Conversion is done by the compiler itself. For built-in numeric types, an implicit conversion can
be made when the value to be stored can fit into the variable without being truncated or rounded off. For
example, a variable of type long (8 byte integer) can store any value that an int (4 bytes on a 32-bit
computer) can store. In the following example, the compiler implicitly converts the value on the right to a
type long before assigning it to bigNum.

// Implicit conversion. num long can


// hold any value an int can hold, and more!
Int num = 2147483647;
long bigNum = num;

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

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 21


DOT NET Technology

Derived d = new Derived();


Base b = d; // Always OK.

// C# program to demonstrate the Implicit Type Conversion

using System;
class ImplicitCasting
{

// Main Method
public static void Main(String []args)
{
int i = 57;

// automatic type conversion


long l = i;

// automatic type conversion


float f = l;

// Display Result
Console.WriteLine("Int value " +i);
Console.WriteLine("Long value " +l);
Console.WriteLine("Float value " +f);
}
}
}

Output:
Int value 57
Long value 57
Float value 57

 Explicit casting or conversion


Explicit Conversion is done by the users according to their need/requirement. User tell the compiler to
do the conversion. However, if a conversion cannot be made without a risk of losing information, the
compiler requires that you perform an explicit conversion, which is called a cast. A cast is a way of
explicitly informing the compiler that you intend to make the conversion and that you are aware that data
loss might occur. To perform a cast, specify the type that you are casting to in parentheses in front of the
value or variable to be converted. The following program casts a double to an int. The program will not
compile without the cast.

// C# program to demonstrate the Explicit Type Conversion


using System;

class ExplicitCasting
{

// Main Method
public static void Main(String []args)
{
double d = 765.12;

// Explicit Type Casting

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 22


DOT NET Technology

int i = (int)d;

// Display Result
Console.WriteLine("Value of i is " +i);
}
}
}
Output:
Value of i is 765

A cast operation between reference types does not change the run-time type of the underlying object;
it only changes the type of the value that is being used as a reference to that object.

Boxing and unboxing

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

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

class TestBoxing
{
static void Main()
{
int i = 123;
object o = i; // Boxing copies the value of i into object o.
i = 456; // Change the value of i.

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


System.Console.WriteLine("The value-type value = {0}", i);
System.Console.WriteLine("The object-type value = {0}", o);
}
}

OUTPUT:
The value-type value = 456
The object-type value = 123

Unboxing is an explicit conversion from the type object to a value type or from an interface type to a value
type that implements the interface. An unboxing operation consists of:
 Checking the object instance to make sure that it is a boxed value of the given value type.
 Copying the value from the instance into the value-type variable.

class TestUnboxing
{

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 23


DOT NET Technology

static void Main()


{
int i = 123;
object o = i; // implicit boxing

try
{
int j = (short)o; // attempt to unbox
System.Console.WriteLine("Unboxing OK.");
}
catch (System.InvalidCastException e)
{
System.Console.WriteLine("{0} Error: Incorrect unboxing.",
e.Message);
}
}
}

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

class Program
{
static void Main(string[] args)
{
string mine = "Forget code";
String referenceType1 = mine; //Boxing
string valueType1 = referenceType1; //Unboxing

bool b = true;
Boolean referenceType2 = b; //Boxing
bool valueType2 = referenceType2; //Unboxing

Console.WriteLine(mine);
Console.WriteLine(referenceType1);
Console.WriteLine(valueType1);

Console.WriteLine(b);
Console.WriteLine(referenceType2);
Console.WriteLine(valueType2);
}

Output:
Forget code
Forget code
Forget code
True
True
True

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 24


DOT NET Technology

Pass by value

C# supports two ways of passing arguments to methods: by value and by reference. The default
passing of arguments is by value. When we pass arguments by value, the method works only with the copies
of the values. This may lead to performance overheads when we work with large amounts of data.
We use the ref keyword to pass a value by reference. When we pass values by reference, the method
receives a reference to the actual values. The original values are affected when modified. This way of
passing values is more time and space efficient. On the other hand, it is more error prone.
It depends on the situation which technique is suitable, either pass by value or by reference. Pass by
value is useful when we want to compute some statistics of the data, we do not need to modify it. Pass by
reference is useful when we work with large amounts of data and the speed of computation is critical and
complex.
The following example shows how we pass arguments by values.

using System;
public class PassingByValues
{
static int a = 4;
static int b = 7;

static void Swap(int a, int b)


{
int temp;
temp = a;
a = b;
b = temp;
Console.WriteLine("Inside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}

static void Main()


{
Console.WriteLine("Before Swapping");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);

Swap(a, b);

Console.WriteLine("After Swapping");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}
}

Another example

using System;
class PassByValue
{
static void Main(string[] args)
{

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 25


DOT NET Technology

int x = 10;
Console.WriteLine("Variable Value Before Calling the Method: {0}", x);
Multiplication(x);
Console.WriteLine("Variable Value After Calling the Method: {0}", x);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}

public static void Multiplication(int a)


{
a *= a;
Console.WriteLine("Variable Value Inside the Method: {0}", a);
}
}
}

Pass by reference

The next code example passes values to the method by reference. The original variables are changed
inside the Swap() method. Both the method definition and the method call must use the ref keyword.

using System;
public class PassingByReference
{
static int a = 4;
static int b = 7;

static void Swap(ref int a, ref int b)


{
int temp;
temp = a;
a = b;
b = temp;
Console.WriteLine("Inside Swap method");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}

static void Main()


{
Console.WriteLine("Before Swapping");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);

Swap(ref a, ref b);

Console.WriteLine("After Swapping");
Console.WriteLine("a is {0}", a);
Console.WriteLine("b is {0}", b);
}
}

Another example
using System;

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 26


DOT NET Technology

class PassByRef
{
static void Main(string[] args)
{
int x = 10;
Console.WriteLine("Variable Value Before Calling the Method: {0}", x);
Multiplication(ref x);
Console.WriteLine("Variable Value After Calling the Method: {0}", x);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}

public static void Multiplication(ref int a)


{
a *= a;
Console.WriteLine("Variable Value Inside the Method: {0}", a);
}
}

Out parameters

The out keyword is similar to the ref keyword. The difference is that when using the ref keyword, the
variable must be initialized before it is being passed. With the out keyword, it may not be initialized. Both
the method definition and the method call must use the out keyword.
using System;

public class OutKeyword


{
static void Main()
{
int val;
setValue(out val);
Console.WriteLine(val);
}

static void setValue(out int i)


{
i = 12;
}
}

Another example
using System;
class OutPara
{
static void Main(string[] args)
{
int x, y;
Multiplication(out x, out y);
Console.WriteLine("x Value: {0}", x);
Console.WriteLine("y Value: {0}", y);
Console.WriteLine("Press Enter Key to Exit..");
Console.ReadLine();
}

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 27


DOT NET Technology

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


{
a = 10;
b = 5;
a *= a;
b *= b;
}
}

Partial class

In C#, a partial class is useful to split the functionality of a particular class into multiple class files
and all these files will be combined into one single class file when the application is compiled. While
working on large scale projects, multiple developers want to work on the same class file at the same time.
To solve this problem, c# provides an ability to spread the functionality of a particular class into
multiple class files using partial keyword. In C#, we can use partial keyword to split the definition of a
particular class, structure, interface or a method over two or more source files.

There are several situations when splitting a class definition is desirable:


 When working on large projects, spreading a class over separate files enables multiple programmers
to work on it at the same time.
 When working with automatically generated source, code can be added to the class without having to
recreate the source file. Visual Studio uses this approach when it creates Windows Forms, Web
service wrapper code, and so on. You can create code that uses these classes without having to
modify the file created by Visual Studio.

The partial keyword indicates that other parts of the class, struct, or interface can be defined in the
namespace. All the parts must use the partial keyword. All the parts must be available at compile time to
form the final type. All the parts must have the same accessibility, such as public, private, and so on. If any
part is declared abstract, then the whole type is considered abstract. If any part is declared sealed, then the
whole type is considered sealed. If any part declares a base type, then the whole type inherits that class. All
the parts that specify a base class must agree, but parts that omit a base class still inherit the base type. Parts
can specify different base interfaces, and the final type implements all the interfaces listed by all the partial
declarations. Any class, struct, or interface members declared in a partial definition are available to all the
other parts. The final type is the combination of all the parts at compile time.

Following is the example of splitting the definition of User class into two class files, User1.cs and User2.cs.

//User1.cs
public partial class User
{
private string name;
private string location;
public User(string a, string b)
{
this.name = a;
this.location = b;
}
}

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 28


DOT NET Technology

If you observe above code, we created a partial class called User in User1.cs class file using
partial keyword with required variables and constructor.
//User2.cs
public partial class User
{
public void GetUserDetails()
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Location: " + location);
}
}

If you observe above code, we created a partial class called User in User2.cs class file using
partial keyword with GetUserDetails() method.
When you execute the above code, the compiler will combine these two partial classes into one User class
like as shown below.

//User.cs
public class User
{
private string name;
private string location;
public User(string a, string b)
{
this.name = a;
this.location = b;
}
public void GetUserDetails()
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Location: " + location);
}
}

This is how the compiler will combine all the partial classes into single class while executing the
application in c# programming language. In c#, we need to follow certain rules to implement a partial class
in our applications.
 To split the functionality of class, structure, interface or a method over multiple files we need to use
partial keyword and all files must be available at compile time to form the final type.
 The partial modifier can only appear immediately before the keywords class, struct or interface.
 All parts of partial type definitions must be in the same namespace or assembly.
 All parts of partial type definitions must have the same accessibility, such as public, private, etc.
 If any partial part is declared as abstract, sealed or base, then the whole type is considered as abstract
or sealed or base based on the defined type.
 In c#, different parts can have different base types but the final type will inherit all the base types.
 Nested partial types are allowed in partial type definitions.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 29


DOT NET Technology

Another example
using System;
public partial class User
{
private string name;
private string location;
public User(string a, string b)
{
this.name = a;
this.location = b;
}
}

public partial class User


{
public void GetUserDetails()
{
Console.WriteLine("Name: " + name);
Console.WriteLine("Location: " + location);
}
}

class PartialClass
{
static void Main(string[] args)
{
User u = new User("Mallikarjun Mathad", "Sangli");
u.GetUserDetails();
Console.WriteLine("\nPress Enter Key to Exit..");
Console.ReadLine();
}
}

Control Structures in C#

C# offers three types of control statements:


Selection Statements – This consists of if, else, Switch and case branching.
The if statement is used to check for a condition and based on it decide whether or not to execute a code
block. The if code block is executed only if the condition is true otherwise further instruction or else block
gets executed. You can write nested if blocks if required. Following diagram shows the basic flow of a
default if-else statement. It is not mandatory to have an else block after an if block. The else statement is
used to specify the code which has to be executed if the condition doesn't return true.

using System;
public class Program
{
public static void Main(string[] args)
{
int i = 100;
if(i > 0)
{Console.WriteLine("Given number is positive!");}
else
{Console.WriteLine("Given number is negative!");}
Console.ReadKey();

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 30


DOT NET Technology

}
}

If we have to specify two conditions which are related to each other, we can use the else if statement to
specify the second condition and its related code block. We can use multiple else if blocks to add multiple
conditions but it requires atleast one if block at the beginning, we can't directly write else and else if
statements without having any if block.

using System;
public class Program
{
public static void Main(string[] args)
{
int i = 0; // Zero is neutral in nature
if(i > 0)
{Console.WriteLine("Given number is positive!");}
else if(i < 0)
{Console.WriteLine("Given number is negative!");}
else
{Console.WriteLine("Given number is neither positive nor
negative!");}
Console.ReadKey();
}
}

The switch statement executes only one statement from multiple given statements associated with
conditions. If any condition returns true, then the code statements below it gets executed. Following diagram
shows the basic flow of a switch statement.

using System;
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine("1.Additon\n2.Subtraction\n3.Division\nEnter your
choice:");
int c = Convert.ToInt32(Console.ReadLine());
switch(c)
{
case 1: Console.WriteLine("\nAddition selected!"); break;
case 2: Console.WriteLine("\nSubtraction selected!"); break;
case 3: Console.WriteLine("\nDivision selected!"); break;
default: Console.WriteLine("\nYour choice not found!");break;
}
Console.ReadKey();
}
}

Iteration Statements – This consists of do, for, foreach, and while looping.
While Statement
It is a simple loop. It executes till the code block while the condition is true. If the condition is going to be
false, the program will exit from the loop.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 31


DOT NET Technology

using System;
class Program
{
public static void Main()
{
int num = 1;
while (num <= 10)
{
Console.WriteLine("The number is {0}", num);
num++;
}
Console.ReadLine();
}
}

Do-While Statement
The do while loop is same as while loop except that it will be running at least one time if condition is
matched or not. It is because it does not check the condition first time. So, it is guaranteed to execute the
code of program at least one iteration.

using System;
class Program
{
public static void Main()
{
int num = 1;
do {
Console.WriteLine("The number is {0}", num);
num++;
} while (num <= 10);
Console.ReadLine();
}
}

For Statement
The For loop is used if you know the start point and end point. You can run a statement or a block of
statements repeatedly until a specified expression evaluates to false. It is useful where you know in advance
how many times program should iterate.

using System;
class Program
{
public static void Main()
{
for (int i = 1; i <= 5; i++)
{
Console.WriteLine("The iteration number is " + i);
}
Console.ReadLine();
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 32
DOT NET Technology

}
}

Jump Statements – This consists of break, continue, return, and goto statements.

The following statements are used to pass control:

Statement Description
It stops the nearest control statement to its location, and passes control to the next statement,
break;
if it exists.
continue; It passes control to the next iteration of the control statement where it is located.
return; It stops execution of the method, and returns a value(optional).
goto It transfers control to a specified statement.

The goto statement is used to transfer the control from a loop or switch case to a specified label. It is also
known as a jump statement. It is generally recommended to avoid using it as it makes the program more
complex. In the following example, if the user is logged in then we have directly jumped our code to success
label.
using System;
public class Program
{
public static void Main(string[] args)
{
string user = "login";
if(user=="login")
{
goto success;
}
success:
Console.WriteLine("Welcome to CIMDR, Sangli!");
Console.ReadKey();
}
}

DLL – (Dynamic Link Library)

Dynamic Link Library (DLL) is Microsoft's implementation of the shared library concept. A DLL
file contains code and data that can be used by multiple programs at the same time; hence it promotes code
reuse and modularization. DLL provides one or more particular functions and a program accesses the
functions by creating either a static or dynamic link to the DLL. A static link remains constant during
program execution while a dynamic link is created by the program as needed. DLLs can also contain just
data. DLL files usually end with the extension .dll, .exe, .drv, or .fon. A DLL can be used by several
applications at the same time. Some DLLs are provided with the Windows operating system and available
for any Windows application. Other DLLs are written for a particular application and are loaded with the
application. A dynamic link library (DLL) is a collection of small programs, any of which can be called
when needed by a larger program that is running in the computer. The small program that lets the larger
program communicate with a specific device such as a printer or scanner is often packaged as a DLL
program (usually referred to as a DLL file). DLL files that support specific device operation are known
as device drivers.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 33


DOT NET Technology

Difference between DLL and EXE

EXE DLL
EXE is an extension used for executable files DLL is the extension for a dynamic link library.
EXE file can be run independently DLL is used by other applications.
EXE file defines an entry point DLL does not defines an entry point.
EXE cannot be reused by other applications DLL file can be reused by other applications
EXE creates its separate process and memory space. DLL would share the same process and memory
space of the calling application
EXE is an Out-Process Component. DLL is an In-Process Component
You cannot create an object of EXE. You can create an object of DLL.
It identifies the file as a program It commonly contains functions and procedures that
can be used by other programs.
EXE would mean creating a process for it to run on DLL might have limited access to resources as it
and a memory space. This is necessary in order for might be taken up by the application itself or by
the program to run properly. other DLLs
The DLL would facilitate the communication
between the hardware and the application that wishes
to use it. DLL files are ideal for distributing device
drivers.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 34


DOT NET Technology

CHAPTER 3

WEB server and WEB browser

A web server is a computer system that processes requests via HTTP, the basic network
protocol used to distribute information on the World Wide Web. The term can refer to the entire system, or
specifically to the software that accepts and supervises the HTTP requests. A Web server is a system that
delivers contents or services to end users over the Internet. A Web server consists of a physical server,
server operating system (OS) and software used to facilitate HTTP communication. A Web server is also
known as an Internet server.
Web servers are computers that deliver (serves up) Web pages. Every Web server has an IP
address and possibly a domain name. For example, if you enter the in your browser, this sends a request to
the Web server whose domain name is www.cimdr.ac.in. The server then fetches the page named
www.cimdr.ac.in/home.html and sends it to your browser. Any computer can be turned into a Web server by
installing server software and connecting the machine to the Internet. There are many Web server software
applications, including public domain software and commercial packages.

Web browser, a browser is a software application used to locate, retrieve and display content on
the World Wide Web, including Web pages, images, video and other files. As client, the browser is
the client run on a computer that contacts the Web server and requests information. The Web server sends
the information back to the Web browser which displays the results on the computer or other Internet-
enabled device that supports a browser.
A web browser is a software application that people use in order to view web pages on the internet. It
can be used to upload or download files on FTP servers. It uses security methods such as SSL and TLS to
secure internet traffic. It also uses cookies to store information and it caches web pages to make internet
surfing more efficiently.

HTTP request and response structure

HTTP - Hypertext Transfer Protocol


It's a stateless request-response based communication protocol, used to send and receive data on the
Web i.e., over the Internet. This protocol uses reliable TCP connections either for the transfer of data to and
from clients which are Web Browsers in this case. HTTP is a stateless protocol means the HTTP Server
doesn't maintain the contextual information about the clients communicating with it and hence we need to
maintain sessions in case we need that feature for our Web-applications.
HTTP is a request-response based protocol, it means the client will initiate the communication by
sending a request (i.e. HTTP Request) and the HTTP Server (or Web Server) will respond back by sending a
response (i.e. HTTP Response). Every time a client needs to send the request, it first establishes a TCP
reliable connection with the Web Server and then transfer the request via this connection. The same happens
in case a Web Server needs to send back an HTTP Response to a client. Any of the two parties - the client or
the server can prematurely stop the transfer by terminating the TCP connection. To terminate the
connection, client can simply click the 'Stop' button of the browser window (or by closing the browser
window itself). Both the Request and the Response have a pre-defined format and both the client (the Web
Browser) and the server (HTTP/Web Server) can understand and communicate properly with each other.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 35


DOT NET Technology

Format of an HTTP Request

It has three main components, which are:-


HTTP Request Method, URI, and Protocol Version - this should always be the first line of an HTTP
Request. It contains the HTTP Request method being used for that particular request, the URI, and the
HTTP protocol name with the version being used. It may look like 'GET /servlet/jspName.jsp HTTP/1.1'
where the request method being used is 'GET', the URI is '/servlet/jspName.jsp', and the protocol (with
version) is 'HTTP/1.1'.

HTTP Request Headers - This section of an HTTP Request contains the request headers, which are used to
communicate information about the client environment. Few of these headers are: Content-Type, User-
Agent, Accept-Encoding, Content-Length, Accept-Language, Host, etc. The names are quite self-
explanatory.

HTTP Request Body - this part contains the actual request being sent to the HTTP Server. The HTTP
Request Header and Body are separated by a blank line (CRLF sequence, where CR means Carriage Return
and LF means Line Feed). This blank line is a mandatory part of a valid HTTP Request.

Format of an HTTP Response


Similar to an HTTP Request, an HTTP Response also has three main components, which are:-

Protocol/Version, Status Code, and its Description - The very first line of a valid HTTP Response is
consists of the protocol name, its version, status code of the request, and a short description of the status
code. A status code of 200 means the processing of request was successful and the description in this case
will be 'OK'. Similarly, a status code of '404' means the file requested was not found at the HTTP Server at
the expected location and the description in this case is 'File Not Found'.

HTTP Response Headers - similar to HTTP Request Headers, HTTP Response Headers also contain useful
information. The only difference is that HTTP Request Headers contain information about the environment
of the client machine whereas HTTP Response Headers contain information about the environment of the
server machine. This is easy to understand as HTTP Requests are formed at the client machine whereas
HTTP Responses are formed at the server machine. Few of these HTTP Response headers
are: Server, Content-Type, Last-Modified, Content-Length, etc.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 36


DOT NET Technology

HTTP Response Body - This actual response which is rendered in the client window (the browser window).
The content of the body will be HTML code. Similar to HTTP Request, in this case also the Body and the
Headers components are separated by a mandatory blank line (CRLF sequence).

Introduction to ASP

ASP stands for Active Server Pages. Microsoft introduced Active Server Pages in December 1996,
beginning with Version 3.0. Microsoft officially defines ASP as: “Active Server Pages is an open, compile-
free application environment in which you can combine HTML, scripts, and reusable ActiveX server
components to create dynamic and powerful Web-based business solutions. Active Server pages enable
server side scripting for IIS (Internet Information Server) with native support for both VBScript and Jscript.”
In other words, ASP is a Microsoft technology that enables you to create dynamic web sites with the help of
server side script, such as VBScript and Jscript. ASP technology is supported on all Microsoft Web servers
that are freely available. If you have Window NT 4.0 Server installed, you can download IIS 3.0 or 4.0. If
you are using Window 2000, IIS 5.0 comes with it as a free component. If you have Window 95/98, you can
download Personal Web Server (PWS), which is a smaller version of IIS, from Window 95/98 CD.
An ASP file is quite like an HTML file. It contains text, HTML tags and scripts, which are executed
on the server. The two widely used scripting languages for an ASP page are VBScript and JScript. VBScript
is pretty much like Visual Basic, whereas Jscript is the Microsoft’s version of JavaScript. However,
VBScript is the default scripting language for ASP. Besides these two scripting languages, you can use other
scripting language with ASP as long as you have an ActiveX scripting engine for the language installed,
such as PerlScript. The difference between HTML file and an ASP file is that an ASP file has the “.asp”
extension. Furthermore, script delimiters for HTML tags and ASP code are also different. A script delimiter
is a character that marks the starting and ending of a unit. HTML tags begins with lesser than < > brackets,
whereas ASP script typically starts with . In between the delimiters are the server-side scripts. To write an
ASP script, you don’t need any additional software because it can be written with any HTML editor, such as
Notepad., if you feel bored with the plain text and would like to use some special software, you can use
Microsoft visual InterDev, which helps you to easily create an ASP page by giving you nice highlights and
debugging dialogue boxes.

Types of Path

A path is a string that provides the location of a file or directory. A path does not necessarily point to
a location on disk; for example, a path might map to a location in memory or on a device. The exact format
of a path is determined by the current platform. For example, on some systems, a path can start with a drive
or volume letter, while this element is not present in other systems. On some systems, file paths can contain
extensions, which indicate the type of information stored in the file. The format of a file name extension is
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 37
DOT NET Technology

platform-dependent; for example, some systems limit extensions to three characters, and others do not. The
current platform also determines the set of characters used to separate the elements of a path, and the set of
characters that cannot be used when specifying paths. Because of these differences, the fields of the Path
class as well as the exact behavior of some members of the Path class are platform-dependent.
A path can contain absolute or relative location information. Absolute paths fully specify a location:
the file or directory can be uniquely identified regardless of the current location. Relative paths specify a
partial location: the current location is used as the starting point when locating a file specified with a relative
path. To determine the current directory, call Directory.GetCurrentDirectory.
Most members of the Path class do not interact with the file system and do not verify the existence of
the file specified by a path string. Path class members that modify a path string, such as ChangeExtension,
have no effect on names of files in the file system. Path members do, however, validate the contents of a
specified path string, and throw an ArgumentException exception if the string contains characters that are
not valid in path strings, as defined in the characters returned from the GetInvalidPathChars method.
For example, on Windows-based desktop platforms, invalid path characters might include quote ("),
less than (<), greater than (>), pipe (|), backspace (\b), null (\0), and Unicode characters 16 through 18 and
20 through 25.
The members of the Path class enable you to quickly and easily perform common operations such as
determining whether a file name extension is part of a path, and combining two strings into one path name.
All members of the Path class are static and can therefore be called without having an instance of a path.
In HTTP, user enters a URL in the browser and an HTTP request is sent over the link to the specified
web server. The server in turn generates some response (Mostly in the form of HTML markups) that the
browser receives and interprets it into the user interface in terms of some understandable output. Once
the HTML markups are generated from the server for a page, browser loads the HTML first and once it is
done loading, it starts loading the elements in the HTML markup that have “path” attributes. For each of
those elements, browser sends an asynchronous request again to the server with the URL that is provided in
their “path” attributes (src or href). Asynchronous request means, browser sends the requests “behind the
scene”, and, doesn’t wait for the response from server while doing other activity. So, the UI remains
responsive to the user, and, when the response is received from the server, the UI is updated with the
response data.
ASP.NET is primarily concerned with "virtual paths", the portion of the path following the hostname or
port number. When working with ASP.NET, you must understand the following types of URL’s thoroughly,
and know how they are handled by ASP.NET and the browser.

Virtual Path
To create a web app in IIS we can place our folder containing application in particular root or we can
point to a location where the application is stored physically (e.g.- D:\MyApp). When we point an app to
another location, then we specify this path. So the app in IIS is pointing to this virtual path. ASP.NET leaves
these alone.

Absolute Path
When we refer to a location from root like C:\Documents\MyFolder, it is absolute path. Browsers
understand absolute paths very well. Only use these for referencing external websites. They're expensive to
maintain.

Relative path
When we refer to a relative location where we currently are, it is called relative path. For example, say
currently you are at Documents folder in C:\Documents, to refer to MyFolder you have two choices:
Absolute (C:\Documents\MyFolder) or relative (\MyFolder). Browsers resolve the path client-side by

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 38


DOT NET Technology

combining it with the domain of the parent document. Use application-relative paths or relative paths
instead. These are also called "absolute virtual paths" and "domain-relative paths". Browsers don't have a
clue what the tilde(~) means, so server-side path resolution is required. Server-side, the tilde is shorthand for
HttpRuntime.AppDomainAppVirtualPath. ASP.NET rebases these as client-side relative paths on some
control attributes, but you must remember to use runat="server". This is the type of path you should use if a
relative path doesn't make sense.

Physical Path
In ASP.NET physical path refers to the absolute path in terms of windows. In web applications we refer to
the web path, which for a web application starts from "/" (root) which is the folder that contains the
application. But that root folder must be in IIS, so the path like K:\Online Lectures Data\Notes\BCA III is
the physical path.

Fragment and Javascript paths.


ASP.NET leaves these alone. The browser is not supposed to create a new request when one of these is
clicked, but to simply perform the action or navigation within the current document. Fragments never appear
in a HTTP request. They are only for the browser's benefit, and are stripped off before the path is sent to
ASP.NET.
Ex. #section2 or javascript:OpenPopup();

FORM tag

All server controls must appear within a <form> tag, and the <form> tag must contain the
runat="server" attribute. The runat="server" attribute indicates that the form should be processed on the
server. It also indicates that the enclosed controls can be accessed by server scripts. An .aspx page can only
contain ONE <form runat="server"> control. A form is most often submitted by clicking on a button. The
Button server control in ASP.NET has the following format:
<asp:Button id="id" text="label" OnClick="sub" runat="server" />
The id attribute defines a unique name for the button and the text attribute assigns a label to the
button. The onClick event handler specifies a named subroutine to execute.
In the following example we declare a Button control in an .aspx file. A button click runs a subroutine which
changes the text on the button. The form tag is not a 'requirement' for asp.net. It is used to 'submit' all input
to the server; you can put 'things' outside the form tag but you would need to keep all the user-entered value
supplying controls on your page within a form tag for sure.
The basic thing about being able to have multiple forms on the same page is that you don’t have to use
JavaScript to fix the default button problem, or use unnecessary ASP.NET web controls or logic on the
server (like the Response.Redirect method). The drawback, for some, is that you cannot have the forms
inside the form (web form) with the runat=”server” attributes, which means that you cannot use all of the
ASP.NET web controls.
ASP.NET is the next generation technology for Web application development. It takes the best from
Active Server Pages (ASP) as well as the rich services and features provided by the Common Language
Runtime (CLR) and add many new features. The result is a robust, scalable, and fast Web development
experience that will give you great flexibility with little coding. Web Forms are the heart and soul of
ASP.NET. Web Forms are the User Interface (UI) elements that give your Web applications their look and
feel. Web Forms are similar to Windows Forms in that they provide properties, methods, and events for the
controls that are placed onto them. However, these UI elements render themselves in the appropriate markup
language required by the request, e.g. HTML. If you use Microsoft Visual Studio® .NET, you will also get
the familiar drag-and-drop interface used to create your UI for your Web application. Web Forms are made

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 39


DOT NET Technology

up of two components: the visual portion (the ASPX file), and the code behind the form, which resides in a
separate class file. Web Forms and ASP.NET were created to overcome some of the limitations of ASP.
These new strengths include:

 Separation of HTML interface from application logic


 A rich set of server-side controls that can detect the browser and send out appropriate markup language
such as HTML
 Less code to write due to the data binding capabilities of the new server-side .NET controls
 Event-based programming model that is familiar to Microsoft Visual Basic programmers
 Compiled code and support for multiple languages, as opposed to ASP which was interpreted as Microsoft
Visual Basic Scripting (VBScript) or Microsoft Jscript
 Allows third parties to create controls that provide additional functionality

On the surface, Web Forms seem just like a workspace where you draw controls. In reality, they can do a
whole lot more. But normally you will just place any of the various controls onto the Web Form to create
your UI. The controls you use determine which properties, events, and methods you will get for each
control. There are two types of controls that you can use to create your user interface: HTML controls and
Web Form controls.

Types of Server Controls

An ASP.NET server control is a tag written in a Web page to represent a programmable server-side
object used for displaying a user interface element in a Web page. ASP.NET server controls are tags that can
be understood by the server. They are coded in a .aspx file and expose properties, methods and events of the
control that can be accessed from server-side code.
ASP.NET is a Web application framework used to develop dynamic websites and Web applications.
An ASP.NET server control is a specific control class of the .NET framework, which is embedded in
ASP.NET pages. It represents a user interface (UI) element on a page, such as a text box or command
button.
Server controls in the ASP.NET page framework are designed to provide a structured programming
model for Web-based applications. Unlike the code in ASP (an earlier version of ASP.NET), these controls
allow for the separation of execution code from the HTML. This helps to separate the presentation from the
content by making use of reusable UI controls, which contain common functionality and are better able to
maintain the code.
The key features of the built-in server controls are:
 Automatic state management, where values are retained across round trips to the server
 Access to object values without using request objects
 Handling events for specific actions in server-side code
 A simple approach for producing a dynamic Web page with complex rendering and behaviour
 Using adaptive rendering to implement "write once render anywhere." Different mark-up and layout
are created to render anywhere for any type of device or browser.

With Classic ASP it is impossible to separate executable code from the HTML itself. This makes the
page difficult to read, and difficult to maintain. ASP.NET has solved this problem with server controls.
Server controls are tags that are understood by the server. There are three kinds of server controls:
 HTML Server Controls - Traditional HTML tags
 Web Server Controls - New ASP.NET tags
 Validation Server Controls - For input validation

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 40


DOT NET Technology

HTML controls
HTML controls are the native browser elements and they are part of HTML language. These are client-side
controls which is accessible only in the HTML page, so it will improve the performance of the web page.
HTML controls on an ASP.NET Web page are not available to the web server.

HTML Server controls


You can add the attribute runat="server" to any HTML control, such cases it will be an HTML server
control. These controls map directly to html tags and without runat="server" it cannot access the control in
code behind.
HTML server controls are HTML tags understood by the server. HTML elements in ASP.NET files
are, by default, treated as text. To make these elements programmable, add a runat="server" attribute to the
HTML element. This attribute indicates that the element should be treated as a server control. The id
attribute is added to identify the server control. The id reference can be used to manipulate the server control
at run time. It also indicates that the enclosed controls can be accessed by server scripts.
ASP.NET provides a way to work with HTML Server controls on the server side; programming with
a set of controls collectively is called HTML Controls.
 These controls are grouped together in the Visual Studio Toolbox in the the HTML Control tab. The
markup of the controls is similar to the HTML control.
 These controls are basically the original HTML controls but enhanced to enable server side processing.
 HTML elements in ASP. NET files are, by default, treated as text. To make these elements programmable,
add a runat="server" attribute to the HTML element. This attribute indicates that the element should be
treated as a server control.

The System.Web.UI.HtmlControls.HtmlControl base class contains all of the common properties. HTML
server controls derive from this class.

Web Server Controls


Web server controls are special ASP.NET tags understood by the server. Like HTML server
controls, Web server controls are also created on the server, and they require a runat="server" attribute to
work. However, Web server controls do not necessarily map to any existing HTML elements and they may
represent more complex elements.
Web Server Controls are group of controls derived directly from the System.Web.UI.WebControls
base class. They are executed on the server side and output HTML sent back to the client browser. These
controls are programmable and reusable that can perform function as the ordinary HTML controls. Web
Server Controls can detect the target browser's capabilities and render themselves accordingly.

The syntax for creating a Web server control is:


<asp:control_name id="some_id" runat="server" />

Web Server Control Advantages


Server controls are easy to use and manage but HTML controls are not. Server control events are handled in
the server side whereas HTML control events are handled in the client-side browser only. It can maintain
data across each requests using view state whereas HTML controls have no such mechanism to store data
between user requests.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 41


DOT NET Technology

Validation controls

Validation is the method of scrutinizing (observing) that the user has entered the correct values in
input fields. A Validation server control is used to validate the data of an input control. If the data does not
pass validation, it will display an error message to the user. Each validation control performs a specific type
of validation (like validating against a specific value or a range of values). By default, page validation is
performed when a Button, ImageButton, or LinkButton control is clicked. You can prevent validation when
a button control is clicked by setting the CausesValidation property to false.
After you create a web form, you should make sure that mandatory fields of the form elements such
as login name and password are not left blank; data inserted is correct and is within the specified range. In
ASP.NET, you can use Validation Controls while creating the form and specify which Validation Controls
you want to use and to which server control you want bind this. Validation Controls are derived from a
common base class and share a common set of properties and methods. You just have to drag and drop the
ASP. NET Validation Control in the web form and write one line of code to describe its functionality. This
reduces the developer time from writing JavaScript for each type of validation. Moreover, through ASP.
NET Validation Controls if any invalid data is entered the browser itself detects the error on the client side
and displays the error without requesting the server. This is another advantage because it reduces the server
load. Following are the types of validation controls supported by ASP.Net: ----

RequiredFieldValidator: The RequiredFieldValidator control ensures that the user does not skip a required
entry field. A RequiredFieldValidator works in conjunction with another control, for example a TextBox
control. Add the control you want to validate to your page before you add the RequiredFieldValidator, so
that you can easily associate the RequiredFieldValidator with it.
To add a RequiredFieldValidator control to a page
 Drag the RequiredFieldValidator control from the Toolbox to your page.
 In the Tag Properties , select the control you want to validate with the RequiredFieldValidator in
the ControlToValidate property dropdown.
 Set the ErrorMessage property to the text you want to be displayed when a user leaves the control
blank.

RangeValidator: The RangeValidator control checks that a user's entry is between specified lower and
upper boundaries. You can check ranges within pairs of numbers, alphabetic characters, and dates.
A RangeValidator works in conjunction with another control, for example a TextBox control. Add the
control you want to validate to your page before you add the RangeValidator so that you can easily associate
the RangeValidator with it.
To add a RangeValidator control to a page
 Drag the RangeValidator control from the Toolbox to your page.
 In the Tag Properties task pane, select the control you want to validate with the RangeValidator in
the ControlToValidate property dropdown.
 Set the MaximumValue and MinimumValue properties to the highest and lowest values,
respectively, that you want to allow a user to enter into the control you are validating.

CompareValidator: The CompareValidator control compares a user's entry against a constant value or
against the value of another control (using a comparison operator such as less than, equal, or greater than),
or for a specific data type. A CompareValidator works in conjunction with another control, for example
a TextBox control. Add the control you want to validate to your page before you add
the CompareValidator so that you can easily associate the CompareValidator with it.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 42


DOT NET Technology

To add a CompareValidator control to a page


 Drag the CompareValidator control from the Toolbox task pane to your page.
 In the Tag Properties task pane, select the control you want to validate with the CompareValidator in
the ControlToValidate property dropdown.
 Set the ControlToCompare or ValueToCompare property to the control or value that you want to
compare.
 Set the Operator property to the comparison you want to
use: Equal, NotEqual, GreaterThan, GeaterThanEqual, LessThan, LessThanEqual,

RegularExpressionValidator: The RegularExpressionValidator control checks that the entry matches a


pattern defined by a regular expression. This type of validation enables you to check for predictable
sequences of characters, such as those in e-mail addresses, telephone numbers, postal codes, and so on.
A RegularExpressionValidator works in conjunction with another control (i.e. TextBox control). Add the
control you want to validate to your page before you add the RegularExpressionValidator so that you can
easily associate the RegularExpressionValidator with it.
To add a RegularExpressionValidator control to a page
 Drag the RegularExpressionValidator control from the Toolbox task pane to your page.
 In the Tag Properties task pane, select the control you want to validate with
the RegularExpressionValidator in the ControlToValidate property dropdown.
 Set the ValidationExpression property to the regular expression that the text in the control must
match to be valid.

CustomValidator: The CustomValidator control checks the user's entry using validation logic that you
write yourself. This type of validation enables you to check for values derived at run time.
A CustomValidator works in conjunction with another control, for example a TextBox control. Add the
control you want to validate to your page before you add the CustomValidator so that you can easily
associate the CustomValidator with it.
To add a CustomValidator control to a page
 Drag the CustomValidator control from the Toolbox task pane to your page.
 In the Tag Properties task pane, select the control you want to validate with the CustomValidator in
the ControlToValidate property dropdown.
 To validate the control in the client browser, set the ClientValidationFunction to the name of the
JavaScript function to use in validation.

ValidationSummary: The ValidationSummary class is used to summarize the error messages from all
validators on a web page in a single location. To add a ValidationSummary control to a page
 Drag the ValidationSummary control from the Toolbox task pane to your page.
 Select the ValidationSummary in Design view, right-click it, and click Properties on the shortcut
menu.
 Set the ValidationGroup property to the name of the group of validation controls. This can be any
string, as long as all the controls in the group have the same value.
 The summary can be displayed as a list, as a bulleted list, or as a single paragraph, based on
the DisplayMode property. The summary can be displayed on the web page and in a message box by
setting the ShowSummary and ShowMessageBox properties, respectively.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 43


DOT NET Technology

Web forms life cycle

ASP.NET is a powerful platform for building Web applications. With any platform, it is important to
understand what is going on behind the scenes to build robust applications. The ASP.NET page life cycle is
a good example to know how and when page elements are loaded and corresponding events are fired.
Every request for a page made from a web server causes a chain of events at the server. These events,
from beginning to end, constitute the life cycle of the page and all its components. The life cycle begins with
a request for the page, which causes the server to load it. When the request is complete, the page is
unloaded. From one end of the life cycle to the other, the goal is to render appropriate HTML output back to
the requesting browser. The life cycle of a page is marked by the following events, each of which you can
handle yourself or leave to default handling by the ASP.NET server:
The requesting of an ASP.NET page triggers a sequence of events that encompass the page life cycle.
The Web browser sends a post request to the Web server. The Web server recognizes the ASP.NET file
extension for the requested page and sends the request to the HTTP Page Handler class. The following list is
a sampling of these events, numbered in the order in which they are triggered.

1. PreInt: This is the entry point of the ASP.NET page life cycle - it is the pre-initialization, so you have
access to the page before it is initialized. Controls can be created within this event. Also, master pages
and themes can be accessed. You can check the IsPostBack property here to determine if it is the first
time a page has been loaded.
2. Init: This event fires when all controls on the page have been initialized and skin settings have been
applied. You can use this event to work with control properties. The Init event of the page is not fired
until all control Init events have triggered - this occurs from the bottom up.
3. InitComplete: This event fires once all page and control initializations complete. This is the last event
fired where ViewState is not set, so ViewState can be manipulated in this event.
4. PreLoad: This event is triggered when all ViewState and Postback data have been loaded for the page
and all of its controls - ViewState loads first, followed by Postback data.
5. Load: This is the first event in the page life cycle where everything is loaded and has been set to its
previous state (in the case of a postback). The page Load event occurs first followed by the Load event
for all controls (recursively). This is where most coding is done, so you want to check the IsPostBack
property to avoid unnecessary work.
6. LoadComplete: This event is fired when the page is completely loaded. Place code here that requires
everything on the page to be loaded.
7. PreRender: This is the final stop in the page load cycle where you can make changes to page contents
or controls. It is fired after all PostBack events and before ViewState has been saved. Also, this is where
control databinding occurs.
8. PreRenderComplete: This event is fired when PreRender is complete. Each control raises this event
after databinding (when a control has its DataSourceID set).
9. SaveStateComplete: This is triggered when view and control state have been saved for the page and all
controls within it. At this point, you can make changes in the rendering of the page, but those changes
will not be reflected on the next page postback since view state is already saved.
10. Load ViewState: The ViewState property of the control is populated. The ViewState information comes
from a hidden variable on the control, used to persist the state across round trips to the server. The input
string from this hidden variable is parsed by the page framework, and the ViewState property is set. This
can be modified via the LoadViewState( ) method: This allows ASP.NET to manage the state of your
control across page loads so that each control is not reset to its default state each time the page is posted.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 44


DOT NET Technology

11. Unload: This event fires for each control and then the page itself. It is fired when the HTML for the
page is fully rendered. This is where you can take care of cleanup tasks, such as properly closing and
disposing database connections.

An interesting fact of the events fired with the loading of a page is the controls within the page and their
events; that is, each control has its own event life cycle. The ASP.NET source is listed first and followed by
the code behind source. The code does not include all events, but it does provide a subset to give you a feel
for how they appear. The events specified in the individual controls that ties them to code blocks.

Event handling in WEB forms

An event is a mechanism via which a class can notify its clients when something happens. For
example, when you click a button, a button-click-event notification is sent to the window hosting the button.
Events are declared using delegates. An event is an action or occurrence such as a mouse click, a key press,
mouse movements, or any system-generated notification. A process communicates through events. When
events occur, the application should be able to respond to it and manage it.
Events in ASP.NET raised at the client machine and handled at the server machine. For example, a
user clicks a button displayed in the browser. A Click event is raised. The browser handles this client-side
event by posting it to the server. The server has a subroutine describing what to do when the event is raised;
it is called the event-handler. Therefore, when the event message is transmitted to the server, it checks
whether the Click event has an associated event handler. If it has, the event handler is executed.
ASP.NET event handlers generally take two parameters and return void. The first parameter
represents the object raising the event and the second parameter is event argument.

The general syntax of an event is:


private void EventName (object sender, EventArgs e);
Application Events:
 Application_Start - It is raised when the application/website is started.
 Application_End - It is raised when the application/website is stopped.

Session events:
 Session_Start - It is raised when a user first requests a page from the application.
 Session_End - It is raised when the session ends.

Page and Control Events: Common page and control events are:
 DataBinding - It is raised when a control binds to a data source.
 Disposed - It is raised when the page or the control is released.
 Error - It is a page event, occurs when an unhandled exception is thrown.
 Init - It is raised when the page or the control is initialized.
 Load - It is raised when the page or a control is loaded.
 PreRender - It is raised when the page or the control is to be rendered.
 Unload - It is raised when the page or control is unloaded from memory.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 45


DOT NET Technology

Event Attribute Controls


Click OnClick Button, image button, link
button, image map
Command OnCommand Button, image button, link
button
TextChanged OnTextChanged Text box
SelectedIndexChanged OnSelectedIndexChanged Drop-down list, list box,
radio button list, check
box list.
CheckedChanged OnCheckedChanged Check box, radio button

Response.Redirect & Server.Transfer

ASP.Net Technology both "Server" and "Response" are objects of ASP.Net. These both methods
(Server.Transfer and Response.Redirect) are used to transfer a user from one page to another. Both methods
are used for the same purpose, but still there are some differences as follows.

Response.Redirect Server.Transfer
1. Response. Redirect() will send you to a new page, Server.Transfer() does not change the address bar;
update the address bar and add it to the Browser we cannot hit back. One should use
History. On your browser you can click back. Server.Transfer() when he/she doesn’t want the user
to see where he is going. Sometime on a "loading"
type page.
2. It redirects the request to some plain HTML pages It transfers current page request to another .aspx
on our server or to some other web server. page on the same server.
It doesn’t preserve Query String and Form Variables1. It preserves Query String and Form Variables
from the original request. Hence, it causes additional (optionally) i.e., preserves server resources and
roundtrips to the server on each request avoids the unnecessary roundtrips to the server.
3. It enables to see the new redirected URL where it is It doesn’t show the real URL where it redirects the
redirected in the browser (and be able to bookmark request in the users Web Browser.
it if it’s necessary).
Response. Redirect simply sends a message down to Server.Transfer executes without the browser
the (HTTP 302) browser knowing anything, the browser request a page, but
the server returns the content of another.
The Response.Redirect method redirects a request to The Server.Transfer method for the current request,
a new URL and specifies the new URL terminates execution of the current page and starts
execution of a new page using the specified URL
path of the page.

The Response.Redirect method first sends a request Server.Transfer sends a request directly to the web
to the web browser so it is the "HTTP 302 Found" server and the web server delivers the response to the
status, then the browser sends a request to the server browser.
and the server delivers a response.
Response.Redirect can be used for both .aspx and Server.Transfer can be used only for .aspx pages and
HTML pages is specific to ASP and ASP.NET.
Response.Redirect can be used to redirect a user to Server.Transfer can be used only on sites running on
an external website the same server.
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 46
DOT NET Technology

The Response.Redirect method, the previous page is You cannot use Server.Transfer to redirect the user
removed from server memory and loads a new page to a page running on a different server.
in memory. Server.Transfer, then the previous page also exists in
server memory

Cross Page Post Back property of Control

Postback is sending all the information from client to web server, then web server process all those
contents and returns back to the client. Most of the time ASP control will cause a post back (e. g.
buttonclick) but some don't unless you tell them to do In certain events ( Listbox Index
Changed,RadioButton Checked etc..) in an ASP.NET page upon which a PostBack might be needed.

IsPostBack is a property of the Asp.Net page that tells whether or not the page is on its initial load or
if a user has perform a button on your web page that has caused the page to post back to itself. The value of
the Page.IsPostBack property will be set to true when the page is executing after a postback, and false
otherwise. We can check the value of this property based on the value and we can populate the controls on
the page. Is Postback is normally used on page _load event to detect if the web page is getting generated due
to postback requested by a control on the page or if the page is getting loaded for the first time.

Postback and IsCrossPagePostBack


A postback of a page means posting back to the same page. We can differentiate between the page’s first
request and any postback by using the Page.IsPostback property.

if (Page.IsPostBack == true)
{
//Do some processing.
}
Instead of checking against a true or false value
if (!Page.IsPostBack)
{
//Do some processing.
}

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 47


DOT NET Technology

Cross page posting means you are posting form data to another page. This is useful when you want
to post data to another page and do not want incur the overhead of reloading the current page. Cross-page
post back is similar to Server.Transfer method, but there are some important differences. Server.Transfer
conserves the post data between pages and also it keeps the URL. And also it has a documented bug with
getting URL parameters from the source page. The Server.Transfer method is a server-based operation
whereas cross-page postback is a client-based transfer. The main aim of the Server.Transfer method is to
reduce client request to the server which makes it faster than Response.Redirect ().Anyway the cross-page
postback can throw the user on another page but with possibility to get the post data.
The AutoPostBack property is used to set or return whether or not an automatic post back occurs
when the user selects an item in a list control. If this property is set to TRUE the automatic post back is
enabled, otherwise FALSE. Default is FALSE. It is the mechanism by which the page will be posted back to
the server automatically based on some events in the web controls. In some of the web controls, the property
called auto post back, if set to true, will send the request to the server when an event happens in the control.
AutoPostBack property allows controls which cannot submit the Form (PostBack) on their own and hence
ASP.Net has provided a feature using which controls like DropDownList, CheckBoxList, RadioButtonList,
etc. can perform PostBack.

ASP.NET state management

Definition “State Management can be defined as the technique or the way by which we can maintain /
store the state of the page or application until the User's Session ends.”

State management is the process by which ASP.Net manages state and page information over multiple pages
for single or multiple web pages. If your application needs to scale to thousands of users then you must
consider the various state management techniques made available by ASP.Net. This reduces load on your
servers thereby enabling it to process more user requests. ASP.Net provides two types of state management
techniques.

Client-Based State Management Options Server-Based State Management Options


View state Application state
Control state Session state
Hidden fields Profile Properties
Cookies
Query strings

Each option has distinct advantages and disadvantages, depending on the scenario.

Client-Based State Management Options


The following options used for state management that involve storing information either in the page or on
the client computer. For these options, no information is maintained on the server between round trips.

View State: View state is a mechanism by which ASP.Net stores user-specific request and response data
between requests. View state is not stored on the server but is stored in the page itself. When the page is
submitted to the server the view state is also submitted to the server. The web server pulls the view state
from the page to reset the property values and controls when the page is being processed. This allows
ASP.Net to have all the object data available to the web server without having to store it on the server. This
results in a scalable web server which can handle more user requests.
Unless disabled, view state is a part of every ASP.Net page. The view state values are hashed,
compressed and encoded for Unicode implementations which provide better optimization and security than
simple hidden fields.
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 48
DOT NET Technology

Control State: Control state (ControlState property) is used to save state information for custom controls
that require view state. It helps to persist state information for custom control but cannot be turned off like
ViewState property.

Hidden Fields: ASP.Net provides a HiddenField control to store data on a page. It can be added on to a
page like any other .Net control but is not visible on the page unless someone views the page’s source. It
stores the data in its Value property. Like view state it can be used to store information on a single page, and
it cannot transfer data between pages. But the data stored in the HiddenField is not hashed or encrypted. So
it cannot be used to store sensitive information.
For hidden-field values to be available during page processing, you must submit the page using an
HTTP POST command. If you use hidden fields and a page is processed in response to a link or an HTTP
GET command, the hidden fields will not be available.

Cookies: A cookie is a small amount of data that is stored either in a text file on the client file system or in-
memory in the client browser session. It contains site-specific information that the server sends to the client
along with page output. Cookies can be temporary (with specific expiration times and dates) or persistent.
You can use cookies to store information about a particular client, session, or application. The cookies are
saved on the client device, and when the browser requests a page, the client sends the information in the
cookie along with the request information. The server can read the cookie and extract its value. A typical use
is to store a token (perhaps encrypted) indicating that the user has already been authenticated in your
application.
The browser can only send the data back to the server that originally created the cookie. However,
malicious users have ways to access cookies and read their contents. It is recommended that you do not store
sensitive information, such as a user name or password, in a cookie. Instead, store a token in the cookie that
identifies the user, and then use the token to look up the sensitive information on the server.

Query Strings: Query strings are appended to the page url and is used to store values for the requested
page. They appear in the url after a question mark “?” followed by the name of the query string parameter,
an equal sign “=” and finally the value.
Query strings are used for some specific purpose. These in a general case are used for holding some
value from a different page and move these values to the different page. The information stored in it can be
easily navigated to one page to another or to the same page as well. Query strings provide a simple but
limited way to maintain state information.
Query strings are lightweight state mechanisms passed in the HTTP request that target a specific
URL. Further, all browsers and client devices, even the simplest devices like WAP phones, support query
strings. However, because the information passed in the query string is visible to the user by simply looking
at the URL, it may pose a security risk for all but the most trivial implementations. And since most browsers
limit the length of a URL to 255 characters, the amount of information that you can pass using a query string
is severely limited.
However, some browsers and client devices impose a 2083-character limit on the length of the URL.
For query string values to be available during page processing, you must submit the page using an HTTP
GET command. That is, you cannot take advantage of a query string if a page is processed in response to an
HTTP POST command.

Server-Based State Management Options

ASP.NET offers you a variety of ways to maintain state information on the server, rather than
persisting information on the client. With server-based state management, you can decrease the amount of
information sent to the client in order to preserve state, however it can use costly resources on the server.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 49


DOT NET Technology

The following sections describe three server-based state management features: application state, session
state, and profile properties.

Application State: ASP.NET allows you to save values using application state — which is an instance of
the HttpApplicationState class — for each active Web application. Application state is a global storage
mechanism that is accessible from all pages in the Web application. Thus, application state is useful for
storing information that needs to be maintained between server round trips and between requests for pages.
Application state is stored in a key/value dictionary that is created during each request to a specific
URL. You can add your application-specific information to this structure to store it between page requests.
Once you add your application-specific information to application state, the server manages it.

Session State: ASP.NET allows you to save values by using session state — which is an instance of
the HttpSessionState class — for each active Web-application session. Session state is similar to application
state, except that it is scoped to the current browser session. If different users are using your application,
each user session will have a different session state. In addition, if a user leaves your application and then
returns later, the second user session will have a different session state from the first.
Session state is structured as a key/value dictionary for storing session-specific information that
needs to be maintained between server round trips and between requests for pages. You can use session
state to accomplish the following tasks:
 Uniquely identify browser or client-device requests and map them to an individual session instance on the
server.
 Store session-specific data on the server for use across multiple browser or client-device requests within
the same session.
 Raise appropriate session management events. In addition, you can write application code leveraging these
events.
Once you add your application-specific information to session state, the server manages this object.
Depending on which options you specify, session information can be stored in cookies, on an out-of-process
server, or on a computer running Microsoft SQL Server.

Profile Properties: ASP.NET provides a feature called profile properties, which allows you to store user-
specific data. This feature is similar to session state, except that the profile data is not lost when a user's
session expires. The profile-properties feature uses an ASP.NET profile, which is stored in a persistent
format and associated with an individual user. The ASP.NET profile allows you to easily manage user
information without requiring you to create and maintain your own database. In addition, the profile makes
the user information available using a strongly typed API that you can access from anywhere in your
application. You can store objects of any type in the profile. The ASP.NET profile feature provides a generic
storage system that allows you to define and maintain almost any kind of data while still making the data
available in a type-safe manner.
To use profile properties, you must configure a profile provider. ASP.NET includes
SqlProfileProvider class that allows you to store profile data in a SQL database, but you can also create your
own profile provider class that stores profile data in a custom format and to a custom storage mechanism
such as an XML file, or even to a web service.
Because data that is placed in profile properties is not stored in application memory, it is preserved
through Internet Information Services (IIS) restarts and worker-process restarts without losing data.
Additionally, profile properties can be persisted across multiple processes such as in a Web farm or a Web
garden.

WEB.config

ASP.NET configuration data is stored in XML text files, each named Web.config. This file can
appear in multiple directories in ASP.NET applications. Using the features of the ASP.NET configuration
system, you can configure all of the ASP.NET applications on an entire server, a single ASP.NET
application, or individual pages or application subdirectories. You can configure features, such as

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 50


DOT NET Technology

authentication modes, page caching, compiler options, custom errors, debug and trace options, and much
more. These files allow you to easily edit configuration data before, during, or after applications are
deployed on the server. You can create and edit ASP.NET configuration files by using standard text editors,
the ASP.NET MMC snap-in, the Web Site Administration Tool, or the ASP.NET configuration API.
ASP.NET configuration files keep application configuration settings separate from application code.
Keeping configuration data separate from code makes it easy for you to associate settings with applications,
change settings as needed after deploying an application, and extend the configuration schema.
The Web.config file for an ASP.NET application that targets the .NET Framework version 3.5
contains configuration elements that are not found in the Web.config files for earlier versions. This
expanded Web.config file is also created when you open an existing Web site in and upgrade the Web site
to target the .NET Framework version 3.5. In that case, Visual Studio updates the application's Web.config
file to include the additional configuration elements.
The ASP.NET configuration system helps protect configuration files from access by unauthorized
users. ASP.NET configures IIS to deny access to any browser that requests access to the Machine.config or
Web.config files. HTTP access error 403 (Forbidden) is returned to any browser that attempts to request a
configuration file directly. Configuration files in one ASP.NET application are prevented from accessing
configuration settings in other ASP.NET applications unless your configuration application is running in
Full trust under an account that has permissions to read the configuration file in the other application.

Benefits of XML-based Configuration files


 ASP.NET Configuration system is extensible as well as application specific information can be stored and
retrieved easily. It is in human readable format.
 You need not restart the web server when the settings are changed in configuration file. ASP.NET
automatically detects the changes and applies them to the running ASP.NET application.
 You can use any standard text editor or XML parser to create and edit ASP.NET configuration files.

There are number of important settings that can be stored in the configuration file. Some of the most
frequently used configurations, stored conveniently inside Web.config file are Database connections,
Caching settings, Session States, Error Handling, Security, etc.

Configuration file looks like this:


<configuration>
<connectionStrings>
<add name ="myCon"
connectionString ="server=MyServer;database=puran;
uid=puranmehra;pwd=mydata1223"/>
</connectionStrings>
</configuration/>

Different types of Configuration files


Machine.config File
Configuration files are applied to an executing site based on a hierarchy. There is a global
configuration file for all sites in a given machine which is called Machine. Config. This file is typically
found in the C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG directory.
The Machine.config file contains settings for all sites running on the machine provided another
.config further up the chain does not override any of these settings. Although Machine.config provides a
global configuration option, you can use .config files inside individual website directories to provide more

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 51


DOT NET Technology

granular control. Between these two poles you can set a number of other .config files with varying degree of
applicable scope.

Application Configuration files (Web.config)


Each and Every ASP.NET application has its own copy of configuration settings stored in a file
called Web.config. If the web application spans multiple folders, each sub folder has its own Web.config file
that inherits or overrides the parent's file settings.

AppDomain

Asp.Net introduces the concept of an Application Domain which is shortly known as AppDomain. It
can be considered as a Lightweight process which is both a container and boundary. The .NET runtime uses
an AppDomain as a container for code and data, just like the operating system uses a process as a container
for code and data. As the operating system uses a process to isolate misbehaving code, the .NET runtime
uses an AppDomain to isolate code inside of a secure boundary. The CLR can allow the multiple .Net
applications to be run in a single AppDomain. The CLR isolates each application domain from all other
application domains and prevents the configuration, security, or stability of running .NET applications from
affecting other applications. An AppDomain can be destroyed without effecting the other AppDomains in
the process.
Multiple AppDomains can exist in Win32 process. As we discussed the main aim of AppDomain is
to isolate applications from each other and the process is same as the working of operating system process.
This isolation is achieved by making sure than any given unique virtual address space runs exactly one
application and scopes the resources for the process or application domain using that address space. Win32
processes provide isolation by having distinct memory addresses. The .Net runtime enforces AppDomain
isolation by keeping control over the use of memory. All memory in the App domain is managed by the run
time so the runtime can ensure that AppDomains do not access each other’s memory.
Operating systems and runtime environments typically provide some form of isolation between
applications. For example, Windows uses processes to isolate applications. This isolation is necessary to
ensure that code running in one application cannot adversely affect other, unrelated applications.
Application domains provide an isolation boundary for security, reliability, and versioning, and for
unloading assemblies. Application domains are typically created by runtime hosts, which are responsible for
bootstrapping the common language runtime before an application is run.

How to create AppDomain


AppDomains are generally created by Hosts for example Internet Explorer and Asp.net. The following is an
example to create instance of an object inside it and then executes one of the objects methods. This is the
explicit way of creating AppDomain by .Net Applications. AppDomains are created using the
CreateDomain method. AppDomain instances are used to load and execute assemblies (Assembly). When an
AppDomain is no longer in use, it can be unloaded.

public class MyAppDomain : MarshalByRefObject


{
public string GetInfo()
{
return AppDomain.CurrentDomain.FriendlyName;
}
}

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 52


DOT NET Technology

public class MyApp


{
public static void Main()
{
AppDomain apd = AppDomain.CreateDomain("Rajendrs Domain");
MyAppDomain apdinfo = (MyAppDomain)apd.CreateInstanceAndUnwrap
(Assembly.GetCallingAssembly().GetName().Name, "MyAppDomain");
Console.WriteLine("Application Name = " + apdinfo.GetInfo());
}
}

The AppDomain class implements a set of events that enable applications to respond when an assembly is
loaded, when an application domain will be unloaded, or when an unhandled exception is thrown.

Advantages
A single CLR operating system process can contain multiple application domains. There are advantages to
having application domains within a single process.
 Lower system cost - many application domains can be contained within a single system process.
 Each application domain can have different security access levels assigned to them, all within a single
process.
 Code in one AppDomain cannot directly access code in another AppDomain.
 The application in an AppDomain can be stopped without affecting the state of another AppDomain
running in the same process.
 An Exception in on AppDomain will not affect other AppDomains or crash the entire process that hosts
the AppDomains.

Benefits of Isolating an application


Historically, process boundaries have been used to isolate applications running on the same
computer. Each application is loaded into a separate process, which isolates the application from other
applications running on the same computer. The applications are isolated because memory addresses are
process-relative; a memory pointer passed from one process to another cannot be used in any meaningful
way in the target process. In addition, you cannot make direct calls between two processes. Instead, you
must use proxies, which provide a level of indirection.
Managed code must be passed through a verification process before it can be run (unless the
administrator has granted permission to skip the verification). The verification process determines whether
the code can attempt to access invalid memory addresses or perform some other action that could cause the
process in which it is running to fail to operate properly. Code that passes the verification test is said to be
type safe. The ability to verify code as type-safe enables the common language runtime to provide as great a
level of isolation as the process boundary, at a much lower performance cost.
Application domains provide a more secure and versatile unit of processing that the common
language runtime can use to provide isolation between applications. You can run several application
domains in a single process with the same level of isolation that would exist in separate processes, but
without incurring the additional overhead of making cross-process calls or switching between processes. The
ability to run multiple applications within a single process dramatically increases server scalability.
Isolating applications is also important for application security. For example, you can run controls
from several Web applications in a single browser process in such a way that the controls cannot access each
other's data and resources.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 53


DOT NET Technology

The isolation provided by application domains has the following benefits:


 Faults in one application cannot affect other applications. Because type-safe code cannot cause memory
faults, using application domains ensures that code running in one domain cannot affect other applications in
the process.
 Individual applications can be stopped without stopping the entire process. Using application domains
enables you to unload the code running in a single application.
 The behavior of code is scoped by the application in which it runs. In other words, the application domain
provides configuration settings such as application version policies, the location of any remote assemblies it
accesses, and information about where to locate assemblies that are loaded into the domain.
 Permissions granted to code can be controlled by the application domain in which the code is running.
 Code running in one application cannot directly access code or resources from another application. The
common language runtime enforces this isolation by preventing direct calls between objects in different
application domains. Objects that pass between domains are either copied or accessed by proxy. If the object
is copied, the call to the object is local. That is, both the caller and the object being referenced are in the
same application domain. If the object is accessed through a proxy, the call to the object is remote. In this
case, the caller and the object being referenced are in different application domains.
 Cross-domain calls use the same remote call infrastructure as calls between two processes or between two
machines. As such, the metadata for the object being referenced must be available to both application
domains to allow the method call to be JIT-compiled properly. If the calling domain does not have access to
the metadata for the object being called, the compilation might fail with an exception of
type System.IO.FileNotFound. The mechanism for determining how objects can be accessed across
domains is determined by the object.

Globalization and Localization

Globalization is the process of designing and developing applications that function for multiple
cultures. Localization is the process of customizing your application for a given culture and locale. The
topics in this section describe how to create ASP.NET Web applications that can be adapted to different
languages and cultures. Most websites on the internet today are designed and developed to support a single
language and culture but making a website or web application to support different languages and cultures is
not difficult and is relatively easy to implement in ASP.Net.
When a web application supports globalization, it means that the application can render it contents
based on the language preference set by a user in his or her browser. Localization involves translating a web
application into different languages and cultures. Making an already deployed website to support
globalization is not an easy task, thus it is always advised to make an application support globalization right
from the development stage, even if there is no current plan to make it support more than one language. If
later there is a decision to translate the application to another language, it will be easy to do, since the
structure has already been put in place.
ASP.Net makes it easy to localize an application using resource files. Resource files are xml files
with .resx extension. Resources can either be a global resource, in which it is accessible throughout the site
and placed in App_GlobalResources folder in a website or a local resource which is specific to a page only
and is placed in App_LocalResourcesfolder. Ex. We are going to have a page that displays GoodMorning
in four different Languages(French, Spanish, German and Hin). Create a new ASP.Net website in Visual
Studio and name it localizationexample, right click the website in solution explorer and select Add ASP.Net
Folder then select App_GlobalResources. After that, right click the App_GlobalResources and
select AddNewItem in the list of items displayed in the dialog box then select ResourceFile , give it any
name which will serve as the default resource file that will be selected if the language selected in the user

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 54


DOT NET Technology

browser is not available. ASP.Net checks the languageid and cultureid combination on the browser to
determine the resource file to be used in rendering contents to that browser.

To add Resource Files to our project:


1. Right-click on the Root Folder Add New Item.
2. Select Resource File from the above Templates. Name it "Resource.resx"
3. You need other Resource Files for storing data depending on the Culture
4. Add another file with the following names of each resource, such as "Resource.en-GB.resx" else you
can give a different name but after the (Dot ) because they are sub-files of "Resource.resx".
o For English you can add "Resource.en-GB.resx"
o For Marathi you can add "Resource.mr-IN.resx"
o For Hindi you can add "Resource.hi-IN.resx"
o For Arabic you can add "Resource.ar-SA.resx"

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 55


DOT NET Technology

Chapter 4

Introduction to ADO.NET

ADO.NET stands for ActiveX Data Objects which is Microsoft technology. The main job that
handles ADO.NET is data management. It is widely used for accessing, selecting, saving, deleting or
managing data with the database. ADO.NET is a data bridge between apps and databases that carry data
between them. ADO.NET has a rich set of classes, methods, and interfaces that allow you to handle data in
the database more efficiently.
ADO.NET is an object-oriented set of libraries that allows you to interact with data sources.
Commonly, the data source is a database, but it could also be a text file, an Excel spreadsheet, or an XML
file. A database is one or more lists of items. You can create a database in a normal computer file, or you
can use a computer environment. For the Microsoft Windows family of operating systems, there are various
applications used to create databases. These include Microsoft Access, Microsoft SQL Server, Oracle,
MySQL, and many others. Some of these tools don't provide the ability to create graphical applications. You
can solve this problem by creating a web-based application

A web-based application can be an interactive web page or web site that allows a visitor to submit
values to a web server. The web page is typically equipped with graphical elements. To create an application
made of graphical user interface (GUI) objects, you can use a separate environment such as Microsoft
Visual Web Developer or Microsoft Visual Studio. You would then create a project that communicates with
the web server, and that web server would have a database application. Microsoft Visual Studio and
Microsoft Visual Web Developer make it easy to create an ASP.NET application that uses a
Microsoft SQL Server database.

ADO.NET relies on the .NET Framework's various classes to process requests and perform the
transition between a database system and the user. The operations are typically handled through the Dataset
class. While ADO.NET is the concept of creating and managing database systems, the Dataset class serves
as an intermediary between the database engine and the user interface, namely the web controls that a visitor
uses to interact with the web page. Besides using features of a database in an ADO.NET application, you
can also fully take advantage of XML as it is completely and inherently supported by the DataSet class. To
fully support XML in your application, the .NET Framework is equipped with the System.Xml.dlllibrary
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 56
DOT NET Technology

ADO.NET Namespaces

Namespaces Description

Contains the definition for columns, relations, tables, database, rows,


System.Data
views, and constraints.

Contains the classes to connect to a Microsoft SQL Server database


System.Data.SqlClient
such as SqlCommand, SqlConnection, and SqlDataAdapter.

Contains classes required to connect to most ODBC drivers. These


System.Data.Odbc
classes include OdbcCommand and OdbcConnection.

Contains classes such as OracleConnection and OracleCommand


System.Data.OracleClient
required to connect to an Oracle database.

Data Controls in ASP.Net

In our daily routine we do lot of spends. But at the end we make reports of all that spends. Like, in
my family my mother has the responsibility of making the report of the monthly expenses and then
comparing it with the monthly income of the family so that we can analyze our economic condition and can
control our extravagant expenses for using it as our future savings. But she does it in manual form. If I talk
about small scale organization they keep their records in excel file where they can analyze their Profit and
losses easily. But when we talk about the large scale organizations, they can’t do it in manual form or in the
excel file. That’s why they develop website for their organization where they keep, analyze and modify the
data on large scale using controls known as data controls. Today, I tried to introduce you with those data
control which .net developer generally used in their websites.
One of the important goals of the Asp.net language is code minimization. Data controls play an important
role in this purpose. Data controls used to display the records in the form of reports.

Some of the Data controls are:


1. Repeater data control
2. Detailsview data control
3. GridView data control
4. DataList data control
5. FormView data control

GridView data control:


This control displays the data in tabular form. It not only support the editing and deleting of data, it also
support sorting and paging of data.
Example:

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 57


DOT NET Technology

DetailsView data control:


This control displays single record of data at a time. It supports updating, insertion or deletion of the record.
It can be used in conjunction with the GridView control to provide a master-detail view of your data.
Example:

FormView data control:


This control displays a single record of data at a time like DetailsView control and supports the editing of
record. This control requires the use of template to define the rendering of each item. Developer can
completely customize the appearance of the record.
Example:

DataListView control:
This control displays data as items in a list. Presentation of the data can be customized via templates. Inline
editing and deleting of data is supported by this control.
Example:

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 58


DOT NET Technology

Repeater Data control:


This control is used to display the repeated list of the items that are bound to the control. It provides
complete flexibility in regards to the HTML presentation. A Repeater has five templates to format it:
 HeaderTemplate
 AlternatingItemTemplate
 Itemtemplate
 SeoperatorTemplate
 FooterTemplate
Example

ADO.NET Architecture

ADO.NET uses a multilayer architecture that has components such as the Connection, Reader,
Command, Adapter and Dataset objects. ADO.NET introduced data providers that are a set of special
classes to access a specific database, execute SQL commands and retrieve data. Data providers are
extensible; developers can create their own providers for proprietary data source. Some examples of data
providers include SQL server providers, OLE DB and Oracle providers.
ADO.NET provides the following two types of classes objects:
 Connected Mode: They are the data provider objects such as Connection, Command, DataAdapter,
and DataReader. They execute SQL statements and connect to a database.
 Dis-Connected Mode (Content-based): They are found in the System.Data namespace and include
DataSet, DataColumn, DataRow, and DataRelation. They are completely independent of the type of
data source.

ADO.NET consists of a set of Objects that expose data access services to the .NET environment. It is a
data access technology from Microsoft .Net Framework, which provides communication between relational
and non-relational systems through a common set of components. System.Data namespace is the core of
ADO.NET and it contains classes used by all data providers. ADO.NET is designed to be easy to use, and
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 59
DOT NET Technology

Visual Studio provides several wizards and other features that you can use to generate ADO.NET data
access code.

Data Providers:
The Data Provider classes are meant to work with different kinds of data sources. They are used to
perform all data-management operations on specific databases. DataSet class provides mechanisms for
managing data when it is disconnected from the data source. The .Net Framework includes mainly three
Data Providers for ADO.NET. They are the Microsoft SQL Server Data Provider, OLEDB Data Provider
and ODBC Data Provider . SQL Server uses the SqlConnectionobject , OLEDB uses the OleDbConnection
Object and ODBC uses OdbcConnection Object respectively. A data provider contains Connection,
Command, DataAdapter, and DataReader objects. These four objects provide the functionality of Data
Providers in the ADO.NET.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 60


DOT NET Technology

Connection
The Connection Object provides physical connection to the Data Source. Connection object needs
the necessary information to recognize the data source and to log on to it properly, this information is
provided through a connection string. The Connection Object is a part of ADO.NET Data Provider and it is
a unique session with the Data Source. The Connection Object provides physical connection to the Data
Source. Connection object needs the necessary information to recognize the data source and to log on to it
properly, this information is provided through a connection string.
The Connection Object connects to the specified Data Source and opens a connection between the
application and the Data Source, depends on the parameter specified in the Connection String. When the
connection is established, SQL Commands will execute with the help of the Command Object and retrieve
or manipulate data in the Data Source. Once the Database activity is over, Connection should be closed and
release the Data Source resources. The type of the Connection is dependent on which Data Source system
you are working with.

Command
The Command Object uses to perform SQL statement to be executed at the Data Source. The
command object provides a number of Execute methods that can be used to perform the SQL queries in a
variety of fashions. The Command Object requires an instance of an ASP.NET Connection Object for
executing the SQL statements. The Command Object in ADO.NET executes SQL statements against the
data source specified in the ASP.NET Connection Object. The Command Object has a property called
CommandText , which contains a String value that represents the command that will be executed against the
Data Source.

ASP.NET ExecuteNonQuery:- ExecuteNonQuery executes a Transact-SQL statement against the connection


and returns the number of rows affected. The ExecuteNonQuery () performs Data Definition tasks as well as
Data Manipulation tasks also. The Data Definition tasks like creating Stored Procedures ,Views etc. perform
by the ExecuteNonQuery() . Also Data Manipulation tasks like Insert , Update , Delete etc. also perform by
the ExecuteNonQuery() of SqlCommand Object. Although the ExecuteNonQuery returns no rows, any
output parameters or return values mapped to parameters are populated with data.

ASP.NET ExecuteReader: - The ExecuteReader () in SqlCommand Object sends the SQL statements to the
Connection Object and populate a SqlDataReader Object based on the SQL statement. When the
ExecuteReader method in SqlCommand Object execute, it will instantiate a SqlClient.SqlDataReader
Object. The SqlDataReader Object is a stream-based, forward-only, read-only retrieval of query results from
the Data Source, which do not update the data it contains. The SqlDataReader cannot be created directly
from code, they can be created only by calling the ExecuteReader method of a Command Object.

ASP.NET ExecuteScalar:- ExecuteScalar method uses to retrieve a single value from a database. The
ExecuteScalar() executes SQL statements as well as Stored Procedure and returns the first column of the
first row in the result set, or a null reference if the result set is empty. It is very useful to use with aggregate
functions like Count(*) or Sum() etc. When compare to ExecuteReader() , ExecuteScalar() uses fewer
System resources.

DataReader
DataReader Object in ADO.NET is a stream-based , forward-only, read-only retrieval of query
results from the Data Sources , which do not update the data. The DataReader cannot be created directly
from code; they can create only by calling the ExecuteReader method of a Command Object. After creating

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 61


DOT NET Technology

an instance of the Command object, you have to create a DataReader by calling Command.ExecuteReader to
retrieve rows from a data source.
When the ExecuteReader method in the SqlCommand Object execute , it will instantiate a
SqlClient.SqlDataReader Object. When we started to read from a DataReader it should always be open and
positioned prior to the first record. The Read() method in the DataReader is used to read the rows from
DataReader and it always moves forward to a new valid row, if any row exist . You should always call the
Close method when you have finished using the DataReader object.

DataAdapter
DataAdapter Object populates a Dataset Object with results from a Data Source. It is a special class
whose purpose is to bridge the gap between the disconnected Dataset objects and the physical data source.
DataAdapter serves as a bridge between a DataSet and SQL Server for retrieving and saving data. We can
use SqlDataAdapter Object in combination with Dataset Object. DataAdapter provides this combination by
mapping Fill method, which changes the data in the DataSet to match the data in the data source, and
Update, which changes the data in the data source to match the data in the DataSet.
The SqlDataAdapter Object and DataSet objects are combining to perform both data access and data
manipulation operations in the SQL Server Database. When the user perform the SQL operations like Select
, Insert etc. in the data containing in the Dataset Object , it won’t directly affect the Database, until the user
invoke the Update method in the SqlDataAdapter.
The DataAdapter can perform Select, Insert, Update and Delete SQL operations in the Data Source.
The Select Command property of the DataAdapter is a Command Object that retrieves data from the data
source. Other command properties of the DataAdapter are Command objects that manage updates to the data
in the data source according to modifications made to the data in the DataSet.

Connected layer of ADO.NET

The architecture of ADO.NET, in which connection must be opened to access the data retrieved from
database is called as connected architecture. Connected architecture was built on the class’s connection,
command, datareader and transaction. Connected architecture is when you constantly make trips to the
database for any CRUD (Create, Read, Update and Delete) operation you wish to do. This creates more
traffic to the database but is normally much faster as you should be doing smaller transactions.
As the name suggests, connected architecture refers to the fact that the connection is established for
the full time between the database and application. For e.g. we make a program in C# that is connected with
the database for the full time, so that will be connected architecture. Connected architecture is forward only
and read-only. This means the connected mode will work only in one particular direction i.e. forward and
that too for read-only purpose. Application issues query then read back results and process them. For
connected architecture, we mainly use the object of the DataReader class. DataReader is used to retrieve the
data from the database and it also ensures that the connection is maintained for the complete interval of time.
In connected architecture, the application is directly linked with the Database.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 62


DOT NET Technology

DataReader in Connected architecture


DataReader is used to store the data retrieved by command object and make it available for .net
application. Data in DataReader is read only and within the DataReader you can navigate only in forward
direction and it also only one record at a time. To access one by one record from the DataReader,
call Read() method of the DataReader whose return type is bool. When the next record was successfully
read, the Read() method will return true and otherwise returns false. In order to make an object of the
DataReader class, we never use the new keyword instead we call the ExecuteReader() of the command
object.
SqlCommand cmd= new SqlCommand(“Select * from Table”);
SqlDatareader rdr=cmd.ExecuteReader(cmd);

Here cmd.ExecuteReader() executes the command and creates the instance of DataReader class and loads
the instance with data. Therefore, we do not use the ‘new’ keyword.

Disconnected layer of ADO.NET

The architecture of ADO.net in which data retrieved from database can be accessed even when
connection to database was closed is called as disconnected architecture. Disconnected architecture of
ADO.net was built on class’s connection, dataadapter, commandbuilder, dataset and dataview. Disconnected
architecture is a method of retrieving a record set from the database and storing it giving you the ability to
do many CRUD (Create, Read, Update and Delete) operations on the data in memory, and then it can be re-
synchronized with the database when reconnecting. A method of using disconnected architecture is using a
Dataset.

DataSet: Dataset is used to store the data retrieved from database by dataadapter and make it available for
.net application. It is used in Disconnected Architecture since all the records are brought at once and there is
no need to keep the connection alive To fill data in to dataset fill() method of dataadapter is used and has the
following syntax.
Da.Fill(Ds,”TableName”);
When fill method was called, dataadapter will open a connection to database, executes select
command, stores the data retrieved by select command in to dataset and immediately closes the connection.
DataSet provides a disconnected representation of result sets from the Data Source, and it is
completely independent from the Data Source. DataSet provides much greater flexibility when dealing with
related Result Sets. DataSet contains rows, columns,primary keys, constraints, and relations with other
DataTable objects. It consists of a collection of DataTable objects that you can relate to each other with
DataRelation objects. The DataAdapter Object provides a bridge between the DataSet and the Data Source.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 63


DOT NET Technology

As connection to database was closed, any changes to the data in dataset will not be directly sent to
the database and will be made only in the dataset. To send changes made to data in dataset to the
database, Update() method of the dataadapter is used that has the following syntax.
Da.Update(Ds,”Tablename”);
When Update method was called, dataadapter will again open the connection to database, executes insert,
update and delete commands to send changes in dataset to database and immediately closes the connection.
As connection is opened only when it is required and will be automatically closed when it was not required,
this architecture is called disconnected architecture. A dataset can contain data in multiple tables.

DataView : DataView is a view of table available in DataSet. It is used to find a record, sort the records and
filter the records. By using dataview, you can also perform insert, update and delete as in case of a DataSet.

DataAdapter: DataAdapter is used to transfer the data between database and dataset. It has commands like
select, insert, update and delete. Select command is used to retrieve data from database and insert, update
and delete commands are used to send changes to the data in dataset to database. It needs a connection to
transfer the data.
DataAdapter class acts as an interface between application and database. It provides the data to the
Dataset which helps the user to perform the operations and finally the modifications are done in the Dataset
which is passed to the DataAdapter which updates the database. DataAdapter takes the decision for the
establishment and termination of the connection. DataAdapter is required for connectivity with the database.
DataAdapter established a connection with the database and fetches the data from the database and fill it
into the Dataset. And finally, when the task is completed, it takes the data from the DataSet and updates it
into the database by again establishing the connection. It can be said that DataAdapter acts as a mediator
between the application and database which allows the interaction in disconnected architecture.

CommandBuilder : By default, data adapter contains only the select command and it doesn’t contain
insert, update and delete commands. To create insert, update and delete commands for the dataadapter,
commandbuilder is used. It is used only to create these commands for the dataadapter and has no other
purpose.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 64


DOT NET Technology

Difference between Connected and disconnected architecture

Connected Mode Disconnected mode

Connected mode is connection oriented. Disconnected mode is disconnected connection


oriented.
In Connection mode, we read data from a database In Disconnection mode, we read data from a
by using a DataReader object. database by using a DataSet object.
DataReader keeps the connection open until all rows DataSet keeps all the records together & brought at
are fetched one by one once, hence no need to keep the connection alive.

Connected mode methods provide faster Disconnection mode get low in speed and
performance. performance.
Connected mode can hold the data of single table. Disconnection mode can hold multiple tables of data.
Connected mode is read only, we can't update the we can perform all option as like update, insert,
data. delete etc.
In Connected Architecture you have to declare the In Disconnected Architecture, you don't need to
connection explicitly by using Open() and close the define the connection explicitly. SqlDataAdopter
connection by using Close() and you can execute itself can open and close the connection and you can
commands using different methods like use dataset for storing the information temporarily
ExecuteNonQuery(),ExecuteScalar() and and Fill() is used to execute the commands give in
ExecuteReader(). adopter.

Connected Environment needs constantly connection Disconnected environment doesn't need any
of user to datasource while performing any connection. Hence, We can’t get updated data
operation. Hence, We get updated data regularly in regularly in disconnected environment.
connected environment.
Only one operation can be performed at a time in Multiple operations can be performed at a time in
connected environment. disconnected environment.

Advantages of ADO .NET


ADO.NET offers several advantages over previous Microsoft data access technologies, including
ADO. The following section will outline these advantages.

Single Object- Oriented API: The ADO.NET provides a single object-oriented set of classes. There are
different data providers to work with different data sources, but the programming model for all these data
providers to work in the same way. So if you know how to work with one data provider, you can easily work
with others. It’s just a matter of changing class names and connection strings. The ADO.NET classes are
easy to use and to understand because of their object- oriented nature. You can use more than one data
provider to access a single data source. For example, you can use ODBC or OleDb data providers to access
Microsoft access databases.

Managed Code: The ADO .NET classes are managed classes. They take all the advantages of .NET CLR,
such as language independency and automatic resource management. All .NET languages access the same
API. So if you know how to use these classes in C#, you’ll have no problem using them in VB.NET.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 65


DOT NET Technology

Another big advantage is you don’t have to worry about memory allocation and freeing it. The CLR will
take care of it for you.

Deployment: In real life, writing database application using ODBC, DAO, and other previous technologies
and deploying on client machines was a big problem was somewhat taken care in ADO except that three are
different versions of MDAC. Now you don’t have to worry about that. Installing distributable .NET
components will take care of it.

XML Support: Today, XML is an industry standard and the most widely used method of sharing data
among applications over the Internet. As discussed earlier in ADO .NET data is cached and transferred in
XML format. All components and applications can share this data and you can transfer data via different
protocols such as HTTP.

Visual Data Components: Visual Studio .NET offers ADO .NET components and data– bound controls to
work in visual form. That means you can use these components as you use any windows controls. You drag
and drop these components on windows and web forms set their properties and write events. It helps
programmers to write less code and develop applications in no time. VS .NET also offers the data form
wizard, which you can use to write full-fledged database applications without writing a single line of code.
Using these components, you can directly bind these components with data-bound controls by setting these
control’s properties at design-time.

Performance and Scalability: Performance and scalability are two major factors when developing web-
based applications and services. Transferring data one source to another is a costly affair over the Internet
because of connection bandwidth limitations and rapidly increasing traffic. Using disconnected cached data
in XML takes care of both problems.

Connections and Disconnected data: With ADO .NET you use as few connections as possible and have
more disconnected data. Both the ADO and ADO .NET models support disconnected data, but ADO’S
record set object wasn’t actually designed to work with disconnected data. So there are performance
problems with that. However, ADO.NET’s dataset is specifically designed to work with disconnected data,
and you can treat a dataset as a local copy of a database. In ADO.NET, you store data in a dataset and close
the make final changes to the data source. The ADO model is not flexible enough for XML users; ADO uses
OLE-DB persistence provider to support XML.

DataReader versus DataSet: The ADO.NET DataReader is used to retrieve read-only (cannot update data
back to a datasource) and forward-only (cannot read backward/random) data from a database. You create a
DataReader by calling Command.ExecuteReader after creating an instance of the Command object.

Data binding using ADO.net

Data binding is the process that establishes a connection between the application UI and business
logic. If the binding has the correct settings and the data provides the proper notifications, when the data
changes its value, the elements that are bound to the data reflect changes automatically. The DataSet is an
in- memory representation of data that provides a consistent relational programming model, regardless of the
source of the data it contains. The ADO.NET 2.0 DataView enables you to sort and filter the data stored in a
DataTable. This functionality is often used in data-binding applications. By using a DataView, you can
expose the data in a table with different sort orders, and you can filter the data by row state or based on a
filter expression. For more information about the DataView object, see DataViews.
BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 66
DOT NET Technology

LINQ to DataSet allows developers to create complex, powerful queries over a DataSet by using
Language-Integrated Query (LINQ). However, a LINQ to DataSet query returns an enumeration of
DataRow objects, which is not easily used in a binding scenario. To make binding easier, you can create a
DataView from a LINQ to DataSet query. This DataView uses the filtering and sorting specified in the
query, but is better suited for data binding. LINQ to DataSet extends the functionality of the DataView by
providing LINQ expression-based filtering and sorting, which allows for much more complex and powerful
filtering and sorting operations than string-based filtering and sorting.
Note that the DataView represents the query itself and is not a view on top of the query. The
DataView is bound to a UI control, such as a DataGrid or a DataGridView, providing a simple data binding
model. A DataView can also be created from a DataTable, providing a default view of that table.
Every ASP.NET web form control inherits the DataBind method from its parent Control class, which
gives it an inherent capability to bind data to at least one of its properties. This is known as simple data
binding or inline data binding.
Simple data binding involves attaching any collection (item collection) which implements the IEnumerable
interface, or the DataSet and DataTable classes to the DataSource property of the control.
On the other hand, some controls can bind records, lists, or columns of data into their structure through a
DataSource control. These controls derive from the BaseDataBoundControl class. This is called declarative
data binding.
The data source controls help the data-bound controls implement functionalities such as, sorting, paging, and
editing data collections.
The BaseDataBoundControl is an abstract class, which is inherited by two more abstract classes:
 DataBoundControl
 HierarchicalDataBoundControl
The abstract class DataBoundControl is again inherited by two more abstract classes:
 ListControl
 CompositeDataBoundControl
The controls capable of simple data binding are derived from the ListControl abstract class and these
controls are:
 BulletedList
 CheckBoxList
 DropDownList
 ListBox
 RadioButtonList
The controls capable of declarative data binding (a more complex data binding) are derived from the abstract
class CompositeDataBoundControl. These controls are:
 DetailsView
 FormView
 GridView
 RecordList

The user can bind values to the respective controls in ADO.NET. Depending on the type of binding offered,
they are distinguished as follows:

1. Simple Data Binding


The Simple Data Binding is the process of binding the control with the single value in the dataset. The
controls like text box, label can be bound to the control through the control properties.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 67


DOT NET Technology

Consider an example to display the result of the students in an examination. The details are added in the
following format.
1. Create a Windows Form Application in Visual Studio .NET. The following customized format is
created for user.

2. Once the design of the form is created, select the View option from the menu bar. Click on the
Properties window.
3. Select the first text box and the properties for it appear in the window.
4. Expand the DataBindings property
5. Select the Text property for enabling the drop down list.
6. Click the Add Project Data Source from the drop down list
7. Make a connection with the CurrentInfo database and select the Student table
8. Select the Other Data Sources, Project Data Sources, CurrentInfoDataSet, Student table.
9. Select the Name column and bind it with the textbox.
10. Bind all the other text boxes with the database values.
11. Press F5 and execute the Windows Form.
12. The following output is displayed to the user.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 68


DOT NET Technology

2. Complex Data Binding


The Complex Data Binding is the process of binding the component with the Database. The controls can
be GridView, Dropdown list, or combo box. Multiple values can be displayed from the dataset through the
binding. The controls that can be used for binding the multiple values from the database to the Windows
Form are listed below.
1. DataGridView: It is used to display the multiple records and columns. The DataSource property of
the DataGridView control is used for binding the specific data element.
2. ComboBox: The control contains a text box for entering the data and drop down list for displaying
the values. The DataSource property is useful for binding the control. The element specific
information can be bind through the DisplayMember property
3. ListBox: It is used for displaying the data for the column from several records of datasets. The
DataSource property is used for binding the control to the data source.
4. The DisplayMember property is used for binding the control to the specific data element.

Navigating Records in ADO.NET


A BindingNavigator control is used for handling the binding to the data source through the pointer to the
current item in the list of records. The navigator control is used with the BindingSource control for enabling
the users to navigate the data records on a form. It provides a layer between the controls and windows form
of the data source. Users can navigate and modify the records in the Windows form. The following figure
displays the BindingNavigator control and the BindingSource control in the Windows Form.

The Binding Navigator control has many controls for modifying the data source. The list of controls and
their functions are mentioned below:
1. bindingNavigatorAddNewItem Button: The + sign indicates that the new row can be added to the
data source.
2. bindingNavigatorDeleteItem Button: The X sign indicates that the current row can be deleted from
the data source.
3. bindingNavigatorMoveFirstItem Button: The button indicates that the user can move to the first item
in the data source.
4. bindingNavigatorMoveLastItem Button: The button indicates that the user can move to the last item
in the data source

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 69


DOT NET Technology

5. bindingNavigatorMoveNextItem Button: The button indicates that the user can move to the next item
in the data source
6. bindingNavigatorMovePreviousItem Button: The button indicates that the user can move to the
previous item in the data source
7. bindingNavigatorPositionItem textbox: The returns current position in the data source
8. bindingNavigatorCountItemText box: The is used to return the total number of items in the data
source.

Consider the Order details table containing the data about the orders to be added. The data is organized into
a format as shown below:
1. Open Visual studio application and add Windows Forms Application from the template pane.
2. Add the labels and a binding Navigator control, and textbox controls to the form
3. Click OK button
4. Click View, Properties Window, and open the Properties Window.
5. Add the appropriate names to the controls present in the web form.

6. Open the Data Source Configuration Wizard. The Database icon must be selected. Click Next Button
7. Click New Connection Button. Add Connection dialog box is shown.
8. Add the Server Name, select Use SQL Server Authentication option from the Log on the server
section
9. Add the User name as sa and password as abcd1234
10. Select the Order Details database and click Test Connection button
11. Click OK and close the Add Connection dialog box
12. Click Next button. In the Choose Your Database Objects dialog box, expand Tables node.
13. Select the Orderdata table and click Finish button.

For binding the data to the control in the Windows Form, the following steps are executed.
1. Select the textbox1, and expand the DataBindings property.
2. Select the Text property and click on the drop down list.
3. Expand the Other Data Sources, Project Data, Sources, Orderdataset, Orderdata nodes.
4. Select the OrderID column and bind it with textbox1.
5. Perform the similar operations for all the textboxes.
Press F5 or click Debug -> Start Debugging option from the menu. The Order Details form is displayed as
shown below:

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 70


DOT NET Technology

User can navigate through the other records using the navigator button of the control.
Close the form and exit the Visual Studio application.

Filtering Data
There are requirements when user wants to display only limited data to the client. The filtering of data is
possible for displaying the desired results. The data can be sorted in ascending or descending order. There
are two ways by which the data can be filtered. They are as mentioned below:

Parameterized Queries
The stored procedures are always useful for accessing data from the database. By using the stored
procedures users can precompiled execution, use of code, less network traffic, and security is high for the
data stored in the system. The parameterized queries are useful for filtering the data based on the conditions
defined by the user at runtime. They are useful when user wants to execute the data based on the situation.
The following query is useful for selecting the student with the ID specified.
Code: SELECT StudName FROM Student WHERE StudID = @StudID

In the above code, the @StudID is the parameter in the query. The value is passed at the runtime by the user.
In ADO.NET, for populating the @StudID parameter, the SqlParameter object in the SqlParameter class for
the command. The SqlParameter object is used for assigning the parameterized values to the queries.
Consider the example for extracting the details of the student. The following code shows the execution
parameterized query.

Code:
SqlConnection con = new SqlConnection();
con.ConnectionString = “DataSource = SQLSERVER02; Initial Catalog=StudData; User ID =
sa; Password=abcd1234”;
con.Open();
string studid;
studid = textbox1.Text;
String query = “ SELECT * from StudData where StudID = @StudID”;
SqlCommand cmd = new SqlCommand( query, con);
cmd.Parameters.Add( new SqlParameter ( “@StudID”, StudID ) );
SqlDataReader dr = cmd.ExecuteReader();

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 71


DOT NET Technology

Filtering data using controls in Windows Form


Once the data is retrieved from the data source by binding the data to the control of the Windows
form, the data filter is used for displaying the selective records. Consider the example of a company where
user wants to view the information about the employee data. The information is displayed in the form of a
grid view. The connection is established with the database and the data binding through the DataGridView
control. If user wants the data only of the specific employees in the organization, they can be filtered using
the following steps.
1. Select the DataGridView control in the form and open the DataGridViewTasks window.
2. Click on the Add Query option. The SearchCriteria Builder dialog box will open.
3. Add the following query in the query text box.
Code: SELECT EmpID, EmpName, EmpRole FROM Employee WHERE ( EmpID = 101 )
4. Click on the Query Builder button
5. Click on the Execute Query button. The output generated by the query can be checked
6. Click OK button and close the Search Criteria Builder dialog box
7. Press F5 and execute the Windows Form.

In the above example, TableAdapter queries are the SQL statements or procedures that are executed. The
FillBy method is useful for executing the TableAdapter queries. The following code can be added to the
Click event of the FillByToolStrip control.
Code:
private void fillByToolStripButton_Click( object sender, EventArgs e )
{
try
{
this.internalCandidateTableAdapter.FillBy(
this.EmpDataSet.Employee);
}
catch( System.Exception ex )
{
System.Windows.Forms.MessageBox.Show( ex.Message );
}
}

In the above code, the FillBy method is used for adding data from the Employee table of the EmpDataSet.

Report generation, simple and parameterized reports

Create a Visual Studio Project


Creating a Project in Visual Studio
1. Open Visual Studio and create a new project.
2. Choose C#.
If you want to choose VB.NET you can go ahead and choose VB.NET. Designing reports with
Crystal Reports is independent of the language or type of application. The steps are the same for both
VB.NET & C#. For this Example, I will choose C#
3. Choose Windows Desktop Application.
4. Under Various Application, Template chose Windows Forms Application
5. Enter Name of the Project as MyFirstReport. Click OK. Visual C# Project is opened for you.
6. Rename the form as frmCrystalReport

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 72


DOT NET Technology

Create a Crystal Report


Now let us create a crystal Report. The following steps will guide you to add the new report
1. Under Solution Explorer select your Project.
2. Right Click and Add New Item. This displays the list of available templates.
3. Select Reporting Template Group.
4. Scroll down to select the Crystal Report template.
5. Enter the name as EmployeeList.
6. Click on Add to Create your first Report. This will take you to Crystal Report Gallery.

Crystal Report Gallery


You can Create Report using the following options
Report Wizard
 Using a Report Wizard. Selecting this option will open the crystal report wizard which takes you
through the various steps to help you in creating the report.
 As a blank Report. This will open a blank report.
 From an Existing Report. Here you are asked to select an existing report and the new report use.

Report Expert.
Crystal Report for Visual Studio comes with three report Experts.
 Standard Format. This expert will create the standard report.
 Cross Tab. This expert will create a specialized report known as cross tab report.
 Mail Label. This expert will create mailing label report where data is displayed in a format that is
suitable for use as address labels on envelopes.

In this example let us select Report Wizard and Standard Expert and then click on next. You will be taken to
the Standard Report Creation wizard.

Standard Report Creation wizard


First dialogue box under this allows you to choose the data source that would be used in the report. It has
three options
1. Project Data. This Option lists the data source connections already available in your project.
2. My Connections. This Option lists the most recently used data source connection so that you can
quickly add it your report.
3. Create New Connection.This Option allows us to create a new connection to data source.
Let us Select OLE/DB option to connect to our data source. click on the plus sign right next
to OLE/DB option. This will open the OLE/DB Dialog Box.

OLE/DB Dialog Box.


This Dialog Box Option displays the list of available OLE/DB Providers. Choose the appropriate OLE/DB
Provider to connect to your data source. Let us chose SQL Server Native Client 11.0 which is used to
connect to the SQL Server Database. Click on next.

OLE/DB Connection Info Dialog Box.


You will then see OLE/DB Connection Info Dialog Box. Here you need to input the database credential to
connect to the data source.
Input server Name. You can either input the user id and password or choose Integrated security option. If
you choose User id and password, then the crystal report will ask you for user id & Password while
displaying the report. I will choose Integrated security.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 73


DOT NET Technology

Select the database from the drop-down. select northwind database. Click on next when you are done.
OLE/DB Advance Information Dialog Box
You will then see OLE/DB Advance Information Dialog Box. Make appropriate changes if any and click
on Finish to go back to Standard Report Creation wizard.

Standard Report Creation wizard


Northwind data connection we just made is displayed under OLE/DB option under Create the new
connection. Click on plus sign to expand to the database. Any Tables, Stored Procedures, Views under the
selected data source connection is automatically displayed under the connection and is available to the
report. Select the appropriate the table/Stored Procedures/View which you want in your report.
1. Select employees table.
2. Click right arrow key to add the table to the report.
The table will appear in the selected tables box on the right side. You can add more than one table to
report. Click on next. You will be taken to Fields Dialog box.

Fields Dialog Box.


On the left side, you can see the list of fields from the employee table. These fields are now available to the
report. You can select any field just by double-clicking on them. Selected fields will appear on fields to
display box on the right side. Select any field on the left side box and click on browse data and view the
database values of the selected field. You can hold the control key and select multiple fields at once.
1. Select FirstName, LastName, Title, Address, City.
2. You can then click on right arrow key to add the fields to the report.
3. The fields will appear on the right side box.
4. You can move the field up and down by dragging the fields or using up or down arrow buttons.
5. Place the fields in the order you want them to appear in the Report.
6. Click on finish. You will then see the crystal report designer and the report is generated for you.

Crystal Report Viewer Control.


The next step is to show the crystal report in our windows form. To do this, you need to add Crystal Report
Viewer control to the form. CrystalReportViewer Control is a usercontrol class and can be used as any
other user control class. Primary Function of is to Display Reports.
1. Open the form frmcrystalreport which we have created.
2. Locate Reporting tab in the toolbox.
CrystalReportViewer control is listed under the Reporting Tab in the toolbox. So go to the toolbox
and locate the reporting tab.
3. Select the crystalReportViewer drag and drop it unto the form.
Good, now we have added the control.

Bind Report to Crystal Report Viewer Control


1. Open frmCrystalReport.
1. Go to the code-behind class.
2. Under the form load event write the following code (Double click form header to create the
event). Declare a variable rpt to hold the instance of the employeeListemployeeList is the name of
the report which we have created.
Assign this to the report source property of the crystal report viewer control.

BCA-II Sem-IV CBCS mpm@cimdr.sangli Page 74

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy