DotNETFAQBest(doc) - DOC SERVE

treescattleΛογισμικό & κατασκευή λογ/κού

2 Νοε 2013 (πριν από 3 χρόνια και 11 μήνες)

368 εμφανίσεις


-

1
-

.NET GENERAL

What is Microsoft.NET platform?

Microsoft .NET is a software development platform based on virtual machine
based architecture. Dot net is designed from the scratch to support programming
language independent application development. The entire

.NET programs are
independent of any particular operating system and physical hardware machine.
They can run on any physical machine, running any operating system that
contains the implementation of .NET Framework. The core component of the .NET
framework

is its Common Language Runtime (CLR), which provides the
abstraction of execution environment (Physical machine and Operating System)
and manages the overall execution of any of the .NET based program.


With dot NET, Microsoft introduces a completely new architecture for Windows
applications (WinForm), Data Access (ADO.NET), Web Applications (ASP.NET),
Windows components (Assemblies), Distributed Ap
plications (.NET remoting), and
above all the XML based Web Services. The famous figure for the representation
of dot net is presented below:


-

2
-


What

is the .NET framework?

The .NET framework is a collection of all the tools and utilities required to execute
the .NET managed applications on a particular platform. The MS.NET framework
includes the standard compilers (C#, VB.NET, J#, C++.NET, Jscript.NET
), various
utilities like (caspol, ngen, installutil, tlbimp, sn, asmreg, ildasm, etc), runtime
environment (CLR), garbage collector, security manager, thread manager,
assembly loader, just in time compilers, and the standard framework or base
class librar
ies. It is important to realize that while the implementation of .Net
applications is platform independent; the implementation of .NET framework is
platform specific. In fact, it is this particular specific implementation of the .NET
framework that makes t
he managed .NET applications platform independent.

What is the VB.NET and C# language comparisons?

VB.NET and C# both are integral part of the .NET framework. Both of the
languages have a lot of similarities in language constructs and language design
with

minor differences in the syntax. C# is more like C++ and Java in its syntax
while VB.NET lends its syntax from VB6 a great deal; although VB.NET can not be
seen as the successor of Visual Basic at the level of overall language design and
the vision of its

creators.

The general conception is that most of the VB6 developers will upgrade to VB.NET
while developers coming from Java or C++ to .NET are likely to go for C#. Since
web developers for Windows using ASP are familiar with VB and VB Scripts,
therefore
, most of the web development with ASP.NET at the start is likely to be

-

3
-

dominated by VB.NET; but after sometime C# will be able to attract at least half
of these developers. Keeping technical side away, C++ and thus C# developers
are generally paid more th
an those of VB developers. So, this might also be the
factor for making C# the language of choice on .NET framework.

What is the difference between Console, Windows,
Web applications and Web services?

Console applications are light weight programs run ins
ide the command prompt
(DOS) window. They are commonly used for test applications. Windows
Applications are form based standard Windows desktop applications for common
day to day tasks. Microsoft word is an example of a Windows application.

Web applicatio
ns are programs that used to run inside some web server (e.g.,
IIS) to fulfill the user requests over the http. A typical example of web application
is Hotmail and Google.

Web services are web applications that provide services to other applications over
the internet. Google search engine’s web service, e.g., allows other applications
to delegate the task of searching over the internet to Google web service and use
the result produced by it in their own applications.

What is meant by language interoperabi
lity and
language integration?

Prior to the introduction of .Net, the code written in one programming language is
considered to be usable only in the programs written with the same programming
languages. For example, an algorithm implemented in Perl progra
mming
language can not be reused in the programs written in the C++. At Windows
platform, Microsoft introduced the standards for COM (Component Object Model)
which allows components written in one programming language to be used in
other programming langua
ge. In Java, JNI (Java Native Interface) is presented to
use
-
up the code written in non
-
Java languages into Java programs. But both the
standards (COM and JNI) are too complex and have their own limitations. They
also don’t allow the language integration,
which means that you can use the
components written in other programming languages but you can’t extend the
functionality of the components.

In Microsoft.Net, the code written in any programming language is compiled to
the same Intermediate Language (Micr
osoft Intermediate Language
-

MSIL or
Common Intermediate Language


CIL) and to same component standard
(assembly). Hence, it is possible for developers to employ the language
interoperability by using and extending the solution implemented by other
devel
opers which might be using different programming language provided
developers at both end are using.Net compliant programming languages.

What is a .Net Assembly?

The .NET assembly is the standard for components developed with the
Microsoft.NET. Dot NET as
semblies may or may not be executable, i.e., they
might exist as the executable (.exe) file or dynamic link library (DLL) file. All
the .NET assemblies contain the definition of types, versioning information for the
type, meta
-
data, and manifest. The desig
ners of .NET have worked a lot on the
component (assembly) resolution.


-

4
-

There are two kind of assemblies in .NET; private and shared. Private assemblies
are simple and copied with each calling assemblies in the calling assemblies folder.
Shared assemblies
(also called strong named assemblies) are copied to a single
location (usually the Global assembly cache). For all calling assemblies within the
same application, the same copy of the shared assembly is used from its original
location. Hence, shared assemb
lies are not copied in the private folders of each
calling assembly. Each shared assembly has a four part name including its face
name, version, public key token and culture information. The public key token
and version information makes it almost impossib
le for two different assemblies
with the same name or for two similar assemblies with different version to mix
with each other.

An assembly can be a single file or it may consist of the multiple files. In case of
multi
-
file, there is one master module con
taining the manifest while other
assemblies exist as non
-
manifest modules. A module in .NET is a sub part of a
multi
-
file .NET assembly. Assembly is one of the most interesting and extremely
useful areas of .NET architecture along with reflections and attr
ibutes, but
unfortunately very few people take interest in learning such theoretical looking
topics.

What are the differences between a .NET Assembly, a
Windows DLL and a COM Component?

A Windows DLL contains library code to be used by any program running

on
Windows. A DLL may contain either structured or object oriented libraries.

COM (Component Object Model) is the component model based on the object
oriented design, which means that the components represented by the COM
component exists in the form of
classes and objects implementing a standard
specification defined by COM. COM components can be used by any program
running on Windows Operating System; be it is written with VB, C++, Java or
even some .NET compliant language like C# and VB.NET.

Dot NET a
ssembly is the component standard specified by the .NET. Hence, dot
net assemblies are understandable to only Microsoft.NET and can be used only
in .NET managed applications.

What are the differences between a .NET Assembly, a
Windows DLL and a COM Compon
ent?

A Windows DLL contains library code to be used by any program running on
Windows. A DLL may contain either structured or object oriented libraries.

COM (Component Object Model) is the component model based on the object
oriented design, which means t
hat the components represented by the COM
component exists in the form of classes and objects implementing a standard
specification defined by COM. COM components can be used by any program
running on Windows Operating System; be it is written with VB, C++
, Java or
even some .NET compliant language like C# and VB.NET.

Dot NET assembly is the component standard specified by the .NET. Hence, dot
net assemblies are understandable to only Microsoft.NET and can be used only
in .NET managed applications.


-

5
-

What i
s the difference between an executable
assembly and a class library?

An executable assembly exists as the .exe file while a class library exists as
the .dll file. Executable assembly represent executable applications having some
entry (e.g., Main() method
in C#). A class library, on the other hand, contains
components and libraries to be used inside various applications. A Class library
can not be executed and thus it does not have any entry point.

What does one need to build or execute .NET
applications?

To execute a standalone .NET application (Windows or Console application), one
needs to first compile all its constituent assemblies and modules including the
executable assembly. Once, the constituent assemblies are compiled, one needs
to make sure that t
he target system contains the .NET framework. The
application can now be executed by running its executable assembly (the .exe
file). The executable assembly (.exe) is a Win32 executable that hosts the .Net
CLR (Common Language Runtime), which exists as a
COM component, in its
process space and initializes it. Once the CLR is hosted and initialized, the starting
point of the .NET executable assembly is passed to the hosted CLR which starts
the execution of the program by translating and executing the parts
of the
program code.

What does it mean by managed code?

By managed code, it means that the complete life cycle and execution is
managed by the .NET Common Language Runtime (CLR). The .NET CLR manages
the memory on behalf of the managed code, performs garb
age collection on the
managed heap, perform assembly validation and assembly (component)
resolution on behalf of the program. The CLR also maintains the security
constraints applied to the managed code.

What is meant by un
-
safe code?

By un
-
safe code, it m
eans that the managed program can access the memory
address using pointers. There are two points to remember here;



Un
-
safe code is different from un
-
managed as it is still managed by the
CLR



You still can not perform pointer arithmetic in un
-
safe code.

What is the difference between Unmanaged and
Unsafe code?

Un
-
managed code runs outside the Common Language Runtime (CLR) control
while the unsafe code runs inside the CLR’s control. Both un
-
safe and un
-
managed codes may use pointers and direct memory addre
sses.

What about the MS.NET standardization?


-

6
-

Microsoft has secured certification for both C# and CLI from ECMA and ISO/IEC
as Industry standards. This is a very important step for Microsoft and .Net
platform because this enhances the credibility of the ne
wer .Net platform and
allures a larger portion of technology industry into adopting .Net as their
development platform. Several companies and government organizations only
utilize ISO certified technologies; for example, in Australia anything ISO certified

is also considered Australian standard according to the rules of the Australian
government. Several academic institutions will now be interested in teaching
standard C#. Another major outcome of having an open industry standard
specification is .Net platf
orm could be getting ported to other platforms like Linux
and UNIX; best example is the Mono Project by Ximian
-

it is an open source
implementation of .Net platform for UNIX and Linux based on ECMA approved
Public Domain Specification of C# and CLI.

Micro
soft submitted the specifications to ECMA, which in turn fast
-
tracked them
through ISO. In doing so, Microsoft released all intellectual property in the core
C#/CLI platform to the public domain. No one needs a license to implement
C#/CLI. This will also h
elp everybody in better understanding the
implementations of C# and CLI which are at the core of .Net platform. However,
the whole of .Net platform is not a Public domain standard
-

Microsoft still owns
complete Intellectual property rights to several class

libraries and API within
the .Net platform.

What about the implementation of .NET other than
Microsoft.Net on Windows Operating System?

Microsoft has implemented .NET framework for all of its operating system suits
(excluding MS Windows 95 and earlier) on

all supported hardware platforms. For
handheld and small devices, Microsoft has released a compact framework of .NET
(
http://msdn.microsoft.com/vstudio/device/compact.aspx

). But, there are
various other implementations being developed on platforms other than Microsoft
Windows. You can read the discussion on

the portability of .NET at (See
http://zdnet.com.com/2100
-
1107
-
960049.ht ml
)


The most popular implementation, after MS.NET, is the open source ‘Mono’
Project on Linux (See
www.go
-
mono.com
)

Microsoft has released almost all the source code of their .NET framewo
rk for
FreeBSD and Mac OS under the title of Shared Source Common Language
Infrastructure (SSCLI). Check out the SSCLI 1.0 release
-

which already builds on
WindowsXP, FreeBSD, and Mac OS X 10.2, released under Microsoft's Shared
Source Initiative.
http://msdn.microsoft.com/net/sscli/

http://www.microsoft.com/resources/sharedsource/default.mspx



What is the difference between trad
itional
development and .NET development?

In traditional programming languages, the source code of a program is compiled
to a specific platform’s assembly language and then machine language code.
Later the library code required by the program is linked to
it. Finally the operating
system executes the program when desired by the user. The complete process is
depicted in the following figure:


-

7
-


In the p
resence of dot net framework, a program is not compiled to the native
machine executable code; rather it gets compiled to an intermediate language
code called Microsoft Intermediate Language (MSIL) or Common Intermediate
Language (CIL). The Dot Net Common
Language Runtime (CLR) then converts
this intermediate code at runtime to the machine executable code. The
optimization is carried out at runtime. A program also does not call the operating
system APIs directly; rather it delegates this task to the CLR whi
ch performs the
desired operations on behalf of the program and returns the results of the
operations back to the program. The CLR also performs the memory management,
garbage collection, security and thread management on behalf of the program.
Dot NET fra
mework is shipped with the supporting object oriented framework of
common code libraries, called the .NET Framework Class Library (FCL), to
facilitate the common operations. Hence the .Net manages the overall execution
of an application. This is the reason

why the code running on .Net framework is
sometimes called the managed code. The complete process is depicted in the
following Figure. Note that only the CLR (and thus the .Net framework and not
the user application) is interacting and coupled with the pl
atform and operating
system.



-

8
-

What are the basic components of .NET platform?

The basic components of .NET platform (framework) are:

Common Langua
ge Runtime (CLR):

The most important part of the .NET Framework is the .Net Common Language
Runtime (CLR) also called .Net Runtime in short. It is a framework layer that
resides above the Operating System and handles/manages the execution of
the .NET appli
cations. Our .Net programs don’t directly communicate with the
Operating System but through CLR


MSIL (Microsoft Intermediate Language) Code:

When
we compile our .Net Program using any .Net compliant language like (C#,
VB.NET, C++.NET) it does not get converted into the executable binary code but
to an intermediate code, called MSIL or IL in short, understandable by CLR. MSIL
is an OS and H/w indepen
dent code. When the program needs to be executed,
this MSIL or intermediate code is converted to binary executable code, called
native code. The presence of IL makes it possible the Cross Language
Relationship as all the .Net compliant languages produce th
e similar standard IL
code.


Just In Time Compilers (JITers)

When our IL compiled code needs to be executed, CLR invokes JIT compilers
which compil
e the IL code to native executable code (.exe or .dll) for the specific
machine and OS. JITers in many ways are different from traditional compilers as
they, as their name suggests, compile the IL to native code only when desired
e.g., when a function is c
alled, IL of function’s body is converted to native code;
just in time of need. So, the part of code that is not used by particular run is not
converted to native code. If some IL code is converted to native code then the
next time when its needed to be us
ed, the CLR uses the same copy without re
-
compiling. So, if a program runs for sometime, then it won’t have any just in time
performance penalty. As JITers are aware of processor and OS exactly at runtime,

-

9
-

they can optimize the code extremely efficiently r
esulting in very robust
applications. Also, since JITer knows the exact current state of executable code,
they can also optimize the code by in
-
lining small function calls (like replacing
body of small function when its called in a loop, saving the functio
n call time).
Although, Microsoft stated that C# and .Net are not competing with languages
like C++ in efficiency, speed of execution, JITers can make your code even faster
than C++ code in some cases when program is run over extended period of time
(like
web
-
servers).

Framework Class Library (FCL)

.NET Framework provides huge set of Framework (or Base) Class Library (FCL)
for common, usual tasks. FCL contains thousands of classes to provide the access
to Windows API and common functions like String Manipu
lation, Common Data
Structures, IO, Streams, Threads, Security, Network Programming, Windows
Programming, Web Programming, Data Access, etc. It is simply the largest
standard library ever shipped with any development environment or
programming language. Th
e best part of this library is they follow extremely
efficient OO design (design patterns) making their access and use very simple
and predictable. You can use the classes in FCL in your program just as you use
any other class and can even apply inheritanc
e and polymorphism on these.

Common Language Specification (CLS)

Earlier we used the term ‘.NET Compliant Language’ and stated that all the .NET
compliant languages can make use of CLR and FCL. But what makes a language
‘.NET compliant language’? The answ
er is Common Language Specification (CLS).
Microsoft has released a small set of specification that each language should meet
to qualify as a .NET Compliant Language. As IL is a very rich language, it is not
necessary for a language to implement all the IL

functionality, rather it meets the
small subset of it, CLS, to qualify as a .NET compliant language, which is the
reason why so many languages (procedural and OO) are now running under .Net
umbrella. CLS basically addresses to language design issues and l
ays certain
standards like there should be no global function declaration, no pointers, no
multiple inheritance and things like that. The important point to note here is that
if you keep your code within CLS boundary, your code is guaranteed to be usable
i
n any other .Net language.

Common Type System (CTS)

.NET also defines a Common Type System (CTS). Like CLS, CTS is also a set of
standards. CTS defines the basic data types that IL understands. Each .NET
compliant language should map its data types to the
se standard data types. This
makes it possible for the 2 languages to communicate with each other by
passing/receiving parameters to/from each other. For example, CTS defines a
type Int32, an integral data type of 32 bits (4 bytes) which is mapped by C#
th
rough int and VB.Net through its Integer data type.

Garbage Collector (GC)

CLR also contains Garbage Collector (GC) which runs in a low
-
priority thread and
checks for un
-
referenced dynamically allocated memory space. If it finds some
data that is no more
referenced by any variable/reference, it re
-
claims it and
returns the occupied memory back to the Operating System; so that it can be

-

10
-

used by other programs as necessary. The presence of standard Garbage
Collector frees the programmer from keeping track of

dangling data.

What is the software development and execution flow
in Microsoft.NET?

With .NET development environment, a developer can write his/her code in
any .NET compliant programming language like C#, VB.NET, J#, C++.NET, etc.
In fact, various modu
les, components, projects of an application can be written
and compiled in different .Net based programming languages. All these
components are compiled to the same Intermediate language code (MSIL or CIL)
understandable by the .NET CLR.


At runtime, the .NET assembly (compiled IL code) is translated to native machine
code and executed by the CLR.

How is MS.NET compared with Java based platforms
(J2
EE)?

At root level architecture and components, MS.NET and J2EE platforms are very
similar. Both are virtual machine based architecture having CLR and Java Virtual
Machine (JVM) as the underlying virtual machine for the management and
execution of programs
. Both provide memory, security and thread management
on behalf of the program and both try to decouple the applications with the
execution environment (OS and physical machine). Both, basically, target the
Web based applications and especially the XML bas
ed web services. Both provide

-

11
-

managed access to memory and no direct access to memory is allowed to their
managed applications.

However, there are few contrasts in the architecture and design of the two virtual
machines. Microsoft .NET framework’s archite
cture is more coupled to the
Microsoft Windows Operating System which makes it difficult to implement it on
various operating systems and physical machines. Java, on the other hand, is
available on almost all major platforms. At the darker side, J2EE archi
tecture and
JVM is more coupled to the Java programming language while Microsoft.NET has
been designed from the scratch to support language independence and language
integration. Microsoft.NET covers the component development and integration in
much more d
etail than Java. The versioning policy of .NET is simply the best
implemented versioning solution in the software development history. Java has
got the support of industry giants like Sun, IBM, Apache and Oracle while the
Microsoft.NET is supported by gian
ts like Microsoft, Intel, and HP.

Why should one use MS.NET for software
development?

Well, most of the software development all over the world is done on and for
Microsoft Windows Operating System. Dot Net is now the standard software
development environ
ment for the Microsoft Windows operating system. It
dramatically simplifies the development of windows, web based, data access
applications, components, controls and web services. Dot net comes with
amazing features like XML configuration, reflection, and
attributes to ease the
overall software development life cycle. Finally, the dot net is supported by the
Microsoft Visual Studio Integrated Development Environment; the best IDE
available for any software development environment. Visual Studio .NET
(VS.NET
) supports all the areas of software development from project creation to
debugging and installation.

What are the shortcomings of MS.NET platform?

The foremost short coming of .NET platform is that it is still the propriety of
Microsoft. It is more coupl
ed with the Microsoft Windows operating system and is
implemented only on Microsoft Windows successfully. MS.NET desktop
applications can run only on Microsoft Windows, Web based applications and web
services can only be deployed on Microsoft Internet Info
rmation Server (IIS).
Since, dot net framework contains a lot of utilities, components, and framework
class libraries, the size of downloadable framework is quite large (25MB compared
to 5MB size of JVM). Not all types of applications can be written in .NE
T managed
applications, for example, you can’t write CLR or Operating System in your
managed applications. The managed .Net applications are somewhat slower to
start and run than the traditional Win32 applications. The compiled code of .Net
managed applica
tions is easier to de
-
compile back to the source code.

How true it is that .NET and Java programs are quite
in
-
efficient when compared to C++?

The startup of managed .NET and Java programs is definitely slower than the
traditional C++ programs as it invol
ves the hosting of CLR into managed
application process in .NET and starting the JVM in a new process in case of Java.
The execution also is a bit slower during the initial period of program execution as
the intermediate code is translated to the machine c
ode on the fly at runtime. But

-

12
-

as the program runs various parts repeatedly, the execution gets pace too. Since,
the CLR and JVM optimizes the code more efficiently than the static C++
compilers, the execution speed of the program may actually be faster af
ter
sometime of the program startup when most of the code is translated. Hence, in
the longer run, the .Net and Java based programs should not be in
-
efficient when
compared to C++. We used ‘should’ here as the actual performance depends on
the particular i
mplementation and implementation strategy.

What are XML Doc comments (comments start with
three slashes ///)?

The XML Doc comments are special kind of comments that can be recognized by
Document utility to automatically generate the documentation of your
methods,
types and regions.

Using COM components in .NET and How to add a
reference to a COM component?

The .NET does not encourage the use of COM component directly inside the
managed application! Although, the .NET framework contains utilities that enab
le
COM components to be used inside the .Net applications seamlessly. How it is
done? The .NET utilities like TlbImp generates the wrapper .NET assembly for the
COM component which provides the same calling interface to the client as
exposed by the COM com
ponent. Inside the wrapper methods, it calls the actual
methods of the COM component and returns the result back to the caller. The
generated wrapper .NET assembly is called the ‘Runtime Callable Wrapper’ or
RCW.

To use a COM component in your Visual Stud
io.NET project, you need to add a
reference of the COM component in the Reference node of the project node of the
solution inside the solution explorer window. The great thing about Visual
Studio.Net is that it allows you to add a reference to the COM comp
onent in
exactly the similar way as you add the reference to the .NET assembly. The Visual
Studio.NET automatically creates the runtime callable wrapper assembly for the
referenced COM component.

To add a reference to a COM component, right click the ‘Ref
erence’ node under
the project node inside the solution explorer and select the ‘Add Reference…’
option. It will show you a user interface screen where you browse for the target
COM component. When you have selected the component, press the ‘Select’
button

and then press OK. This will add a new reference node in the Reference
sub tree of the project. By selecting the added reference node, you can edit its
properties from the properties window.

Note:

The process of importing a COM component into .NET is cal
led ‘COM
interoperability with .NET’

What is .NET Framework and what are CLR, CTS and
CLS?

. NET is a software platform. It's a language
-
neutral environment for
developing .NET applications that can easily and securely operate within it.


-

13
-

The .NET Framewo
rk has two main components: the Common Language Runtime
(CLR) and the .NET Framework class library.

The Runtime can be considered an agent that manages code at execution time.
Thus providing core services such as memory management, thread management,
and
remoting. Also incorporating strict type safety, security and robustness.

The class library is a comprehensive collection of reusable types that you can use
to develop traditional command
-
line, WinForm (graphical user interface)
applications, Web Forms an
d XML Web services.

The .NET Framework provides a Runtime environment called the Common
Language Runtime or (CLR) that handles the execution of the code and provides
useful services for the implementation of the application. CLR takes care of code
managem
ent upon program execution and provides various services such as
memory management, thread management, security management and other
system services. The managed code targets CLR benefits by using useful features
such as cross
-
language integration, cross
-
l
anguage exception handling,
versioning, enhanced security, deployment support, and debugging.

Common Type System (CTS) describes how types are declared, used and
managed. CTS facilitates cross
-
language integration, type safety, and high
performance code e
xecution. The CLS is a specification that defines the rules to
support language integration. This is done in such a way, that programs written
in any language (.NET compliant) can interoperate with one another. This also
can take full advantage of inherita
nce, polymorphism, exceptions, and other
features.

What is MSIL / IL? What is JIT (Just In Time)?

When compiling the source code to managed code, the compiler translates the
source into Microsoft intermediate language (MSIL). This is a CPU
-
independent
set

of instructions that can efficiently be converted to native code. Microsoft
intermediate language (MSIL) is a translation used as the output of a number of
compilers. It is the input to a just
-
in
-
time (JIT) compiler. The Common Language
Runtime includes a

JIT compiler for the conversion of MSIL to native code.

Before Microsoft Intermediate Language (MSIL) can be executed it, must be
converted by the .NET Framework just
-
in
-
time (JIT) compiler to native code. This
is CPU
-
specific code that runs on the same
computer architecture as the JIT
compiler. Rather than using time and memory to convert all of the MSIL in a
portable executable (PE) file to native code. It converts the MSIL as needed whilst
executing, then caches the resulting native code so its accessi
ble for any
subsequent calls.

What is Code Access Security (CAS)? How does CAS
work? Who defines the CAS code groups?

Code Access Security (CAS) is part of the .NET security model. CAS determines
whether or not a piece of code is allowed to run and also w
hat resources to use.
For example, CAS will prevent malicious code from entering your system and
causing havoc.


-

14
-

The CAS security policy revolves around two key concepts
-

code groups and
permissions. Each .NET assembly is a member of a particular code gro
up and
each code group is granted the permissions specified in a named permission set.
An example: Using the default security policy, a control downloaded from a web
site belongs to the 'Zone
-

Internet' code group which complies to the
permissions defined

by the 'Internet' named permission set.

Microsoft defines some default policies but you can modify these and even create
your own. To view the code groups defined on your system; Run 'caspol' from the
command
-
line and checkout the different options on di
splay.

What is serialization in .NET and what are the ways
to control serialization?

Serialization is the process of converting an object into a stream of bytes. On the
other hand Deserialization is the process of creating an object from a stream of
bytes.

Serialization/Deserialization is used to transport or to persist objects.
Serialization can be defined as the process of storing the state of an object to a
storage medium. During this process, the public and private fields of the object
and the name of t
he class, including the assembly are converted to a stream of
bytes. Which is then written to a data stream. Upon the object's subsequent
deserialized, an exact clone of the original object is created.

Binary serialization preserves Type fidelity, which i
s useful for preserving the
state of an object between different invocations of an application. For example:
An object can be shared between different applications by serializing it to the
clipboard.

You can serialize an object to a stream, disk, memory,
over a network, and so
forth. Remoting uses serialization to pass objects "By Value" from one computer
or application domain to another. XML serialization serializes only public
properties and fields and does not preserve Type fidelity. This is useful when

you
want to provide or consume data without restricting the application that uses the
data.

As XML is an open standard, it is an attractive choice for sharing data across the
Web. SOAP is also an open standard, which makes it an attractive choice too.
Th
ere are two separate mechanisms provided by the .NET class library
-

XmlSerializer

and
SoapFormatter/BinaryFormatter
. Microsoft uses
XmlSerializer

for Web Services, and uses
SoapFormatter/BinaryFormatter

for remoting. Both are available for use in your own

code.

What is Active Directory? What namespace should I
use to use Active Directories?

Active Directory Service Interfaces (ADSI) is a programmatic interface for the
Microsoft Windows Active Directory. It enables your applications to interact with
differ
ent directories on a network using a single interface.

Visual Studio .NET and the .NET Framework make it easy to add ADSI
functionality with the
DirectoryEntry

and
DirectorySearcher

components.
Using ADSI you can create applications that perform common ad
ministrative
tasks, such as backing up databases, accessing printers and managing user
accounts. ADSI allows:


-

15
-

1) Log on once to work with diverse directories. The
DirectoryEntry

component
class provides username and password properties that can be entered

at Runtime
and are passed to the Active Directory object you are bound to.

2) Use of an Application
-
Programming Interface (API) to perform tasks on
multiple directory systems. This includes multi protocol support. The
DirectoryServices

namespace provides

the classes to perform most
administrative functions such as creating users.

3) Perform "Rich Querying" on directory systems. ADSI technology supports
searching for objects with two query dialects: SQL and LDAP.

4) Access and use a single or hierarchica
l tree structure for administering and
maintaining a diverse and complicated network.

5) Integrate directory information with databases such as

?
SQL Server. The
D
irectoryEntry

path may be used as an ADO.NET connection string.

Name space to be imported when working with Active Directories:

System.DirectoryServices


Can I use the Win32 API from a .NET Framework
program?

Using platform invoke it's possible. .NET Fra
mework programs can access native
code libraries by means of static DLL entry points.

Here is an example of C# calling the Win32 MessageBox function:



using System;

using System.Runtime.InteropServices;



class MainApp

{


[DllImport("user32.dll",

EntryPoint="MessageBox")]


public static extern int MessageBox(int hWnd, String


strMessage, String strCaption, uint uiType);




public static void Main()


{


MessageBox(0, "This is PInvoke in operation!",


".NET", 0 );


-

16
-


}

}

How

do I send an attachment in an email?

The following code shows how to add an attachment to an email.


Using System.IO;

Using System.Web.Mail;


MailAttachment ma=new MailAttachment("c:
\
sample.txt");

MailMessage mm=new MailMessage();

mm.To ="xyz@program
mersheaven.com";

mm.From="abc@yahoo.com";

mm.Body ="Attachment";

mm.Subject="Check out the attached text file";


mm.Attachments.Add(ma);


SmtpMail.SmtpServer="mail.programmersheaven.com";

SmtpMail.Send(mm);





-

17
-

C# .NET

What is C#?

C# (pronounced C
-
Sh
arp) is a new programming language introduced with the
Microsoft .NET framework and is no doubt the language of choice in .NET
environment. It was first created in the late 1990's as part of Microsoft’s
whole .NET strategy. It is a whole new language free
of backward compatibility
curse and a whole bunch of new, exciting and promising features. It is an Object
Oriented Programming language, which at its core, has similarities with Java,
C++ and VB.

In fact, C# combines the power & efficiency of C++, simple

& clean OO design of
Java, and code simplification of Visual Basic. Like Java, C# also does not allow
multiple inheritance and use of pointers (in safe and managed code) while it does
provide garbage memory collection at runtime, type and memory access ch
ecking.
But, contrary to java, C# keeps the different useful concepts of C++ like operator
overloading, enumerations, pre
-
processor directives, pointers (in unmanaged and
un
-
safe code), function pointers (in the form of delegates), also promises to have
te
mplate support (with the name of generics) in next versions. Like VB it also
supports the concepts of properties (context sensitive accessor to fields).

In addition to this, C# comes up with some new/exciting features like reflections,
attributes, marshal
ling, remoting, threads, streams, data access with ADO.NET,
etc. C# programming language is designed from the scratch keeping in mind the
Microsoft.Net environment. MS.Net (and thus C#) programs runs on top of the
Common Language Runtime (CLR), which provi
des the runtime support to them.

Sample C# Application


Using System

Class Sample

{

public static void main()

{

Console.WriteLine (“Hello World”)

}

}



What are Jagged Arrays in C#?

A special type of array is introduced in C#. A Jagged Array is an
array o
f an
array

in which the length of each array index can differ.

Example: A Jagged Array can be used is to create a table in which the lengths of
the rows are not same. This Array is declared using square brackets ( [ ] ) to
indicate each dimension.

The fo
llowing code demonstrates the creation of a two
-
dimensional jagged array.

Class Jagged

{

public static void Main()


-

18
-

{

int [][] jagged=new int [3][];

jagged[0]=mew int[4]

jagged[1]=mew int[3]

jagged[2]=mew int[5]

int I;

‘Storing values in first array

for (I
=0;I<4;I++)

jagged[0][I]=I;

‘Storing values in second array


for( I=0;I<3;I++)

jagged[1][I]=I;

‘Storing values in third array


for(I=0;I<5;I++)

jagged[2][I]=I;

‘Displaying values from first array


for (I=0;I<4;I++)

Console.WriteLine(jagged[0][I])

‘Displayi
ng values from second array


for (I=0;I<3;I++)

Console.WriteLine(jagged[1][I])


‘Displaying values from third array

for(I=0;I<5;I++)

Console.WriteLine(jagged[2][I])


}

}



-

19
-

What is the difference between "Value Types" and
"Reference Types"?

Many programming
languages provide built
-
in data types such as integers and
floating
-
point numbers. These are copied when they are passed in to arguments
i.e. they are passed "By Value". In .NET terms, these are called Value Types".

The RunTime supports two kinds of Value

Types:

1
Built
-
in value types


The .NET Framework defines built
-
in value types such as System.Int32 and
System.Boolean which correspond and are identical to primitive data types used
in programming languages.

2
User
-
defined value types


The language you

are using will provide functionality to define your own Value
Types. These user defined Types derive from System.ValueType. If you want to
define a Type representing a value that is a complex number (two floating
-
point
numbers), you might choose to define

it as a value type. Why? Because you can
pass the Value Type efficiently "By Value". If the Type you are defining could be
more efficiently passed "By Reference", you should define it as a class instead.
Variables of Reference Types are referred to as obj
ects. These store references to
the actual data.

The following are the Reference Types:



class



interface



delegate

This following are the "built
-
in" Reference Types:



object



string

ADO .NET

What is ADO.Net?

Most of the today’s applications need to int
eract with database systems to persist,
edit or view data. In .Net data access service is provided through ADO.Net
(ActiveX Data Object in Dot Net) components. ADO.Net is an object oriented
framework that allows you to interact with database systems. We us
ually interact
with database systems through SQL queries or stored procedures. ADO.Net
encapsulates our queries and commands to provide a uniform access to various
database management systems.


-

20
-


ADO.Net is a successor of ADO (ActiveX Data Object). The prime features of
ADO.Net are its disconnected data access architecture and XML integration.

What does it mean by disconnected data access
architecture
of ADO.Net?

ADO.Net introduces the concept of disconnected data architecture. In traditional
data access components, you make a connection to the database system and
then interact with it through SQL queries using the connection. The application
stays conn
ected to the DB system even when it is not using DB services. This
commonly wastes the valuable and expensive database resource as most of the
time applications only query and view the persistent data. ADO.Net solves this
problem by managing a local buffer

of persistent data called data set. Your
application automatically connects to the database server when it needs to pass
some query and then disconnects immediately after getting the result back and
storing it in dataset. This design of ADO.Net is called
disconnected data
architecture and is very much similar to the connection less services of http over
the internet. It should be noted that ADO.Net also provides the connection
oriented traditional data access services.

Traditional Data Access Architecture


ADO.Net Disconnected Data Access Architecture


Another important aspect of the disconnected architecture is that it maintains the
local repository of data in the dataset object. The dataset object stores the tables,

-

21
-

their relationship and different constraints. The user performs operations like
update, insert, delete to this dataset locally and finally the changed dataset is
stored in actual database as a batch when needed. This greatly reduces the
network traffic and results in the better performance.

What does it mean by connected data access
architecture of ADO.Net?

In the connected environment, it is your responsibility to open and close the
database connection. You first establish the database connection, perform the
interested operations to the database and when you are done, close the data
base
connection. All the changes are done directly to the database and no local
(memory) buffer is maintained.

What's the difference between accessing data with
dataset or data reader?

The dataset is generally used when you like to employ the disconnected

architecture of the ADO.Net. It reads the data into the local memory buffer and
perform the data operations (update, insert, delete) locally to this buffer.

The data reader, on the other hand, is directly connected to the database
management system. It p
asses all the queries to the database management
system, which executes them and returns the result back to the application.

Since no memory buffer is maintained by the data reader, it takes up fewer
resources and performs more efficiently with small numb
er of data operations.
The dataset, on the other hand is more efficient when large number of updates
are to be made to the database. All the updates are done in the local memory
and are updated to the database in a batch. Since database connection remains
open for the short time, the database management system does not get flooded
with the incoming requests.

What are the performance considerations when using
dataset?

Since no memory buffer is maintained by the data reader, it takes up fewer
resources and pe
rforms more efficiently with small number of data operations.
The dataset, on the other hand is more efficient when large number of updates
are to be made to the database. All the updates are done in the local memory
and are updated to the database in a ba
tch. Since database connection remains
open for the short time, the database management system does not get flooded
with the incoming requests.

However, since the dataset stores the records in the local buffer in the
hierarchical form, it does take up mor
e resources and may affect the overall
performance of the application.


-

22
-

How to select dataset or data reader?

The data reader is more useful when you need to work with large number of
tables, database in non
-
uniform pattern and you need not execute the la
rge no.
of queries on few particular table.

When you need to work on fewer no. of tables and most of the time you need to
execute queries on these fewer tables, you should go for the dataset.

It also depends on the nature of application. If multiple user
s are using the
database and the database needs to be updated every time, you must not use
the dataset. For this, .Net provides the connection oriented architecture. But in
the scenarios where instant update of database is not required, dataset provides
op
timal performance by making the changes locally and connecting to database
later to update a whole batch of data. This also reduces the network bandwidth if
the database is accessed through network.

Disconnected data access is suited most to read only ser
vices. On the down side,
disconnected data access architecture is not designed to be used in the
networked environment where multiple users are updating data simultaneously
and each of them needs to be aware of current state of database at any time
(e.g.,
Airline Reservation System).

How XML is supported in ADO.Net?

The dataset is represented in the memory as an XML document. You can fill the
dataset by XML and can also get the result in the form of XML. Since XML is an
international and widely accepted st
andard, you can read the data using the
ADO.Net in the XML form and pass it to other applications using Web Service.
These data consuming application need not be the essentially Dot Net based.
They may be written with Java, C++ or any other programming lan
guage and
running on any platform.

What are the different components of ADO.Net?

The famous diagram of the ADO.Net architecture and its components is presented
in the figure below:


-

23
-


All generic classes for data access are contained in the System.Data namespace.
A short description of the core classes of ADO.Net is presented below:

Class

Description

DataSet

The DataSet is a local buffer of tables

or a collection of disconnected
record sets

DataTable

DataTable is used to contain the data in tabular form using rows and
columns. DataRow Represents a single record or row in DataTable

DataRow

Represents a single record or row in DataTable

DataC
olumn

Represents a column or field of DataTable

DataRelation

Represents the relationship between different tables in a data set.

Constraint

Represents the constraints or limitations that apply to a particular field
or column.

ADO.Net also contains

some database specific classes. This means that different
database system providers may provide classes (or drivers) optimized for their
particular database system. The provider for such classes are called the Dot Net
Framework Data Providers. Microsoft i
tself has provided the specialized and
optimized classes for their SQL server database system. The name of these
classes start with ‘Sql’ and these are contained in System.Data.SqlClient
namespace. Similarly, Oracle has also provided its classes (driver) o
ptimized for
Oracle DB System. Microsoft has also provided the general classes which can
connect your application to any OLE supported database server. The name of
these classes start with ‘OleDb’ and these are contained in System.Data.OleDb
namespace. In
fact, you can use OleDb classes to connect to SQL server or Oracle
database but using the database specific classes generally provides optimized
performance.

The core objects that make up a data provider are:

Class

Description

Connection

Represents a

connection to the database system

Command

Represents SQL query or command to be executed at the database

-

24
-

management system

DataAdapter

A class that connects to the database system, fetch the record and fill the
dataset. It contains four different co
mmands to perform database
operations; Select, Update, Insert, Delete.

DataReader

A stream that reads data from the database in connected design

Parameter

Represents a parameter to a stored procedure



What is a dataset?

A dataset is the local repo
sitory of the data used to store the tables and
disconnected record set. When using disconnected architecture, all the updates
are made locally to dataset and then the updates are performed to the database
as a batch.

What is a data adapter?

A data adapte
r is the component that exists between the local repository
(dataset) and the physical database. It contains the four different commands
(SELECT, INSERT, UPDATE and DELETE). It uses these commands to fetch the
data from the DB and fill into the dataset and

to perform updates done in the
dataset to the physical database. It is the data adapter that is responsible for
opening and closing the database connection and communicates with the dataset.

What is a database connection?

A database connection represents

a communication channel between you
application and database management system (DBMS). The application uses this
connection to pass the commands and queries to the database and obtain the
results of the operations from the database.

What is a database co
mmand?

A database command specifies which particular action you want to perform to the
database. The commands are in the form of SQL (Structured Query Language).
There are four basic SQL statements that can be passed to the database.

SQL SELECT Statement

This query is used to select certain columns of certain records from a database
table.

SELECT * from emp

selects all the fields of all the records from the table name ‘emp’

SELECT empno, ename from emp

selects the fields empno and ename of all records fr
om the table name ‘emp’

SELECT * from emp where empno < 100


-

25
-

selects all those records from the table name ‘emp’ that have the value of the
field empno less than 100

SELECT * from article, author where article.authorId = author.authorId

selects all those
records from the table name ‘article’ and ‘author’ that have same
value of the field authorId

SQL INSERT Statement

This query is used to insert a record to a database table.

INSERT INTO emp(empno, ename) values(101, ‘John Guttag’)

inserts a record to emp

table and set its empno field to 101 and its ename field to
‘John Guttag’

SQL UPDATE Statement

This query is used to edit an already existing record in a database table.

UPDATE emp SET ename =‘Eric Gamma’ WHERE empno = 101

updates the record whose empno

field is 101 by setting its ename field to ‘Eric
Gamma’

SQL DELETE Statement

This query is used to delete the existing record(s) from the database table

DELETE FROM emp WHERE empno = 101

deletes the record whose empno field is 101 from the emp table

Wh
at is a data reader?

The data reader is a component that reads the data from the database
management system and provides it to the application. The data reader works in
the connected manner; it reads a record from the DB, pass it to the application,
then r
eads another and so on.

How do different components of ADO.Net interact
with each other in disconnected architecture?

The Data Adapter contains in it the Command and Connection object. It uses the
connection object to connect to the database, execute the
containing command,
fetch the result and update the DataSet.


-

26
-


How do different components of ADO.Net interact
with each other in connected architect
ure?

Here, the Command object contains the Connection object. The Command object
uses the containing connection (that must be opened) to execute the SQL query
and if the SQL statement is SELECT, returns the DataReader object. The data
reader object is the
stream to the database which reads the resulting records
from the DB and passes them to the application


What does it mean by Dot Net Framework Data

Provider?

Dot Net Framework Data Provider is a set of classes that establishes the database
communication between an application and the database management system
based on the standards of ADO.Net framework. Different data providers provide
specialized a
nd optimized connectivity to particular database management
system or to a particular class of DBMS. For example, the MS SQL Server data
provider provides the optimized connectivity between dot net application and MS
SQL Server DBMS while the OLEDB data pr
ovider provides the uniform
connectivity between dot net application and the OLEDB databases.

What are the core objects that make up a dot net
framework data provider?

The core objects that make up a data provider are:

Class

Description

Connection

Re
presents a connection to the database system

Command

Represents SQL query or command to be executed at the database
management system

DataAdapter

A class that connects to the database system, fetch the record and fill the

-

27
-

dataset. It contains four di
fferent commands to perform database
operations; Select, Update, Insert, Delete.

DataReader

A stream that reads data from the database in connected design

Parameter

Represents a parameter to a stored procedure



What are the standard dot net framew
ork data
providers that are shipped with the Dot Net
Framework 1.1?

The Dot Net Framework 1.1 is shipped with four different data providers:



Dot Net Framework data provider for Microsoft SQL Server DBMS



Dot Net Framework data provider for Oracle DBMS (av
ailable only in
Framework 1.1)



Dot Net Framework data provider for OLEDB supporting DBMS



Dot Net Framework data provider for ODBC supporting data sources
(available only in Framework 1.1)

Why should one use a specialized data provider when
the data can
be accessed with general data providers?

The specialized data providers (e.g., SQL Server and Oracle) are built specially for
a particular kind of DBMS and works much more efficiently than the general data
providers (e.g., OLEDB and ODBC). In practice, the

specialized data providers are
many times efficient than the general data providers.

What is the Dot Net Framework data provider for SQL
Server?

The dot net framework data provider for SQL Server is the optimized data
provider for Microsoft SQL Server 7
or later. It is recommended to use SQL
Server data provider to access the SQL Server DB than general provider like
OLEDB. The classes for this provider are present in the System.Data.SqlClient
namespace.

What is the Dot Net Framework data provider for
Ora
cle?

The dot net framework data provider for Oracle is the optimized data provider for
Oracle DBMS. It is recommended to use Oracle data provider to access the Oracle
DB than general provider like OLEDB. It supports the Oracle Client version 8.1.7
and late
r. The classes for this provider are present in the
System.Data.OracleClient namespace. This provider is included in the .Net
framework 1.1 and was not available in the Dot Net framework 1.0.

What is the Dot Net Framework data provider for
OLEDB?


-

28
-

The dot
net framework data provider for OLEDB provides connectivity with the
OLEDB supported database management systems. It is the recommended middle
tier for the SQL Server 6.5 or earlier and Microsoft Access Database. It is a
general data provider. You can also

use it to connect with the SQL Server or
Oracle Database Management Systems. The classes for this provider are present
in the System.Data.OleDBClient namespace.

What is the Dot Net Framework data provider for
ODBC?

The dot net framework data provider for

ODBC provides connectivity with the
ODBC supported database management systems and data sources. It is a general
data provider. You can also use it to connect with the SQL Server or Oracle
Database Management Systems. The classes for this provider are pre
sent in the
System.Data.ODBCClient namespace. This provider is included in the .Net
framework 1.1 and was not available in the Dot Net framework 1.0.

What are the basic steps involved in data access with
ADO.Net in disconnected environment?

Data access us
ing ADO.Net involves the following steps:



Defining the connection string for the database server



Defining the connection (SqlConnection, OleDbConnection, etc) to the
database using the connection string



Defining the command (SqlCommand, OleDbCommand, et
c) or command
string that contains the query



Defining the data adapter (SqlDataAdapter, OleDbDataAdapter, etc) using
the command string and the connection object



Creating a new DataSet object



If the command is SELECT, filling the dataset object with the

result of the
query through the data adapter



Reading the records from the DataTables in the datasets using the
DataRow and DataColumn objects



If the command is UPDATE, INSERT or DELETE, then updating the dataset
through the data adapter



Accepting to sa
ve the changes in the dataset to the database

Which namespaces I need to add to my project for
each of the standard data provider?

You need to add following namespaces for the specified data providers:

Data Provider

Namespace

MS SQL Server

System.Data.S
qlClient

Oracle Database

System.Data.OracleClient

OLE DB Databases

System.Data.OleDBClient

ODBC Data Sources

System.Data.ODBCClient




-

29
-

How do I define a connection string for the database
server?

For MS SQL Server, used with the SQL Server data provider
, we can write the
connection string like:

C# Version

// for Sql Server

string connectionString = "server=P
-
III; database=programmersheaven;" +_

"uid=sa; pwd=;";

VB.Net Version

' for Sql Server

Dim connectionString As String = "server=P
-
III; database=prog
rammersheaven;"
+ _ "uid=sa; pwd=;"

First of all we have defined the instance name of the server, which is P
-
III on my
system. Next we defined the name of the database, user id (uid) and password
(pwd). Since my SQL server doesn't have a password for the

System
Administrator (sa) user, I have left it blank in the connection string. (Yes I know
this is very dangerous and is really a bad practice
-

never, ever use a blank
password on a system that is accessible over a network)

For Oracle Database Server, u
sed with the Oracle data provider, we can write the
connection string like:

C# Version

string connectionString = "Data Source=Oracle8i;User Id=username;" +


"Password=pwd; Integrated Security=no;";

VB.Net Version

Dim connectionString As String = "Data S
ource=Oracle8i;User Id=username;" +
_

"Password=pwd; Integrated Security=no;"

For MS Access Database, used with the OLE DB data provider, we can write the
connection string like:

C# Version

// for MS Access

string connectionString = "provider=Microsoft.Je
t.OLEDB.4.0;" +

"data source = c:
\
\
programmersheaven.mdb";

VB.Net Version

' for MS Access

Dim connectionString As String = "provider=Microsoft.Jet.OLEDB.4.0;" + _






"data source =
c:
\
programmersheaven.mdb"

First we have defined the provider of the ac
cess database. Then we have defined
the data source which is the address of the target database.

For MS SQL Server, used with the ODBC data provider, we can write the
connection string like:


-

30
-

C# Version

string connectionString = "Driver={SQL
Server};Serve
r=FARAZ;Database=pubs;Uid=sa;Pwd=;";

VB.Net Version

Dim connectionString As String = "Driver={SQL
Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;"



How do I find the connection string for the database
server?

Usually the connection string options are prov
ided in the documentation, you can
also find the connection strings on the internet. A good website for the
connections strings is
http://www.connectionstrings.com


How do I define the connection to database?

A connection is defined using the connection string. The Connection object is used
by the data adapter or data reader to connect to and disconn
ect from the
database. For SQL Server used with SQL Server data provider, the connection is
created like this:

C# Version

SqlConnection conn = new SqlConnection(connectionString);

VB.Net Version

Dim conn As New SqlConnection(connectionString)

For Oracle D
atabase Server used with Oracle data provider, the connection is
created like this:

C# Version

OracleConnection conn = new OracleConnection(connectionString);

VB.Net Version

Dim conn As New OracleConnection(connectionString)

For OLE DB provider, the conne
ction is created like this:

C# Version

OleDbConnection conn = new OleDbConnection(connectionString);

VB.Net Version

Dim conn As New OleDbConnection(connectionString)

For ODBC data provider, the connection is created like this:

C# Version

OdbcConnection c
onn = new OdbcConnection(connectionString);


-

31

-

VB.Net Version

Dim conn As New OdbcConnection(connectionString)

Here we have passed the connection string to the constructor of the connection
object.

How do I create a command and supply the SQL query
to ADO.Ne
t? (Command object and command string)

First of all, you create a command object (SqlCommand, OracleCommand,
OleDbCommand, OdbcCommand) using the connection object (SqlConnection,
OracleConnection, OleDbConnection, OdbcConnection) and set its CommandText
p
roperty to the SQL query to execute.

C# Version

OdbcCommand cmd = conn.CreateCommand();

cmd.CommandText = "select * from authors";

VB.Net Version

Dim cmd As OdbcCommand

cmd = conn.CreateCommand()

cmd.CommandText = "select * from authors"



How do I defin
e a data adapter?

The data adapter stores your command (query) and connection and using these
connect to the database when asked, fetch the result of query and store it in the
local dataset.

The DataAdapter class (SqlDataAdapter, OracleDataAdapter, OleDbD
ataAdapter,
OdbcDataAdapter) may be instantiated in three ways:

1.

by supplying the command string (SQL Select command) and connection
string

2.

by supplying the command string (SQL Select command) and a connection
object

3.

by supplying the command object (SqlC
ommand, OracleCommand,
OleDbCommand, OdbcCommand)

For example, with SQL Server, the data adapter is created as

C# Version

// for Sql Server

SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, conn);

VB.Net Version

Dim da As New SqlDataAdapter(
commandString, conn)

Here we have created a new instance of data adapter and supplied it command
string and connection object in the constructor call.


-

32
-

For Access, the data adapter is created like

C# Version

// for MS Access

OleDbDataAdapter dataAdapter =

new OleDbDataAdapter(commandString,
connectionString);

VB.Net Version

Dim da As New OleDbDataAdapter(commandString, connectionString)

Here we have created a new instance of data adapter and supplied it command
string and connection string in the construct
or call.

How do I get the result of my command and fill it to
the dataset?

DataSet is a local and offline container of the data. The DataSet object is created
simply like

C# Version

DataSet ds = new DataSet();

VB.Net Version

Dim ds As New DataSet()

Now w
e need to fill the DataSet with the result of the query. We will use the
dataAdapter object for this purpose and call its Fill() method. This is the step
where data adapter connects to the physical database and fetch the result of the
query.

C# Version

da
taAdapter.Fill(ds, "prog");

VB.Net Version

da.Fill(ds, "prog")

Here we have called the Fill() method of dataAdapter object. We have supplied it
the dataset to fill and the name of the table (DataTable) in which the result of
query is filled.

This is all w
e needed to connect and fetch the data from the database. Now the
result of query is stored in the dataset object in the prog table which is an
instance of DataTable. We can get a reference to this table by using the indexer
property of dataset object’s Ta
bles collection

C# Version

DataTable dataTable = ds.Tables["prog"];

VB.Net Version

Dim dataTable As DataTable

dt = ds.Tables("prog")


-

33
-

The indexer we have used takes the name of the table in dataset and returns the
corresponding DataTable object. Now we can

use the tables Rows and Columns
collection to access the data in the table.

How do I read records from the data tables?

You can read the records from the data table using its Rows collection. With the
Rows collection, you need to specify the row number a
nd column name or
number to access a particular field of the specified row. For example, if we have
read the ‘Student’ table in our data table, we can access its individual fields as:

C# Version

DataTable dt = ds.Tables["student"];

string stId = dt.Rows[0
]["StudentID"].ToString();

string stName = dt.Rows[0]["StudentName"].ToString();

string stDateOfBirth = dt.Rows[0][2].ToString();

VB.Net Version

Dim dt As DataTable

dt = ds.Tables("student")


Dim stId As String

stId = dt.Rows(0)("StudentID").ToString()

Di
m stName As String

stName = dt.Rows(0)("StudentName").ToString()

Dim stDateOfBirth As String

stDateOfBirth = dt.Rows(0)(2).ToString()

Here we have retrieved various fields of the first record of the student table read
in the dataset. As you can see, we can

either specify the column name in string
format or we can specify the column number in integer format. Also note that the
field value is returned in the form of Object, so we need to convert it to the string
before using it. Similarly, you need to cast va
riables of other data types before
using them.

C# Version

int stAge = int.Parse(dt.Rows(0)("Age").ToString());

VB.Net Version

Dim stage As Integer

stAge = Integer.Parse(dt.Rows(0)("Age").ToString())



How do I save the changes, made in the dataset, to
the

database?


-

34
-

We update the dataset and table by calling the Update method of the data
adapter. This saves the changes in the local repository of data: dataset. To save
the changed rows and tables to the physical database, we call the
AcceptChanges() method o
f the DataSet class.

C# Version

dataAdapter.Update(ds, "student");

ds.AcceptChanges();

VB.Net Version

da.Update(ds, "student")

ds.AcceptChanges()

Here ‘da’ is the reference to the data adapter object, ‘ds’ is the reference to the
dataset, and ‘student’ is

the name of table we want to update.

Note: For the next four FAQs, we will demonstrate sample applications. For these
applications to work, you need following database and tables created in your
database server. A database named ‘ProgrammersHeaven’ is cr
eated. It has a
table named ‘Article’. The fields of the table ‘Article’ are

Field Name

Type

Description

artId (Primary Key)

Integer

The unique identity of article

Title

String

The title of the article

Topic

String

Topic or Series name of the article l
ike ‘Multithreading
in Java’ or ‘C# School’

authorId (Foreign
Key)

Integer

Unique identity of author

Lines

Integer

No. of lines in the article

dateOfPublishing

Date

Date of publishing of the article

The ‘ProgrammersHeaven’ database also contains a tabl
e named ‘Author’ with the
following fields

Field Name

Type

Description

authorId (Primary Key)

Integer

The unique identity of author

name

String

Name of author



How do I make my first “Hello, ADO.Net” Application
in C#?

Let’s now create a demonstration

application for accessing data. First create a
windows form application and make the layout like the following snapshot


-

35
-


We have set the Name prope
rty of the text boxes (from top to bottom) as
txtArticleID, txtArticleTitle, txtArticleTopic, txtAuthorId, txtAuthorName,
txtNumOfLines and txtDateOfPublishing. Also we have set the ReadOnly property
of all the text boxes to true as don’t want the user of
application to change the
text. The names of buttons (from top to bottom) are btnLoadTable, btnNext and
btnPrevious. Initially we have disabled the Next and Previous buttons (by setting
their Enabled property to false).

We have also defined three variable
s in the Form class as

public class ADOForm : System.Windows.Forms.Form

{

DataTable dataTable;

int currRec=0;

int totalRec=0;

The dataTable object will be used to reference the table returned as a result of
the query. The currRec and totalRec integer vari
ables are used to keep track of
the current record and total records in the table.

Loading table

For LoadTable button, we have written the following event handler

private void btnLoadTable_Click(object sender, System.EventArgs e)

{


// for Sql Server


st
ring connectionString =

"server=P
-
III;
database=programmersheaven;" +







"uid=sa; pwd=;";



-

36
-


// for MS Access


/*string connectionString =

"provider=Microsoft.Jet.OLEDB.4.0;" +







"data source =
c:
\
\
programmersheaven.mdb";*/



// for Sql Server


SqlC
onnection conn = new SqlConnection(connectionString);



// for MS Access


//OleDbConnection conn = new OleDbConnection(connectionString);



string commandString = "SELECT " +







"artId, title, topic, " +







"article.authorId as
authorId, " +







"name, lines,
dateOfPublishing " +






"FROM " +







"article, author " +






"WHERE " +







"author.authorId =
article.authorId";



// for Sql Server


SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString,
conn);



// for MS Access


//OleDbDataAdapter dataAdapter = new OleDbDataAdapter(commandString,
conn);



DataSet ds = new DataSet();


-

37
-


dataAdapter.Fill(ds, "prog");



dataTable = ds.Tables["prog"];


currRec = 0;


totalRec = dataTable.Rows.Count;



FillControls();



btnNext.Enabled =
true;


btnPrevious.Enabled = true;

}

In the start, we have created the connection, data adapter and filled the dataset
object which we have discussed earlier. It should be noted that we have
commented the code for OleDb provider (MS
-
Access) and are using t
he SQL
Server specific code. If you like to use Access database, you can simply comment
the SQL server code and de
-
comment the Access code.

Next we assigned the data table resulted from query to the dataTable object
which we declared at class level, assig
ned zero to currRec variable and assigned
the number of rows in the dataTable to totalRec variable



dataTable = ds.Tables["prog"];

currRec = 0;

totalRec = dataTable.Rows.Count;

Then we called the FillControls() method which fills the controls (text boxes
) on
the form with the current record of table “prog”. Finally we have enabled the Next
and Previous Button

Filling the controls on the Form

The FillControls() method in our program fills the controls on the form with the
current record of the data table.

The method is defined as

private void FillControls()

{

txtArticleId.Text = dataTable.Rows[currRec]["artId"].ToString();

txtArticleTitle.Text = dataTable.Rows[currRec]["title"].ToString();

txtArticleTopic.Text = dataTable.Rows[currRec]["topic"].ToString()
;

txtAuthorId.Text = dataTable.Rows[currRec]["authorId"].ToString();

txtAuthorName.Text = dataTable.Rows[currRec]["name"].ToString();

txtNumOfLines.Text = dataTable.Rows[currRec]["lines"].ToString();

txtDateOfPublishing.Text =
dataTable.Rows[currRec]["date
OfPublishing"].ToString();

}


-

38
-

Here we have set the Text property of the text boxes to the string values of the
corresponding fields of current record. We have used the Rows collection of the
dataTable and using its indexer we have got the DataRow representi
ng the
current record. We then accessed the indexer property of this DataRow using the
column name to get the data in the respective field. If this explanation looks
weird to you, you can simplify the above statements as



DataRow row = dataTable.Rows[cur
rRec]; // getting current row

object data = row["artId"];


// getting data in the artId field

string strData = data.ToString();

// converting to string

txtArticleId.Text = strData;


// display in the text box

which is equivalent to

txtArticleId.Text = d
ataTable.Rows[currRec]["artId"].ToString();

Hence when you start the application and press the LoadTable button, you will
see the following output



How do I make my first “Hello, ADO.Net” Application
in VB.Net?

Let's now create a demonstration application for accessing data. First create a
windows form application and make the layout shown the following snapshot.


-

39
-


We have set the Name property of the text boxes (from top to bottom) as
txtArticleID, txtArticleTitle, txtArticleTopic, txtAuthorId, txtAuthorName,
txtNumOfLines and txtDateOfPublishin
g. Also we have set the ReadOnly property
of all the text boxes to true as don't want the user to change the text. The names
of the buttons (from top to bottom) are btnLoadTable, btnNext and btnPrevious.
Initially we have disabled the Next and Previous but
tons (by setting their Enabled
property to false). We have also defined three variables in the Form class:



Public Class ADOForm

Inherits System.Windows.Forms.Form ' Private global members to be used in
various methods

Private dataTable As dataTa
ble

Private currRec As Integer = 0

Private totalRec As Integer = 0


...

The dataTable object will be used to reference the table returned as a result of
the query. The currRec and totalRec integer variables are used to keep track of
the current re
cord and total number of records in the table. Loading table For the
LoadTable button, we have written the following event handler





Private Sub btnLoadTable_Click(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles btnLoadTable.Click



' for Sql Server


Dim connectionString As String = "server=P
-
III;
database=programmersheaven;" + _


"uid=sa; pwd=;"



' for MS Access


-

40
-


'Dim connectionString As String =
"provider=Microsoft.
Jet.OLEDB.4.0;" +


' "data source =
c:
\
\
programmersheaven.mdb"



' for Sql Server


Dim conn As New SqlConnection(connectionString)



' for MS Access


'Dim conn As New OleDbConnection(connectionS
tring)



Dim commandString As String = "SELECT " + _


"artId, title, topic, " + _


"article.authorId as authorId, " + _


"name, lines, dateOfPublishing " + _



"FROM " + _


"article, author " + _


"WHERE " + _


"author.authorId = article.authorId"



' for Sql Server


Dim dataAdapte
r As New SqlDataAdapter(commandString, conn)



' for MS Access


'Dim dataAdapter As New OleDbDataAdapter(commandString, conn)



Dim ds As New DataSet()


dataAdapter.Fill(ds, "prog")



dataTable = ds.Tables("prog")


-

41
-



currRec = 0


totalRec = dataTable.Rows.Count



FillControls()



btnNext.Enabled = True


btnPrevious.Enabled = True



End Sub





First we created the connection, data adapter and filled the dataset object, all of
which we ha
ve discussed earlier. It should be noted that we have commented out
the code for the OleDb provider (MS
-
Access) and are using SQL Server specific
code. If you would like to use an Access databases, you can simply comment the
SQL server code out and de
-
comm
ent the Access code. Next, we have assigned
the data table resulting from the query to the dataTable object which we declared
at the class level, assigned zero to currRec variable and assigned the number of
rows in the dataTable to the totalRec variable:



dataTable=ds.Tables("prog")currRec=0totalRec=dataTable.Rows.Count

Then we called the FillControls() method, which fills the controls (text boxes) on
the form with the current record of the table "prog". Finally we enabled the Next
and Previous Buttons.

Filling the controls on the Form

The FillControls() method in our program fills the controls on the form with the
current record of the data table. The method is defined as follows:

Private Sub FillControls()

txtArticleId.Text=dataTable.Rows(currRec)("ar
tId").ToString()

txtArticleTitle.Text=dataTable.Rows(currRec)("title").ToString()

txtArticleTopic.Text=dataTable.Rows(currRec)("topic").ToString()