You are on page 1of 168

.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 ommon !anguage "untime # !"$, which provides the abstraction of e%ecution environment #&hysical machine and 'perating (ystem$ and manages the overall e%ecution of any of the .NET based program.

)ith dot NET, Microsoft introduces a completely new architecture for )indows applications #)inForm$, Data *ccess #*D'.NET$, )eb *pplications #*(&.NET$, )indows components #*ssemblies$, Distributed *pplications #.NET remoting$, and above all the +M! based )eb (ervices. The famous figure for the representation of dot net is presented below,

What is the .NET framework?


The .NET framework is a collection of all the tools and utilities re-uired to e%ecute the .NET managed applications on a particular platform. The M(.NET framework includes the standard compilers # ., /0.NET, 1., 22.NET, 1script.NET$, various utilities like #caspol, ngen, installutil, tlbimp, sn, asmreg, ildasm, etc$, runtime environment # !"$, garbage collector, security manager, thread manager, assembly loader, 3ust in time compilers, and the standard framework or base class libraries. 4t is important to reali5e that while the implementation of .Net applications is platform independent6 the implementation of .NET framework is platform specific. 4n fact, it is this particular specific implementation of the .NET framework that makes the managed .NET applications platform independent.

What is the VB.NET and

! lan"#a"e comparisons?

/0.NET and . both are integral part of the .NET framework. 0oth of the languages have a lot of similarities in language constructs and language design with minor differences in the synta%. . is more like 22 and 1ava in its synta% while /0.NET lends its synta% from /07 a great deal6 although /0.NET can not be seen as the successor of /isual 0asic at the level of overall language design and the vision of its creators. The general conception is that most of the /07 developers will upgrade to /0.NET while developers coming from 1ava or 22 to .NET are likely to go for .. (ince web developers for )indows using *(& are familiar with /0 and /0 (cripts, therefore, most of the web development with *(&.NET at the start is likely to be

dominated by /0.NET6 but after sometime . will be able to attract at least half of these developers. 8eeping technical side away, 22 and thus . developers are generally paid more than those of /0 developers. (o, this might also be the factor for making . the language of choice on .NET framework.

What is the difference $etween onsole% Windows% We$ applications and We$ ser&ices?
onsole applications are light weight programs run inside the command prompt #D'($ window. They are commonly used for test applications. )indows *pplications are form based standard )indows desktop applications for common day to day tasks. Microsoft word is an e%ample of a )indows application. )eb applications are programs that used to run inside some web server #e.g., 44($ to fulfill the user re-uests over the http. * typical e%ample of web application is 9otmail and :oogle. )eb services are web applications that provide services to other applications over the internet. :oogle search engine;s web service, e.g., allows other applications to delegate the task of searching over the internet to :oogle web service and use the result produced by it in their own applications.

What is meant $' lan"#a"e interopera$ilit' and lan"#a"e inte"ration?


&rior 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 e%ample, an algorithm implemented in &erl programming language can not be reused in the programs written in the 22. *t )indows platform, Microsoft introduced the standards for 'M # omponent 'b3ect Model$ which allows components written in one programming language to be used in other programming language. 4n 1ava, 1N4 #1ava Native 4nterface$ is presented to use<up the code written in non<1ava languages into 1ava programs. 0ut both the standards # 'M and 1N4$ are too comple% 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 e%tend the functionality of the components. 4n Microsoft.Net, the code written in any programming language is compiled to the same 4ntermediate !anguage #Microsoft 4ntermediate !anguage < M(4! or ommon 4ntermediate !anguage = 4!$ and to same component standard #assembly$. 9ence, it is possible for developers to employ the language interoperability by using and e%tending the solution implemented by other developers which might be using different programming language provided developers at both end are using.Net compliant programming languages.

What is a .Net Assem$l'?


The .NET assembly is the standard for components developed with the Microsoft.NET. Dot NET assemblies may or may not be e%ecutable, i.e., they might e%ist as the e%ecutable #.e%e$ file or dynamic link library #D!!$ file. *ll the .NET assemblies contain the definition of types, versioning information for the type, meta<data, and manifest. The designers of .NET have worked a lot on the component #assembly$ resolution.

There are two kind of assemblies in .NET6 private and shared. &rivate assemblies are simple and copied with each calling assemblies in the calling assemblies folder. (hared assemblies #also called strong named assemblies$ are copied to a single location #usually the :lobal assembly cache$. For all calling assemblies within the same application, the same copy of the shared assembly is used from its original location. 9ence, shared assemblies 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 impossible for two different assemblies with the same name or for two similar assemblies with different version to mi% with each other. *n assembly can be a single file or it may consist of the multiple files. 4n case of multi<file, there is one master module containing the manifest while other assemblies e%ist as non<manifest modules. * module in .NET is a sub part of a multi<file .NET assembly. *ssembly is one of the most interesting and e%tremely useful areas of .NET architecture along with reflections and attributes, but unfortunately very few people take interest in learning such theoretical looking topics.

What are the differences $etween a .NET Assem$l'% a Windows (LL and a )M omponent?
* )indows D!! contains library code to be used by any program running on )indows. * D!! may contain either structured or ob3ect oriented libraries. 'M # omponent 'b3ect Model$ is the component model based on the ob3ect oriented design, which means that the components represented by the 'M component e%ists in the form of classes and ob3ects implementing a standard specification defined by 'M. 'M components can be used by any program running on )indows 'perating (ystem6 be it is written with /0, 22, 1ava or even some .NET compliant language like . and /0.NET. Dot NET assembly is the component standard specified by the .NET. 9ence, dot net assemblies are understandable to only Microsoft.NET and can be used only in .NET managed applications.

What are the differences $etween a .NET Assem$l'% a Windows (LL and a )M omponent?
* )indows D!! contains library code to be used by any program running on )indows. * D!! may contain either structured or ob3ect oriented libraries. 'M # omponent 'b3ect Model$ is the component model based on the ob3ect oriented design, which means that the components represented by the 'M component e%ists in the form of classes and ob3ects implementing a standard specification defined by 'M. 'M components can be used by any program running on )indows 'perating (ystem6 be it is written with /0, 22, 1ava or even some .NET compliant language like . and /0.NET. Dot NET assembly is the component standard specified by the .NET. 9ence, dot net assemblies are understandable to only Microsoft.NET and can be used only in .NET managed applications.

What is the difference $etween an e*ec#ta$le assem$l' and a class li$rar'?


*n e%ecutable assembly e%ists as the .e%e file while a class library e%ists as the .dll file. E%ecutable assembly represent e%ecutable applications having some entry #e.g., Main#$ method in .$. * class library, on the other hand, contains components and libraries to be used inside various applications. * lass library can not be e%ecuted and thus it does not have any entry point.

What does one need to $#ild or e*ec#te .NET applications?


To e%ecute a standalone .NET application #)indows or onsole application$, one needs to first compile all its constituent assemblies and modules including the e%ecutable assembly. 'nce, the constituent assemblies are compiled, one needs to make sure that the target system contains the .NET framework. The application can now be e%ecuted by running its e%ecutable assembly #the .e%e file$. The e%ecutable assembly #.e%e$ is a )in>? e%ecutable that hosts the .Net !" # ommon !anguage "untime$, which e%ists as a 'M component, in its process space and initiali5es it. 'nce the !" is hosted and initiali5ed, the starting point of the .NET e%ecutable assembly is passed to the hosted !" which starts the e%ecution of the program by translating and e%ecuting the parts of the program code.

What does it mean $' mana"ed code?


0y managed code, it means that the complete life cycle and e%ecution is managed by the .NET ommon !anguage "untime # !"$. The .NET !" manages the memory on behalf of the managed code, performs garbage collection on the managed heap, perform assembly validation and assembly #component$ resolution on behalf of the program. The !" also maintains the security constraints applied to the managed code.

What is meant $' #n+safe code?


0y un<safe code, it means that the managed program can access the memory address using pointers. There are two points to remember here6 @n<safe code is different from un<managed as it is still managed by the !" Aou still can not perform pointer arithmetic in un<safe code.

What is the difference $etween ,nmana"ed and ,nsafe code?


@n<managed code runs outside the ommon !anguage "untime # !"$ control while the unsafe code runs inside the !";s control. 0oth un<safe and un< managed codes may use pointers and direct memory addresses.

What a$o#t the M-.NET standardi.ation?

Microsoft has secured certification for both . and !4 from E M* and 4('B4E as 4ndustry standards. This is a very important step for Microsoft and .Net platform because this enhances the credibility of the newer .Net platform and allures a larger portion of technology industry into adopting .Net as their development platform. (everal companies and government organi5ations only utili5e 4(' certified technologies6 for e%ample, in *ustralia anything 4(' certified is also considered *ustralian standard according to the rules of the *ustralian government. (everal academic institutions will now be interested in teaching standard .. *nother ma3or outcome of having an open industry standard specification is .Net platform could be getting ported to other platforms like !inu% and @N4+6 best e%ample is the Mono &ro3ect by +imian< it is an open source implementation of .Net platform for @N4+ and !inu% based on E M* approved &ublic Domain (pecification of . and !4. Microsoft submitted the specifications to E M*, which in turn fast<tracked them through 4('. 4n doing so, Microsoft released all intellectual property in the core .B !4 platform to the public domain. No one needs a license to implement .B !4. This will also help everybody in better understanding the implementations of . and !4 which are at the core of .Net platform. 9owever, the whole of .Net platform is not a &ublic domain standard< Microsoft still owns complete 4ntellectual property rights to several class libraries and *&4 within the .Net platform.

What a$o#t the implementation of .NET other than Microsoft.Net on Windows )peratin" -'stem?
Microsoft has implemented .NET framework for all of its operating system suits #e%cluding M( )indows CD and earlier$ on all supported hardware platforms. For handheld and small devices, Microsoft has released a compact framework of .NET #http,BBmsdn.microsoft.comBvstudioBdeviceBcompact.asp% $. 0ut, there are various other implementations being developed on platforms other than Microsoft )indows. Aou can read the discussion on the portability of .NET at #(ee http,BB5dnet.com.comB?EFF<EEFG<C7FFHC.html$ The most popular implementation, after M(.NET, is the open source IMono; &ro3ect on !inu% #(ee www.go<mono.com$ Microsoft has released almost all the source code of their .NET framework for Free0(D and Mac '( under the title of (hared (ource ommon !anguage 4nfrastructure #(( !4$. heck out the (( !4 E.F release < which already builds on )indows+&, Free0(D, and Mac '( + EF.?, released under MicrosoftJs (hared (ource 4nitiative. http,BBmsdn.microsoft.comBnetBsscliB http,BBwww.microsoft.comBresourcesBsharedsourceBdefault.msp%

What is the difference $etween traditional de&elopment and .NET de&elopment?


4n traditional programming languages, the source code of a program is compiled to a specific platform;s assembly language and then machine language code. !ater the library code re-uired by the program is linked to it. Finally the operating system e%ecutes the program when desired by the user. The complete process is depicted in the following figure,

4n the presence of dot net framework, a program is not compiled to the native machine e%ecutable code6 rather it gets compiled to an intermediate language code called Microsoft 4ntermediate !anguage #M(4!$ or ommon 4ntermediate !anguage # 4!$. The Dot Net ommon !anguage "untime # !"$ then converts this intermediate code at runtime to the machine e%ecutable code. The optimi5ation is carried out at runtime. * program also does not call the operating system *&4s directly6 rather it delegates this task to the !" which performs the desired operations on behalf of the program and returns the results of the operations back to the program. The !" also performs the memory management, garbage collection, security and thread management on behalf of the program. Dot NET framework is shipped with the supporting ob3ect oriented framework of common code libraries, called the .NET Framework lass !ibrary #F !$, to facilitate the common operations. 9ence the .Net manages the overall e%ecution 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 !" #and thus the .Net framework and not the user application$ is interacting and coupled with the platform and operating system.

What are the $asic components of .NET platform?


The basic components of .NET platform #framework$ are,

ommon Lan"#a"e R#ntime / LR01


The most important part of the .NET Framework is the .Net ommon !anguage "untime # !"$ also called .Net "untime in short. 4t is a framework layer that resides above the 'perating (ystem and handlesBmanages the e%ecution of the .NET applications. 'ur .Net programs don;t directly communicate with the 'perating (ystem but through !"

M-2L /Microsoft 2ntermediate Lan"#a"e0

ode1

)hen we compile our .Net &rogram using any .Net compliant language like # ., /0.NET, 22.NET$ it does not get converted into the e%ecutable binary code but to an intermediate code, called M(4! or 4! in short, understandable by !". M(4! is an '( and 9Bw independent code. )hen the program needs to be e%ecuted, this M(4! or intermediate code is converted to binary e%ecutable code, called native code. The presence of 4! makes it possible the ross !anguage "elationship as all the .Net compliant languages produce the similar standard 4! code.

3#st 2n Time

ompilers /32Ters0

)hen our 4! compiled code needs to be e%ecuted, !" invokes 14T compilers which compile the 4! code to native e%ecutable code #.e%e or .dll$ for the specific machine and '(. 14Ters in many ways are different from traditional compilers as they, as their name suggests, compile the 4! to native code only when desired e.g., when a function is called, 4! of function;s body is converted to native code6 3ust in time of need. (o, the part of code that is not used by particular run is not converted to native code. 4f some 4! code is converted to native code then the ne%t time when its needed to be used, the !" uses the same copy without re< compiling. (o, if a program runs for sometime, then it won;t have any 3ust in time performance penalty. *s 14Ters are aware of processor and '( e%actly at

runtime, they can optimi5e the code e%tremely efficiently resulting in very robust applications. *lso, since 14Ter knows the e%act current state of e%ecutable code, they can also optimi5e the code by in<lining small function calls #like replacing body of small function when its called in a loop, saving the function call time$. *lthough, Microsoft stated that . and .Net are not competing with languages like 22 in efficiency, speed of e%ecution, 14Ters can make your code even faster than 22 code in some cases when program is run over e%tended period of time #like web<servers$.

4ramework

lass Li$rar' /4 L0

.NET Framework provides huge set of Framework #or 0ase$ lass !ibrary #F !$ for common, usual tasks. F ! contains thousands of classes to provide the access to )indows *&4 and common functions like (tring Manipulation, ommon Data (tructures, 4', (treams, Threads, (ecurity, Network &rogramming, )indows &rogramming, )eb &rogramming, Data *ccess, etc. 4t is simply the largest standard library ever shipped with any development environment or programming language. The best part of this library is they follow e%tremely efficient '' design #design patterns$ making their access and use very simple and predictable. Aou can use the classes in F ! in your program 3ust as you use any other class and can even apply inheritance and polymorphism on these.

ommon Lan"#a"e -pecification / L-0


Earlier we used the term I.NET ompliant !anguage; and stated that all the .NET compliant languages can make use of !" and F !. 0ut what makes a language I.NET compliant language;K The answer is ommon !anguage (pecification # !($. Microsoft has released a small set of specification that each language should meet to -ualify as a .NET ompliant !anguage. *s 4! is a very rich language, it is not necessary for a language to implement all the 4! functionality, rather it meets the small subset of it, !(, to -ualify as a .NET compliant language, which is the reason why so many languages #procedural and ''$ are now running under .Net umbrella. !( basically addresses to language design issues and lays 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 !( boundary, your code is guaranteed to be usable in any other .Net language.

ommon T'pe -'stem / T-0


.NET also defines a ommon Type (ystem # T($. !ike !(, T( is also a set of standards. T( defines the basic data types that 4! understands. Each .NET compliant language should map its data types to these standard data types. This makes it possible for the ? languages to communicate with each other by passingBreceiving parameters toBfrom each other. For e%ample, T( defines a type 4nt>?, an integral data type of >? bits #H bytes$ which is mapped by . through int and /0.Net through its 4nteger data type.

Gar$a"e

ollector /G 0

!" also contains :arbage ollector #: $ which runs in a low<priority thread and checks for un<referenced dynamically allocated memory space. 4f it finds some data that is no more referenced by any variableBreference, it re<claims it and returns the occupied memory back to the 'perating (ystem6 so that it can be

used by other programs as necessary. The presence of standard :arbage ollector frees the programmer from keeping track of dangling data.

What is the software de&elopment and e*ec#tion flow in Microsoft.NET?


)ith .NET development environment, a developer can write hisBher code in any .NET compliant programming language like ., /0.NET, 1., 22.NET, etc. 4n fact, various modules, components, pro3ects of an application can be written and compiled in different .Net based programming languages. *ll these components are compiled to the same 4ntermediate language code #M(4! or 4!$ understandable by the .NET !".

*t runtime, the .NET assembly #compiled 4! code$ is translated to native machine code and e%ecuted by the !".

5ow is M-.NET compared with 3a&a $ased platforms /36EE0?


*t root level architecture and components, M(.NET and 1?EE platforms are very similar. 0oth are virtual machine based architecture having !" and 1ava /irtual Machine #1/M$ as the underlying virtual machine for the management and e%ecution of programs. 0oth provide memory, security and thread management on behalf of the program and both try to decouple the applications with the e%ecution environment #'( and physical machine$. 0oth, basically, target the )eb based applications and especially the +M! based web services. 0oth provide

10

managed access to memory and no direct access to memory is allowed to their managed applications. 9owever, there are few contrasts in the architecture and design of the two virtual machines. Microsoft .NET framework;s architecture is more coupled to the Microsoft )indows 'perating (ystem which makes it difficult to implement it on various operating systems and physical machines. 1ava, on the other hand, is available on almost all ma3or platforms. *t the darker side, 1?EE architecture and 1/M is more coupled to the 1ava 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 detail than 1ava. The versioning policy of .NET is simply the best implemented versioning solution in the software development history. 1ava has got the support of industry giants like (un, 40M, *pache and 'racle while the Microsoft.NET is supported by giants like Microsoft, 4ntel, and 9&.

Wh' sho#ld one #se M-.NET for software de&elopment?


)ell, most of the software development all over the world is done on and for Microsoft )indows 'perating (ystem. Dot Net is now the standard software development environment for the Microsoft )indows operating system. 4t dramatically simplifies the development of windows, web based, data access applications, components, controls and web services. Dot net comes with ama5ing features like +M! configuration, reflection, and attributes to ease the overall software development life cycle. Finally, the dot net is supported by the Microsoft /isual (tudio 4ntegrated Development Environment6 the best 4DE available for any software development environment. /isual (tudio .NET #/(.NET$ supports all the areas of software development from pro3ect creation to debugging and installation.

What are the shortcomin"s of M-.NET platform?


The foremost short coming of .NET platform is that it is still the propriety of Microsoft. 4t is more coupled with the Microsoft )indows operating system and is implemented only on Microsoft )indows successfully. M(.NET desktop applications can run only on Microsoft )indows, )eb based applications and web services can only be deployed on Microsoft 4nternet 4nformation (erver #44($. (ince, dot net framework contains a lot of utilities, components, and framework class libraries, the si5e of downloadable framework is -uite large #?DM0 compared to DM0 si5e of 1/M$. Not all types of applications can be written in .NET managed applications, for e%ample, you can;t write !" or 'perating (ystem in your managed applications. The managed .Net applications are somewhat slower to start and run than the traditional )in>? applications. The compiled code of .Net managed applications is easier to de<compile back to the source code.

5ow tr#e it is that .NET and 3a&a pro"rams are 7#ite in+efficient when compared to 88?
The startup of managed .NET and 1ava programs is definitely slower than the traditional 22 programs as it involves the hosting of !" into managed application process in .NET and starting the 1/M in a new process in case of 1ava. The e%ecution also is a bit slower during the initial period of program e%ecution as the intermediate code is translated to the machine code on the fly at runtime. 0ut

11

as the program runs various parts repeatedly, the e%ecution gets pace too. (ince, the !" and 1/M optimi5es the code more efficiently than the static 22 compilers, the e%ecution speed of the program may actually be faster after sometime of the program startup when most of the code is translated. 9ence, in the longer run, the .Net and 1ava based programs should not be in<efficient when compared to 22. )e used Ishould; here as the actual performance depends on the particular implementation and implementation strategy.

What are 9ML (oc comments /comments start with three slashes :::0?
The +M! Doc comments are special kind of comments that can be recogni5ed by Document utility to automatically generate the documentation of your methods, types and regions.

,sin" )M components in .NET and 5ow to add a reference to a )M component?


The .NET does not encourage the use of 'M component directly inside the managed applicationL *lthough, the .NET framework contains utilities that enable 'M components to be used inside the .Net applications seamlessly. 9ow it is doneK The .NET utilities like Tlb4mp generates the wrapper .NET assembly for the 'M component which provides the same calling interface to the client as e%posed by the 'M component. 4nside the wrapper methods, it calls the actual methods of the 'M component and returns the result back to the caller. The generated wrapper .NET assembly is called the I"untime allable )rapper; or " ). To use a 'M component in your /isual (tudio.NET pro3ect, you need to add a reference of the 'M component in the "eference node of the pro3ect node of the solution inside the solution e%plorer window. The great thing about /isual (tudio.Net is that it allows you to add a reference to the 'M component in e%actly the similar way as you add the reference to the .NET assembly. The /isual (tudio.NET automatically creates the runtime callable wrapper assembly for the referenced 'M component. To add a reference to a 'M component, right click the I"eference; node under the pro3ect node inside the solution e%plorer and select the I*dd "eferenceM; option. 4t will show you a user interface screen where you browse for the target 'M component. )hen you have selected the component, press the I(elect; button and then press '8. This will add a new reference node in the "eference sub tree of the pro3ect. 0y selecting the added reference node, you can edit its properties from the properties window. Note1 The process of importing a interoperability with .NET; 'M component into .NET is called I 'M

What is .NET Framework and what are CLR, CTS and CLS?
. NET is a software platform. 4tJs a language<neutral environment for developing .NET applications that can easily and securely operate within it.

12

The .NET Framework has two main components, the # !"$ and the .NET Framework class library.

ommon !anguage "untime

The "untime can be considered an agent that manages code at e%ecution time. Thus providing core services such as memory management, thread management, and remoting. *lso 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, )inForm #graphical user interface$ applications, )eb Forms and +M! )eb services. The .NET Framework provides a "untime environment called the ommon !anguage "untime or # !"$ that handles the e%ecution of the code and provides useful services for the implementation of the application. !" takes care of code management upon program e%ecution and provides various services such as memory management, thread management, security management and other system services. The managed code targets !" benefits by using useful features such as cross<language integration, cross<language e%ception handling, versioning, enhanced security, deployment support, and debugging. ommon Type (ystem # T($ describes how types are declared, used and managed. T( facilitates cross<language integration, type safety, and high performance code e%ecution. The !( 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 inheritance, polymorphism, e%ceptions, and other features.

What is MSIL / IL? What is JIT (J st In Time!?


)hen compiling the source code to managed code, the compiler translates the source into Microsoft intermediate language #M(4!$. This is a &@<independent set of instructions that can efficiently be converted to native code. Microsoft intermediate language #M(4!$ is a translation used as the output of a number of compilers. 4t is the input to a 3ust<in<time #14T$ compiler. The ommon !anguage "untime includes a 14T compiler for the conversion of M(4! to native code. 0efore Microsoft 4ntermediate !anguage #M(4!$ can be e%ecuted it, must be converted by the .NET Framework 3ust<in<time #14T$ compiler to native code. This is &@<specific code that runs on the same computer architecture as the 14T compiler. "ather than using time and memory to convert all of the M(4! in a portable e%ecutable #&E$ file to native code. 4t converts the M(4! as needed whilst e%ecuting, then caches the resulting native code so its accessible for any subse-uent calls.

What is Code "##ess Se# rit$ (C"S!? %ow does C"S work? Who de&ines the C"S #ode 'ro (s?
ode *ccess (ecurity # *($ is part of the .NET security model. *( determines whether or not a piece of code is allowed to run and also what resources to use. For e%ample, *( will prevent malicious code from entering your system and causing havoc.

13

The *( security policy revolves around two key concepts < code groups and permissions. Each .NET assembly is a member of a particular code group and each code group is granted the permissions specified in a named permission set. *n e%ample, @sing the default security policy, a control downloaded from a web site belongs to the JNone < 4nternetJ code group which complies to the permissions defined by the J4nternetJ 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 system6 "un JcaspolJ from the command<line and checkout the different options on display.

What is seria)i*ation in .NET and what are the wa$s to #ontro) seria)i*ation?
(eriali5ation is the process of converting an ob3ect into a stream of bytes. 'n the other hand Deseriali5ation is the process of creating an ob3ect from a stream of bytes. (eriali5ationBDeseriali5ation is used to transport or to persist ob3ects. (eriali5ation can be defined as the process of storing the state of an ob3ect to a storage medium. During this process, the public and private fields of the ob3ect and the name of the class, including the assembly are converted to a stream of bytes. )hich is then written to a data stream. @pon the ob3ectJs subse-uent deseriali5ed, an e%act clone of the original ob3ect is created. 0inary seriali5ation preserves Type fidelity, which is useful for preserving the state of an ob3ect between different invocations of an application. For e%ample, *n ob3ect can be shared between different applications by seriali5ing it to the clipboard. Aou can seriali5e an ob3ect to a stream, disk, memory, over a network, and so forth. "emoting uses seriali5ation to pass ob3ects O0y /alueO from one computer or application domain to another. +M! seriali5ation seriali5es 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. *s +M! is an open standard, it is an attractive choice for sharing data across the )eb. ('*& is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library < 9ml-eriali.er and -oap4ormatter:Binar'4ormatter. Microsoft uses 9ml-eriali.er for )eb (ervices, and uses -oap4ormatter:Binar'4ormatter for remoting. 0oth are available for use in your own code.

What is "#ti+e ,ire#tor$? What names(a#e sho )d I se to se "#ti+e ,ire#tories?


*ctive Directory (ervice 4nterfaces #*D(4$ is a programmatic interface for the Microsoft )indows *ctive Directory. 4t enables your applications to interact with different directories on a network using a single interface. /isual (tudio .NET and the .NET Framework make it easy to add *D(4 functionality with the (irector'Entr' and (irector'-earcher components. @sing *D(4 you can create applications that perform common administrative tasks, such as backing up databases, accessing printers and managing user accounts. *D(4 allows,

14

E$ !og on once to work with diverse directories. The (irector'Entr' component class provides username and password properties that can be entered at "untime and are passed to the *ctive Directory ob3ect you are bound to. ?$ @se of an *pplication<&rogramming 4nterface #*&4$ to perform tasks on multiple directory systems. This includes multi protocol support. The (irector'-er&ices namespace provides the classes to perform most administrative functions such as creating users. >$ &erform O"ich PueryingO on directory systems. *D(4 technology supports searching for ob3ects with two -uery dialects, (P! and !D*&. H$ *ccess and use a single or hierarchical tree structure for administering and maintaining a diverse and complicated network. D$ 4ntegrate directory information with databases such as K(P! (erver. The (irector'Entr' path may be used as an *D'.NET connection string. Name space to be imported when working with *ctive Directories,
System.DirectoryServices

Can I se the Win-. "/I &rom a .NET Framework (ro'ram?


@sing platform invoke itJs possible. .NET Framework programs can access native code libraries by means of static D!! entry points. 9ere is an e%ample of . calling the )in>? Message0o% function,

using System; using System.Runtime.InteropServices; class MainApp { [DllImport("user32. ll"! "ntry#oint$"Message%o&"'( pu)lic static e&tern int Message%o&(int *+n ! String

strMessage! String str,aption! uint ui-ype';

pu)lic static voi {

Main('

Message%o&(.! "-*is is #Invo/e in operation0"!

".1"-"! . ';

15

2 2

%ow do I send an atta#hment in an emai)?


The following code shows how to add an attachment to an email.
3sing System.I4; 3sing System.+e).Mail; MailAttac*ment ma$ne5 MailAttac*ment("c67sample.t&t"'; MailMessage mm$ne5 MailMessage('; mm.-o $"&y89programmers*eaven.com"; mm.:rom$"a)c9ya*oo.com"; mm.%o y $"Attac*ment"; mm.Su);ect$",*ec/ out t*e attac*e te&t <ile"; mm.Attac*ments.A (ma';

SmtpMail.SmtpServer$"mail.programmers*eaven.com"; SmtpMail.Sen (mm';

16

! .NET What is !?

. #pronounced <(harp$ is a new programming language introduced with the Microsoft .NET framework and is no doubt the language of choice in .NET environment. 4t was first created in the late ECCFJs as part of Microsoft;s whole .NET strategy. 4t is a whole new language free of backward compatibility curse and a whole bunch of new, e%citing and promising features. 4t is an 'b3ect 'riented &rogramming language, which at its core, has similarities with 1ava, 2 2 and /0. 4n fact, . combines the power Q efficiency of 22, simple Q clean '' design of 1ava, and code simplification of /isual 0asic. !ike 1ava, . 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 checking. 0ut, contrary to 3ava, . keeps the different useful concepts of 22 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 template support #with the name of generics$ in ne%t versions. !ike /0 it also supports the concepts of properties #conte%t sensitive accessor to fields$. 4n addition to this, . comes up with some newBe%citing features like reflections, attributes, marshalling, remoting, threads, streams, data access with *D'.NET, etc. . programming language is designed from the scratch keeping in mind the Microsoft.Net environment. M(.Net #and thus .$ programs runs on top of the ommon !anguage "untime # !"$, which provides the runtime support to them. -ample ! Application

3sing System ,lass Sample { pu)lic static voi main(' { ,onsole.+rite=ine (>?ello +orl @' 2 2

What are Ja''ed "rra$s in C0?


* special type of array is introduced in .. * 1agged *rray is an arra' of an arra' in which the length of each array inde% can differ. E%ample, * 1agged *rray can be used is to create a table in which the lengths of the rows are not same. This *rray is declared using s-uare brackets # R S $ to indicate each dimension. The following code demonstrates the creation of a two<dimensional 3agged array.
,lass Aagge {

17

pu)lic static voi Main(' { int [([( ;agge $ne5 int [3([(; ;agge [.($me5 int[B( ;agge [C($me5 int[3( ;agge [2($me5 int[D( int I; EStoring values in <irst array <or (I$.;IFB;IGG' ;agge [.([I($I; EStoring values in secon array

<or( I$.;IF3;IGG' ;agge [C([I($I; EStoring values in t*ir array

<or(I$.;IFD;IGG' ;agge [2([I($I; EDisplaying values <rom <irst array

<or (I$.;IFB;IGG' ,onsole.+rite=ine(;agge [.([I(' EDisplaying values <rom secon array

<or (I$.;IF3;IGG' ,onsole.+rite=ine(;agge [C([I('

EDisplaying values <rom t*ir <or(I$.;IFD;IGG'

array

,onsole.+rite=ine(;agge [2([I('

2 2

18

What is the di&&eren#e 1etween 23a) e T$(es2 and 2Re&eren#e T$(es2?


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 O0y /alueO. 4n .NET terms, these are called /alue TypesO. The "unTime supports two kinds of /alue Types, E B#ilt+in &al#e t'pes The .NET Framework defines built<in value types such as (ystem.4nt>? and (ystem.0oolean which correspond and are identical to primitive data types used in programming languages. ? ,ser+defined &al#e t'pes The language you are using will provide functionality to define your own /alue Types. These user defined Types derive from (ystem./alueType. 4f you want to define a Type representing a value that is a comple% number #two floating<point numbers$, you might choose to define it as a value type. )hyK 0ecause you can pass the /alue Type efficiently O0y /alueO. 4f the Type you are defining could be more efficiently passed O0y "eferenceO, you should define it as a class instead. /ariables of "eference Types are referred to as ob3ects. These store references to the actual data. The following are the "eference Types, class interface delegate

This following are the Obuilt<inO "eference Types, ob3ect string

A() .NET What is A().Net?


Most of the today;s applications need to interact with database systems to persist, edit or view data. 4n .Net data access service is provided through *D'.Net #*ctive+ Data 'b3ect in Dot Net$ components. *D'.Net is an ob3ect oriented framework that allows you to interact with database systems. )e usually interact with database systems through (P! -ueries or stored procedures. *D'.Net encapsulates our -ueries and commands to provide a uniform access to various database management systems.

19

*D'.Net is a successor of *D' #*ctive+ Data 'b3ect$. The prime features of *D'.Net are its disconnected data access architecture and +M! integration.

What does it mean $' disconnected data access architect#re of A().Net?


*D'.Net introduces the concept of disconnected data architecture. 4n traditional data access components, you make a connection to the database system and then interact with it through (P! -ueries using the connection. The application stays connected to the D0 system even when it is not using D0 services. This commonly wastes the valuable and e%pensive database resource as most of the time applications only -uery and view the persistent data. *D'.Net solves this problem by managing a local buffer of persistent data called data set. Aour application automatically connects to the database server when it needs to pass some -uery and then disconnects immediately after getting the result back and storing it in dataset. This design of *D'.Net is called disconnected data architecture and is very much similar to the connection less services of http over the internet. 4t should be noted that *D'.Net also provides the connection oriented traditional data access services.

Traditiona) ,ata "##ess "r#hite#t re

",4.Net ,is#onne#ted ,ata "##ess "r#hite#t re

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

20

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 $' connected data access architect#re of A().Net?


4n the connected environment, it is your responsibility to open and close the database connection. Aou first establish the database connection, perform the interested operations to the database and when you are done, close the database connection. *ll the changes are done directly to the database and no local #memory$ buffer is maintained.

What;s the difference $etween accessin" data with dataset or data reader?
The dataset is generally used when you like to employ the disconnected architecture of the *D'.Net. 4t 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. 4t passes all the -ueries to the database management system, which e%ecutes them and returns the result back to the application. (ince no memory buffer is maintained by the data reader, it takes up fewer resources and performs 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. *ll the updates are done in the local memory and are updated to the database in a batch. (ince database connection remains open for the short time, the database management system does not get flooded with the incoming re-uests.

What are the performance considerations when #sin" dataset?


(ince no memory buffer is maintained by the data reader, it takes up fewer resources and performs 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. *ll the updates are done in the local memory and are updated to the database in a batch. (ince database connection remains open for the short time, the database management system does not get flooded with the incoming re-uests. 9owever, since the dataset stores the records in the local buffer in the hierarchical form, it does take up more resources and may affect the overall performance of the application.

21

5ow 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 e%ecute the large no. of -ueries on few particular table. )hen you need to work on fewer no. of tables and most of the time you need to e%ecute -ueries on these fewer tables, you should go for the dataset. 4t also depends on the nature of application. 4f multiple users 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. 0ut in the scenarios where instant update of database is not re-uired, dataset provides optimal 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 services. 'n 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., *irline "eservation (ystem$.

5ow 9ML is s#pported in A().Net?


The dataset is represented in the memory as an +M! document. Aou can fill the dataset by +M! and can also get the result in the form of +M!. (ince +M! is an international and widely accepted standard, you can read the data using the *D'.Net in the +M! form and pass it to other applications using )eb (ervice. These data consuming application need not be the essentially Dot Net based. They may be written with 1ava, 22 or any other programming language and running on any platform.

What are the different components of A().Net?


The famous diagram of the *D'.Net architecture and its components is presented in the figure below,

22

*ll generic classes for data access are contained in the (ystem.Data namespace. * short description of the core classes of *D'.Net is presented below,

Description The DataSet is a local buffer of tables or a collection of disconnected DataSet record sets DataTable is used to contain the data in tabular form using ro s and DataTable columns! Data"o "e#resents a single record or ro in DataTable Data"o "e#resents a single record or ro in DataTable Data$olumn "e#resents a column or field of DataTable Data"elation "e#resents the relationshi# bet een different tables in a data set! "e#resents the constraints or limitations that a##l% to a #articular field or $onstraint column!
*D'.Net also contains some database specific classes. This means that different database system providers may provide classes #or drivers$ optimi5ed for their particular database system. The provider for such classes are called the Dot Net Framework Data &roviders. Microsoft itself has provided the speciali5ed and optimi5ed classes for their (P! server database system. The name of these classes start with I(-l; and these are contained in (ystem.Data.(-l lient namespace. (imilarly, 'racle has also provided its classes #driver$ optimi5ed for 'racle D0 (ystem. Microsoft has also provided the general classes which can connect your application to any '!E supported database server. The name of these classes start with I'leDb; and these are contained in (ystem.Data.'leDb namespace. 4n fact, you can use 'leDb classes to connect to (P! server or 'racle database but using the database specific classes generally provides optimi5ed performance. The core ob3ects that make up a data provider are,

Class

Class Description $onnection "e#resents a connection to the database s%stem "e#resents S&' (uer% or command to be e)ecuted at the database $ommand management s%stem 23

* class that connects to the database s%stem+ fetch the record and fill the Data*da#ter dataset! ,t contains four different commands to #erform database o#erations- Select+ .#date+ ,nsert+ Delete! Data"eader * stream that reads data from the database in connected design /arameter "e#resents a #arameter to a stored #rocedure

What is a dataset?
* dataset is the local repository of the data used to store the tables and disconnected record set. )hen 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?


* data adapter is the component that e%ists between the local repository #dataset$ and the physical database. 4t contains the four different commands #(E!E T, 4N(E"T, @&D*TE and DE!ETE$. 4t uses these commands to fetch the data from the D0 and fill into the dataset and to perform updates done in the dataset to the physical database. 4t is the data adapter that is responsible for opening and closing the database connection and communicates with the dataset.

What is a data$ase connection?


* database connection represents a communication channel between you application and database management system #D0M($. The application uses this connection to pass the commands and -ueries to the database and obtain the results of the operations from the database.

What is a data$ase command?


* database command specifies which particular action you want to perform to the database. The commands are in the form of (P! #(tructured Puery !anguage$. There are four basic (P! statements that can be passed to the database.

S5L SELECT Statement


This -uery is used to select certain columns of certain records from a database table.
S"=",- H <rom emp

selects all the fields of all the records from the table name Iemp;
S"=",- empno! ename <rom emp

selects the fields empno and ename of all records from the table name Iemp;
S"=",- H <rom emp 5*ere empno F C..

24

selects all those records from the table name Iemp; that have the value of the field empno less than EFF
S"=",- H <rom article! aut*or 5*ere article.aut*orI $ aut*or.aut*orI

selects all those records from the table name Iarticle; and Iauthor; that have same value of the field author4d

S5L INSERT Statement


This -uery is used to insert a record to a database table.
I1S"R- I1-4 emp(empno! ename' values(C.C! EAo*n IuttagJ'

inserts a record to emp table and set its empno field to EFE and its ename field to I1ohn :uttag;

S5L 6/,"TE Statement


This -uery is used to edit an already e%isting record in a database table.
3#DA-" emp S"- ename $E"ric IammaJ +?"R" empno $ C.C

updates the record whose empno field is EFE by setting its ename field to IEric :amma;

S5L ,ELETE Statement


This -uery is used to delete the e%isting record#s$ from the database table
D"="-" :R4M emp +?"R" empno $ C.C

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

What 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 manner6 it reads a record from the D0, pass it to the application, then reads another and so on.

5ow do different components of A().Net interact with each other in disconnected architect#re?
The Data *dapter contains in it the ommand and onnection ob3ect. 4t uses the connection ob3ect to connect to the database, e%ecute the containing command, fetch the result and update the Data(et.

25

5ow do different components of A().Net interact with each other in connected architect#re?
9ere, the ommand ob3ect contains the onnection ob3ect. The ommand ob3ect uses the containing connection #that must be opened$ to e%ecute the (P! -uery and if the (P! statement is (E!E T, returns the Data"eader ob3ect. The data reader ob3ect is the stream to the database which reads the resulting records from the D0 and passes them to the application

What does it mean $' (ot Net 4ramework (ata <ro&ider?


Dot Net Framework Data &rovider is a set of classes that establishes the database communication between an application and the database management system based on the standards of *D'.Net framework. Different data providers provide speciali5ed and optimi5ed connectivity to particular database management system or to a particular class of D0M(. For e%ample, the M( (P! (erver data provider provides the optimi5ed connectivity between dot net application and M( (P! (erver D0M( while the '!ED0 data provider provides the uniform connectivity between dot net application and the '!ED0 databases.

What are the core o$=ects that make #p a dot net framework data pro&ider?
The core ob3ects that make up a data provider are,

Class Description $onnection "e#resents a connection to the database s%stem "e#resents S&' (uer% or command to be e)ecuted at the database $ommand management s%stem Data*da#ter * class that connects to the database s%stem+ fetch the record and fill the

26

dataset! ,t contains four different commands to #erform database o#erations- Select+ .#date+ ,nsert+ Delete! Data"eader * stream that reads data from the database in connected design /arameter "e#resents a #arameter to a stored #rocedure

What are the standard dot net framework data pro&iders that are shipped with the (ot Net 4ramework >.>?
The Dot Net Framework E.E is shipped with four different data providers, Dot Net Framework data provider for Dot Net Framework data provider for Framework E.E$ Dot Net Framework data provider for Dot Net Framework data provider for #available only in Framework E.E$ Microsoft (P! (erver D0M( 'racle D0M( #available only in '!ED0 supporting D0M( 'D0 supporting data sources

Wh' sho#ld one #se a speciali.ed data pro&ider when the data can $e accessed with "eneral data pro&iders?
The speciali5ed data providers #e.g., (P! (erver and 'racle$ are built specially for a particular kind of D0M( and works much more efficiently than the general data providers #e.g., '!ED0 and 'D0 $. 4n practice, the speciali5ed data providers are many times efficient than the general data providers.

What is the (ot Net 4ramework data pro&ider for -?L -er&er?
The dot net framework data provider for (P! (erver is the optimi5ed data provider for Microsoft (P! (erver G or later. 4t is recommended to use (P! (erver data provider to access the (P! (erver D0 than general provider like '!ED0. The classes for this provider are present in the (ystem.Data.(-l lient namespace.

What is the (ot Net 4ramework data pro&ider for )racle?


The dot net framework data provider for 'racle is the optimi5ed data provider for 'racle D0M(. 4t is recommended to use 'racle data provider to access the 'racle D0 than general provider like '!ED0. 4t supports the 'racle lient version T.E.G and later. The classes for this provider are present in the (ystem.Data.'racle lient namespace. This provider is included in the .Net framework E.E and was not available in the Dot Net framework E.F.

What is the (ot Net 4ramework data pro&ider for )LE(B?


27

The dot net framework data provider for '!ED0 provides connectivity with the '!ED0 supported database management systems. 4t is the recommended middle tier for the (P! (erver 7.D or earlier and Microsoft *ccess Database. 4t is a general data provider. Aou can also use it to connect with the (P! (erver or 'racle Database Management (ystems. The classes for this provider are present in the (ystem.Data.'leD0 lient namespace.

What is the (ot Net 4ramework data pro&ider for )(B ?


The dot net framework data provider for 'D0 provides connectivity with the 'D0 supported database management systems and data sources. 4t is a general data provider. Aou can also use it to connect with the (P! (erver or 'racle Database Management (ystems. The classes for this provider are present in the (ystem.Data.'D0 lient namespace. This provider is included in the .Net framework E.E and was not available in the Dot Net framework E.F.

What are the $asic steps in&ol&ed in data access with A().Net in disconnected en&ironment?
Data access using *D'.Net involves the following steps, Defining the connection string for the database server Defining the connection #(-l onnection, 'leDb onnection, etc$ to the database using the connection string Defining the command #(-l ommand, 'leDb ommand, etc$ or command string that contains the -uery Defining the data adapter #(-lData*dapter, 'leDbData*dapter, etc$ using the command string and the connection ob3ect reating a new Data(et ob3ect 4f the command is (E!E T, filling the dataset ob3ect with the result of the -uery through the data adapter "eading the records from the DataTables in the datasets using the Data"ow and Data olumn ob3ects 4f the command is @&D*TE, 4N(E"T or DE!ETE, then updating the dataset through the data adapter *ccepting to save the changes in the dataset to the database

Which namespaces 2 need to add to m' pro=ect for each of the standard data pro&ider?
Aou need to add following namespaces for the specified data providers,

Data Provider Namespace 0S S&' Ser1er S%stem!Data!S(l$lient 2racle Database S%stem!Data!2racle$lient 2'3 D4 Databases S%stem!Data!2leD4$lient 2D4$ Data Sources S%stem!Data!2D4$$lient

28

5ow do 2 define a connection strin" for the data$ase ser&er?


For M( (P! (erver, used with the (P! (erver data provider, we can write the connection string like,

C0 3ersion
KK <or SLl Server string connectionString $ "server$#MIII; "ui $sa; p5 $;"; ata)ase$programmers*eaven;" GN

37.Net 3ersion
O <or SLl Server Dim connectionString As String $ "server$#MIII; G N "ui $sa; p5 $;" ata)ase$programmers*eaven;"

First of all we have defined the instance name of the server, which is &<444 on my system. Ne%t we defined the name of the database, user id #uid$ and password #pwd$. (ince my (P! server doesnJt have a password for the (ystem *dministrator #sa$ user, 4 have left it blank in the connection string. #Aes 4 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 'racle Database (erver, used with the 'racle data provider, we can write the connection string like,

C0 3ersion
string connectionString $ "Data Source$4raclePi;3ser I $username;" G "#ass5or $p5 ; Integrate Security$no;";

37.Net 3ersion
Dim connectionString As String $ "Data Source$4raclePi;3ser I $username;" G N "#ass5or $p5 ; Integrate Security$no;"

For M( *ccess Database, used with the '!E D0 data provider, we can write the connection string like,

C0 3ersion
KK <or MS Access string connectionString $ "provi er$Microso<t.Aet.4="D%.B..;" G " ata source $ c677programmers*eaven.m )";

37.Net 3ersion
O <or MS Access Dim connectionString As String $ "provi er$Microso<t.Aet.4="D%.B..;" G N " ata source $ c67programmers*eaven.m )"

First we have defined the provider of the access database. Then we have defined the data source which is the address of the target database. For M( (P! (erver, used with the 'D0 connection string like, data provider, we can write the

29

C0 3ersion
string connectionString $ "Driver${SQ= Server2;Server$:ARAR;Data)ase$pu)s;3i $sa;#5 $;";

37.Net 3ersion
Dim connectionString As String $ "Driver${SQ= Server2;Server$:ARAR;Data)ase$pu)s;3i $sa;#5 $;"

5ow do 2 find the connection strin" for the data$ase ser&er?


@sually the connection string options are provided in the documentation, you can also find the connection strings on the internet. * good website for the connections strings is http,BBwww.connectionstrings.com

5ow do 2 define the connection to data$ase?


* connection is defined using the connection string. The onnection ob3ect is used by the data adapter or data reader to connect to and disconnect from the database. For (P! (erver used with (P! (erver data provider, the connection is created like this,

C0 3ersion
SLl,onnection conn $ ne5 SLl,onnection(connectionString';

37.Net 3ersion
Dim conn As 1e5 SLl,onnection(connectionString'

For 'racle Database (erver used with 'racle data provider, the connection is created like this,

C0 3ersion
4racle,onnection conn $ ne5 4racle,onnection(connectionString';

37.Net 3ersion
Dim conn As 1e5 4racle,onnection(connectionString'

For '!E D0 provider, the connection is created like this,

C0 3ersion
4leD),onnection conn $ ne5 4leD),onnection(connectionString';

37.Net 3ersion
Dim conn As 1e5 4leD),onnection(connectionString'

For 'D0

data provider, the connection is created like this,

C0 3ersion
4 )c,onnection conn $ ne5 4 )c,onnection(connectionString';

30

37.Net 3ersion
Dim conn As 1e5 4 )c,onnection(connectionString'

9ere we have passed the connection string to the constructor of the connection ob3ect.

5ow do 2 create a command and s#ppl' the -?L 7#er' to A().Net? / ommand o$=ect and command strin"0
First of all, you create a command ob3ect #(-l ommand, 'racle ommand, 'leDb ommand, 'dbc ommand$ using the connection ob3ect #(-l onnection, 'racle onnection, 'leDb onnection, 'dbc onnection$ and set its ommandTe%t property to the (P! -uery to e%ecute.

C0 3ersion
4 )c,omman cm $ conn.,reate,omman ('; cm .,omman -e&t $ "select H <rom aut*ors";

37.Net 3ersion
Dim cm As 4 )c,omman cm $ conn.,reate,omman (' cm .,omman -e&t $ "select H <rom aut*ors"

5ow do 2 define a data adapter?


The data adapter stores your command #-uery$ and connection and using these connect to the database when asked, fetch the result of -uery and store it in the local dataset. The Data*dapter class #(-lData*dapter, 'racleData*dapter, 'leDbData*dapter, 'dbcData*dapter$ may be instantiated in three ways, E. by supplying the command string #(P! (elect command$ and connection string ?. by supplying the command string #(P! (elect command$ and a connection ob3ect >. by supplying the command ob3ect #(-l ommand, 'racle ommand, 'leDb ommand, 'dbc ommand$ For e%ample, with (P! (erver, the data adapter is created as

C0 3ersion
KK <or SLl Server SLlDataA apter ataA apter $ ne5 SLlDataA apter(comman String! conn';

37.Net 3ersion
Dim a As 1e5 SLlDataA apter(comman String! conn'

31

9ere we have created a new instance of data adapter and supplied it command string and connection ob3ect in the constructor call. For *ccess, the data adapter is created like

C0 3ersion
KK <or MS Access 4leD)DataA apter ataA apter $ ne5 4leD)DataA apter(comman String! connectionString';

37.Net 3ersion
Dim a As 1e5 4leD)DataA apter(comman String! connectionString'

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

5ow do 2 "et the res#lt of m' command and fill it to the dataset?
Data(et is a local and offline container of the data. The Data(et ob3ect is created simply like

C0 3ersion
DataSet s $ ne5 DataSet(';

37.Net 3ersion
Dim s As 1e5 DataSet('

Now we need to fill the Data(et with the result of the -uery. )e will use the data*dapter ob3ect 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 -uery.

C0 3ersion
ataA apter.:ill( s! "prog"';

37.Net 3ersion
a.:ill( s! "prog"'

9ere we have called the Fill#$ method of data*dapter ob3ect. )e have supplied it the dataset to fill and the name of the table #DataTable$ in which the result of -uery is filled. This is all we needed to connect and fetch the data from the database. Now the result of -uery is stored in the dataset ob3ect in the prog table which is an instance of DataTable. )e can get a reference to this table by using the inde%er property of dataset ob3ect;s Tables collection

C0 3ersion
Data-a)le ata-a)le $ s.-a)les["prog"(;

37.Net 3ersion
32

Dim ata-a)le As Data-a)le t $ s.-a)les("prog"'

The inde%er we have used takes the name of the table in dataset and returns the corresponding DataTable ob3ect. Now we can use the tables "ows and olumns collection to access the data in the table.

5ow do 2 read records from the data ta$les?


Aou can read the records from the data table using its "ows collection. )ith the "ows collection, you need to specify the row number and column name or number to access a particular field of the specified row. For e%ample, if we have read the I(tudent; table in our data table, we can access its individual fields as,

C0 3ersion
Data-a)le t $ s.-a)les["stu ent"(; string stI $ t.Ro5s[.(["Stu entID"(.-oString('; string st1ame $ t.Ro5s[.(["Stu ent1ame"(.-oString('; string stDate4<%irt* $ t.Ro5s[.([2(.-oString(';

37.Net 3ersion
Dim t As Data-a)le t $ s.-a)les("stu ent"'

Dim stI stI $

As String t.Ro5s(.'("Stu entID"'.-oString('

Dim st1ame As String st1ame $ t.Ro5s(.'("Stu ent1ame"'.-oString('

Dim stDate4<%irt* As String stDate4<%irt* $ t.Ro5s(.'(2'.-oString('

9ere we have retrieved various fields of the first record of the student table read in the dataset. *s you can see, we can either specify the column name in string format or we can specify the column number in integer format. *lso note that the field value is returned in the form of 'b3ect, so we need to convert it to the string before using it. (imilarly, you need to cast variables of other data types before using them.

C0 3ersion
int stAge $ int.#arse( t.Ro5s(.'("Age"'.-oString('';

37.Net 3ersion
Dim stage As Integer stAge $ Integer.#arse( t.Ro5s(.'("Age"'.-oString(''

33

5ow do 2 sa&e the chan"es% made in the dataset% to the data$ase?


)e update the dataset and table by calling the @pdate 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 *ccept hanges#$ method of the Data(et class.

C0 3ersion
ataA apter.3p ate( s! "stu ent"'; s.Accept,*anges(';

37.Net 3ersion
a.3p ate( s! "stu ent"' s.Accept,*anges('

9ere Ida; is the reference to the data adapter ob3ect, Ids; is the reference to the dataset, and Istudent; is the name of table we want to update. Note, For the ne%t four F*Ps, we will demonstrate sample applications. For these applications to work, you need following database and tables created in your database server. * database named I&rogrammers9eaven; is created. 4t has a table named I*rticle;. The fields of the table I*rticle; are

Field Name Type Description art,d 5/rimar% 6e%7 ,nteger The uni(ue identit% of article Title String The title of the article To#ic or Series name of the article li8e 90ultithreading in To#ic String :a1a; or 9$< School; author,d 5=oreign ,nteger .ni(ue identit% of author 6e%7 'ines ,nteger >o! of lines in the article date2f/ublishing Date Date of #ublishing of the article
The I&rogrammers9eaven; database also contains a table named I*uthor; with the following fields

Field Name Type Description author,d 5/rimar% 6e%7 ,nteger The uni(ue identit% of author name String >ame of author

5ow do 2 make m' first @5ello% A().NetA Application in !?


!et;s now create a demonstration application for accessing data. First create a windows form application and make the layout like the following snapshot

34

)e have set the Name property of the te%t bo%es #from top to bottom$ as t%t*rticle4D, t%t*rticleTitle, t%t*rticleTopic, t%t*uthor4d, t%t*uthorName, t%tNum'f!ines and t%tDate'f&ublishing. *lso we have set the "ead'nly property of all the te%t bo%es to true as don;t want the user of application to change the te%t. The names of buttons #from top to bottom$ are btn!oadTable, btnNe%t and btn&revious. 4nitially we have disabled the Ne%t and &revious buttons #by setting their Enabled property to false$. )e have also defined three variables in the Form class as
pu)lic class AD4:orm 6 System.+in o5s.:orms.:orm { Data-a)le ata-a)le; int currRec$.; int totalRec$.;

The dataTable ob3ect will be used to reference the table returned as a result of the -uery. The curr"ec and total"ec integer variables are used to keep track of the current record and total records in the table.

Loadin' ta1)e
For !oadTable button, we have written the following event handler
private voi )tn=oa -a)leN,lic/(o);ect sen er! System."ventArgs e' { KK <or SLl Server string connectionString $ "server$#MIII; ata)ase$programmers*eaven;" G "ui $sa; p5 $;";

35

KK <or MS Access KHstring connectionString $ "provi er$Microso<t.Aet.4="D%.B..;" G " ata source $ c677programmers*eaven.m )";HK

KK <or SLl Server SLl,onnection conn $ ne5 SLl,onnection(connectionString';

KK <or MS Access KK4leD),onnection conn $ ne5 4leD),onnection(connectionString';

string comman String $ "S"=",- " G "artI ! title! topic! " G "article.aut*orI aut*orI ! " G "name! lines! ate4<#u)lis*ing " G ":R4M " G "article! aut*or " G "+?"R" " G "aut*or.aut*orI article.aut*orI "; $ as

KK <or SLl Server SLlDataA apter conn'; ataA apter $ ne5 SLlDataA apter(comman String!

KK <or MS Access KK4leD)DataA apter conn'; ataA apter $ ne5 4leD)DataA apter(comman String!

DataSet

s $ ne5 DataSet(';

36

ataA apter.:ill( s! "prog"';

ata-a)le $ currRec $ .; totalRec $

s.-a)les["prog"(;

ata-a)le.Ro5s.,ount;

:ill,ontrols(';

)tn1e&t."na)le

$ true; $ true;

)tn#revious."na)le 2

4n the start, we have created the connection, data adapter and filled the dataset ob3ect which we have discussed earlier. 4t should be noted that we have commented the code for 'leDb provider #M(<*ccess$ and are using the (P! (erver specific code. 4f you like to use *ccess database, you can simply comment the (P! server code and de<comment the *ccess code. Ne%t we assigned the data table resulted from -uery to the dataTable ob3ect which we declared at class level, assigned 5ero to curr"ec variable and assigned the number of rows in the dataTable to total"ec variable
ata-a)le $ s.-a)les["prog"(; currRec $ .; totalRec $ ata-a)le.Ro5s.,ount;

Then we called the Fill ontrols#$ method which fills the controls #te%t bo%es$ on the form with the current record of table UprogV. Finally we have enabled the Ne%t and &revious 0utton

Fi))in' the #ontro)s on the Form


The Fill ontrols#$ method in our program fills the controls on the form with the current record of the data table. The method is defined as
private voi :ill,ontrols(' { t&tArticleI .-e&t $ ata-a)le.Ro5s[currRec(["artI "(.-oString('; t&tArticle-itle.-e&t $ ata-a)le.Ro5s[currRec(["title"(.-oString('; t&tArticle-opic.-e&t $ ata-a)le.Ro5s[currRec(["topic"(.-oString('; t&tAut*orI .-e&t $ ata-a)le.Ro5s[currRec(["aut*orI "(.-oString('; t&tAut*or1ame.-e&t $ ata-a)le.Ro5s[currRec(["name"(.-oString('; t&t1um4<=ines.-e&t $ ata-a)le.Ro5s[currRec(["lines"(.-oString('; t&tDate4<#u)lis*ing.-e&t $ ata-a)le.Ro5s[currRec( [" ate4<#u)lis*ing"(.-oString('; 2

37

9ere we have set the Te%t property of the te%t bo%es to the string values of the corresponding fields of current record. )e have used the "ows collection of the dataTable and using its inde%er we have got the Data"ow representing the current record. )e then accessed the inde%er property of this Data"ow using the column name to get the data in the respective field. 4f this e%planation looks weird to you, you can simplify the above statements as
DataRo5 ro5 $ ata-a)le.Ro5s[currRec(; KK getting current ro5 o);ect ata $ ro5["artI "(; KK getting ata in t*e artI <iel string strData $ ata.-oString('; KK converting to string t&tArticleI .-e&t $ strData; KK isplay in t*e te&t )o&

which is e-uivalent to
t&tArticleI .-e&t $ ata-a)le.Ro5s[currRec(["artI "(.-oString(';

9ence when you start the application and press the !oadTable button, you will see the following output

5ow do 2 make m' first @5ello% A().NetA Application in VB.Net?


!etJs now create a demonstration application for accessing data. First create a windows form application and make the layout shown the following snapshot.

38

)e have set the Name property of the te%t bo%es #from top to bottom$ as t%t*rticle4D, t%t*rticleTitle, t%t*rticleTopic, t%t*uthor4d, t%t*uthorName, t%tNum'f!ines and t%tDate'f&ublishing. *lso we have set the "ead'nly property of all the te%t bo%es to true as donJt want the user to change the te%t. The names of the buttons #from top to bottom$ are btn!oadTable, btnNe%t and btn&revious. 4nitially we have disabled the Ne%t and &revious buttons #by setting their Enabled property to false$. )e have also defined three variables in the Form class,
#u)lic ,lass AD4:orm In*erits System.+in o5s.:orms.:orm various met*o s #rivate ata-a)le As ata-a)le #rivate currRec As Integer $ . #rivate totalRec As Integer $ . O #rivate glo)al mem)ers to )e use in

...

The dataTable ob3ect will be used to reference the table returned as a result of the -uery. The curr"ec and total"ec integer variables are used to keep track of the current record and total number of records in the table. !oading table For the !oadTable button, we have written the following event handler

#rivate Su) )tn=oa -a)leN,lic/(%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les )tn=oa -a)le.,lic/ O <or SLl Server Dim connectionString As String $ "server$#MIII; ata)ase$programmers*eaven;" G N "ui $sa; p5 $;"

O <or MS Access

39

ODim connectionString As String $ "provi er$Microso<t.Aet.4="D%.B..;" G O c677programmers*eaven.m )" " ata source $

O <or SLl Server Dim conn As 1e5 SLl,onnection(connectionString'

O <or MS Access ODim conn As 1e5 4leD),onnection(connectionString'

Dim comman String As String $ "S"=",- " G N "artI ! title! topic! " G N "article.aut*orI "name! lines! ":R4M " G N "article! aut*or " G N "+?"R" " G N "aut*or.aut*orI $ article.aut*orI " as aut*orI ! " G N

ate4<#u)lis*ing " G N

O <or SLl Server Dim ataA apter As 1e5 SLlDataA apter(comman String! conn'

O <or MS Access ODim ataA apter As 1e5 4leD)DataA apter(comman String! conn'

Dim

s As 1e5 DataSet('

ataA apter.:ill( s! "prog"'

ata-a)le $

s.-a)les("prog"'

40

currRec $ . totalRec $ ata-a)le.Ro5s.,ount

:ill,ontrols('

)tn1e&t."na)le

$ -rue $ -rue

)tn#revious."na)le

"n

Su)

First we created the connection, data adapter and filled the dataset ob3ect, all of which we have discussed earlier. 4t should be noted that we have commented out the code for the 'leDb provider #M(<*ccess$ and are using (P! (erver specific code. 4f you would like to use an *ccess databases, you can simply comment the (P! server code out and de<comment the *ccess code. Ne%t, we have assigned the data table resulting from the -uery to the dataTable ob3ect which we declared at the class level, assigned 5ero to curr"ec variable and assigned the number of rows in the dataTable to the total"ec variable,
ata-a)le$ s.-a)les("prog"'currRec$.totalRec$ ata-a)le.Ro5s.,ount

Then we called the Fill ontrols#$ method, which fills the controls #te%t bo%es$ on the form with the current record of the table OprogO. Finally we enabled the Ne%t and &revious 0uttons.

4illin" the controls on the 4orm


The Fill ontrols#$ method in our program fills the controls on the form with the current record of the data table. The method is defined as follows,
#rivate Su) :ill,ontrols(' t&tArticleI .-e&t$ ata-a)le.Ro5s(currRec'("artI "'.-oString(' t&tArticle-itle.-e&t$ ata-a)le.Ro5s(currRec'("title"'.-oString(' t&tArticle-opic.-e&t$ ata-a)le.Ro5s(currRec'("topic"'.-oString(' t&tAut*orI .-e&t$ ata-a)le.Ro5s(currRec'("aut*orI "'.-oString(' t&tAut*or1ame.-e&t$ ata-a)le.Ro5s(currRec'("name"'.-oString(' t&t1um4<=ines.-e&t$ ata-a)le.Ro5s(currRec'("lines"'.-oString(' t&tDate4<#u)lis*ing.-e&t$ ata-a)le.Ro5s(currRec' (" ate4<#u)lis*ing"'.-oString(' "n Su)

9ere we have set the Te%t property of the te%t bo%es to the string values of the corresponding fields of the current record. )e have used the "ows collection of the dataTable and using its inde%er we have got the Data"ow representing the current record. )e have then accessed the inde%er property of this Data"ow

41

using the column name to get the data in the respective field. 4f this e%planation looks weird to you, you can simplify the above statements to,<
Dim ro5 As DataRo5 $ ata-a)le.Ro5s(currRec' Dim ata As 4);ect $ ro5("artI "' <iel Dim strData As String $ ata.-oString(' t&tArticleI .-e&t $ strData O getting current ro5 O getting ata in t*e artI O converting to string O isplay in t*e te&t )o&

which is e-uivalent to
t&tArticleI .-e&t $ ata-a)le.Ro5s(currRec'("artI "'.-oString('

9ence when you start the application and press the !oadTable button, you will see the following output,

5ow do 2 na&i"ate thro#"h the records?


Navigating through the records is again very easy. For the Ne%t button, we have written the following simple event handler
#rivate Su) )tn1e&tN,lic/(%ySal sen er As System.4);ect! N %ySal e As System."ventArgs' ?an les )tn1e&t.,lic/ currRec G$ C I< currRec T$ totalRec -*en currRec $ .

42

"n I< :ill,ontrols(' "n Su)

9ere we first increment the integer variable curr"ec and check if it has crossed the last record #using the total"ec variable$ in the table. 4f it has, then we move the current record to the first record. )e then call the Fill ontrols#$ method to display the current record on the form. (imilarly the event handler for the &revious button looks like this,
#rivate Su) )tn#reviousN,lic/(%ySal sen er As System.4);ect! N %ySal e As System."ventArgs' ?an les )tn#revious.,lic/ currRec M$ C I< currRec F totalRec -*en currRec $ totalRec M C "n I< :ill,ontrols(' "n Su)

9ere we decrement the curr"ec variable and check if has crossed the first record and if it has then we move it to the last record. 'nce again, we call the Fill ontrols#$ method to display the current record. Now you can navigate through the records using the Ne%t and &revious buttons.

5ow do 2 #pdate ta$les in the dataset?


@pdating a table in *D'.Net is very interesting and easy. Aou need to follow these steps to update, insert and delete records,

43

The Data *dapter class #(-lData*dapter$ has properties for each of the insert, update and delete commands. First of all we need to prepare the command #(-l ommand$ and add it to the data adapter ob3ect. The commands are simple (P! commands with parameters. Aou may use the /isual (tudio .Net designer to easily create these commands. (econdly we need to add parameters to these commands. The parameters are simply the names of the data table fields involved in the particular command. /isual (tudio .Net also build it for you in its Data *dapter configuration wi5ard. The two steps described above are done only once in the application. For each insert, update and delete6 we insert, update and delete the corresponding data row #Data"ow$ of the data table #DataTable$ ob3ect. *fter any update we call the @pdate#$ method of the data adapter class by supplying to it, the dataset and table name as parameters. This updates our local dataset. Finally we call the *ccept hanges#$ method of the dataset ob3ect to store the changes in the dataset to the physical database.

5ow do 2 #se a ommandB#ilder o$=ect to prepare the #pdate commands in m' dataset?
Each data provider has a command builder ob3ect that prepares the update, insert and delete commands for you. Aou can use these #(-l ommand0uilder, 'racle ommand0uilder, 'leDb ommand0uilder, 'dbc ommand0uilder$ ob3ects to generate commands automatically using the (elect command you specified when defining the data adapter. 4n the following code, we have created and set the update, insert and delete commands using the (-l ommand0uilder ob3ect

C0 3ersion
SLl,onnection conn $ ne5 SLl,onnection("server$:ARAR; ata)ase$programmers*eaven; ui $sa; p5 $;"'; string cm Str $ "select H <rom article"; SLlDataA apter a $ ne5 SLlDataA apter(cm Str! conn'; DataSet s $ ne5 DataSet('; a.:ill( s! "Article"'; SLl,omman %uil er cm %uil er $ ne5 SLl,omman %uil er( a'; a.Insert,omman $ cm %uil er.IetInsert,omman ('; a.3p ate,omman $ cm %uil er.Iet3p ate,omman ('; a.Delete,omman $ cm %uil er.IetDelete,omman (';

37.Net 3ersion
Dim conn As 1e5 SLl,onnection("server$:ARAR; ui $sa; p5 $;"' ata)ase$programmers*eaven;

Dim cm Str As String cm Str $ "select H <rom article" Dim a As 1e5 SLlDataA apter(cm Str! conn'

44

Dim

s As 1e5 DataSet

a.:ill( s! "Article"'

Dim cm %uil er As 1e5 SLl,omman %uil er( a' a.Insert,omman a.3p ate,omman a.Delete,omman $ cm %uil er.IetInsert,omman (' $ cm %uil er.Iet3p ate,omman (' $ cm %uil er.IetDelete,omman ('

What are the "eneral steps for #pdatin" the records in dataset?
The Data *dapter class #(-lData*dapter$ has properties for each of the insert, update and delete commands. First of all we need to prepare the command #(-l ommand$ and add it to the data adapter ob3ect. (econdly we need to add parameters to these commands. The two steps described above are done only once in the application. For each insert, update and delete6 we insert, update and delete the corresponding data row #Data"ow$ of the data table #DataTable$ ob3ect. *fter any update we call the @pdate#$ method of the data adapter class by supplying to it, the dataset and table name as parameters. This updates our local dataset. Finally we call the *ccept hanges#$ method of the dataset ob3ect to store the changes in the dataset to the physical database.

5ow do 2 #pdate the dataset with the #pdates in records?


Aou can update the dataset by calling the @pdate#$ method of the data adapter.

C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[2(["lines"( $ U..;

a.3p ate( s! "Article"';

37.Net 3ersion
Dim t $ s.-a)les("Article"' t.Ro5s(2'("lines"' $ V..

a.3p ate( s! "Article"'

45

9ere Ida; and Ids; are the references of the Data*dapter and Data(et ob3ects respectively.

5ow do 2 #pdate the ph'sical data$ase with the chan"es in the dataset?
Aou can update the physical database by calling the *ccept hanges#$ method of the data set.

C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[2(["lines"( $ U..;

a.3p ate( s! "Article"'; s.Accept,*anges(';

37.Net 3ersion
Dim t $ s.-a)les("Article"' t.Ro5s(2'("lines"' $ V..

a.3p ate( s! "Article"' s.Accept,*anges('

9ere Ida; and Ids; are the references of the Data*dapter and Data(et ob3ects respectively.

5ow do 2 #pdate a record in the ta$le #sin" A().Net dataset?


'nce you have the @pdate ommand prepared in the data adapter, you can update individual records simply by updating the field values in the data table;s rows. The above code demonstrate how we can update the Ilines; field of the third record of the table I*rticle;

C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[2(["lines"( $ U..;

a.3p ate( s! "Article"'; s.Accept,*anges(';

37.Net 3ersion
Dim t $ s.-a)les("Article"' t.Ro5s(2'("lines"' $ V..

46

a.3p ate( s! "Article"' s.Accept,*anges('

5ow do 2 insert a record in the ta$le #sin" A().Net dataset?


To insert a record in the data table, you create an ob3ect of the Data"ow using the DataTable ob3ect. Then you set the appropriate field values and finally add it to the DataTable;s "ows collection.

C0 3ersion
Data-a)le t $ s.-a)les["Article"(; KK Insert DataRo5 r $ t.1e5Ro5('; r[.( $ B; r[C( $ "M:, #rogramming"; r[2( $ "S,GG M:, =i)rary"; r[3( $ 3; r[B( $ 3...; r[D( $ Date-ime.#arse("PKCBKCWWW"'; t.Ro5s.A ( r';

a.3p ate( s! "Article"'; s.Accept,*anges(';

37.Net 3ersion
Dim t As Data-a)le t $ s.-a)les("Article"'

O Insert Dim r $ r As DataRo5 t.1e5Ro5('

r(.' $ B r(C' $ "M:, #rogramming" r(2' $ "S,GG M:, =i)rary" r(3' $ 3 r(B' $ 3... r(D' $ Date-ime.#arse("PKCBKCWWW"' t.Ro5s.A ( r'

47

a.3p ate( s! "Article"' s.Accept,*anges('

5ow do 2 delete a record in the ta$le #sin" A().Net dataset?


To delete a record, you first get the Data"ow ob3ect from the DataTable ob3ect. Then you simply call the Delete#$ method of the data row ob3ect to delete a record from the data table.

C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[3(; KK Delete DataRo5 r $ r.Delete(';

a.3p ate( s! "Article"'; s.Accept,*anges(';

37.Net 3ersion
Dim t As Data-a)le t $ s.-a)les("Article"'

O Delete Dim r $ r As DataRo5 t.Ro5s(3'

r.Delete('

a.3p ate( s! "Article"' s.Accept,*anges('

What is the architect#re of connected en&ironment of data access in A().Net?

48

The connected environment of data access is the traditional procedure for accessing data programmatically. The differentiating property of the connected data access environment is that here you #the programmer$ is re-uired to manage the connection with the database. Aou can only perform database operations when, there e%ists an open connection to the database. 9ence, before performing any database operation #select, update, insert, delete$, the programmer opens a database connection and close the database connection after performing the database operations. The important ob3ects for working in the connected environment are, onnection #(-l onnection, 'leDb onnection, etc$, 4t represents a connection to the database. *ll the connection ob3ects in the *D'.Net implement the (ystem.Data.4Db onnection interface. ommand #(-l ommand, 'leDb ommand, etc$, 4t represents the (P! command sent to the database, e.g., (E!E T, @&D*TE, 4N(E"T, DE!ETE. *ll commands in *D'.Net implements 4Db ommand interface Data"eader #(-lData"eader, 'leDbData"eader, etc$, 4t represents a data stream that can be used to read the result of your -uery returned by the database server. @sing this ob3ect, you read the individual records and their fields returned as a result of your -uery to the database server. *ll the data readers in *D'.Net implement the (ystem.Data.4Data"eader interface.

5ow do 2 read data /or records0 from data$ase #sin" data reader?
To read data from the database, you first make a connection ob3ect #(-l onnection, etc$ and open it.

C0 3ersion
string connString $ "server$:ARAR; ata)ase$programmers*eaven;" G "ui $sa; p5 $"; SLl,onnection conn $ ne5 SLl,onnection(connString'; conn.4pen(';

37.Net 3ersion
Dim connString As String $ "server$sira;; ata)ase$programmers*eaven;" G N "ui $sa; p5 $" Dim conn As 1e5 SLl,onnection(connString' conn.4pen('

Then you create a command using this connection and the command te%t.

C0 3ersion
string cm String $ "select H <rom aut*or"; SLl,omman cm $ ne5 SLl,omman (cm String! conn';

37.Net 3ersion
Dim cm String As String $ "select H <rom aut*or" Dim cm As 1e5 SLl,omman (cm String! conn'

49

Then you e%ecute the command with the command ob3ect;s E%ecute"eader#$ method. The E%ecute"eader method returns the ob3ect of type 4Data"eader

C0 3ersion
SLlDataRea er rea er $ cm ."&ecuteRea er(';

37.Net 3ersion
Dim rea er As SLlDataRea er $ cm ."&ecuteRea er('

Now you read the individual records using this data reader. To advance to the ne%t record, you call its "ead#$ method which returns 0oolean to indicate if there e%ists a ne%t row. 4f the Data"eader;s "ead#$ method returns true then the Data"eader acts as a database row #record$. Now you can access the fields of this particular row specifying the column names #or integral inde%es$ in its inde%ers.

C0 3ersion
5*ile(rea er.Rea ('' { t&tData.-e&t t&tData.-e&t t&tData.-e&t t&tData.-e&t 2 G$ G$ G$ G$ rea er["aut*orI "(.-oString('; "! "; rea er["name"(.-oString('; "7r7n";

37.Net 3ersion
+*ile rea er.Rea t&tData.-e&t t&tData.-e&t t&tData.-e&t t&tData.-e&t "n +*ile (' G$ G$ G$ G$ rea er("aut*orI "'.-oString(' "! " rea er("name"'.-oString(' v),r=<

Finally, you need to close the database connection opened before performing the database operation #(E!E T, in our case$

C0 3ersion
conn.,lose(';

37.Net 3ersion
conn.,lose('

!et;s look at the complete code now for review

C0 3ersion
string connString $ "server$sira;; ata)ase$programmers*eaven;" G "ui $sa; p5 $"; SLl,onnection conn $ ne5 SLl,onnection(connString'; string cm String $ "select H <rom aut*or"; SLl,omman cm $ ne5 SLl,omman (cm String! conn';

conn.4pen('; SLlDataRea er rea er $ cm ."&ecuteRea er(';

50

5*ile(rea er.Rea ('' { t&tData.-e&t G$ rea er["aut*orI "(.-oString('; t&tData.-e&t G$ "! "; t&tData.-e&t G$ rea er["name"(.-oString('; t&tData.-e&t G$ "7r7n"; 2 conn.,lose(';

37.Net 3ersion
Dim connString As String $ "server$sira;; ata)ase$programmers*eaven;" G N "ui $sa; p5 $" Dim conn As 1e5 SLl,onnection(connString' Dim cm String As String $ "select H <rom aut*or" Dim cm As 1e5 SLl,omman (cm String! conn'

conn.4pen(' Dim rea er As SLlDataRea er $ cm ."&ecuteRea er('

+*ile rea er.Rea (' t&tData.-e&t G$ rea er("aut*orI "'.-oString(' t&tData.-e&t G$ "! " t&tData.-e&t G$ rea er("name"'.-oString(' t&tData.-e&t G$ v),r=< "n +*ile

conn.,lose('

5ow do 2 insert records #sin" data reader?


The procedure for updating records using 4N(E"T commands is very similar to the one we presented in the previous e%ample #of (E!E T$ e%cept that here the command does not return anything and thus the method to call on the (-l ommand ob3ect is called E%ecuteNonPuery#$.

51

C0 3ersion
string connString $ "server$:ARAR; ata)ase$programmers*eaven;" G "ui $sa; p5 $"; SLl,onnection conn $ ne5 SLl,onnection(connString'; KK I1S"R- Query string cm String $"I1S"R- I1-4 Aut*or " G "(aut*orI ! name' " G "SA=3"S(3! OAn ers ?e;ls)ergO'"; SLl,omman cm $ ne5 SLl,omman (cm String! conn';

conn.4pen('; cm ."&ecute1onQuery('; conn.,lose(';

37.Net 3ersion
Dim connString As String $ "server$:ARAR; ata)ase$programmers*eaven;" G N "ui $sa; p5 $" Dim conn As 1e5 SLl,onnection(connString'

O I1S"R- Query Dim cm String As String $ "I1S"R- I1-4 Aut*or " G N "(aut*orI ! name' " G N "SA=3"S(3! OAn ers ?e;ls)ergO'"

Dim cm

As 1e5 SLl,omman (cm String! conn'

conn.4pen(' cm ."&ecute1onQuery(' conn.,lose('

5ow do 2 #pdate records #sin" data reader?


The procedure for updating records using 4N(E"T commands is very similar to the one we presented in the previous e%ample #of (E!E T$ e%cept that here the command does not return anything and thus the method to call on the (-l ommand ob3ect is called E%ecuteNonPuery#$.

52

C0 3ersion
string connString $ "server$:ARAR; ata)ase$programmers*eaven;" G "ui $sa; p5 $"; SLl,onnection conn $ ne5 SLl,onnection(connString'; KK 3#DA-" Query string cm String $ "3#DA-" Aut*or " G "S"- name $ OIra y %ooc*O " G "+?"R" aut*orI $ 3";

SLl,omman

cm

$ ne5 SLl,omman (cm String! conn';

conn.4pen('; cm ."&ecute1onQuery('; conn.,lose(';

37.Net 3ersion
Dim connString As String $ "server$:ARAR; ata)ase$programmers*eaven;" G N "ui $sa; p5 $" Dim conn As 1e5 SLl,onnection(connString'

O 3#DA-" Query Dim cm String As String $ "3#DA-" Aut*or " G N "S"- name $ OIra y %ooc*O " G N "+?"R" aut*orI $ 3"

Dim cm

As 1e5 SLl,omman (cm String! conn'

conn.4pen(' cm ."&ecute1onQuery(' conn.,lose('

5ow do 2 delete records #sin" data reader?


The procedure for updating records using 4N(E"T commands is very similar to the one we presented in the previous e%ample #of (E!E T$ e%cept that here the

53

command does not return anything and thus the method to call on the (-l ommand ob3ect is called E%ecuteNonPuery#$.

C0 3ersion
string connString $ "server$:ARAR; ata)ase$programmers*eaven;" G "ui $sa; p5 $"; SLl,onnection conn $ ne5 SLl,onnection(connString'; KK D"="-" Query string cm String $ "D"="-" :R4M Aut*or " G "+?"R" aut*orI $ 3";

SLl,omman

cm

$ ne5 SLl,omman (cm String! conn';

conn.4pen('; cm ."&ecute1onQuery('; conn.,lose(';

37.Net 3ersion
Dim connString As String $ "server$:ARAR; ata)ase$programmers*eaven;" G N "ui $sa; p5 $" Dim conn As 1e5 SLl,onnection(connString'

O D"="-" Query Dim cm String As String $ "D"="-" :R4M Aut*or " G "+?"R" aut*orI $ 3"

Dim cm

As 1e5 SLl,omman (cm String! conn'

conn.4pen(' cm ."&ecute1onQuery(' conn.,lose('

5ow do 2 write common code for different dot net framework data pro&iders?

54

The (ystem.Data namespace contains the interfaces implemented by different dot net framework data providers, such as, 4Db onnection implemented by (-l onnection, 'racle onnection, 'leDb onnection, 'dbc onnection classes represents a connection with the database server 4Db ommand implemented by (-l ommand, 'racle ommand, 'leDb ommand, 'dbc ommand classes represents an (P! command passed to the database server 4DbData*dapter implemented by (-lData*dapter, 'racleData*dapter, 'leDbData*dapter, 'dbcData*dapter classes represents a data adapter used to fill the data set in the disconnected environment of the *D'.Net 4Data"eader implemented by (-lData"eader, 'racleData"eader, 'leDbData"eader, 'dbcData"eader classes represents a data reader used to read records from the database server, analogous to read only, forward only cursor 4DbTransaction implemented by (-lTransaction, 'racleTransaction, 'leDbTransaction, 'dbcTransaction classes represents a transaction established with the database server

)e strongly recommend the readers to use the references of these interface type to perform the database operations wherever possible. @sing these, you can write a code that is data provider independent. onsider a data access module which is supplied the database connection and which performs the database operations using this connection. This module does not know which data provider the connection belongs and uses the interface approach. Following code demonstrate this data access module

C0 3ersion
internal class DataAccessMo ule { private ID),onnection conn; private ID),omman cm ;

private const string IetSalue,m -e&t $"S"=",- value :R4M My-a)le +?"R" name $ O";

pu)lic DataAccessMo ule(ID),onnection conn' { t*is.conn $ conn; cm $ conn.,reate,omman (';

conn.4pen('; 2

pu)lic string IetSalue(string name'

55

{ cm .,omman -e&t $ IetSalue,m -e&t G name G "O"; IDataRea er rea er $ cm ."&ecuteRea er('; i<(rea er.Rea ('' { return rea er["value"(.-oString('; 2 else { return null; 2 2

KK more <unctions... 2

37.Net 3ersion
:rien ,lass DataAccessMo ule

#rivate conn As ID),onnection #rivate cm As ID),omman

#rivate ,onst IetSalue,m -e&t As String $"S"=",- value :R4M My-a)le +?"R" name $ O"

#u)lic Su) 1e5(%ySal conn As ID),onnection' Me.conn $ conn cm $ conn.,reate,omman ('

conn.4pen(' "n Su)

56

#u)lic :unction IetSalue(%ySal name As String' As String cm .,omman -e&t $ IetSalue,m -e&t G name G "O" Dim rea er As IDataRea er $ cm ."&ecuteRea er(' I< (rea er.Rea ('' -*en Return rea er("value"'.-oString(' "lse Return 1ot*ing "n "n I<

:unction

O More :unctions....

"n

,lass

What is a stored proced#re?


* stored procedure is a precompiled e%ecutable ob3ect that contains one or more (P! statements. * stored procedure may be written to accept inputs and return output.

What is the ad&anta"e of #sin" stored proced#re o&er the -?L 7#eries?
)riting the (P! statements inside our code is usually not a good idea. 4n this way you e%pose your database schema #design$ in the code which may be changed. 9ence most of the time programmers use stored procedures instead of plain (P! statements. * stored procedure is a precompiled e%ecutable ob3ect that contains one or more (P! statements. 9ence you can replace your comple% (P! statements with a single stored procedure. (ince, stored procedures are precompiled ob3ects they e%ecute faster at the database server. Most of the time, stored procedures contain more than one command6 in this case, the time to pass the individual commands to the database server from the program is saved. The database is issued 3ust one command #to e%ecute the stored procedure$ and the D0 server e%ecutes all the commands and returns the result in the end. 9ence, the overall interaction time with the D0 server reduces in a great deal. This can result in a huge optimi5ation in case where the D0 server is accessed via a slow network.

57

5ow do stored proced#re look like% can 'o# pro&ide some sample stored proced#res?
9ere we are presenting a brief review of four basic type of stored procedure for (E!E T, 4N(E"T, @&D*TE and DE!ETE operations. 4n (P! (erver, you can create and add stored procedures to your database using the (P! (erver Enterprise Manager.

6/,"TE Stored /ro#ed re


* simple stored procedure to update a record is
,R"A-" #R4,"D3R" 3p ate#roc ( 9artI as int! 9title as varc*ar(C..'! 9topic as varc*ar(C..'! 9aut*orI as int! 9lines as int! 9 ate4<#u)lis*ing as atetime' AS 3#DA-" Article S"title$9title! topic$9topic! aut*orI $9aut*orI ! lines$9lines! ate4<#u)lis*ing$9 ate4<#u)lis*ing +?"R" artI $9artI I4

The name of stored procedure is @pdate&roc and it has the input parameters for each of the fields of our *rticle table. The -uery to be e%ecuted when the stored procedure is run updates the record with the supplied primary key #Wart4d$ using the supplied parameters. 4t is very similar to the code we have written to initiali5e command in the previous e%ample and we hope you don;t have any problem in understanding this even you are not familiar with stored procedure.

INSERT Stored /ro#ed re


* simple stored procedure to insert a record is
,R"A-" #R4,"D3R" Insert#roc ( 9artI as int! 9title as varc*ar(C..'! 9topic as varc*ar(C..'! 9aut*orI as int! 9lines as int! 9 ate4<#u)lis*ing as atetime' AS I1S"R- I1-4 article (artI ! title! topic! aut*orI ! lines! ate4<#u)lis*ing' SA=3"S(9artI ! 9title! 9topic! 9aut*orI ! 9lines! 9 ate4<#u)lis*ing' I4

The stored procedure above is named 4nsert&roc and is very similar to the @pdate&roc e%cept that here we are using the 4N(E"T (P! statement instead of the @&D*TE command.

,ELETE Stored /ro#ed re


* simple stored procedure to delete a record is
,R"A-" #R4,"D3R" Delete#roc (9artI as int' AS D"="-" :R4M article +?"R" artI $ 9artI I4

9ere we have used only one parameter as to delete a record you only need its primary key value.

58

SELECT Stored /ro#ed re


* simple stored procedure to delete a record is
,R"A-" #R4,"D3R" Select#roc AS S"=",- H :R4M Article I4

This probably is the simplest of all. 4t does not take any parameter and only selects all the records from the *rticle table. *ll the four stored procedures presented above are kept e%tremely simple so that the reader does not find any difficulty in understanding the use of stored procedure in his .B/0.Net code. The real world stored procedures are much more comple% and off course useful than theseL

5ow do 2 call a stored proced#re from m' application #sin" A().Net?


@sing stored procedures with *D'.Net in . is e%tremely simple, especially when we have developed the application with (P! commands. *ll we need is, reate a command ob3ect #(-l ommand, etc$ and specify the stored procedure name (et the ommandType property of the command ob3ect to the ommandType.(tored&rocedure enumeration value. This tells the runtime that the command used here is a stored procedure.

That;s itL The sample code to use with data adapter is,

C0 3ersion
KK #reparing Insert SQ= ,omman SLl,omman insert,omman $ ne5 SLl,omman ("Insert#roc"! conn'; insert,omman .,omman -ype $ ,omman -ype.Store #roce ure; ataA apter.Insert,omman $ insert,omman ; insert,omman .3p ate Ro5Source $ 3p ateRo5Source.1one; ...

37.Net 3ersion
O #reparing Insert SQ= ,omman Dim insert,omman $ 1e5 SLl,omman ("Insert#roc"! conn' insert,omman .,omman -ype $ ,omman -ype.Store #roce ure ataA apter.Insert,omman $ insert,omman insert,omman .3p ate Ro5Source $ 3p ateRo5Source.1one

5ow do 2 make m' first application to call stored proced#re #sin" A().Net?
&lease download the attached source code for the sample application using the stored procedures to access the data with *D'.Net in /0 and ..

What are the important points when de&elopin" a data access app with A().Net?

59

*lways try to use the base interfaces for connection, command, data reader and other ob3ects. *lways try to use the (-l lient, (-l(erver e and 'racle lient to connect with the (-l (erver, (-l (erver E and 'racle Database servers as they are speciali5ed and optimi5ed for the specific database servers. (till remember to reference the data provider specific ob3ects #(-l onnection, 'racle ommand$ to reference with the base interface #4Db onnection, 4Db ommand$

C0 3ersion
ID),onnection conn $ ne5 SLl,onnection('; ... ID),omman cm $ ne5 4racle,omman (';

37.Net 3ersion
Dim conn As ID),onnection conn $ 1e5 SLl,onnection('; ... Dim cm As ID),omman cm $ ne5 4racle,omman (';

Do not write the connection string in your code as it may change. Either write it in a te%t file or an %ml file and read it on the application startup. For security purposes, you may also write the encrypted connection string in the te%tB%ml file Try to use the stored procedures wherever possible especially when you are to write a series of -ueries whose individual results are not re-uired to be used in the code in between this series of -ueries. Do not use the comple% -ueries in the source code. 4f the -uery is getting comple%, try to make the views inside the database server and use the views instead. &ractice using the transactions when it makes sense, especially with error handling codes &ut special consideration in the error handling code. The database operation may fail due to various reasons such as invalid connection string, invalid tableBfield name in the -uery, database server failure, connection failure, too many connections on the server or the server busy, invalid -uery, etc Aou need to consider all these while writing the code for error handling. @sing /isual (tudio.Net;s debugger is a very good and useful practice to find the possible errors. "emember, *do.Net e%ception messages are not much useful #or -uite vague$ in general for debugging6 hence the use of watch and -uick watch debugger windows is e%tremely useful and helpful in when debugging the code. )hen using dataset and disconnected architecture, we don;t update the data source #by calling Data*dapter;s @pdate#$ method and Data(et;s *ccept hanges#$ method$ for each update. 4nstead we make the changes local and update all these changes later as a batch. This provides optimi5ed use of network bandwidth. 0@T, this off course is not a better option when multiple users are updating the same database. )hen changes are not to be done locally and need to be reflected at database server at the same time, it is preferred to use the connected oriented environment for all the changes #@&D*TE, 4N(E"T and DE!ETE$ by calling the E%ecuteNonPuery#$ method of your command #(-l ommand or 'leDb ommand$ ob3ect.

60

Disconnected data access is suited most to read only services. 4n common practice clients are often interested in reading and displaying data. 4n this type of situation, the disconnected data access e%cels as it fetches the whole data in a single go and store it in the local buffer #dataset$. This local storage of data eliminates the need of staying connecting to the database and fetching single record at a time. 'n 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., *irline "eservation (ystem$.

What is data "rid and what is the #se of it?


Data :rid is the standard control for viewing data in .Net environment. * data grid control is represented in .Net by (ystem.)indows.Forms.Data:rid class. The data grid control can display the data from a number of data sources e.g. data table, dataset, data view and array.

5ow can 2 make m' first application with (ataGrid #sin" the data from A().Net?
!et;s create a simple application first that loads a table data from database server to the data grid control. First of all, add a data grid control and a button to your form from /isual (tudio toolbo%. )e have set the Name property of data grid to IdgDetails; and its aptionTe%t property to I&rogrammers9eaven Database;. The name of button is Ibtn!oadData;. The event handler for button is,

C0 3ersion
private voi )tn=oa DataN,lic/(o);ect sen er! System."ventArgs e' { string connectionString $ "server$:ARAR; ata)ase$programmers*eaven;" G "ui $sa; p5 $;"; SLl,onnection conn $ ne5 SLl,onnection(connectionString'; string cm String $ "S"=",- H :R4M article"; SLlDataA apter ataA apter $ ne5 SLlDataA apter(cm String! conn'; DataSet s $ ne5 DataSet('; ataA apter.:ill( s! "article"';

gDetails.SetData%in ing( s! "article"'; 2

37.Net 3ersion
#rivate Su) )tn=oa DataN,lic/(%ySal sen er As System.4);ect! N %ySal e As System."ventArgs' ?an les )tn=oa Data.,lic/

Dim connectionString As String $ "server$#MIII; ata)ase$programmers*eaven;" G N "ui $sa; p5 $;"

61

Dim conn As 1e5 SLl,onnection(connectionString' Dim cm String As String $ "S"=",- H :R4M article" Dim Dim ataA apter As 1e5 SLlDataA apter(cm String! conn' s As 1e5 DataSet('

ataA apter.:ill( s! "article"'

gDetails.SetData%in ing( s! "article"'

"n

Su)

9ere we first created data adapter and filled the data set using it as we used to do in other applications. The only new thing is the binding of UarticleV table to the data grid control which is done by calling the (etData0inding#$ method of the Data:rid class. The first parameter of this method is the dataset while the second parameter is the name of table in the dataset.

C0 3ersion
gDetails.SetData%in ing( s! "article"';

37.Net 3ersion
gDetails.SetData%in ing( s! "article"'

)hen you e%ecute this program and select the !oad button you will see the output presented in the previous figure.

5ow can 2 make m' data "rid to &iew data from m#ltiple related ta$les?
!et;s see how we can use Data :rid control to show multiple related tables. )hen two tables are related, one is called the parent table while the other is called the child table. The child table contains the primary key of parent table as a foreign key. For e%ample in our &rogrammers9eaven database, table *uthor is the parent table of the *rticle table as the *rticle table contains I*uthor4d; as foreign key which is a primary key in the *uthor table. 4n this e%ample, we will use data grid to show the related records from article and author table. 4n order to specify the relationship between the two tables we need to use the Data"elation class as,

C0 3ersion
gDetails.SetData%in ing( s! "article"' DataRelation relation $ ne5 DataRelation("ArtAut*"! s.-a)les["aut*or"(.,olumns["aut*orI "(! s.-a)les["article"(.,olumns["aut*orI "( ';

37.Net 3ersion
62

Dim relation As 1e5 DataRelation("ArtAut*"! N s.-a)les("aut*or"'.,olumns("aut*orI "'! N s.-a)les("article"'.,olumns("aut*orI "' N '

9ere the first argument of Data"elation constructor is the name for the new relation while second and third arguments are the columns of the tables which will be used to relate the two tables. *fter creating this relationship we need to add it to the "elations collection of the dataset.

C0 3ersion
s.Relations.A (relation';

37.Net 3ersion
s.Relations.A (relation'

9ence the modified code for the !oad Data button is,

C0 3ersion
private voi )tn=oa DataN,lic/(o);ect sen er! System."ventArgs e' { string connectionString $ "server$#MIII; ata)ase$programmers*eaven;" G "ui $sa; p5 $;"; SLl,onnection conn $ ne5 SLl,onnection(connectionString';

string cm String $ "S"=",- H :R4M article"; SLlDataA apter DataSet ataA apter $ ne5 SLlDataA apter(cm String! conn';

s $ ne5 DataSet(';

ataA apter.:ill( s! "article"';

cm String $ "S"=",- H :R4M aut*or"; ataA apter $ ne5 SLlDataA apter(cm String! conn'; ataA apter.:ill( s! "aut*or"';

DataRelation relation $ ne5 DataRelation("ArtAut*"! s.-a)les["aut*or"(.,olumns["aut*orI "(! s.-a)les["article"(.,olumns["aut*orI "( '; s.Relations.A (relation';

63

DataSie5

v $ ne5 DataSie5( s.-a)les["aut*or"('; v;

gDetails.DataSource $ 2

37.Net 3ersion
#rivate Su) )tn=oa DataN,lic/(%ySal sen er As System.4);ect! N %ySal e As System."ventArgs' ?an les )tn=oa Data.,lic/

Dim connectionString As String $ "server$#MIII; ata)ase$programmers*eaven;" G N "ui $sa; p5 $;" Dim conn As 1e5 SLl,onnection(connectionString' Dim cm String As String $ "S"=",- H :R4M article" Dim Dim ataA apter As 1e5 SLlDataA apter(cm String! conn' s As 1e5 DataSet('

ataA apter.:ill( s! "article"'

cm String $ "S"=",- H :R4M aut*or" ataA apter $ 1e5 SLlDataA apter(cm String! conn' ataA apter.:ill( s! "aut*or"'

Dim relation As 1e5 DataRelation("ArtAut*"! N s.-a)les("aut*or"'.,olumns("aut*orI "'! N s.-a)les("article"'.,olumns("aut*orI "' N ' s.Relations.A (relation'

Dim

v As 1e5 DataSie5( s.-a)les("aut*or"'' v

gDetails.DataSource $ "n Su)

64

4n the above code we first filled the dataset with the two tables, defined the relationship between them and then added it to the dataset. 4n the last two lines, we created an instance of Data/iew class by supplying the parent table in its constructor call and then set the Data(ource property of data grid to this data view. )hen we compile and e%ecute this application, the data grid will show the records of parent table with I2; button on the left of each record

)hen you press the I2; button on the left of the record, it will e%pand to show the name of relationship as a link

Now when you click the relation name, the data grid will show all the related records in the child table

65

(till you can see the parent record at the top of all the rows of the child table. Aou can go back to the parent table using the back arrow button #X$ at the title bar of the data grid.

What are the iss#es related to the deplo'ment of data access application?
(ome of the basic issues related to the deployment of the data access applications are, an we suppose the re-uired database e%ists at the target locationK 4f the database does e%ist then how can we get the connection string of itK (hould we get it at the installation timeK 'r at the first runK 4f the database does not e%ist then how it can be createdK 4s it the responsibility of human installing our applicationK 'r the application should create it at the time of installationK 4f the database is to be created by the application installation, then how does the installation setup know where #on which machine$ to create the databaseK *nd what user name and password the setup should use to create the databaseK 'nce, the database is created or its connection string is found at the setup time, then how to store the connection string for later use #regular e%ecution$K )hat if the database address #connection string$ is changed during the application life cycle then what should be the application behaviorK 9ow can the application be aware of the new connection stringK 4f the database schema is hard<coded in the code #like table and field names$ and the D0 schema is changed #tableBfield name or data type is changed or new fieldBtable added or some fieldsBtables deleted$ because of any reason, then how to fi% this problemK

Aou can see from the above points that the basic issue is the identification of the address #or connection string$ of the database server. The most important point to remember here is that the application must perform in any condition and must not be crashed because of any condition and most of the problems #if not all$

66

should be handled without any change in the code or any update patch installation

5ow do 2 sol&e the deplo'ment iss#es /mentioned in the pre&io#s 4A?0?


'k, let;s discuss some of the issues and their solution briefly. The specific detail of these solutions is given in the ne%t F*Ps. The easiest and very sound solution is to provide the database script to create necessary database and tables along with the installation and ask your user to run the script on the target database server to create the re-uired database. Then ask the user to supply the connection string at the installation setup time. Aou can create the database with the installation by e%ecuting the database creation script with the installation. 0ut before this, you have to ask the user the location #the computer on the network$ where the database server e%ists, and the user name, password to login to the database. The connection string should be stored in a te%t or binary or %ml file. Aou can also encrypt the connection string before writing it to the file. The application, thus, is re-uired to decrypt and load the connection string in the memory at each startup. The application should load the connection string at each startup and attempt to connect to the database. 4f the connection attempt fails then it should inform the user that the database is not available and ask the user to setup the database and try again. The application should also allow the user to change the database connection string any time and, it the application logic permits, let the user specify to work without database. 4f the user specifies a new connection string during the application startup or regular e%ecution, the application should save it for later use. 'ne solution to the schema changed problem is to use views and stored procedure wherever possible. 0ut if this is not done or the change is too big to be catered by the views andBor stored procedure then you can supply a new data access module update #a new D!! may be$. For this reason, it is advised to separate the data access code in a separate physical and logical module #or assembly in .Net language$ so you can change it without affecting the overall application. 0ut when using this, the interface #the method signatures$ should be made that abstract that they does not e%actly map to the physical database schema but to the logical schema. Finally, if the database schema change is ma3or #which is not a very good sign for the application overall design$ then there is no solution but to change the code and ship the installation againLLL

5ow do 2 set the connection strin" at installation 1specific data pro&ider?


)ell this is -uite tricky and interesting. onnection strings are database dependent and different database servers allow connection strings in different formats. 4f you are using the database specific provider classes #like those from (ystem.Data.(-l lient or (ystem.Data.'racle lient$ then you can generate the connection string easily by taking the specific inputs from the user. For e%ample,

67

if you are using (P! (erver and the classes from the (ystem.Data.(-l lient namespace then we can ask user the (P! (erver instance name, the user name, password of if heBshe is using the )indows *uthentication to log in and the database name.

5ow do 2 set the connection strin" at installation 1"eneral data pro&ider?


The problem arises when you are using the general data providers such as classes from (ystem.Data.'leDb and (ystem.Data.'dbc namespaces. Aou can;t make a general :@4 to generate the connection string for all the database servers. Then what to do nowK The solution is the Data!ink Dialog. Aou must have seen the dialog which looks like this in many windows applications,

(o how you can use this dialog in your programK For this you need add a reference to 'M component IMicrosoft '!E D0 (ervice omponent E.F Type !ibrary; which should be available if you have installed Microsoft *ctive+ Data omponents. 'nce you have added the component, you can show the Data !ink &roperties dialog bo% by making an ob3ect of type M(D*( .Data!ink class and calling its &romptNew#$ method.

C0 3ersion
MSDAS,.Data=in/s u l $ ne5 MSDAS,.Data=in/s,lass('; u l.#rompt1e5(';

37.Net 3ersion
68

Dim u l As MSDAS,.Data=in/s u l $ 1e5 MSDAS,.Data=in/s,lass u l.#rompt1e5('

The above code will show the Data !ink &roperties dialog bo%. 0ut how can we get the connection string generated by the dialog bo%K The &romptNew#$ method returns a connection type ob3ect which can be captured in an ob3ect of type *D'D0. onnection. 9ence for this, add a reference to Iadodb; .Net assembly in your pro3ect, and get the connection string using the onnection(tring property of this ob3ect. The following code snippets demonstrate this,

C0 3ersion
string connStr $ "";

MSDAS,.Data=in/s u l $ ne5 MSDAS,.Data=in/s,lass('; AD4D%.,onnection conn $ (AD4D%.,onnection' u l.#rompt1e5(';

i<(conn 0$ null' { connStr $ conn.,onnectionString; 2

37.Net 3ersion
Dim connStr As String

Dim u l As MSDAS,.Data=in/s u l $ 1e5 MSDAS,.Data=in/s,lass Dim conn As AD4D%.,onnection $ u l.#rompt1e5('

I< 1ot conn Is 1ot*ing -*en connStr $ conn.,onnectionString "n I<

Aou can use this code in the overrided 4nstall#$ method of your pro3ect;s installer class #the class derived from (ystem. onfiguration.4nstall.4nstaller class$, and add the pro3ect output in the I ustom *ctions; of the setup pro3ect.

5ow do 2 s#ppl' the connection strin" d#rin" first r#n or d#rin" the re"#lar e*ec#tion?
69

)ell that should be very simple 1ust add the Data !ink &roperties dialog bo% at the start of the application or during the regular e%ecution of the application whenever you need it. *lternatively, you can also provide your own designed user interface for connection string related properties, if your application supports specific .Net data providers #like (ystem.Data.(-l lient or (ystem.Data.'racle lient$

5ow do 2 store : retrie&e the connection strin" in : from a te*t file?


Aou can store the connection string in the te%t file or an %ml file and later retrieve it. !et;s see some e%ample code to write a connection string to the te%t file and read it back

C0 3ersion
string connStr $ "";

KK get connection string in t*e connStr varia)le

KK +rite connection string to te&t <ile Stream+riter s5 $ ne5 Stream+riter(9",67,onnectionString.t&t"'; s5.+rite=ine(connStr';

KK ...

KK Rea

connection string <rom t*e te&t <ile

StreamRea er sr $ ne5 StreamRea er(9",67,onnectionString.t&t"'; connStr $ sr.Rea =ine(';

37.Net 3ersion
Dim connStr As String $ ""

O get connection string in t*e connStr varia)le

O +rite connection string to te&t <ile Dim s5 As 1e5 Stream+riter(",67,onnectionString.t&t"' s5.+rite=ine(connStr'

70

O ...

O Rea

connection string <rom t*e te&t <ile

Dim sr As 1e5 StreamRea er(",67,onnectionString.t&t"' connStr $ sr.Rea =ine('

5ow do 2 store : retrie&e the connection strin" in : from an 9ML file?


'nce you get the connection string, you can store the connection string in the te%t file or an %ml file and later retrieve it. !et;s see some e%ample code to write a connection string to an +M! file and read it back

C0 3ersion
string connStr $ "";

KK get connection string in t*e connStr varia)le

KK +rite connection string to &ml <ile XmlDocument &mlDoc $ ne5 XmlDocument('; Xml1o e &n $ &mlDoc.,reate1o e(Xml1o e-ype."lement! ",onnectionString"! ""'; &n.Inner-e&t $ connStr; &mlDoc.Appen ,*il (&n'; &mlDoc.Save(9",67,onnectionString.&ml"';

KK ...

KK Rea

connection string <rom t*e te&t <ile

XmlDocument &mlDoc $ ne5 XmlDocument('; &mlDoc.=oa (9",67,onnectionString.&ml"'; Xml1o e &n $ &mlDoc.SelectSingle1o e(",onnectionString"'; connStr $ &n.Inner-e&t;

71

37.Net 3ersion
Dim connStr As String $ ""

O get connection string in t*e connStr varia)le

O +rite connection string to &ml <ile Dim &mlDoc As 1e5 XmlDocument Dim &n As Xml1o e &n $ &mlDoc.,reate1o e(Xml1o e-ype."lement! ",onnectionString"! ""' &n.Inner-e&t $ connStr &mlDoc.Appen ,*il (&n' &mlDoc.Save(",67,onnectionString.&ml"'

O ...

O Rea

connection string <rom t*e &ml <ile

Dim &mlDoc As 1e5 XmlDocument &mlDoc.=oa (",67,onnectionString.&ml"' Dim &n As Xml1o e &n $ &mlDoc.SelectSingle1o e(",onnectionString"' connStr $ &n.Inner-e&t

5ow do 2 make m' first @5ello% (ata Access Application (eplo'mentA set#p pro"ram?
)e will start with the assumption that you have a data access application. Note that we are only providing here the . e%ample. The /0.Net e%ample is e%actly similar. )hy we didn;t include the /0.Net e%ampleK 0ecause, the intent here is not to e%plain the code but the procedure of how to create the data accessing application;s deployment pro3ect which is independent of the language being used. *ll the code we will present here has already been presented in the previous F*Ps and e%plained in much detail. The first step, then, is to add an installer class. The easiest way to do is to right click the pro3ect icon in the solution e%plorer and select I*dd New 4temM; and in the pop<up window, select 4nstaller class, name it appropriately and select I'pen; button to add it. Now right click the newly added installer class and select view

72

code. Aou will notice that this new class is automatically inherited from the (ystem. onfiguration.4nstall.4nstaller class
pu)lic class InstallerC 6 System.,on<iguration.Install.Installer

The only thing you need to do now in this class is to override the 4nstall#$ method of the base class, write the code you want to e%ecute when the installation setup is e%ecuted. )e have written the code to display the Data !ink &roperties dialog bo% and save the resulted connection string into an %ml file, so later the application can use it.
pu)lic overri e voi Install(IDictionary stateSaver' { )ase.Install (stateSaver'; string connStr $ "";

MSDAS,.Data=in/s u l $ ne5 MSDAS,.Data=in/s,lass('; AD4D%.,onnection conn $ (AD4D%.,onnection' u l.#rompt1e5(';

i<(conn 0$ null' { connStr $ conn.,onnectionString; 2

KK +rite connection string to &ml <ile XmlDocument &mlDoc $ ne5 XmlDocument('; Xml1o e &n $ &mlDoc.,reate1o e(Xml1o e-ype."lement! ",onnectionString"! ""'; &n.Inner-e&t $ connStr; &mlDoc.Appen ,*il (&n'; &mlDoc.Save(9",67,onnectionString.&ml"'; 2

This is all for the setup, we have added a button to our database deployment application form which displays the connection string in a message bo%. 4t retrieves the connection string from the %ml file generated by the installation setup program.
private voi )tnS*o5,onnStrN,lic/(o);ect sen er! System."ventArgs e' { string connStr $ "";

73

KK Rea

connection string <rom t*e &ml <ile

XmlDocument &mlDoc $ ne5 XmlDocument('; &mlDoc.=oa (9",67,onnectionString.&ml"'; Xml1o e &n $ &mlDoc.SelectSingle1o e(",onnectionString"'; connStr $ &n.Inner-e&t; Message%o&.S*o5(connStr! ",onnection String <rom XM= <ile"';

Now the application is ready. )e will start building our setup pro3ect. For this, add a new I(etup and Deployment; pro3ect to the solution by right clicking the solution and selecting I*dd New &ro3ectM; in the pop<up window, selecting the I(etup &ro3ect; from the I(etup and Deployment &ro3ects; section. 'nce the setup pro3ect is added to the solution, right click it in the solution e%plorer and select /iew<<YFile (ystem. 9ere right click the application folder icon and select &ro3ect 'utput <<Y &rimary 'ut put of your data access pro3ect. This will automatically add the pro3ect dependencies. Now right click the I&rimary 'utput of your pro3ect; and create its short cut. opy this shortcut to the Desktop folder and the @ser &rogram Menu and rename shortcut appropriately.

74

Now to ask the setup pro3ect run our custom installation code #we have written in the 4nstaller class in the data access application$, we need to add the primary output of our pro3ect to the custom actions of the setup pro3ect. To do this, right click the setup pro3ect in the solution e%plorer, and select /iew <<Y ustom *ctions. 9ere right click I4nstall; and select I*dd ustom *ction;. 4n the popup window, select the primary output of the database access application from the application folder and click '8.

75

This is all we need to doL "ebuild the solution and remove any minor bugs #if they do popup$. )hen your setup pro3ect will be built, it will generate a (etup.e%e file in its debug #or release folder depending on the pro3ect configuration$. "un this setup.e%e to install this application. The setup will ask you the connection string and save it in the %ml file.

76

*fter installation is complete, run the application using its desktop icon. )hen you will click the button on the form, it will read the connection string from the %ml file and display it in the message bo%.

77

%ow to

se re)ation o18e#ts in a dataset?

(ata-etJs that contain multiple (ataTa$le ob3ects can use (ataRelation ob3ects to relate one table to another. *dding a Data"elation to a Data(et adds by default a ,ni7#e onstraint to the parent table and a Foreign8ey onstraint to the child table. The code sample below creates a (ataRelation using two (ataTa$le ob3ects in a (ata-et. Each DataTable contains a column named ust4D which serves as a OrelationO between two the DataTable ob3ects. The e%ample adds a single Data"elation to the "elations collection of the Data(et. The first argument in the sample specifies the name of the Data"elation being created. The second argument sets the parent Data olumn and the third argument sets the child Data olumn.
custDS.Relations.A (",ust4r ers"! custDS.-a)les[",ustomers"(.,olumns[",ustID"(! custDS.-a)les["4r ers"(.,olumns[",ustID"(';

'"
private voi ,reateRelation(' { Data,olumn parent,ol; Data,olumn c*il ,ol;

parent,ol $ DataSetC.-a)les[",ustomers"(.,olumns[",ustID"(; c*il ,ol $ DataSetC.-a)les["4r ers"(.,olumns[",ustID"(;

DataRelation rel,ust4r er; rel,ust4r er $ ne5 DataRelation(",ustomers4r ers"!

parent,ol! c*il ,ol';

DataSetC.Relations.A

(rel,ust4r er';

,ataReader 3s ,ataSet?
The *D'.NET (ataReader is used to retrieve Oread<onlyO B Oforward<onlyO data from a database. @sing the (ataReader increases application performance and reduces system overheads. This is due to one row at a time is stored in memory. Aou create a (ataReader by calling ommand.E*ec#teReader after creating an instance of the ommand ob3ect.

78

The following line of code is used to retrieve rows from a data source.
SLlDataRea er myRea er $ my,omman ."&ecuteRea er(';

The Read method of the Data"eader ob3ect is used to obtain a row from the results of the -uery, like so.
(myRea er.Rea ('' ,onsole.+rite=ine("7t{.27t{C2"! myRea er.IetInt32(.'! myRea er.IetString(C''; myRea er.,lose(';

The (ata-et is a in<memory representation of data that provides a consistent relational programming model regardless of the data source. 4t can be used with multiple data sources. The (ata-et represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and ob3ects in a (ata-et are consistent with those in the relational database model. The Data(et can also persist and reload its contents as +M! and its schema as +M! (chema definition language #+(D$ schema. The (ataAdapter acts as a bridge between a Data(et and a data source for retrieving and saving data. The (ataAdapter provides this bridge by Omapping 4illO. )hich changes the data in the (ata-et to match the data in the data source. @pon this an ,pdate occurs, which changes the data in the data source to match the data in the (ata-et. 'n connecting to a Microsoft K(P! (erver database, an increase in overall performance can be obtained by using the -7l(ataAdapter along with its associated -7l ommand and -7l onnection. For other )LE (B<supported databases, use the (ataAdapter with its associated )le($ ommand and )le($ onnection.

%ow do I a##ess a S5L stored (ro#ed re?


Aou can access (P! stored procedures the same way as e%ecuting other (P! commands. (et the -uery string as the name of the stored proced#re and then set the ommandT'pe to be ommandT'pe.-tored<roced#re. 0elow is an e%ample of one input and one output parameter.
i<(my,onn.State $$ ,onnectionState.,lose 'my,onn.4pen('; SLl,omman my,m $ ne5

SLl,omman ("spNmyNstore Nproce ure"!my,onn'; my,m .,omman -ype $ ,omman -ype.Store #roce ure;

SLl#arameter parm; parm $ my,m .#arameters.A (ne5 SLl#arameter("9custi "!

79

SLlD)-ype.Sar,*ar!D.''; parm.Direction $ #arameterDirection.Input; my,m .#arameters["9custi "(.Salue $ 4r erID;

parm $ my,m .#arameters.A

(ne5 SLl#arameter("9cust1ame"!

SLlD)-ype.Sar,*ar!D.''; parm.Direction $ #arameterDirection.4utput;

SLlDataA apter

a $ ne5 SLlDataA apter('; ("your mapping"!"your mapping"';

a.-a)leMappings.A a.Select,omman DataSet

$ my,m ;

s $ ne5 DataSet(';

a.:ill( s'; Data-a)le result-a)le $ s.-a)les[.(;

Methods o& the Command 418e#ts with data1ases?


The ommand ob3ect is represented by two corresponding classes, -7l ommand and )le($ ommand. ommand ob3ects are used to e%ecute statements #commands$ to a database via a data connection. The ommand ob3ects can be used to e%ecute stored procedures on the Database, (P! statements, or return complete tables directly. ommand ob3ects provide three methods that are used to e%ecute commands on the database, E*ec#teNon?#er'. E%ecutes direct (P! commands, such as 4N(E"T, @&D*TE or DE!ETE. E*ec#te-calar. "eturns a single value from a Database Puery. E*ec#teReader. "eturns a result set by way of a Data"eader ob3ect.

%ow do I dis()a$ a data ta1)e in a data 'rid?


The following code -ueries an M( *ccess Table, then displays all the columns of that table in a Data :rid.
O"sta)lis* a connection to t*e Dim ,onnString As String ata source.

80

,onnString $ "#rovi er$Microso<t.Aet.4="D%.B..;" Y Source$,67-est.m )"

"Data

Dim ,onn As 1e5 System.Data.4leD).4leD),onnection(,onnString' ,onn.4pen(' Dim apt As 1e5 System.Data.4leD).4leD)DataA apter("-a)leC"! ,onn'

Dim

st As 1e5 DataSet

apt.:ill( st! "-a)leC"'

DataIri C.SetData%in ing( st! "-a)leC"'

,onn.,lose('

@pon running the above code, TableE from the a OTestO database will be displayed in a Data:rid.

%ow do I insert data entered in a te9t1o9 into the data1ase?


The data you enter in the te%tbo%es will be inserted into the database when of the click of a 0utton. The working senario is a database called OEmpO with a table named OTableEO with three columns. *lso a Form with three Te%t0o%es and one ommand 0utton.
Imports System.Data.4leD) Dim cn As 4leD),onnection Dim cm As 4leD),omman Dim r As 4leD)DataRea er Dim icount As Integer Dim str As String #rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an lesN %utton2.,lic/ -ry cn $ 1e5 4leD),onnection("#rovi er$Microso<t.Aet.4="D%.B..;Data Source$,67emp.m );#ersist SecurityN In<o$:alse"' cn.4pen(' str $ "insert into ta)leC values(" Y ,Int(-e&t%o&C.-e&t' Y "!O" Y -e&t%o&2.-e&t Y "O!O" Y -e&t%o&3.-e&t Y "O'" Ostring stores t*e comman Oan ,Int is use to convert num)er! to string cm $ 1e5 4leD),omman (str! cn' icount $ cm ."&ecute1onQuery

81

Message%o&.S*o5(icount' O isplays num)er o< recor s inserte ,atc* "n "n -ry Su)

%ow do I a##ess S5L ser+er in 37.NET?


To access data from a table in K(P! (erver you need to import the namespace (ystem.Data.(-l lient and establish a connection from the application to the server. The following code demonstrates how to connect to a K(P! (erver and display data from the ODiscountsO table in the sample database O&@0(O.
Imports System.Data.SLl,lient #u)lic ,lass :ormC In*erits System.+in o5s.:orms.:orm Dim my,onnection As SLl,onnection Dim my,omman As SLl,omman Dim r As 1e5 SLlDataRea er(' O eclaring t*e o);ects nee #rivate Su) :ormCN=oa (%ySal sen er As System.4);ect! %ySal e AsN System."ventArgs' ?an les My%ase.=oa my,onnection $ 1e5 SLl,onnection("server$local*ost;ui $sa;p5 $; ata)ase$pu)s"' Oesta)lis*ing connection -ry my,onnection.4pen(' Oopening t*e connection my,omman $ 1e5 SLl,omman ("Select H <rom

iscounts"! my,onnection'

Oe&ecuting t*e comman an assigning it to connection r $ my,omman ."&ecuteRea er(' +*ile r.Rea (' Orea ing <rom t*e atarea er Message%o&.S*o5(" iscounttype" Y r(.'.-oString('' Message%o&.S*o5("storNi " Y r(C'.-oString('' Message%o&.S*o5("lo5Lty" Y r(2'.-oString('' Message%o&.S*o5("*ig*Lty" Y r(3'.-oString('' Message%o&.S*o5(" iscount" Y r(B'.-oString('' O isplaying t*e ata <rom t*e ta)le "n +*ile r.,lose(' my,onnection.,lose(' ,atc* e As "&ception "n -ry "n "n Su) ,lass

82

%ow to insert an ima'e in "##ess ,ata1ase?


The following code asks for a path of a :if image. Then inserts the :if image to an *ccess database.
:ile name is Image.v) Imports System Imports System.I4 Imports System.Data #u)lic ,lass SaveImage S*are Su) main(' Dim o As System.I4.:ileStream Dim r As StreamRea er Dim gi<:ile As String ,onsole.+rite(""nter a Sali gi<:ile $ ,onsole.Rea =ine .Ii< <ile pat*"'

I< Dir(gi<:ile' $ "" -*en ,onsole.+rite("Invali :ile #at*"' "&it Su) "n I< o $ 1e5 :ileStream(gi<:ile! :ileMo e.4pen! :ileAccess.Rea ! :ileS*are.Rea ' r $ 1e5 StreamRea er(o' -ry Dim :ile%yteArray(o.=engt* M C' As %yte o.Rea (:ile%yteArray! .! o.=engt*' Dim ,on As 1e5 N System.Data.4leD).4leD),onnection("#rovi er$Microso<t.Aet.4="D%.3.DC;#ersist Security In<o$:alse;Data Source$-est.m )"' Dim SLl As String $ "I1S"R- I1-4 Images (#ic!:ileSi8e' SA=3"S (Z!Z'" Dim ,m As 1e5 System.Data.4leD).4leD),omman (SLl! ,on' ,m .#arameters.A ("9#ic"! System.Data.4leD).4leD)-ype.%inary! o.=engt*'.Salue $ :ile%yteArray ,m .#arameters.A ("9:ileSi8e"! System.Data.4leD).4leD)-ype.Sar,*ar! C..'.Salue $ o.=engt* ,on.4pen(' ,m ."&ecute1onQuery(' ,on.,lose(' ,atc* e& As "&ception ,onsole.+rite(e&.-oString' "n "n "n -ry Su) ,lass

* file will be inserted in the Database each time the code is e%ecuted.

83

A-<.NET
What is the difference $etween A-< and A-<.NET?
)eb application development in .NET with *(&.NET has evolved a great deal. The overall architecture of web applications in .Net is much more improved and robust. The enhanced features in *(&.NET make it the best available technology for web application development. The code behind the *(&.Net scripts can be in written in any .Net compliant programming language. The script #*(&.NET scripts$, logic #code behind$ and presentation #view$ are separated from each other so they may evolve independently. There are much more server controls now available in .Net including the standard calendar and ama5ingly useful data grid controls. The *(&.Net web applications can now use .NET assemblies and 'M components to serve the client re-uests. *(&.NET pages are now compiled contrary to the *(& pages which are interpreted by the 4(* server. Truly speaking, there is no comparison between *(& and *(&.NET... *(&.NET simply rulesL

What is "S/.NET?
*(&.NET is a powerful programming platform for developing web<based applications and services. 4t comes with rich set of web controls to create dynamic, fast and interactive web pages. )eb pages built using *(&.NET are called *(&.NET web pages or web forms. *(&.NET simplifies web development by using )A(4)A: #what you see is what you get$ editors. *(&.NET helps to build comple% web applications with the use of drag and drop control support. /isual (tudion.NET helps us to build web applications #*(&.NET$ using either the . or /0 programming language. The following features are making developers choose *(&.NET over other technologies, *(&.NET applications can be designed and developed using "*D #"apid *pplication Development$ tools. *(&.NET web forms support a variety of controls and also support user created and third party controls. *ny .NET Frame)ork language can be used to develop *(&.NET applications. *(&.NET uses the ommon !anguage "untime # !"$ resource and benefits from itJs features.

What is the

se o& We1.#on&i' &i)e?

*(&.NET configuration files are +M!<based te%t files. Each Oweb.configO file applies configuration settings to the directory it is located in and to all virtual sub directories under it. (ettings in sub directories can optionally override or modify settings specified in main directories. The root configuration file OWinNTBMicrosoft.NETB4rameworkBC&ersionDBconfi"Bmachine.confi" O provides default configuration settings for the entire machine. *(&.NET configures 44( to prevent direct browser access to Oweb.configO files. This ensures that their values cannot become public #*ttempts to access them

84

will cause *(&.NET to return HF>, *ccess Forbidden$. *t run time, *(&.NET uses these Oweb.configO configuration files to hierarchically compute a uni-ue collection of settings for each incoming @"! target re-uest. These settings are calculated only once and then cached across subse-uent re-uests. *(&.NET automatically watches for file changes and will invalidate the cache if any of the configuration files change.

What are We1 Ser+i#es and the sed with it?

nder)$in' (roto#o)

)eb (ervices are applications that provide services on the internet. )eb services allow for programmatic access of business logic over the )eb. )eb services typically rely on +M!<based protocols, messages, and interface descriptions for communication and access. )eb services are designed for use by other programs or applications rather than directly by end user. &rograms invoking a )eb service are called clients. ('*& over 9TT& is the most commonly used protocol for invoking )eb services. There are three main uses of )eb services. *pplication integration )eb services within an intranet are commonly used to integrate business applications running on different platforms. For e%ample, a .NET client running on )indows ?FFF can easily invoke a 1ava )eb service running on a mainframe or @ni% machine to retrieve data from a legacy application. 0usiness integration )eb services allow trading partners to engage in e<business allowing them to leverage the e%isting 4nternet infrastructure. 'rgani5ations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e<business with )eb services means a low barrier to entry because )eb services can be added to e%isting applications running on any platform without changing legacy code. ommercial )eb services focus on selling content and business services to clients over the 4nternet similar to familiar )eb pages. @nlike )eb pages, commercial )eb services target applications as their direct users. E%ample, ontinental *irlines e%poses flight schedules and status )eb services for travel )eb sites and agencies to use in their applications. !ike )eb pages, commercial )eb services are valuable only if they offer services that are needed. 4t makes sense to sell real<time weather information or stock -uotes as a )eb service. Technology can help you add value to your services and e%plore new markets. 9owever ultimately customers pay for contents andBor business services, not for technology.

%ow to 'enerate a We1Ser+i#e (ro9$? What are S4"/, WS,L, and 6,,I?
('*& is an +M!<based messaging protocol designed for e%changing formatted data #messages$ over the 4nternet. @sing ('*& you can send re-uest and reply messages. ('*& is simple, easy to use, light weight and completely neutral with respect to operating systems, programming languages, and distributed computing platforms. *fter ('*& came into e%istence as a mechanism for e%changing +M! messages among enterprises, a function was needed to describe the messages and how they are e%changed.

85

The )eb (ervices Description !anguage #)(D!$ is a particular form of an +M! (chema. Developed by Microsoft and 40M for the purpose of defining the +M! message, operation, and protocol mapping of a web service accessed using ('*& or other +M! protocol. )(D! defines web services in terms of OendpointsO that operate on +M! messages. The )(D! synta% allows both the messages and the operations on the messages to be defined abstractly, so they can be mapped to multiple physical implementations. The current )(D! specification describes how to map messages and operations to ('*& E.E, 9TT& :ETB&'(T and M4ME. )(D! creates web service definitions by mapping a group of endpoints into a logical se-uence of operations on +M! messages. The same +M! message can be mapped to multiple operations #or services$ and bound to one or more communications protocols using OportsO. The O@niversal Description, Discovery, and 4ntegrationO #@DD4$ defines a data model #in +M!$. *lso ('*& *&4Js for registration and searching business information, web services that a business e%poses to the 4nternet are also covered. @DD4 is an independent consortium of vendors founded by Microsoft, 40M and *riba. This pro3ect purpose of developing an 4nternet standard for web service description registration and discovery. Microsoft, 40M and *riba also are hosting the initial deployment of the @DD4 service. This is conceptually patterned after DN( #the 4nternet service that translates @"!s into T & addresses$. @DD4 uses a private agreement profile of ('*& #@DD4 doesnJt use the ('*& seriali5ation format because itJs not well suited to passing complete +M! documents #itJs aimed at "& style interactions$. The main idea is that businesses use ('*& *&4s to register themselves with @DD4. 'ther businesses search the @DD4 when they want to discover a trading partner. The information in @DD4 is categori5ed according to industry type and geographical location, allowing @DD4 subscribers to search through lists of potentially matching businesses. 'nce a specific business is chosen, another call to @DD4 is made to obtain the specific contact information for that business. The contact information includes a pointer to the target businessJs )(D! or other +M! schema file describing the web service that the target business publishes.

What is the tra#e

ti)it$

sed &or?

,sin" the -)A< Trace ,tilit' The Microsoft (imple 'b3ect *ccess &rotocol #('*&$ Toolkit ?.F includes a T &B4& trace utility, M(('*&T.E+E. Aou use this trace utility to view the ('*& messages sent by 9TT& between a ('*& client and a service on a server. 4n order to use the Trace @tility, perform the following steps on the server. 'pen the )eb (ervices Description !anguage #)(D!$ file. E$ 4n the )(D! file, locate the Zsoap,addressY element that corresponds to the service and change the location attribute for this element to port TFTF. For e%ample, change
F*ttp6KKMyServerKSDirKService.5s lT

to

F*ttp6KKMyServer6P.P.KSDirKService.5s lT

86

. ?$ "un M(('*&T.e%e. >$ File menu, New, lick OFormatted TraceO #if you donJt want to see 9TT& headers$ or click @nformatted Trace #if you want to see 9TT& headers$. H$ 4n the Trace (etup dialog bo%, click '8 to accept the default values. ,sin" the Trace ,tilit' on lient

To see all sendBreceive messages from a service, do the following steps on the client. E$ opy the )(D! file from the server to the client.

?$ Modify location attribute of the Zsoap,addressY element in the local copy of the )(D! document to direct the client to
local*ost6P.P.

Make a note of the current host and port. For e%ample, to hange

F*ttp6KKMyServerKSDirKService.5s lT F*ttp6KKlocal*ost6P.P.KSDirKService.5s lT

and make note of OMy(erverO. >$ 'n the client, run M(('&T.e%e. H$ File menu, New, and either click Formatted Trace #if you donJt want to see 9TT& headers$ or click @nformatted Trace #if you do want to see 9TT& headers$. D$ 4n the Destination host bo%, enter the host specified in (tep ?. 7$ 4n the Destination port bo%, enter the port specified in (tep ?. G$ lick '8.

%ow do I

()oad a &i)e &rom m$ "S/.NET (a'e?

To upload a file with your *(&.NET page, you need the use of two classes, -'stem.We$.,2.5tml ontrols.5tml2np#t4ile class and the -'stem.We$.5ttp<osted4ile. The 5tml2np#t4ile class represents an 9TM! input control that the user will use on the client to select a file to upload. The 5ttp<osted4ile class represents the uploaded file. This is obtained from the .<osted4ile property of the 9tml4nputFile control. 4n order to use the 9tml4nputFile control, you need to add the enct'pe attribute to your form tag as follows,
F<orm i $"uploa " met*o $"post" runat$"server" enctype$"multipartK<ormM ata"T

87

0elow is a simple e%ample of how to upload a file via an *(&.NET page using

..

F[9 Import 1amespace$"System" [T F[9 Import 1amespace$"System.+e)" [T F[9 Import 1amespace$"System.+e).3I.?tml,ontrols" [T F[9 Import 1amespace$"System.I4" [T F[9 Import 1amespace$"System.Dra5ing" [T F*tmlT F*ea T FtitleTuploa NcsFKtitleT FK*ea T Fscript language$",\" runat$"server"T pu)lic voi 3ploa :ile(o);ect sen er! "ventArgs e' { i< (lo:ile.#oste :ile 0$ null' { try { String str:ile1ame! str:ile1ame#at*! str:ile:ol er; str:ile:ol er $ ,onte&t.Server.Map#at*(9" ata7"'; str:ile1ame $ lo:ile.#oste :ile.:ile1ame; str:ile1ame $ #at*.Iet:ile1ame(str:ile1ame'; str:ile1ame#at* $ str:ile:ol er G str:ile1ame; lo:ile.#oste :ile.SaveAs(str:ile1ame#at*'; l)l:ile1ame.-e&t $ str:ile1ame; l)l:ile=engt*.-e&t $ lo:ile.#oste :ile.,ontent=engt*.-oString('; l)l:ile-ype.-e&t $ lo:ile.#oste :ile.,ontent-ype; pnStatus.Sisi)le $ true; 2 catc* ("&ception &' { =a)el l)l"rror $ ne5 =a)el('; l)l"rror.:ore,olor $ ,olor.Re ; l)l"rror.-e&t $ ""&ception occurre 6 " G &.Message; l)l"rror.Sisi)le $ true; t*is.,ontrols.A (l)l"rror'; 2 2 2 FKscriptT F)o yT F<orm i $"uploa Ncs" met*o $"post" runat$"server" enctype$"multipartK<ormM ata"T F#T FI1#3- type$"<ile" i $"lo:ile" runat$"server"T FK#T F#T Fasp6%utton i $")tn3ploa " runat$"server" -e&t$" 3ploa " 4n,lic/$"3ploa :ile"TFKasp6%uttonTFK#T F#T Fasp6#anel i $"pnStatus" runat$"server" Sisi)le$":alse"T Fasp6=a)el i $"l)l:ile1ame" :ontM%ol $"-rue" Runat$"server"TFKasp6=a)elT uploa e F%RT Fasp6=a)el i $"l)l:ile=engt*" Runat$"server"TFKasp6=a)elT )ytesF%RT Fasp6=a)el i $"l)l:ile-ype" Runat$"server"TFKasp6=a)elT FKasp6#anelTFK#T FK<ormT FK)o yT FK*tml

Tip The Bdata directory is the only directory with write permissions enabled for an anonymous user. Therefore, you will need to make sure that your code uploads the file to the Bdata directory or one of its subdirectories.

88

%ow do I send an emai) &rom m$ "S/.NET (a'e?


4nclude the (ystem.)eb.Mail.MailMessage and the (ystem.)eb.Mail.(mtpMail classes to send email from *(&+ pages. 0elow is a sample of sending email using said classes in ..

F[9 Import 1amespace$"System" [T F[9 Import 1amespace$"System.+e)" [T F[9 Import 1amespace$"System.+e).Mail" [T F*tmlT F*ea T FtitleTMail -estFKtitleT FK*ea T Fscript language$",\" runat$"server"T private voi #ageN=oa (4);ect sen er! "ventArgs e' { try { MailMessage mail4); $ ne5 MailMessage('; mail4);.:rom $ "&y89programmers*eaven.com"; Omail <rom a ress mail4);.-o $ "a)c9*otmail.com"; Omail to a ress mail4);.Su);ect $ "1e5 Article Suggestion"; Omail su);ect mail4);.%o y $ "I am sen ing a lin/ to t*is article 5*ic* is really very interesting"; Omail )o y mail4);.%o y:ormat $ Mail:ormat.-e&t; SmtpMail.SmtpServer $ "mail.programmers*eaven.com"; Ospeci<y mail server name epen ing on your mail server SmtpMail.Sen (mail4);'; Response.+rite("Mail sent success<ully"'; 2 catc* ("&ception &' { Response.+rite("]our message 5as not sent6 " G &.Message'; 2 2 FKscriptT F)o yT F<orm i $"mailNtest" met*o $"post" runat$"server"T FK<ormT FK)o yT FK?-M=T

Tip 4n order to send email through your mail server, you should set the static (mtp(erver property of the (mtpMail class to mail<fwd.

IIS with Windows Ser+er .::- 1ene&its?


0elow are the benefits of using 44( 7.F with )indows (erver ?FF>. E. Faster sites without the need for high spec hardware for )eb sites, intranets, and )eb<based applications. ?. Aou can check your siteJs potential speed improvement with real<time ompression heck tool provided by &ortTF (oftware.

89

>. "educes total response time per page re-uest. @sing 9TT& compression helps end users e%perience a DF[ reduction in download time. H. 9TT& compression reduces the si5e of files sent from your )eb server to the )eb browser by an average of >F to DF percent which is a dramatic decrease in bandwidth. D. @sing 44( 7.F compression feature you can have savings in monthly bandwidth charges. 7. Aou can reduce bandwidth by enabling compression, and serve more users with the same hardware. G. Aou can delay or eliminate the need to add more )eb servers by enabling 44( 7.F compression, even when your site gets more traffic. T. Management code for compression is now part of core 44( 7.F )eb server for speed and stability. C. (erver<side compatibility issues are resolved. EF. :ranular compression allows turning compression onBoff at the global, site, folder, and file levels.

What is State Mana'ement and what are the di&&erent wa$s to maintain a state in .Net?
)eb pages are recreated each time a page is posted to a server. 4n traditional )eb programming, this would ordinarily mean that all information associated with the page and the controls within the page would be lost with each round trip. To overcome this inherent limitation of traditional )eb programming, the *(&.NET page framework includes various options to help you preserve changes when Managing the (tate. The page framework includes a facility called &iew state that automatically preserves property values of the page and all controls on it between round trips. 9owever, you will probably also have application<specific values that you want to preserve. This can be done using state management options. lient+Based -tate Mana"ement )ptions1 /iew (tate 9idden Form Fields ookies Puery (trings -er&er+Based -tate Mana"ement )ptions1 *pplication (tate (ession (tate Database (upport

What ser+er #ontro)s #ome with "S/.NET?


(erver controls are supplied with *(&.NET. (erver controls in *(&.NET are different to the normal windows controls as they work within the .NET Frame)ork. The different types of server controls in *(&.NET are,

90

5TML -er&er ontrols, These controls refer to the 9TM! elements that can be used in server code. The 9TM! elements can be converted into 9TM! server controls. A-<.NET -er&er controls, *(&.NET server controls are the general controls like te%tbo%, buttons, tables etc. Validation ontrols, these controls are used to validate user input. Normally these controls are attached with te%tbo%es, checkbo%es and radio buttons to check the values entered or selected. ,-ER ontrols, These controls are those controls that are created by the user and are used 3ust like all other controls.

What is the "dRotator #ontro) and it;s

ses?

*d"otator is a special control in *(&.NET used to display flashing banner advertisments. The control can display advertisments randomly or se-uentially as set by the developer. ,sin" the AdRotator control To use the control, drag it from the toolbo%. 4n the properties window you will there are three key properties, .*dvertisementsFile .8eywordFilter .Target The advertisement file is an +M! file which contains information about the image to be displayed and the page to which the user should be redirected on click. The following e%ample assumes there are two images named one.gif and two.gif. 0elow is the +M! to correspond with our e%ample,
FA vertisementT FA T FImage3rlT one.gi< FKImage3rlT F1avigate3rlT *ttp6KK555.co epe ia.com FK1avigate3rlT FAlternate-e&tT -*e +e)Os <astest gro5ing tec*nical encyclop ia FKAlternate-e&tT FImpressionsT C FKImpressionsT F^ey5or T Sisual %asic FK^ey5or T FKA T FA T FImage3rlT t5o.gi< FKImage3rlT F1avigate3rlT *ttp6KK555.programmers*eaven.com FK1avigate3rlT FAlternate-e&tT +*ere t*e proOs are

91

FKAlternate-e&tT FImpressionsT C FKImpressionsT F^ey5or T #rogramming FK^ey5or T FKA T FKA vertisementsT

The above tags are e%plained below, C2ma"e,rlD, The image @"! that presents the advertisement image. CNa&i"ate,rlD, The on click redirect @"!. CAlternateTe*tD, 4mage descriptionBname thats show when the mouse is over the image # 'ptional use $. CEe'wordD, 'ptional parameter that specifies the keyword #category$ like books, programming etc. C2mpressionsD, * number input that indicates the weight of the advertisment. This can be use to control the order of rotation with respect to other advertisments in the file. *gain, this is optional.

What is a Ca)endar #ontro) and how do I

se it?

The alendar control is used to display the calendar year on a web page. Aou can view dates or select a specific day, week or month. The default event of the alendar control is (election hanged event that is called when a selection is made on the control. Drag a calendar control and a te%tbo% from the toolbo%. )e will display the date selected from the calendar control in the te%tbo%. The sample code for that is,
#rivate Su) ,alen arCNSelection,*ange (%ySal sen er As System.4);ect! %ySalN e As System."ventArgs' ?an les ,alen arC.Selection,*ange -e&t%o&C.-e&t $ ,alen arC.Selecte Dat

"n

Su)

4n "untime Mode < (elect a date from the calendar control. That date will now be the .Te%t /alue of the te%tbo%.

What is a Re< iredFie)d3a)idator #ontro)?


The "e-uiredField/alidator is a control that checks whether the value of an assigned input control is different from its initial value. To work with this control drag a "e-uiredField/alidator control, ommand 0utton and two Te%t0o%es from the Toolbo%. The intention is to display the te%t entered in Te%t0o%E in Te%t0o%? when the ommand 0utton is clicked. 4f there is no value in Te%t0o%E, an error message #O(aying Te%tbo%E needs a valueO$ will be spawned.

92

*ll you have to make the "e-uiredField/alidator work is to open the properties of the control. !ooking at two properties6 ErrorMessa"e and ontroltoValidate specifically. The ErrorMessage property should be completed with a warning that the field needs to be completed. (econdly, the ontrolto/alidate property is used to tag which control is to be validated. The sample code for that is,
#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySalN e As System."ventArgs' ?an les %uttonC.,lic/ -e&t%o&2.-e&t $ -e&t%o&C.-e&t

"n

Su)

What is a Com(are3a)idatorContro)?
ompare/alidator is used to make sure that a value matches a specified value. This control is often used when validating passwords. 4mportant properties of this control are . ontrolToValidate and . ontrolTo ompare. . ontrolTo&alidate property is used to set the control to be validated and the . ontrolTo ompare property is used to identify the control to be compared. To work with this control drag a ompare/alidator ontrol, a ommand 0utton and two Te%t0o%es from the Tool0o%. The intention is to enter two values the te%tbo%es. 4f the two values do not match, an error is generated denoting that the values are not alike. (et the following control properties in ompare/alidator ontrol6 . ontrolTo ompare property as Te%t0o%E and . ontroltoValidate property as Te%t0o%?. "un the code and enter some te%t in both the te%tbo%es and click the button. 4f both the Te%t0o% values are the same then no error message will arise else an error.

What is a Ran'e3a)idator #ontro)?


* "ange/alidator control is used to determine whether a control value falls within a specified range. The "ange/alidator checks whether the value passed to the control is within the range specified. This type of watch dog is generally used when buying products online like tickets etc. To work with the "ange/alidator control, drag a Te%t0o% and a "ange/alidator ontrol from the toolbo%. 'pen the "ange/alidator control properties and enter a value of T in the Ma%imum/alue field, > in the Minimum/alue field and set Te%t0o%E as the control to be validated. "un the code and try entering some values in the Te%t0o%. 4f the value entered is within the specified range # T 9igh, > !ow $ then nothing happens else an error message is displayed.

93

What is a Re' )arE9(ression3a)idator?


"egularE%pression/alidator control is used to check a value against a regular e%pression. 4t checks whether the value of the associated input control matches the pattern of the regular e%pression. This ontrol generally used to check whether the entered phone number or email address matches a set format. * notable property of this control is the /alidationE%pression property, which is used to set the validation criteria and which comes with some predefined formats. To work with a "egularE%pression/alidator control6 Drag a Te%t0o% and a ommand 0utton from the Tool0o%. 'ur intention is to check for the format of an email address and display an error message if the input format is not correct. *n e%ample of a correctly formated inpput would be O%y5Wprogrammersheaven.comO. To implement format definition. 4n the properties window of the "egulare%pression click on the ellipse button for /alidationE%pression and select 4nternet E<mail *ddress from the pop<up window. )hen you run the program and enter a value not in the format of abcW%y5.com the error message is displayed.

What is the di&&eren#e 1etween a We1 6ser Contro) and a We1 C stom Contro)?
)eb custom controls are compiled components that run on the server and encapsulate the user<interface and other related functionality into reusable packages. They can include all the design<time features of standard *(&.NET server controls, including full support for /isual (tudio design features such as the &roperties window, the visual designer, and the Toolbo%. There are several ways to create )eb custom controls, Aou can compile a control that combines the functionality of two or more e%isting controls. For e%ample, if you need a control that encapsulates a button and a te%t bo%. Aou can create it by compiling the e%isting controls together. 4f an e%isting server control almost meets your re-uirements but lacks some re-uired features, you can customi5e the control by deriving from it and overriding its properties, methods, and events. 4f none of the e%isting )eb server controls #or their combinations$ meet your re-uirements, you can create a custom control by deriving from one of the base control classes. These classes provide all the functionality like other )eb server controls. Aou only need to write the logic for the programming features you re-uire. 4f none of the e%isting *(&.NET server controls meet the specific re-uirements of your applications, you can create either a We$ #ser control or a We$ c#stom control that encapsulates the functionality you need. The main difference between the two controls lies in ease of creation vs. ease of use at design time. )eb user controls are easy to make, but they can be less convenient to use in advanced scenarios. )eb user controls can be developed almost e%actly the same way that you develop )eb Form pages. !ike )eb Forms, user controls can be created in the visual designer or they can be written with code separate from the 9TM!. They can also support e%ecution events. 9owever, since )eb user controls are compiled dynamically at run time

94

they cannot be added to the Toolbo% and they are represented by a simple placeholder when added to a page. This makes )eb user controls harder to use if you are accustomed to full /isual (tudio .NET design<time support, including the &roperties window and Design view previews. *lso the only way to share the user control between applications is to put a separate copy in each application, which takes more maintenance if you make changes to the control. )eb custom controls are compiled code, which makes them easier to use but more difficult to create. )eb custom controls must be authored in code. 'nce you have created the control you can add it to the Toolbo% and display it in a visual designer with full &roperties window support and all the other design<time features of *(&.NET server controls. 4n addition you can install a single copy of the )eb custom control in the global assembly cache and share it between applications, which make maintenance easier.

Windows 4orms What are windows form applications?


)indows form applications are standard applications for )indows operating system having a user interface. * windows form application usually has one or more forms containing menus and other user interface controls like buttons, te%t bo%es, tree view, etc. )indows form applications are like any other application on )indows e%cept that it has its own :raphical @ser 4nterface #:@4$. ommon e%amples of windows form applications include Microsoft )ord, *dobe &hotoshop and )inamp. )indows form applications are event based, i.e., they perform certain operations on user action. For e%ample, Microsoft )ord saves the document into disk file only when you ask the application to do so #selecting File Y (ave$.

5ow are the Windows form applications different from the onsole Applications?
)indows applications are facilitated with the )indows standard user interface controls #like button, te%t bo%, list bo%, picture bo% and etc$ and the standard events of )indows operating system. 'n the other hand, the onsole *pplication can only take user input and output fromBto the onsole, command or a shell window. )indows form applications are more responsive and may use a lot of features like shortcut and icons. 'n the other hand, console applications are light weight and are used for testing and background service type applications. (everal 1ava based web servers are implemented on )indows using onsole application.

5ow are the Windows form applications different from the onsole Applications?
)indows applications are facilitated with the )indows standard user interface controls #like button, te%t bo%, list bo%, picture bo% and etc$ and the standard events of )indows operating system. 'n the other hand, the onsole *pplication can only take user input and output fromBto the onsole, command or a shell window. )indows form applications are more responsive and may use a lot of features like shortcut and icons. 'n the other hand, console applications are light

95

weight and are used for testing and background service type applications. (everal 1ava based web servers are implemented on )indows using onsole application.

What s#pport does the Vis#al -t#dio.NET pro&ide for the de&elopment of .NET win form applications?
/isual (tudio.NET provides an enormous support for the development of )in Form applications. The key features of /isual (tudio.NET 4DE include, The form designer allows you to design the @ser 4nterface #@4$ of the applications by simple drag and drop of the controls. The &roperties window allows you to set different properties for form and a number of windows controls The 4ntellisense #help completing the synta% as you place dot #.$ with ob3ects, enumeration and namespace and when you create new ob3ects$ &ro3ect and solution management with solution e%plorer that helps manage applications consisting of multiple files, which is what usually happens (tandard debugger that allows you to debug your program by putting break points for observing run<time behavior of the variables and ob3ects in the program 9ot compiler that checks the synta% of your code as you type it and report any errors present Dynamic 9elp on number of topics using Microsoft Development Network #M(DN$ !ibrary ompilation and building applications E%ecution of your application withBwithout debugger Deploying your .NET application over the 4nternet or on Ds

5ow do 2 make m' first @5ello% Win4ormA .NET form application #sin" V-.NET and Vis#al !?
. /ersion @sing /isual (tudio.NET to build the U9ello )inFormV *pplication (o we have had a lot of /isual (tudio.NET introduction. Now, let;s use /isual (tudio.NET 4DE to build the U9ello )inFormV application which we created earlier in the lesson. reating a new &ro3ect First of all, we need to create a new . )indows *pplication &ro3ect. For this, start /isual (tudio.NET and click File <Y New <Y &ro3ect. 4t will show the following screen R4M*:EES From the above screen, select I/isual . &ro3ects; in &ro3ect types and I)indows *pplication; in Templates. )rite the name of the new pro3ect #I!earning)inForm; in the above figure$ in the te%t bo% labeled Name. (elect the disk path where you wish to store the pro3ect using 0rowseM 0utton and click '8. 4t will show you an empty form in the designer view similar to the figure below R4M*:E?S The layout of the form designer screen may be somewhat different from the one shown above. Aour toolbo% and properties window may be visible and some other

96

windows may not be visible. Aou can change these settings using /iew menu as described earlier in the lesson. (etting various properties of the form Aou can change the default properties of the form using the &roperties window. For this, select #click$ the form and select the properties window #4f the properties window is not visible in the right hand pan, select /iew <Y &roperties )indow$. Now change the title of the form and the name of the form;s class in the code using Te%t and Form;s Name property respectively as shown in the following figure. 4M*:E>S *dding ontrols to the Form Now select the !abel control from toolbo% and place it on the form and resi5e it as appropriate. (elect #click$ the label on the form and from the properties window, set its Te%t property to U9ello )inFormV and the Name property to Ilbl:reeting;. The name of a control is the name of its corresponding instance in the source code. Now select the 0utton control from toolbo% and place it on the form and resi5e it appropriately. (elect #click$ the button and set its Name property as IbtnE%it; and Te%t property as IE%it; from the properties window. The form should now look like R4M*:EHS *dding Event 9andling Now, we need to add the event handling code for the E%it button. For this, simply double click the E%it button in the designer. 4t will create a new event handler for the E%it button;s lick event and take you to the source code as shown in the following figure R4M*:EDS )rite the code to close the application #*pplication.E%it#$$ in the event handler. The 4DE in fact has not only created the event handler but also has registered it with the E%it button;s lick event. E%ecuting the application That is itL The I9ello )inForm; application is complete. To compile and e%ecute the application, select 0uild <Y 0uild (olution #or press trl2(hift20$ and then select Debug <Y (tart )ithout Debugging #or press trl2FD$. *uthor;s Note, @nfortunately, my copy of /isual (tudio.NET ?FFE does not change the name of form #from FormE to MyForm in our case$ in the call to *pplication."un#$ method in the Main#$ method. 4 have to e%plicitly change the Main#$ method like this
static voi Main(' { Application.Run(ne5 My:orm(''; 2

4f you are also e%periencing the same problem with your copy of /isual (tudio.NET, make sure to change the name of the form in Main#$ method also whenever you change its name in the &roperties )indow in order to avoid the compilation error This will compile and start the I9ello )inForm; application in a new window as shown below

97

R4M*:E7S To close the application, click the E%it button or the close button at the title bar of the window. The code generated by the Form Designer Aou can toggle between Form Designer and ode using /iew <Y Designer and /iew <Y ode. *fter switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

5ow do 2 make m' first @5ello% Win4ormA .NET form application #sin" V-.NET and Vis#al Basic.NET?
/0.NET /ersion @sing /isual (tudio.NET to build the O9ello )inFormO *pplication !etJs use the /isual (tudio.NET 4DE to build the O9ello )inFormO application. reating a new &ro3ect First of all, we need to create a new /0.NET )indows *pplication &ro3ect. For this, start /isual (tudio.NET and click File <Y New <Y &ro3ect. 4t will show the following screen, R4M*:EGS From the above screen, select J/isual 0asic &ro3ectsJ in &ro3ect types and J)indows *pplicationJ in Templates. )rite the name of the new pro3ect #J!earning)inFormJ in the above figure$ in the te%t bo% labeled Name. (elect the location where you wish to store the pro3ect using the 0rowse... 0utton and click '8. 4t will show you an empty form in the designer view similar to the figure below, R4M*:ETS The layout of the form designer screen may be somewhat different from the one shown above. Aour toolbo% and properties window may be visible and some other windows may not be visible. Aou can change these settings using the /iew menu as described earlier in the lesson. (etting various properties of the form Aou can change the default properties of the form using the &roperties window. For this, select #click$ the form and select the properties window #4f the properties window is not visible in the right hand pane, select /iew <Y J&roperties )indow$. Now change the title of the form and the name of the formJs class in the code by changing the Te%t and Name properties, as shown in the following figure. R4M*:ECS *dding ontrols to the Form Now select the !abel control from the toolbo%, place it on the form and resi5e it as appropriate. (elect #click$ the label on the form and from the properties window, set its Te%t property to O9ello )inFormO and the Name property to Jlbl:reetingJ. The name of a control is the name of its corresponding instance in the source code. Now select the 0utton control from the toolbo%, place it on the form and resi5e it appropriately. (elect #click$ the button and set its Name property to JbtnE%itJ and its Te%t property to JE%itJ using the properties window. The form should now look like this, R4M*:EEFS *dding Event 9andling Now we need to add the event handling code for the E%it button. For this, simply double click the E%it button in the designer.

98

This will create a new event handler for the E%it buttonJs to the source code as shown in the following figure,

lick event and take you

R4M*:EEES )rite the code to close the application #*pplication.E%it#$$ in the event handler. The 4DE in fact has not only created the event handler but also has registered it with the E%it buttonJs lick event. E%ecuting the application That is itL The J9ello )inFormJ application is complete. To compile and e%ecute the application, select 0uild <Y0uild (olution #or press trl2(hift20$ and then select Debug <Y (tart )ithout Debugging #or press trl2FD$. This will compile and start the J9ello )inFormJ application in a new window as shown below, R4M*:EE?S To close the application, click the E%it button or the close button on the title bar of the window. The code generated by the Form Designer Aou can toggle between the Form Designer and ode using /iew <Y Designer and /iew <Y ode. *fter switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

What is the architect#re of .NET win form applications? ! Version


)inForm *rchitecture *s stated earlier, .NET provides )inForm and other controls through base classes in the (ystem.)indows.Forms namespace. The class (ystem.)indows.Forms.Form is the base class of all )inForms in .NET. 4n order to design a windows application, we need, E. reate a )indows *pplication pro3ect in /isual (tudio.NET or add references to (ystem.)indows.Forms and (ystem.Drawing to your current pro3ect. 4f you are not using /isual (tudio at all, use Breference option of the command line compiler to add these assemblies. ?. )rite a new class to represent the )inForm and derive it from (ystem.)indows.Forms.Form class as
class My:orm 6 System.+in o5s.:orm { ... 2

>. 4nstantiate various controls, set their appropriate properties and add these to MyForm;s ontrols collection. H. )rite another class containing the Main#$ method. 4n the Main#$ method, call the (ystem.*pplication."un#$ method by supplying it an instance of MyForm.
class -est { static voi Main(' { Application.Run(ne5 My:orm(''; 2 2

The *pplication."un#$ method registers your form as a windows application in the operating system so that it may receive event messages from the )indows 'perating (ystem.

99

VB.NET Version
)inForm *rchitecture *s stated earlier, .NET provides the )inForm and other controls through base classes in the (ystem.)indows.Forms namespace. The class (ystem.)indows.Forms.Form is the base class of all )inForms in .NET. 4n order to design a windows application, we need to, E. reate a )indows *pplication pro3ect in /isual (tudio.NET, or add references to (ystem.)indows.Forms and (ystem.Drawing to your current pro3ect. 4f you are not using /isual (tudio at all, use the Breference option of the command line compiler to add these assemblies. ?. )rite a new class to represent the )inForm and derive it from the
System.+in o5s.:orms.:orm class6 #u)lic ,lass My:orm In*erits System.+in o5s.:orms.:orm _ "n ,lass

>. 4nstantiate various controls, set their appropriate properties and add these to MyFormJs ontrols collection. H. )rite another class containing the Main#$ method. 4n the Main#$ method, call the (ystem.*pplication."un#$ method, supplying it with an instance of
My:orm. ,lass -est #u)lic Su) Main(' Application.Run(1e5 My:orm('' "n Su)

"n

,lass

The *pplication."un#$ method registers your form as a windows application in the operating system so that it may receive event messages from the )indows 'perating (ystem. 4nde%

5ow do 2 make m' first @5ello% Win4ormA .NET form application witho#t V-.NET in Vis#al !? ! Version
B#ildin" the @5ello Win4ormA Application !et;s now build our first windows application called U9ello )inFormV. The application will present a simple window with U9ello )inFormV greeting at the center. The source code of the program is,
using System; using System.+in o5s.:orms; using System.Dra5ing;

namespace ,S*arpSc*ool

10

{ class -est { static voi { Application.Run(ne5 My+in o5(''; 2 2 Main('

class My+in o5 6 :orm { pu)lic My+in o5(' 6 )ase(' { t*is.-e&t $ "My :irst +in o5s Application"; t*is.Si8e $ ne5 Si8e(3..! 3..';

=a)el l)lIreeting $ ne5 =a)el('; l)lIreeting.-e&t $ "?ello +in:orm"; l)lIreeting.=ocation $ ne5 #oint(C..! C..';

t*is.,ontrols.A 2 2 2

(l)lIreeting';

3n erstan ing t*e ,o e In t*e start! 5e inclu e using System; using System.+in o5s.:orms; t*ree namespaces to our application

10

using System.Dra5ing;

The (ystem namespace, as we stated in the first lesson, is the necessary ingredient of all . applications. 4n fact, the *pplication class that we used later in the Main#$ method is defined in this namespace. The (ystem.)indows.Forms namespaces contains the base classes for windows controls like Form, !abel and 0utton. Finally, including the (ystem.Drawing namespace is necessary as it contains the useful classes related to the drawing of controls. The (i5e and &oint classes used later in the program are actually defined in (ystem.Drawing namespace. !ater, we derived a new class IMy)indow; from the Form class defined in
System.+in o5s.:orms class My+in o5 6 :orm { ... 2

4n the constructor of My)indow, we specified the si5e and title of the form. The si5e is defined using the (ystem.Drawing namespace;s (i5e class. )e passed two integers to the constructor of (i5e to specify the width and the height of the form.
pu)lic My+in o5(' 6 )ase(' { t*is.-e&t $ "My :irst +in o5s Application"; t*is.Si8e $ ne5 Si8e(3..! 3..';

Ne%t in the constructor, we created a te%t label and added it to the ontrols collection of the Form. * te%t label is used to write some te%t on the form. The (ystem.)indows.Forms.!abel class is used to create a te%t label in windows applications. )e set the te%t of the !abel using its Te%t property which is of string type. *ll the controls contained by a form must be added to its ontrols collection6 hence we have also added our label to this collection.
pu)lic My+in o5(' 6 )ase(' { t*is.-e&t $ "My :irst +in o5s Application"; t*is.Si8e $ ne5 Si8e(3..! 3..';

=a)el l)lIreeting $ ne5 =a)el('; l)lIreeting.-e&t $ "?ello +in:orm"; l)lIreeting.=ocation $ ne5 #oint(C..! C..';

t*is.,ontrols.A 2

(l)lIreeting';

Finally, we have created a Test class containing the Main#$ method. 4n the Main#$ method, we have instantiated the My)indow class and passed its reference to the *pplication."un#$ method so it may receive messages from the )indows 'perating (ystem.

10

)hen we e%ecute the above code, the following screen is presented as output To close the application, press the close button on the title bar. *dding Event 9andling !et;s now add a button labeled IE%it; to the form. The IE%it; button will close the application when it is clicked. 4n .NET, &ush 0uttons are instances of the (ystem.)indows.Forms.0utton class. To associate some action with the button click, we need to create an event handler and register #or add$ it to the 0utton;s lick event. Following is the code for this modified application
using System; using System.+in o5s.:orms; using System.Dra5ing;

namespace ,S*arpSc*ool { class -est { static voi { Application.Run(ne5 My+in o5(''; 2 2 Main('

class My+in o5 6 :orm { pu)lic My+in o5(' 6 )ase(' { KK :orm t*is.-e&t $ "My :irst +in o5s Application"; t*is.Si8e $ ne5 Si8e(3..! 3..'; t*is.Start#osition $ :ormStart#osition.,enterScreen;

KK =a)el

10

=a)el l)lIreeting $ ne5 =a)el('; l)lIreeting.-e&t $ "?ello +in:orm"; l)lIreeting.=ocation $ ne5 #oint(C..! C..';

KK %utton %utton )tn"&it $ ne5 %utton('; )tn"&it.-e&t $ ""&it"; )tn"&it.=ocation $ ne5 #oint(CP.! CP.'; )tn"&it.Si8e $ ne5 Si8e(P.! 3.'; )tn"&it.,lic/ G$ ne5 "vent?an ler(%tn"&it4n,lic/';

KK A

ing controls to :orm Range(ne5 ,ontrol[( {l)lIreeting!

t*is.,ontrols.A )tn"&it2'; 2

pu)lic voi {

%tn"&it4n,lic/(o);ect sen er! "ventArgs e'

Application."&it('; 2 2 2

4n the constructor of My)indow, first we have set certain properties of the Form. 4n this code, we have also used the (tart&osition property of the Form, which sets the start up position of the form on the screen. The type of this property is an enumeration called IForm(tart&osition;. )e have set the start position of the form to the center of the screen. The new inclusion in the code is the E%it button called IbtnE%it;. )e have created the button using the base class (ystem.)indows.Forms.0utton. !ater, we set various properties of the button like its te%t label #Te%t$, its !ocation and its (i5e. Finally, we have created an event handler method for this button called 0tnE%it'n lick#$. 4n the 0tnE%it'n lick#$ method, we have written the code to e%it the application. )e have also registered this event handler to the btnE%it;s lick event #To understand the event handling in ., see lesson EF of the . school$. 4n the end, we have added a label and button to the form;s ontrols

10

collection. Note that this time we have used *dd"ange#$ method of form class to add an array of controls to the ontrols collection of form. This method takes an array of type ontrol as its parameter. The output of the code will be Now you can press either the E%it 0utton or the close button at title bar to e%it the application.

5ow do 2 make m' first @5ello% Win4ormA .NET form application witho#t V-.NET in Vis#al Basic.NET? VB.NET Version
B#ildin" the F5ello Win4ormF Application !etJs build our first windows application, which we will call O9ello )inFormO. The application will present a simple window with a O9ello )inFormO greeting at the center. The source code of the program is,
Imports System Imports System.+in o5s.:orms Imports System.Dra5ing

,lass -est #u)lic Su) Main(' Application.Run(1e5 My:orm('' "n Su)

"n

,lass

,lass My:orm In*erits :orm

#u)lic Su) 1e5(' My%ase.ne5(' Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

10

Dim l)lIreeting As 1e5 =a)el(' l)lIreeting.-e&t $ "?ello +in:orm" l)lIreeting.=ocation $ 1e5 #oint(C..! C..'

Me.,ontrols.A "n "n Su)

(l)lIreeting'

,lass

@nderstanding the application,

ode *t the start, we included three namespaces in our

Imports System Imports System.+in o5s.:orms Imports System.Dra5ing

The (ystem namespace, as we stated in the first lesson, is the necessary ingredient of all /0.NET applications. 4n fact, the *pplication class that we used later in the Main#$ method is defined in this namespace. The (ystem.)indows.Forms namespaces contains the base classes for windows controls, e.g. Form, !abel and 0utton. Finally, including the (ystem.Drawing namespace is necessary as it contains the classes related to the drawing of controls. The (i5e and &oint classes used later in the program are actually defined in the (ystem.Drawing namespace. The (ystem.)indows.Forms and (ystem.Drawing namespaces can not be added to a pro3ect 3ust by writing 4mports statement for them. )e also need to add references to the assemblies #for now take assemblies as )indows D!!;s or library files for .NET$ that contain the code of types these namespaces. For this we need to add reference to (ystem.)indows.Forms.dll and (ystem.Drawing.dll. To add a reference write click the I"eference; folder under the current pro3ect in the solution e%plorer and select *dd "eferenceM 4t will show the following window From the J.NETJ tab of the *dd "eference Dialog bo%, select the (ystem.)indows.Forms.dll and (ystem.Drawing.dll and select '8. This completes the process of adding references to assemblies in your pro3ect. !ets go back to our sample application. !ater, we derived a new class, JMyFormJ, from the Form class defined in
System.+in o5s.:orms. ,lass My:orm In*erits :orm ...

"n "n

Su)

,lass

4n the constructor of MyForm, we specified the si5e and title of the form #by setting the si5e and te%t properties$. The si5e is defined using the

10

(ystem.Drawing namespaceJs (i5e class. )e passed two integers to the constructor of (i5e to specify the width and the height of the form.
#u)lic Su) 1e5(' My%ase.ne5(' Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

Ne%t in the constructor, we created a te%t label and added it to the ontrols collection of the Form. * te%t label is used to write some te%t on the form. The (ystem.)indows.Forms.!abel class defines a te%t label in a )indows application. )e set the te%t of the !abel using its Te%t property, which is of the string type. *ll the controls contained by a form must be added to its ontrols collection6 hence we have also added our label to this collection.
#u)lic Su) 1e5(' My%ase.ne5(' Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

Dim l)lIreeting As 1e5 =a)el(' l)lIreeting.-e&t $ "?ello +in:orm" l)lIreeting.=ocation $ 1e5 #oint(C..! C..'

Me.,ontrols.A "n Su)

(l)lIreeting'

Finally, we have created a Test class containing the Main#$ method. 4n the Main#$ method, we have instantiated the MyForm class and passed its reference to the *pplication."un#$ method so it may receive messages from the )indows 'perating (ystem. )hen we e%ecute the above code, the following screen is displayed, To close the application, press the close button on the title bar. *dding Event 9andling !etJs now add a button labeled JE%itJ to the form. The JE%itJ button will close the application when it is clicked. 4n .NET, &ush 0uttons are instances of the (ystem.)indows.Forms.0utton class. To associate some action with the button click, we need to create an event handler and register #or add$ it to the 0uttonJs lick event. 0elow is the code for this application.
Imports System Imports System.+in o5s.:orms Imports System.Dra5ing

,lass -est #u)lic Su) Main(' Application.Run(1e5 My:orm(''

10

"n

Su)

"n

,lass

,lass My:orm In*erits :orm

#u)lic Su) 1e5(' My%ase.ne5(' O :orm Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

O =a)el Dim l)lIreeting As 1e5 =a)el(' l)lIreeting.-e&t $ "?ello +in:orm" l)lIreeting.=ocation $ 1e5 #oint(C..! C..'

O %utton Dim )tn"&it As 1e5 %utton(' )tn"&it.-e&t $ ""&it" )tn"&it.=ocation $ 1e5 #oint(CP.! CP.' )tn"&it.Si8e $ 1e5 Si8e(P.! 3.' A ?an ler )tn"&it.,lic/! A ress4< %tn"&it4n,lic/

Me.,ontrols.A "n Su)

Range(1e5 ,ontrol(' {l)lIreeting! )tn"&it2'

10

#u)lic Su) %tn"&it4n,lic/(%ySal sen er As 4);ect! %ySal e As "ventArgs' Application."&it(' "n Su)

"n

,lass

4n the constructor of MyForm, first we have set certain properties of the Form. 4n this code, we have also used the (tart&osition property of the Form, which sets the position of the form on the screen when the application starts. The type of this property is an enumeration called JForm(tart&ositionJ. )e have set the start position of the form to the center of the screen. The new inclusion in the code is the E%it button called JbtnE%itJ. )e have created the button using the base class (ystem.)indows.Forms.0utton. !ater, we have set various properties of the button, specifically its te%t label #Te%t$, its !ocation and its (i5e. Finally, we have created an event handler method for this button called 0tnE%it'n lick#$. 4n the 0tnE%it'n lick#$ method, we have written the code to e%it the application. )e have also subscribed this event handler to the btnE%itJs lick event #To understand the event handling in /0.Net, see lesson EF of the /0.Net school$. 4n the end, we have added both the label and the button to the formJs ontrols collection. Note that this time we have used the *dd"ange#$ method of form class to add an array of controls to the ontrols collection of form. This method takes an array of type ontrol as its parameter. )hen the code is run, the following window will be displayed, Now you can press either the E%it 0utton or the close button at title bar to e%it the application. *lternate procedure for Event 9andling = @sing the I9andles; 8eyword Note that in the previous code, we subscribed E%it buttons event handler using the I*dd9andler; keyword. )e can also do this using the I9andles; keyword with the Event 9andler method. 0ut to use the I9andles; keyword, the E%it button needs to be instance variable of the form class defined with the I)ithEvents; keyword. The complete source code of the MyForm class is
,lass My:orm In*erits :orm

O :orm controls are usually private O instance mem)ers o< t*e <orm class #rivate +it*"vents )tn"&it As 1e5 %utton(' #rivate l)lIreeting As 1e5 =a)el('

#u)lic Su) 1e5(' My%ase.ne5('

10

O :orm Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

O =a)el

l)lIreeting.-e&t $ "?ello +in:orm" l)lIreeting.=ocation $ 1e5 #oint(C..! C..'

O %utton )tn"&it.-e&t $ ""&it" )tn"&it.=ocation $ 1e5 #oint(CP.! CP.' )tn"&it.Si8e $ 1e5 Si8e(P.! 3.' OA ?an ler )tn"&it.,lic/! A ress4< %tn"&it4n,lic/

Me.,ontrols.A "n Su)

Range(1e5 ,ontrol(' {l)lIreeting! )tn"&it2'

#u)lic Su) %tn"&it4n,lic/(%ySal sen er As 4);ect! %ySal e As "ventArgs' ?an les )tn"&it.,lic/ Application."&it(' "n Su)

"n

,lass

This procedure of event handling #using the I9andles; keyword$ is usually followed by /isual (tudio.NET standard code for Form based applications #)indows and )eb *pplications$

5ow do 2 pro&ide the e&ent handlin" for m' form and controls #sin" V-.NET?

11

Addin" E&ent 5andlin" Aou can provide event handling for forms and controls by implementing their respective event handlers. To implement an event handler for a form or control, go to Events tab of the properties window, and double click the desired event handler name. The form designer will add the event handler for the selected event in the source code of the application and take you there. 4f you want to implement a default event handler of the form or control, simply double click it. For e%ample, to add the event handling code for the E%it button in the 9ello )inForm application #demonstrated in F*P D$, simply double click the E%it button in the designer. 4t will create a new event handler for the E%it button;s lick event and take you to the source code as shown in the following figure

! Version
)rite the code to close the application #*pplication.E%it#$$ in the event handler. The 4DE in fact has not only created the event handler but also has registered it with the E%it button;s lick event.

5ow e&ent handlin" is implemented in win form and .NET form controls with !? ! Version
Addin" E&ent 5andlin" * control e%poses an event by defining its delegate. )e can add our own event handler for the event by writing an event handler method and adding it to the event;s delegate. For e%ample, add a button labeled IE%it; to the form of F*P T. The IE%it; button will close the application when it is clicked. 4n .Net, &ush 0uttons are instances of the (ystem.)indows.Forms.0utton class. To associate some action with the button click, we need to create an event handler and register #or add$ it to the 0utton;s lick event. Following is the code for this modified application
using System; using System.+in o5s.:orms; using System.Dra5ing;

namespace ,S*arpSc*ool { class -est { static voi { Application.Run(ne5 My+in o5(''; 2 Main('

11

class My+in o5 6 :orm { pu)lic My+in o5(' 6 )ase(' { KK :orm t*is.-e&t $ "My :irst +in o5s Application"; t*is.Si8e $ ne5 Si8e(3..! 3..'; t*is.Start#osition $ :ormStart#osition.,enterScreen;

KK =a)el =a)el l)lIreeting $ ne5 =a)el('; l)lIreeting.-e&t $ "?ello +in:orm"; l)lIreeting.=ocation $ ne5 #oint(C..! C..';

KK %utton %utton )tn"&it $ ne5 %utton('; )tn"&it.-e&t $ ""&it"; )tn"&it.=ocation $ ne5 #oint(CP.! CP.'; )tn"&it.Si8e $ ne5 Si8e(P.! 3.'; )tn"&it.,lic/ G$ ne5 "vent?an ler(%tn"&it4n,lic/';

KK A

ing controls to :orm Range(ne5 ,ontrol[( {l)lIreeting!

t*is.,ontrols.A )tn"&it2'; 2

pu)lic voi

%tn"&it4n,lic/(o);ect sen er! "ventArgs e'

11

{ Application."&it('; 2 2 2

)e have highlighted the interested parts in the above code by bold formatting. )e have created the E%it button called IbtnE%it; using the class (ystem.)indows.Forms.0utton. !ater, we set various properties of the button like its te%t label #Te%t$, its !ocation and its (i5e. Finally, we have created an event handler method for this button called 0tnE%it'n lick#$. 4n the 0tnE%it'n lick#$ method, we have written the code to e%it the application. )e have also registered this event handler to the btnE%it;s lick event #To understand the event handling in ., see lesson EF of the . school$. 4n the end, we have added a label and button to the form;s ontrols collection. The output of the code will be Now you can press either the E%it 0utton or the close button at title bar to e%it the application.

5ow e&ent handlin" is implemented in win form and .NET form controls with VB.NET? VB.NET Version
Addin" E&ent 5andlin" * control e%poses an event by defining its Idelegate;. )e can add our own event handler for the event by writing an event handler method and adding it to the eventJs delegate. !etJs add a button labeled JE%itJ to the form. The JE%itJ button will close the application when it is clicked. 4n .Net, &ush 0uttons are instances of the (ystem.)indows.Forms.0utton class. To associate some action with the button click, we need to create an event handler and register #or add$ it to the 0uttonJs lick event. 0elow is the code for this application.
Imports System Imports System.+in o5s.:orms Imports System.Dra5ing

,lass -est #u)lic Su) Main(' Application.Run(1e5 My:orm('' "n Su)

"n

,lass

11

,lass My:orm In*erits :orm

#u)lic Su) 1e5(' My%ase.ne5(' O :orm Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

O =a)el Dim l)lIreeting As 1e5 =a)el(' l)lIreeting.-e&t $ "?ello +in:orm" l)lIreeting.=ocation $ 1e5 #oint(C..! C..'

O %utton Dim )tn"&it As 1e5 %utton(' )tn"&it.-e&t $ ""&it" )tn"&it.=ocation $ 1e5 #oint(CP.! CP.' )tn"&it.Si8e $ 1e5 Si8e(P.! 3.' A ?an ler )tn"&it.,lic/! A ress4< %tn"&it4n,lic/

Me.,ontrols.A "n Su)

Range(1e5 ,ontrol(' {l)lIreeting! )tn"&it2'

#u)lic Su) %tn"&it4n,lic/(%ySal sen er As 4);ect! %ySal e As "ventArgs' Application."&it('

11

"n

Su)

"n

,lass

The interesting lines defining the event handler for the button is highlighted with bold formatting. )e have created an event handler method for this button called 0tnE%it'n lick#$. 4n the 0tnE%it'n lick#$ method, we have written the code to e%it the application. )e have also subscribed this event handler to the btnE%itJs lick event #To understand the event handling in /0.NET, see lesson EF of the /0.NET school$. Now you can press either the E%it 0utton or the close button at title bar to e%it the application. *lternate procedure for Event 9andling = @sing the I9andles; 8eyword Note that in the previous code, we subscribed E%it buttons event handler using the I*dd9andler; keyword. )e can also do this using the I9andles; keyword with the Event 9andler method. 0ut to use the I9andles; keyword, the E%it button needs to be instance variable of the form class defined with the I)ithEvents; keyword. The complete source code of the MyForm class is
,lass My:orm In*erits :orm

O :orm controls are usually private O instance mem)ers o< t*e <orm class #rivate +it*"vents )tn"&it As 1e5 %utton(' #rivate l)lIreeting As 1e5 =a)el('

#u)lic Su) 1e5(' My%ase.ne5(' O :orm Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'

O =a)el

l)lIreeting.-e&t $ "?ello +in:orm" l)lIreeting.=ocation $ 1e5 #oint(C..! C..'

O %utton

11

)tn"&it.-e&t $ ""&it" )tn"&it.=ocation $ 1e5 #oint(CP.! CP.' )tn"&it.Si8e $ 1e5 Si8e(P.! 3.' OA ?an ler )tn"&it.,lic/! A ress4< %tn"&it4n,lic/

Me.,ontrols.A "n Su)

Range(1e5 ,ontrol(' {l)lIreeting! )tn"&it2'

#u)lic Su) %tn"&it4n,lic/(%ySal sen er As 4);ect! %ySal e As "ventArgs' ?an les )tn"&it.,lic/ Application."&it(' "n Su)

"n

,lass

Note that the button is now instantiated with the I)ithEvents; keyword and the event handler is specifically marked with the I9andles; keyword to -ualify it as an event handler method. This procedure of implementing event handling #using the I9andles; keyword$ is usually followed by /isual (tudio.NET standard code for Form based applications #)indows and )eb *pplications$

What are the lifetime e&ents of a form?


(ome important lifetime events of a form include, Load, This event is fired when the form is first loaded in the program. 4t is called when the Form.(how#$ or Form.(howDialog#$ method is called for the first time. Acti&ated, This event is triggered whenever the form gets the application focus. 4t is fired when the form is first loaded #along with !oad event$, when the form is brought in front, or when the form is restored from the minimi5ed state. Visi$le han"ed, 4t is called whenever the /isible property of the form is changed or the form is hidden or shown. (eacti&ated, This event is triggered whenever the form loses the application focus. 4t is fired when the form is closed, when the form is brought into background, or when the form is minimi5ed. losin", 4t is fired when the application wishes to be closed, or the application is in the process of close but has not yet closed.

11

losed, 4t is raised when the application is finally closed.

5ow do 2 chan"e the title of m' window?


@se the Te%t property of the Form to change the title of the form.

5ow do 2 chan"e the application name?


To change the application name, change the name of the startup pro3ect by right clicking the pro3ect node in the solution e%plorer and selecting properties. 4t will show the property pages for the pro3ect. 9ere in the ommon &roperties <Y :eneral, you can change the assembly name to change the resulting e%ecutable #.e%e$ file name.

5ow do 2 set the start#p position of the form?


To change the startup position of the form, select the form in the designer and change its (tart&osition property. The (tart&osition is an enumeration and has the following useful properties, enter-creen, The form should be displayed at the center of the screen Windows(efa#ltLocation, The formJs startup position should be selected by the )indows 'perating (ystem enter<arent, The form should be displayed at the center of the parent form. This option is useful when you are building an MD4 #Multiple Document 4nterface$ application. The MD4 child form can be set, in this way, to be displayed at the center of the MD4 parent form.

5ow do 2 set the initial /start#p0 si.e of the form?


The si5e property can be used to set the startup si5e of the form. The data type of the si5e property is (ystem.Drawing.(i5e. The si5e can be set as,

! Version
myForm.(i5e \ new (ystem.Drawing.(i5e#HFF, >FF$6

VB.NET Version
myForm.(i5e \ New (ystem.Drawing.(i5e#HFF, >FF$

What does it mean $' -tart#p Window -tate of the form? 5ow do 2 set the start#p window state of the form?
The startup window state specifies whether the form should be displayed in normal, ma%imi5ed or minimi5ed state. 4t can be set using the )indow(tate property of the form. The data type of this property is (ystem.)indows.Forms.Form)indow(tate enumeration, which has three members6 Ma%imi5ed, Minimi5ed and Normal.

11

! Version
my:orm.+in o5State $ :orm+in o5State.Ma&imi8e ;

VB.NET Version
my:orm.+in o5State $ :orm+in o5State.Ma&imi8e

5ow do 2 hide m' form?


Aou can hide your form or any other control by setting its /isible property to False.

! Version
my:orm.Sisi)le $ :alse;

VB.NET Version
my:orm.Sisi)le $ :alse

5ow do 2 show m' form?


Aou can show your hidden form or any other control by setting its I/isible; property to True.

! Version
my:orm.Sisi)le $ -rue;

VB.NET Version
my:orm.Sisi)le $ -rue

Aou can also display your form for the first time using the (how#$ or the (howDialog#$ methods of the form class. The (how#$ method displays the form in Non<Modal fashion, while the (howDialog#$ method displays the form in Modal mode. (ee the following F*Ps for the description of Modal and Non<Modal forms

What is the difference $etween modal and non+modal dialo"s?


The modal form, when displayed on the screen, does not allow you to go and select any other form of the window. The typical e%ample of the Modal form is the Message 0o%6 you must select '8 #or other appropriate$ button to go back to other forms of the applications. The Non modal form, on the other hand, does not prevent you from accessing other form windows of the application, when they are present on the screen using the (how#$ method of the form.

11

! Version
my:orm.S*o5(';

VB.NET Version
my:orm.S*o5('

0y default, all the forms are Non<modal.

5ow do 2 show m' form as a modal dialo"?


To show your form as the Modal dialog, call the (howDialog#$ method of the form to display it on the screen.

! Version
my:orm.S*o5Dialog(';

VB.NET Version
my:orm.S*o5Dialog('

4t will display the form as a Modal dialog and would not allow the user to access any other form of the application when it is present on the screen.

5ow do 2 minimi.e% ma*imi.e and restore m' form pro"rammaticall'?


Aou can minimi5e, ma%imi5e and restore the form by setting the )indow(tate property of the form. The following code e%ample will minimi5e the form, wait for ? seconds, restore the form, wait for ? seconds and then ma%imi5e the form. 4 have written this code on the a button;s lick event.

! Version
private voi )uttonCN,lic/(o);ect sen er! System."ventArgs e' { KK Minimi8e t*e <orm 5in o5 t*is.+in o5State $ :orm+in o5State.Minimi8e ;

-*rea .Sleep(2...';

KK 5ait <or 2 secon s

KK Restore t*e <orm 5in o5 t*is.+in o5State $ :orm+in o5State.1ormal;

-*rea .Sleep(2...';

KK 5ait <or 2 secon s

11

KK Ma&imi8e t*e <orm 5in o5 t*is.+in o5State $ :orm+in o5State.Ma&imi8e ; 2

VB.NET Version
#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! N %ySal e As System."ventArgs' N ?an les %uttonC.,lic/

O Minimi8e t*e <orm 5in o5 Me.+in o5State $ :orm+in o5State.Minimi8e

-*rea .Sleep(2...'

O 5ait <or 2 secon s

O Restore t*e <orm 5in o5 Me.+in o5State $ :orm+in o5State.1ormal

-*rea .Sleep(2...'

O 5ait <or 2 secon s

O Ma&imi8e t*e <orm 5in o5 Me.+in o5State $ :orm+in o5State.Ma&imi8e "n Su)

Note that the above code snippet is using the (ystem.Threading.Thread class; (leep method to suspend the form for ? seconds. 9ence, you would be re-uired to include the (ystem.Threading namespace to your form class source code.

! Version
3sing System.-*rea ing;

VB.NET Version
Imports System.-*rea ing

5ow do 2 hide ma*imi.e% minimi.e and close $o* at the form title $ar?
To disable the ma%imi5e bo% at the form title bar, set the Ma%imi5e property of the form to false.

12

To disable the minimi5e bo% at the form title bar, set the Minimi5e property of the form to false. Aou can not hide only the close bo% from the form title bar using the form;s property. (imilarly, you can not only hide ma%imi5e or minimi5e bo%es from the title window. Aou can hide ma%imi5e and minimi5e bo%es from the title bar by setting the Form0order(tyle property of the form to the Fi%edTool)indow or the (i5ableTool)indow. 0ut remember that with Form0order(tyle set to the Fi%edTool)indow or (i5ableTool)indow, the form will not be displayed in the )indows task bar or in the window that appears when the user presses *!T2T*0. Aou can hide the ontrol bo% from the title bar of the form by setting the ontrol0o% property of the form to false. This will hide the control bo% and system menu from the form window.

5ow do 2 make m' form non+resi.a$le or fi*ed len"th?


Aou can make your form non<resi5able or fi%ed length by setting its 4ormBorder-t'le property to 4i*edG( or 4i*ed-in"le or 4i*ed(ialo"

5ow do 2 chan"e the icon of m' form to $e displa'ed at title $ar?


Aou can change the icon of the form by changing its icon property. "emember that this property will only change the icon of the form and not of the application. To change the icon of the application or assembly, change the icon from the property pages of the pro3ect. The property pages for the pro3ect are displayed when you right click the pro3ect and select properties.

5ow do 2 make m' form not to appear in the task $ar?


To make your form not to appear in the task bar, set the (how4nTaskbar property of the form to false.

5ow do 2 make and displa' a form witho#t title $ar?


To display your from without the title bar, set the Form0order(tyle property of the form to None

5ow do 2 close the form pro"rammaticall'?


To close the form programmatically, call the lose#$ method of the form.

! Version
my:orm.,lose(';

12

VB.NET Version
my:orm.,lose('

"emember that this will only close the form and not the application. To close or e%it the application, call the Application.E*it/0 method.

5ow do 2 e*it m' win form application pro"rammaticall'?


To e%it the win form application programmatically, call the Application.E*it/0 method.

! Version
Application."&it(';

VB.NET Version
Application."&it('

5ow do 2 displa' a messa"e $o* in m' form application?


To show the message bo%, call the Message0o% class; (how#$ method. The message bo% is the modal form that notifies the user about certain event in the application and optionally takes the user feedback. The (how#$ is an static # .$ B (hared #/0.NET$ method of the (ystem.)indows.Forms.Message0o% class. 4t has a number of overloaded versions. The simplest one take the message te%t and display it in the message bo%.

! Version
Message%o&.S*o5("+elcome to +in :orm"';

VB.NET Version
Message%o&.S*o5("+elcome to +in :orm"'

To add the title to the message bo%, call the Message0o%.(how#$ like,

! Version
Message%o&.S*o5("+elcome to +in :orm"! "Ireeting"';

VB.NET Version
Message%o&.S*o5("+elcome to +in :orm"! "Ireeting"'

12

The following e%ample code shows the message bo% with Aes, No, ancel button to confirm application close and closes the application if the user selects the Aes button

! Version
DialogResult lgRes $ null lgRes $ Message%o&.S*o5( "Are you sure you 5ant to close 5it*out saving t*e ",on<irm Document ,lose"! Message%o&%uttons.]es1o,ancel! Message%o&Icon.Question';

ocument"!

i<( lgRes $$ DialogResult.]es' { Application."&it('; 2

VB.NET Version
Dim lgRes As DialogResult lgRes $ Message%o&.S*o5( N "Are you sure you 5ant to close 5it*out saving t*e ",on<irm Document ,lose"! N Message%o&%uttons.]es1o,ancel! N Message%o&Icon.Question'

ocument"! N

I<

lgRes $ DialogResult.]es -*en Application."&it('

"n

I<

5ow do 2 add another form into m' win form application?


To add and design a new form at design time, right click the target pro3ect node in the (olution E%plorer and select *dd]*dd )indows FormM This will add a new form6 design it by placing controls and setting necessary properties. To show the new form at run time, instantiate the new form and call its (how#$ or (howDialog#$ method. !et we name the new form as IMy(econdForm;, then on the click event of the button of our first #startup$ form, we can write the following code,

! Version
MySecon :orm <rm2 $ ne5 MySecon :orm(';

12

<rm2.S*o5(';

KK 5ill present t*e nonMmo al <orm

KK <rm2.S*o5Dialog(';

KK 5ill present t*e mo al <orm

VB.NET Version
Dim <rm2 As 1e5 MySecon :orm(' <rm2.S*o5(' O 5ill present t*e nonMmo al <orm

O <rm2.S*o5Dialog('

O5ill present t*e mo al <orm

5ow do 2 set the first form to $e loaded at application start#p?


The first form to be loaded at the application startup is called the startup or main form of the application. Aou can set the startup form of the application by right clicking the target pro3ect node and selecting properties. 4t will show you the property pages for the pro3ect. 9ere in the ommon &roperties]:eneral, you can set the startup form by selecting its name from the drop down list of I(tartup 'b3ect;.

! Note
"emember that only those forms that have a valid Main#$ method can be selected as the startup ob3ect.

What does it mean $' scrolla$le forms in .NET? 5ow can make m' own form scrolla$le?
.NET introduces with it a concept of scrollable forms. * scrollable form is 3ust like an html page that can be scrolled. Aou can access its controls by scrolling it down or right6 if the contents #controls$ don;t fit in the form display area. Aou can make a form scrollable by setting its *ut(croll property to true

5ow do 2 make a splash screen in m' win form application?


There is no built<in support for the splash screen in the Microsoft.NET win form applications. 9owever, you can create a splash screen by creating a form with no title bar #by setting its Form0order(tyle to None$, making it not appear in the taskbar #by setting its (how4nTaskbar property to false$, making it the top most form #by setting$ its TopMost property to true, and making it appear on the center of the screen #by setting its (tartup&osition as enter(creen$. Aou can now show this splash form when the main application is loading.

12

! Version
private voi :ormCN=oa (o);ect sen er! System."ventArgs e' { t*is.?i e('; :orm2 <rmSplas* $ ne5 :orm2('; <rmSplas*.S*o5('; <rmSplas*.3p ate('; -*rea .Sleep(D...'; <rmSplas*.,lose('; t*is.Sisi)le $ true; 2

VB.NET Version
#rivate Su) :ormCN=oa (%ySal sen er As System.4);ect! N ySal e As System."ventArgs' ?an les My%ase.=oa

Me.?i e(' Dim <rmSplas* As 1e5 :orm2 <rmSplas*.S*o5(' <rmSplas*.3p ate(' -*rea .Sleep(D...' <rmSplas*.,lose(' Me.Sisi)le $ -rue "n Su)

What $asics sho#ld $e remem$ered while de&elopin" win form apps?


(ome 4mportant &oints for designing )indows *pplications Make your form layout simple and easy to understand. 4t is important that the user of your application finds it familiar. The behavior should be e%pected and should not surprise the user. The Format menu of the /isual (tudio.NET 4DE is very useful when designing the form layout. 4t provides a number of useful options for alignment and si5e of the controls. *lmost all the controls have some similar properties like !ocation, (i5e, Enabled, /isible, Tab4nde%, etc. The Tab4nde% property is very important. 4t describes the se-uence followed by the windows focus when the user presses the Tab button of keyboard. @sually we donJt change the Name property of labels as we don;t need to use the label variable in our code most of the time. The controls should be named so that their purpose can be recogni5ed, e.g., you may name the I&urchase; button as btn&urchase, te%t bo% for entering email may be t%tEmail and so on.

12

*lthough now it is not a standard convention, but it is useful to add a three letter prefi% to the name of your controls so that they are recogni5able with their name. Most of the developers used to follow the convention like prefi%ing !abel with lbl #lbl:reeting$, Te%t0o% with t%t #t%t omments$, 0utton with btn #btn&urchase$, heck0o% with cb% #cb%&rog ($, "adio0utton with rbn #rbnFull&ayment$ and :roup0o% with gb% #gb%&aymentMode$.

%ow do I #han'e the i#on o& the a(()i#ation I am workin' with?


hanging the 4con of your application is simple. (elect &ro3ect<Y&roperties. 4n the windows OstyleO section click on the O4conO 0utton. Then make your choice.

%ow do I (re+ent a

ser &rom resi*in' a &orm?

The following code shows how a 4ormJs si5e can be restricted at runtime. &lace the following code in the load event of the form.
#u)lic ,lass :orm2 In*erits System.+in o5s.:orms.:orm

\Region " +in o5s :orm Designer generate

co e "

#rivate Su) :orm2N=oa (%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les My%ase.=oa Me.Ma&imi8e%o& $ :alse "n "n Su)

,lass

Controls
What are win form controls? 5ow the' are represented in .NET framework class li$rar'?
* form may contain various user interface #@4$ controls. The controls represent the visual components that allow user to interact with the application and perform the desired task. *ll the controls, in .Net, are represented by subclasses of (ystem.)indows.Forms. ontrol class. Each form has a collection #named I ontrols;$ to store the constituent controls of the form. 4n fact, a form itself is a special type of control called ontainer ontrol, i.e., the Form class itself is derived from the ontainer ontrol class which is a subclass of the ontrol class. * container control, as the name suggests, may contain other controls. 'ther e%amples of the ontainer control include &anel and Tab ontrol.

12

Each control, and thus form, e%poses a number of events that can be triggered on certain user action or application behavior. For e%ample, a button raises lick event whenever it is clicked and the te%t bo% raises the Te%t hanged event whenever its te%t is changed. The application developer can write even handler to catch these events and perform corresponding action. 0eside these, a form also has certain set of events called the form life cycle events. These events are triggered during the life cycle of form to indicate the current state of the form.

What are the f#ndamental and common properties of .NET controls?


*lmost all the controls have some similar properties like !ocation, (i5e, Enabled, /isible, Tab4nde%, Name, Te%t, 0ac8 olor, Fore olor, Font, etc. The Tab4nde% property is very important. 4t describes the se-uence followed by the windows focus when the user presses the Tab button of keyboard

5ow do 2 set the ta$ order of the controls on the form?


To set the tab order of the controls on the form, select /iew <Y Tab 'rder. This will start a wi5ard for setting the tab order. Aou can set the order of tab for the control by 3ust clicking it in the same se-uence as of re-uired tab order.

What does it mean $' anchorin" of controls?


*n anchoring is the property of the control to keep a specific distance with a particular edge of the window #or other containing control$. Aou can anchor a control to any edge or side of the window, e.g., left, top, right, bottom, left and top, etc. 4f a control is anchored to the left of the window, it will keep the constant distance from the left side of the window6 even when the window is resi5ed. The constant distance that the control will keep with the window is the distance it has at the form startup or defined by its !ocation property. 4n the figure below, the button is anchored to the top edge of the window. )hen the window is resi5ed, it shifts itself on the form to keep the same distance from the top, see the figure below, 4f we have defined the top and bottom anchoring and the form is resi5ed, the control will resi5e itself to have the same distance from top and bottom. onsider the figure below6 here the button is anchored top and bottom )hen the form is resi5ed, the button resi5es itself to keep the same distance from top and bottom The default anchoring of a control is left and top.

5ow do 2 set the anchorin" propert' of m' controls?


To change the anchoring property of the control, set the *nchor property of the control from the properties window. )hen you click the *nchor property of the control in the properties window, /isual (tudio.NET will show you a tab to set the edges with which you wish to anchor the control

12

What does it mean $' dockin" of controls?


Docking is the property of the control to attach itself to a particular edge of the window #or other containing control$. Aou can either dock a control to an edge or to fill the available space in the parent control or window. ommon e%amples of docking includes menu bar and toolbars which dock themselves at the top of the window so that they may remain at top regardless of the si5e and of the window. 4n the figure below, we have docked the button to the top of the window )hen the control is resi5ed, the control remains stuck to the top of the window #Does it remind you the famous outlook barK$ Aou can define a control to have a fill dock property so that it may fill all the available space in the parent window or parent control. 4n the figure below, we have docked the tree view control at left and the list view control with fill docking property )hen the form is resi5ed, the tree view will remain at left #changing only its height and not width$ while the list view will e%pand itself to the rest of the available space on the form #Does it remind you the famous )indows E%plorerK$ * control is not docked to any edge, by default.

5ow do 2 set the dockin" propert' of m' controls?


To change the docking property of the control, set the Dock property of the control from the properties window. )hen you click the Dock property of the control in the properties window, /isual (tudio.NET will show you a tab to set the edges with which you wish to dock the control

%ow do I set the width o& a Com1o7o9 to &it the #ontents?


Move through the inde% items to find the longest item by character length using the Meas#re-trin" function. @se the this value as the ombo0o% width.
System.Dra5ing.Irap*ics g $ com)o%o&C.,reateIrap*ics('; <loat ma&+i t* $ .<; <oreac*(o);ect o in com)o%o&C.Items' { <loat 5 $ g.MeasureString(o.-oString('! com)o%o&C.:ont'.+i t*; Oc*ec/ing t*e com)o)o& <or t*e longest te&t i<(5 T ma&+i t*' ma&+i t* $ 5; Osetting t*e 5i t* )y c*ec/ing t*e longest te&t 2 g.Dispose('; com)o%o&C.+i t* $ (int' ma&+i t*

12

%ow do I set the #o)or and &ont in a Ri#hEdit7o9?


@se the -election4ont and -election olor properties to set the font and color of a "ichEdit0o%. The following code will set the Oselected te%tO to a blue<italic< verdana font set. Note. 4f no te%t is selected then any all new te%t will be blue<italic<verdana within the "ichEdit0o%.
Ric*-e&t%o&C.:ocus('; Ric*-e&t%o&C.Selection,olor $ ,olor.%lue; Ric*-e&t%o&C.Selection:ont $ ne5 :ont ("Ser ana"! C2! :ontStyle.Italic';

%ow do I 1rowse and read a te9t &i)e into a Te9t7o9?


Aou use the )pen4ile(ialo" to implement this functionailty.
using System.-e&t; using System.I4; private voi )uttonCN,lic/(o);ect sen er! System."ventArgs e' { 4pen:ileDialog o< $ ne5 4pen:ileDialog('; o< .-itle $ "4pen t*e te&t <ile you 5is*" ; o< .InitialDirectory $ "c67" ; o< .:ilter $ "t&t <iles (H.t&t'`H.t&t`All <iles (H.H'`H.H" ; i<(o< .S*o5Dialog(' $$ DialogResult.4^' { StreamRea er sr $ :ile.4pen-e&t(o< .:ile1ame'; string s $ sr.Rea =ine('; String%uil er s) $ ne5 String%uil er('; 5*ile (s 0$ null' { s).Appen (s'; s $ sr.Rea =ine('; 2 sr.,lose('; te&t%o&C.-e&t $ s).-oString('; 2 2

%ow to

se the S()itter #ontro)?

The (plitter control is used to resi5e other controls. The purpose of this is to save space on the form. This control can be very useful when you are working with controls both at design time and run time #which are not visible at design time$.

12

%ow do I ()a#e restri#tion when enterin' some te9t in a te9t1o9?


Aou can restrict a user from entering te%t against a set pattern. 'r you can re-uest the user only to enters certain type of characters. E.g. 'nly a single digit number or a double digit number and so on. To control the input, use the 8ey&ress event like below,
#rivate Su) -e&t%o&CN^ey#ress(%ySal sen er As 4);ect!%ySal e As N System.+in o5s.:orms.^ey#ress"ventArgs' ?an les

-e&t%o&C.^ey#ress I<(e.^ey,*ar F "C." 4r e.^ey,*ar T "C.."' -*en Message%o&.S*o5(""nter Dou)le Digits"' "n "n I< Su)

%ow do I a##ess #ontro)s on another Form?


To access controls on other )inForms follow the e%ample. This e%ample reads the te%t in a te%tbo% from other form and displays it in the te%tbo% on the current form. 'pen two forms #formE and form?$, add a FormE and a Te%tbo% to Form?. The following code relates to formE.
#u)lic ,lass :ormC In*erits System.+in o5s.:orms.:orm Dim 1e5+in o5 As 1e5 :orm2('

ommand 0utton and a Te%tbo% to

#rivate Su) :ormCN=oa (%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les My%ase.=oa 1e5+in o5.S*o5(' "n Su)

#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les %uttonC.,lic/ -e&t%o&C.-e&t $ 1e5+in o5.-e&t%o&C.-e&t "n Su)

13

"n

,lass

)hen you run the code, 0oth

%ow #an I a##ess a We1site/We1(a'e with a 37.NET LinkLa1e) #ontro)?


To access a )ebsite or a )ebpage using a /0.NET application. Drag a LinkLa$el control and write the following code in it;s click event.
#rivate Su) =in/=a)elCN=in/,lic/e (%ySal sen er As System.4);ect! %ySal e As

System.+in o5s.:orms.=in/=a)el=in/,lic/e "ventArgs'?an lesN =in/=a)elC.=in/,lic/e System.Diagnostics.#rocess.Start("555.ya*oo.com"' "n Su)

@pon running the application,click on the Te%t on the !ink!abel. The website, Aahoo.com will open in a new browser.

%ow do I add items to a Com1o7o9 and sort them?


The following code shows how to add items to a ombo0o%.

#rivate Su) :ormCN=oa (%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les My%ase.=oa

,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A ,om)o%o&C.Items.A

(>In ia@' (>Australia@' (>S5e en@' (>Spain@' (>"nglan @' (>3nite States@'

(>Russia@' (>,*ina@' (>Aapan@' (>1e5 Relan @'

13

"n

Su)

To sort the items alpahbetically, select the .-orted property and set it to True.

%ow do I )oad a (i#t re into the /i#t re7o9 #ontro)?


To load a &icture into the &icture0o% control drag a &icture0o% control and a ommand 0utton from the Toolbo%. )hen you click the ommand 0utton, the picture you specified will be loaded into the &icturebo%. The following code is a demonstration.
#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les %uttonC.,lic/ #icture%o&C.Image$Image.:rom:ile(",67images7image.gi<"' OAssuming you *ave a <ol er name images in ,6 rive an a gi< image in t*at "n Su)

%ow do I add a #ontro) to windows &orm at r ntime?


To add a control to a Form at "untime, firstly decide which control is needed. (et all relevent properties and finally use the ontrols.Add/controlname0 function. *n an e%ample of how to add a Te%t0o%,
Dim t) as -e&t%o& $ 1e5 -e&t%o&(' O eclaring a te&t)o& t).Si8e $ 1e5 Si8e(C3.! 2D' Osetting t*e si8e <or t*e te&t)o& t).=ocation $ 1e5 #oint( D.! V.' Osetting t*e location t).-e&t $ "-e&t)o&C" Osetting t*e te&t Me.,ontrols.A (t)' Oa ing t*e te&t)o& to t*e <orm

%ow to #reate an 2E9()orer st$)e2 a(()i#ation in 37.NET?


Displaying all the drives, folders and files in an application like OE%plorerO can be done easily in /0.NET. To do this follow these simple instructions, 'pen a new pro3ect *dd a ommand 0utton to the Form. &lace the following code in the click event of the command button.
#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySal e As N System."ventArgs' ?an les %uttonC.,lic/ Dim e&pl As 1e5 "&plorerStyleSie5er(' e&pl.S*o5(' "n Su)

What is a Too)ti( #ontro) and how sho )d I

se it?

* Tooltip is a tag that displays some te%t when an o3ects Mouse 'ver event is triggered. This is usually a decription of the ob3ect or the action that will follow if the ob3ect is say for e%ample clicked.

13

*ssume that there is a Te%t0o% on a Form and we want to display a description when the mouse is over the Te%t0o%. 0elow is an e%ample,
#rivate Su) :ormDN=oa (%ySal sen er As System.4);ect! %ySal e N As System."ventArgs' ?an les My%ase.=oa -ool-ipC.Set-ool-ip(-e&t%o&C! ""nter Some te&t"' Ousing t*e Set-ool-ip met*o to set t*e tip <or t*e -e&t%o& an t*e te&t t*at s*oul appear "n Su)

9ML 5ow do 'o# test if an attri$#te e*ists in the *ml doc#ment?


String Salue$"";

i< (1o e.Attri)utes["Attri)uteC"( $$ null' { KK oesnOt e&ist Salue$""; 2 else { KK e&ists Salue$1o e.Attri)utes["Attri)uteC"(.Salue.-oString('; 2

Visual studio .net


What is Vis#al -t#dio.NET?
Microsoft /isual (tudio.NET is an integrated development environment which is the successor of Microsoft /isual (tudio 7. 4t eases the development process of .NET *pplication to great deal for /isual ..NET, /isual 0asic.NET, /isual 2 2.NET, /isual 1(cript.NET, /isual 1..NET, *(&.NET, etc The revolutionary approach in this new /isual (tudio.NET is that for all the /isual (tudio.NET ompliant !anguages there is a single 4DE, debugger, pro3ect and solution

13

e%plorer, class view, properties tab, tool bo%, standard menu and toolbars. The key features of /isual (tudio.NET 4DE include, 8eywords and synta% highlighting 4ntellisense #help completing the synta% as you place dot #.$ with ob3ects, enumeration and namespace and when you create new ob3ects$ &ro3ect and solution management with solution e%plorer that help manage applications consisting of multiple files, which is what usually happens 9elp building user interface with simple drag and drop over the form window &roperties tab that allows you to set different properties on a number of windows and web controls (tandard debugger that allows you to debug your program by putting break points for observing run<time behavior of the variables and ob3ects in the program 9ot compiler that checks the synta% of your code as you type it and report any errors present Dynamic 9elp on number of topics using Microsoft Developer Network #M(DN$ !ibrary ompilation and building applications E%ecution of your application withBwithout debugger Deploying your .Net application over the 4nternet or on Ds

Wh' #se the 2(E when we can de&elop a .NET application for free?
The basic purpose of using the /isual (tudio.NET or any 4DE is to manage the application code. *s the re-uirements and thus application evolves, the si5e of code increases. 4t is important to manage this code well, so the later modification and debugging can be carried out smoothly. This code management also makes it possible to use the library code developed previously and to develop the application in such a way so that various parts of it can be reused in future applications. The application is divided into several modules that are linked to work together to perform the re-uired functionality. This is where the 4ntegrated Development Environment #4DE$ comesL *n 4DE helps manage the application by assisting you to break your application into pro3ects, separate files and grouping the files into folders. For e%ample if you are developing an accounts management system, you may break it into three pro3ects6 one for user interface application, other for accounts implementation, and the last one for information storage #into database or file system$.

Then, you may further divide the user interface pro3ect to three folders6 first #Forms$ containing user interface forms second #*ccounts*ccessor$ containing classes to interact with the accounts implementation pro3ect third #(torage*ccessor$ containing classes to interact with the information storage pro3ect

13

*part from this, an 4DE also provide its support from the start of development to the creation of final installation. 4t provides an intelligent te%t editor that recogni5es various parts of your code and also highlights the possible errors as you type it. 4t helps you in compiling and testing individual pro3ects and also the complete application. 4t provides an integrated debugger to identify the bugs in your program and the possible cause of them. 'ne of the most appealing features of an 4DE like /isual (tudio.Net is that it provides designers for various tasks like )indows *pplication @ser 4nterface designing, )eb form designing and the database connection with simple drag and drop and setting a few properties. 'nce you have completed the application development and tested it through debugger, the 4DE also helps you in building its installation program so that the application can be shipped to the client. 9ence, an 4DE supports developers throughout the life cycle of the application.

2s there an' other 2(E a&aila$le for the de&elopment of .NET pro"rams?
Fortunately, there are a number of 4DE;s and source code editors available for the development of .Net programs. (ome of these are introduced below, Borland !B#ilder for the Microsoft? .NET 4ramework http,BBwww.borland.comBcsharpbuilderB 0orland . 0uilder is perhaps the second most popular 4DE for development with . programming language after /isual (tudio.Net. *ccording to 0orland, U4t is an integral component of the 0orland solution for application lifecycle management, .0uilder accelerates the delivery of .NET Framework solutions with a design<driven approach to development that increases team productivity. .0uilder provides support for direct interoperability between the .NET Framework, the 1?EEK platform, and '"0*K infrastructure, helping to simplify and reduce the cost of integrating .NET solutions with your e%isting software systems. *nd for faster, easier, and more fle%ible database development, .0uilder delivers high<performance native support for ma3or enterprise<class databases.V !de&elop /read as -harp+(e&elop0 http,BBwww.icsharpcode.netB'pen(ourceB(DB 4t is a free 4DE for . and /0.NET pro3ects on MicrosoftJs .NET platform. 4t is open<source #:&!$, and you can download both source code and e%ecutables from there site. 4n addition, you can find the latest information and changes on .develop, as well as get in touch with the team in the forum.

13

<rimal ode http,BBwww.sapien.comBprimalcode.htm &rimal ode is an innovative .NET development environment incorporating complete capability in a compact si5e that works with your e%isting hardware. 4deal for professional coders, &rimal ode streamlines every .NET pro3ect phase, from start<up to deployment. Aou can work faster, free from hours of repetitive and routine tasks. 0est of all, &rimal ode needs only minimal drive space, so it runs full speed on your e%isting desktops or laptops.

What are the different parts and areas of Vis#al -t#dio.NET 2(E;s called?
The figure below highlights various parts of the /isual (tudio.NET 4DE.

13

Aou can see the toolbo% window at the left hand side #.E$ and the properties window at the right hand side #.?$ of the above snapshot. The toolbo% allows you to add different controls to your form. 'nce the control is placed on the form, you can change its various properties from the &roperties window. Aou can also change the location and si5e of the controls using the mouse. Event properties can be changed by switching to the Event &roperties panel #.>$ in the &roperties )indow. The Toolbo%, &roperties )indow, 9elp )indow, (olution E%plorer )indow, lass /iew )indow, 'utput )indow and other helping windows in /isual (tudio 4DE can be set for (ockin" and A#to hidin". )indows that are set for auto hide appears only when they get focus #e.g. they have mouse pointer over them or receive a mouse click$, and hide when they lose focus. * window can be set for auto hide by the button marked .H in the above figure. The hidden windows are always accessible through the left and right hand panes of the form designer window. The right hand pane is marked with .D in the above figure and has got the class view, help and solution e%plorer windows in the hidden state. 4f some of these windows are not visible in your visual studio 4DE, you can make them visible from the /iew menu on the standard menu bar. -ol#tion E*plorer The solution e%plorer presents the hierarchical view of the pro3ects included in the current solution. 4t presents the detailed view of the individual pro3ects with the contained source code files #which may be grouped into some folders$, the references to the assemblies #pro3ects or library code$ used by the pro3ect and any other resource files like icons, pictures, sounds, animation, etc. The solution e%plorer does not only present the view of the solution hierarchy but also allows you to customi5e the solution or pro3ects settings. 4t allows you to add and remove e%isting and new pro3ects to the solutions, add and remove the references and resource files. 4t also allows you to change the name of the

13

solution, pro3ects, folders and files, their build options, output file names and things like that.

Tool$o*% <roperties and

lass View Ta$s

Now there is a single toolbo% for all the /isual (tudio.NET;s languages and tools. The toolbo% #usually present on the left hand side$ contains a number of common controls for windows, web and data applications like te%t bo%, check bo%, tree view, list bo%, menus, file open dialog, etc. &roperties Tab #usually present on the right hand side in 4DE$ allows you to set the properties on different controls and form without getting into code lass /iew Tab shows all the classes that your pro3ect contains along with the methods and fields in tree hierarchy. This is similar to / 22 7;s class view. Men#s in the Vis#al -t#dio .NET 2(E File Menu, @sed to create, open, save and close the pro3ect, solution or individual source files. Edit Menu, @sed for te%t editing and searching in the /isual (tudio source code editor. /iew Menu, &rovides options for setting the visibility of different /isual (tudio windows and to switch between code and designer views. &ro3ect Menu, @sed for setting different properties of the /isual (tudio &ro3ect. * /isual (tudio pro3ect is a collection of files that make up a single assembly or a single ob3ect file #we will e%plore the concept of assemblies in coming lessons$. 0uild Menu, This menu is used to compile and build the source file, pro3ect or solution. The result of a build is an e%ecutable file or a code library. Debug Menu, This menu provides various options related to the /isual (tudio.Net Debugger. Debugging is the process of finding logical errors in the program, and a debugger helps make this proccess easier. Data Menu, &rovides various options for Data *ccess in .Net Format Menu, &rovides access to a set of useful operations for formatting the controls and their layout in the Form Designer view. Tools Menu, &rovides the access to various useful /isual (tudio.NET tools.

13

4orm (esi"ner The /isual (tudio.NET form designer allows you to design the windows and web forms for your application;s user interface. 4t simplifies the task by allowing you to 3ust drag and drop the re-uired controls from the toolbo% to the designer;s emulated form. 4t even sets the default properties for your controls. Aou can then change the properties of the form and control through the &roperties Tab of the /isual (tudio.NET 4DE. The form designer also allows you to attach the even handlers with the controls. ode Editor The /isual (tudio.NET ode Editor supports you in writing the code for your application. The code editor is tightly integrated with the designers. *s you change the properties and add controls, the designer puts the re-uired code in you application source code files which can be viewed using the code editor. The code editor is -uite smart6 it highlights the various categories of the code like keyword, constant and even the synta% and semantic errors. 4t provides the code completion through its intellisense6 when you place dot #in . and /0.NET$ with your ob3ect references and namespaces it automatically shows the list of all available options to select from. Finally, the code editor is also used to debug the application using the integrated debugger.

What are V-.NET sol#tions and pro=ects?


* &ro3ect is a combination of e%ecutable and library files that make an application or one of its modules #not a .NET assembly or /0.NET module6 simply a separate part of the overall application$. * pro3ect;s information is usually placed in a file with e%tension like I.vbpro3; where Ivb; represents /isual 0asic #source programming language$ and Ipro3; stands for &ro3ect. (imilarly . pro3ects are stored as I.cspro3; file where Ics; stands for (harp. There are different kind of pro3ects like onsole *pplication, )indows application, *(&.Net )eb *pplication, lass !ibrary, )indows ontrol !ibrary, )eb (ervices and others. * solution on the other hand is a placeholder for different logically related pro3ects that make up an application. For e%ample, a solution may consist of *(&.NET )eb *pplication pro3ect and )indows Form pro3ect. The information for solution is stored in I.sln; files while they can be managed using /isual (tudio.NET;s (olution E%plorer. (olutions are similar to /0 7;s &ro3ect :roup and / 22 7;s workspace. * great thing about the /isual (tudio.NET solutions is that it may contain pro3ects built with any of the /(.NET compliant language. 9ence, now your solution may consists of a database handling pro3ect in /isual ., the :@4 *pplication pro3ect in /0.NET and the protocol implementation pro3ect in / 22.NETL

What are the different t'pes of pro=ects that can $e created with Vis#al -t#dio.NET?
/isual (tudio.NET allows you to create pro3ects of these types, onsole applications are light weight programs run inside the command prompt #D'($ window. They are commonly used for test applications. Windows Applications are form based standard )indows desktop applications for common day to day tasks. Microsoft word is an e%ample of a )indows application.

13

We$ applications are programs that used to run inside some web server #e.g., 44($ to fulfill the user re-uests over the http. * typical e%ample of web application is 9otmail and :oogle. We$ ser&ices are web applications that provide services to other applications over the internet. :oogle search engine;s web service, e.g., allows other applications to delegate the task of searching over the internet to :oogle web service and use the result produced by it in their own applications. lass li$rar' contains components and libraries to be used inside other applications. * lass library can not be e%ecuted and thus it does not have any entry point. Windows ontrol Li$rar' contains user defined windows controls to be used by )indows applications We$ ontrol Li$rar' contains user defined web controls to be used by web applications

5ow are pro=ects different from the namespaces?


* &ro3ect is a physical grouping of the source code and resource files that make up an assembly and stored into some file. * namespace, on the other hand, is a logical grouping of related types which not necessarily reside into same assembly. * namespace may contain sub or child namespaces while there is not concept of child or sub pro3ects. Finally, pro3ect is a /isual (tudio.NET standard, while namespace is a .NET standard.

5ow are namespaces different from assem$lies?


*n assembly is a physical grouping of the source code and resource files that is stored into some file#s$. * namespace, on the other hand, is a logical grouping of related types which not necessarily reside into same assembly. * namespace may contain sub or child namespaces while there is not concept of child or sub assemblies #module is something different from child namespace, as modules are integral and necessary parts of an assembly$. *n assembly not only contains the source code, it also contains manifest, version information #optional public key token$ and culture information. * program may reference two or more assemblies with the same name #but with different versions$ but a program can not contain two namespaces with the same name.

What does it mean $' code foldin" in Vis#al -t#dio.NET?


The /isual (tudio.NET automatically groups the code at various boundaries #method, property, class, structure, interface, and namespace bodies$. 4t then allows you to e%pandBcollapse the regions of these code body groups using the familiar plusBminus sign used in the tree<view control #e.g., in )indows E%plorer$ which allows you to fold #collapse$Bunfold #e%pand$ the code regions

14

Aou can also define your own regions using the .regionM.end region block with your code.

What does it mean $' s'nta* hi"hli"htin"?


/isual (tudio.NET ode Editor highlights the keywords and synta% errors in your code as you type it with different colors and waves. This is called the synta% highlighting.

What does it mean $' V-.NET hot compilation?

14

The hot compiler highlights the synta% errors in your program as you type the code. The following figure shows an illustration of hot compiler in /isual (tudio.NET

What are re"ions in Vis#al -t#dio.NET 2(EHs code &iew?


* region is a part of the code that can be foldedBun<folded in the /isual (tudio.NET code editor. Aou can also define your own regions using the .regionM .end region block with your code.

What is the difference $etween the (esi"n View and the ode View of the Vis#al -t#dio.NET?
The design view opens the /(.NET form designer that allows you to place user interface controls on the form by simple drag and drop, resi5e them and set various properties in the convenient way. The designer automatically generates the re-uired code for the program. The code view opens the source code editor that allows you to see the actual code of the program and perform any desired edition.

5ow can 2 compile and $#ild a partic#lar pro=ect and the whole sol#tion?
To compile all the source files of the pro3ect and build the resulting assembly, right click the target pro3ect node in the solution e%plorer and select "ebuild pro3ect. To compile all the source files of all the pro3ects contained in a solution and build the resulting assemblies or the complete application, right click the solution node in the solution e%plorer and select "ebuild solution.

What feat#res does the Vis#al -t#dio.NET de$#""er pro&ide to the de&elopers?
/isual (tudio.NET provides an integrated debugger. The debugger allows you to debug your application from within the /isual (tudio.NET 4DE and code editor. Aou can use the code editor to specify the break points and see the runtime values of the variables of a program. Aou can control the e%ecution of your program step by step6 e.g. you can pause the e%ecution of the program after each line, you can 3ump the control of e%ecution to the ne%t method in the e%ecution se-uence. Aou can even change the runtime values of the variables at runtime and re<e%ecute itL 4t;s simply an ama5ing toolL

14

What is the difference $etween r#nnin" an application with and witho#t de$#""er?
)hen an application is run with debugger, the debugger will provide its services during the e%ecution. This may slow down the e%ecution of the program and is useful when the program is in the development and testing phase. )hen program is run without debugger, it is e%ecuted in the similar way as it will be e%ecuted at the client #user of the application$ machine. The e%ecution of the program without debugging is useful when application is about to be deployed or in the testing phase, when we are interested in measuring the efficiency and the throughput of the application.

5ow can 2 r#n an application with and witho#t de$#""er?


To run the application with debugger, select Debug Y "un or press FD. To run the application without debugger, select Debug Y "un without debugger or press trl2FD

What are $reak points in conte*t with the de$#""er?


* break point is the line of code at which you want your program to be paused #when running in debugger mode$ and see the runtime values of different variables in the program. 4f the program control ever reaches this line during the e%ecution of the program, it pause the e%ecution and allows you to see and edit the values of the variables of your program.

5ow can 2 add a $reak point in m' code? 5ow can 2 remo&e a $reakpoint?
To add a break point for some line, click at its left panel. Aou can also do this by right clicking the target line and selecting the J4nsert breakpointJ. To remove a break point from some line, click on its left pan. Aou can also do the same by right clicking on a target line and select J"emove breakpointJ.

5ow can 2 see the r#ntime &al#es of different &aria$les of m' code #sin" de$#""er?
Aou can see the runtime value of a particular variable by 3ust pointing a mouse over it when the program is running in debugger mode and is paused at some breakpoint. 4t will only show the value of any live variable. To see the runtime values of all the local variables of a method, see the J!ocalsJ debug window. This window is also accessible from Debug Y )indows Y !ocals

14

4nde%

5ow can 2 see the r#ntime &al#es of the content of a class or str#ct#re?
* class or a structure is represented in I!ocals; and other debug windows with e%pandable tree. Aou can see its members by e%panding its ob3ect node

What does it mean $' ;watch; in conte*t of the de$#""er?


4nstead of pointing mouse pointer over a variable to show its value or using the !ocals to view the values of all the local variables, you can also add only interested variables in the Debugger;s )atch )indow #accessible through Debug <Y )indows <Y )atches <Y )atch E$. The values in )atch window are always visible in the bottom of your /(.Net. To add any variable to )atch )indow, right click on the variable and choose J*dd )atchJ or drag it to the watch window.

When the e*ec#tion of a pro"ram is pa#sed at a $reakpoint% how can 2 res#me the e*ec#tion?
Aou can resume the e%ecution, either by selecting Debug Y ontinue #press FD$ or using the various I(tep; options like (tep 4nto #FEE$ or (tep 'ver #FEF$.

5ow do 2 step into and step o&er the code with de$#""er? What do Isteppin" intoHand steppin" o&erH act#all' mean?
The (tep 4nto option #accessible through Debug <Y (tep 4nto or key FEE$ takes the e%ecution control inside the calling method. For e%ample, if the e%ecution is paused at a line having code

14

int p $ o);.IetInteger(';

Then pressing FEE, will take us to the body of the :et4nteger#$ method and the e%ecution control will pause at its first line. The (tep 'ver option #accessible through Debug](tep 'ver or key FEF$ e%ecutes the code in the line at which the debugger is paused and takes the e%ecution control to the ne%t line. For e%ample, if the e%ecution is paused at a line marked line E in the code below,
int p $ o);.IetInteger('; KK line C ,onsole.+rite=ine(p'; KK line 2

Then pressing FEF, will e%ecute the code at Iline E; and will take the e%ecution control to the line marked Iline ?; in the above code and the e%ecution control will pause at the line BB ?.

5ow are pro=ects and sol#tions mapped to .NET assem$lies?


4n /isual (tudio.NET, each pro3ect is compiled to a single assembly with references to the referenced assemblies and other code libraries. 4t is important to remember that up<till now /isual (tudio.NET #?FF>$ only supports single file assembly and not a multi<file assembly. 4t means that all the source code of a pro3ect is built to a single file representing the pro3ect;s assembly. 9ence, if a solution contains five pro3ects then when it #the solution$ is built, it will emit five different assemblies each containing a single .dll or .e%e file depending on the type of pro3ect selected. * solution is a logical binding for the pro3ects and it does not have any representation in the build files.

5ow m#ch pro=ects a sol#tion ma' ha&e?


There is no such limit6 a solution may contain any number of pro3ects. The pro3ects can be coded in any /(.NET compliant programming language. * solution, basically, representation the raw application and it should contain only those pro3ects which are the part of the application.

5ow to set the start application of a m#lti pro=ect sol#tion?


Aou can specify the startup pro3ect of the application by selecting it from the startup pro3ect property of the solution which can be accessed by right clicking the solution and selecting the properties option from the pop up menu. 4t will show the property pages for the solution. Aou can change the startup pro3ect from ommon &roperties <Y (tartup pro3ect <Y (ingle (tartup pro3ect. Note that the startup pro3ect must represent an e%ecutable assembly # onsole application, windows application or a web application$ and not a library pro3ect.

5ow do 2 chan"e the name of the res#ltin" assem$l' files /.e*e and .dll0?

14

"ight click the pro3ect and select properties. 4t will show the property pages for the pro3ect. Aou can change the resulting assembly name from ommon &ropertiesY :eneral Y *ssembly Name.

What is the difference $etween a de$#" and a release $#ild?


The debug build is created with some embedded information which allows the debugger to debug the application and e%poses the runtime behavior of the application. 'n the down side, the debug build is a bit slower and inefficient in e%ecution and larger in si5e. Aou may specify the build type of an assembly #pro3ect$ by right clicking its pro3ect and selecting properties from the pop up menu. 4t will show the property pages for the pro3ect. Aou can select the build type by selecting onfiguration &roperties and then selecting the build type from the combo bo% at top labeled onfiguration

What are references in conte*t of the V-.NET pro=ects?


* reference is the name and address of the .NET assembly or a 'M component used inside some source files of the pro3ect. The /isual (tudio.NET uses these added references when compiling your pro3ect assembly. * reference enables the language compiler to locate the referenced assemblies and 'M component.

5ow man' t'pes of reference are there in the Vis#al -t#dio.NET?


There are basically three types of references that can be added to a pro3ect, "eference to the .NET assembly #including components, library and controls$ )eb reference to web services #see the succeeding -uestion for details$ "eference to 'M component #see the succeeding -uestion for details$

What are we$ references in conte*t of the V-.NET pro=ects?


* web reference represents a reference to the web service, at its simplest. :etting inside, a web reference is a reference to the pro%y classes to call the web service. These pro%y classes are implemented for you by the /(.NET 4DE for you through the )eb (ervice Description !anguage #wsdl$ file downloaded from the web service @"!. These pro%y classes provide the same calling interface to the clients of web service. )hen you call methods on a pro%y class, it in turn calls the methods of the web service over the internet through ('*& #(imple 'b3ect *ccess &rotocol$ and returns the result back to your program.

5ow do 2 add a reference to a .NET assem$l' in m' pro=ect?

14

To add a reference to a .NET assembly, right click the I"eference; option under the pro3ect inside the solution e%plorer and select the I*dd "eferenceM; option. 4t will show you a user interface screen where you browse for the target assembly. )hen you have selected the assembly, press the I(elect; button and then press '8. This will add a new reference node in the "eference sub tree of the pro3ect. 0y selecting the added reference node, you can edit its properties from the properties window. 4nde%

What is 3is a) St dio.NET I,E and what is the im(ortan#e o& it?
The /isual (tudio .NET 4DE is the default Development Environment for all Microsoft .NET based applications. 4ts got a full set set of usefull features. The /(.NET 4DE provides many options for developers and is packed with much funtionality that simplifies application development. 2mportant 4eat#res of Vis#al -t#dio .NET 2(E. 'ne 4DE for all .NET based &ro3ects /isual (tudio .NET 4DE provides a single environment for developing all types of .NET applications. *pplication;s range from single form applications to comple% n<tier applications and also "ich )eb *pplications. The option to choose from Multiple &rogramming !anguages Aou can customi5e the 4DE based on your preferences. 0y use of OMy &rofile settingsO. )ith these settings you can set the 4DE screen the way you want, the way the keyboard behaves and you can also filter the help files based on the language of your choice. The 4DE comes with a built<in browser that helps you navigate the 4nternet without launching another browser app.

What are the de+e)o(in' o(tions in 3S.NET? "nd what (ro8e#t tem()ates are there?
@pon starting developing applications with /isual (tudio .NET, 4ts possible to develop applications based on your choice. 9ere is a rundown of the different types of applications that can be developed using a vanilla install of /(.NET. )penin" a new pro=ect1 The following are the different options available in /(.NET and what they are used for. Windows Applications1 This template allows you to create standard windows based applications.

14

lass Li$rar'1 lass libraries are those that provide functionality similar to *ctive + and D!!Js by creating classes that that can be used from other applications. Windows ontrol Li$rar'1 This allows the creation of your own windows controls. These can also be added to the tool bo% to make it easier if you wish to use these resources in other pro3ects. A-<.NET We$ Applications1 reate web<based application using 44(. Aou can develop )eb pages, "ich )eb *pplications and )eb (ervices. A-<.NET We$ -er&ice1 For developing +M! )eb (ervices. We$ ontrol Li$rar'1 *llows you to create @ser<defined controls for the )eb. (imilar to user defined windows controls but these are specifically for )eb usage. onsole Application1 Development of command line based applications. No :@4 needed Windows -er&ice1 )indows (ervices are background programs that run without promp. *n e%ample would eb an (MT& server. )ther1 This template is to develop other kinds of applications such as enterprise applications, database applications etc.

5ow do 2 chan"e the icon of m' application?


"ight click the startup pro3ect node in the solution e%plorer window and select the properties option. 4t will show the property pages for the pro3ect. Aou can change the application icon from ommon &roperties <Y :eneral <Y *pplication 4con. Note that this is the icon for the application that will be attached with its e%ecutable file and shortcuts to it. To change the icon of the individual forms of your application, select the icon by editing the icon property of your form.

5ow do 2 make folders in the pro=ect?


To create a folder into a pro3ect, right click the target pro3ect node in the solution e%plorer and select I*dd FolderM; option. This will add a new folder to the pro3ect, specify the name of the folder and press Enter. The folders inside a pro3ect help you manage and separate source files for different purpose in the same pro3ect. For e%ample, you may divide the windows form pro3ect to three folders6 first #Forms$ containing user interface forms second # onstants$ containing constant values #enumerations and error codes$ to be used in the pro3ect third #(torage*ccessor$ containing classes for the database handling.

5ow do 2 add a new or e*istin" file to a pro=ect or to a pro=ect folder?


To add a file to a pro3ect or to a pro3ect folder, right click its node in the solution e%plorer and select either I*dd New 4temM; or I*dd E%isting 4temM; option. This

14

will show you a user interface screen that allows you to add various kinds of items like report, icon, class file, windows form, etc. (elect the appropriate item from here.

5ow do 2 add a new or e*istin" pro=ect to a sol#tion?


To add a pro3ect to a solution, right click the solution node inside the solution e%plorer and select the I*dd &ro3ectM; or I*dd e%isting pro3ect; option. 4t will show you a user interface screen where you can browse for the target pro3ect. This will add a new pro3ect node in the solution tree.

What is

!?

. #pronounced <(harp$ is a new programming language introduced with the Microsoft .NET framework and is no doubt the language of choice in .NET environment. 4t was first created in the late ECCFJs as part of Microsoft;s whole .NET strategy. 4t is a whole new language free of backward compatibility curse and a whole bunch of new, e%citing and promising features. 4t is an 'b3ect 'riented &rogramming language, which at its core, has similarities with 1ava, 2 2 and /0. 4n fact, . combines the power Q efficiency of 22, simple Q clean '' design of 1ava, and code simplification of /isual 0asic. !ike 1ava, . 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 checking. 0ut, contrary to 3ava, . keeps the different useful concepts of 22 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 template support #with the name of generics$ in ne%t versions. !ike /0 it also supports the concepts of properties #conte%t sensitive accessor to fields$. 4n addition to this, . comes up with some newBe%citing features like reflections, attributes, marshalling, remoting, threads, streams, data access with *D'.NET, etc. . programming language is designed from the scratch keeping in mind the Microsoft.Net environment. M(.Net #and thus .$ programs runs on top of the ommon !anguage "untime # !"$, which provides the runtime support to them. -ample ! Application

3sing System ,lass Sample { pu)lic static voi main(' { ,onsole.+rite=ine (>?ello +orl @' 2 2

What are Ja''ed "rra$s in C0?


* special type of array is introduced in .. * 1agged *rray is an arra' of an arra' in which the length of each array inde% can differ.

14

E%ample, * 1agged *rray can be used is to create a table in which the lengths of the rows are not same. This *rray is declared using s-uare brackets # R S $ to indicate each dimension. The following code demonstrates the creation of a two<dimensional 3agged array.
,lass Aagge { pu)lic static voi Main(' { int [([( ;agge $ne5 int [3([(; ;agge [.($me5 int[B( ;agge [C($me5 int[3( ;agge [2($me5 int[D( int I; EStoring values in <irst array <or (I$.;IFB;IGG' ;agge [.([I($I; EStoring values in secon array

<or( I$.;IF3;IGG' ;agge [C([I($I; EStoring values in t*ir array

<or(I$.;IFD;IGG' ;agge [2([I($I; EDisplaying values <rom <irst array

<or (I$.;IFB;IGG' ,onsole.+rite=ine(;agge [.([I(' EDisplaying values <rom secon array

<or (I$.;IF3;IGG' ,onsole.+rite=ine(;agge [C([I('

EDisplaying values <rom t*ir <or(I$.;IFD;IGG'

array

,onsole.+rite=ine(;agge [2([I('

15

2 2

"un the code to see the output.

What is the di&&eren#e 1etween 23a) e T$(es2 and 2Re&eren#e T$(es2?


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 O0y /alueO. 4n .NET terms, these are called /alue TypesO. The "unTime supports two kinds of /alue Types, E B#ilt+in &al#e t'pes The .NET Framework defines built<in value types such as (ystem.4nt>? and (ystem.0oolean which correspond and are identical to primitive data types used in programming languages. ? ,ser+defined &al#e t'pes The language you are using will provide functionality to define your own /alue Types. These user defined Types derive from (ystem./alueType. 4f you want to define a Type representing a value that is a comple% number #two floating<point numbers$, you might choose to define it as a value type. )hyK 0ecause you can pass the /alue Type efficiently O0y /alueO. 4f the Type you are defining could be more efficiently passed O0y "eferenceO, you should define it as a class instead. /ariables of "eference Types are referred to as ob3ects. These store references to the actual data. The following are the "eference Types, class interface delegate

This following are the Obuilt<inO "eference Types, ob3ect string

15

VB.NET 4re7#enl' Asked ?#estions

What is the difference $etween VBJ and VB.NET


There are -uite a few differences in /07 and /0.NET. )e will highlight some of these here in points, The greatest change in /07 and /0.NET is of runtime environment. /07 used the /0<"untime while /0.NET uses the .Net ommon !anguage "untime #.Net !"$. The !" is much better designed and implemented than /0<"untime. The !" uses better code translation through 1ust in Time compiler while /0<"untime interprets the code. The !" :arbage ollector is also more efficient than /07 one as it may detect cyclic references too. /07 was interpreter based language while /0.NET is a compiled language /07 was not a type<safe language while /0.NET is a type safe language. There is no variant type in /0.NET and no magical type conversions happen in /0.NET /07 used I'n Error :oto; synta% to handle e%ceptions at runtime. /0.NET uses the TryM atchMFinally synta% to handle e%ceptions at runtime. * lot of code #like user interface code$ in /07 was hidden from developer. 4n /0.NET no code is hidden from developer and you can access and control each part of your application /0.NET has much enhanced ob3ect oriented support than /07 /07 does not allow developing the multithreaded applications. 4n /0.NET you can create multithreaded applications. /07 was only considered good for desktop windows application. 4n /0.NET you can also develop web applications, distributed applications, create .NET windows and web controls and components, write windows and web services. 4n /0.NET, you can also use reflections to read the meta<data of types and using reflection emit you can also generate code to define and invoke types at runtime. /0.NET uses .NET framework class library along with speciali5ed /0 library #(ystem./isual0asic$ as a standard library. *s a result, the standard library for /0.NET is much enhanced and useful compared to /07 standard library /0.NET is platform independent because of .Net framework. &rograms written in /0.NET can run on any platform where .Net framework is present. The platform include both hardware and software #operating system$ platforms.

15

/0.NET also supports language interoperability with various .NET compliant languages. This means that you can use and enhance the code written in other .NET compliant languages. (imilarly the code written in /0.NET can also be used and enhanced by other .NET compliant languages. *lthough /07 also provided this functionality through 'M but it was limited and difficult to use and manage. /0.Net makes it easier because of the presence of 4ntermediate !anguage #4!$ and ommon !anguage (pecification # !($ of the .NET architecture. /07 uses 'M # omponent 'b3ect Model$ as component architecture. /0.NET uses assemblies as its component architecture. The *ssemblies architecture has removed a lot of problems with 'M including D!!<9ell and versioning problem. omponents created in /07 # 'M$ need to make and update registry entries. /0.NET does not re-uire any registry entry making the deployment easier /07 used *(& to build web applications. /0.NET uses *(&.NET to build web applications. /07 used *D'D0 and record<sets to implement data access applications. /0.NET uses *D'.NET and datasets to build data access applications. The *D'.NET also supports the disconnected data access.

What are Conso)e "(()i#ations in 37.NET?


onsole *pplications have only recently been introduced in /0 #E%cluding /0 for D'($. They are command line based and run in within a D'( (hell #D'( )indow$. @nlike )indows *pplications, onsole *pplications do not support )indows :@4Js. )hich means that you canJt work with controls from the toolbo%. To work with onsole *pplications select File<YNew<Y&ro3ect and in selected O onsole *pplicationO from the template under /isual 0asic or /isual .. E%ample #(ample.vb$ of a onsole *pplication.

Mo ule Mo ule C Su) Main (' System.,onsole.+rite=ine ("?ello +orl @' "n Su) "n Mo ule

"un the program by pressing OFDO on the keyboard or by selecting Debug<Y(tart. The output of the program is U9ello )orldV. ompilation of the program using the /isual (tudio .NET ommand &rompt is also possible. To compile the program using that type Ovbc sample.vbO at the command prompt.

15

What are names(a#es and what is the im(ortan#e o& them?


* namespace is a collection of different classes which are built into .NET. This very much like packages in 1ava. Aou need to import these namespaces to work with any .NET language. *ll the functionality of .NET is within these namespaces. The main namespace is the -'stem namespace and all other namespaces are built into this (ystem namespace. (ome of these namespaces and what they are used for are summari5ed below. -'stem1 4ncludes essential classes and base classes that define commonly used Data Types, events, interfaces, attributes etc. -'stem.(ata1 4ncludes classes that make up *D'.NET and allows to build data<handling components. -'stem.(rawin"1 &rovides access to graphics that gives access to drawing methods. -'stem.2)1 &rovides access to writing data streams and Files. -'stem.Net1 &rovides interface to many protocols used on the 4nternet. -'stem.-ec#rit'1 4ncludes classes to support the security system. -'stem.Threadin"1 4ncludes classes that support threading. -'stem.We$.-er&ices1 4ncludes classes for creating and using )eb (ervices. -'stem.Windows.4orms.1 4ncludes classes for creating windows based applications.

What is the im(ortan#e o& the 4(tion statement?


The )ption statement is used to prevent synta% and logical errors in code. The possible suffi%es of this statement are, )ption E*plicit1 4s the default abd is 'n. 'ption E%plicit re-uires declaration of all variables before they are used. )ption ompare1 This can be set to 0inary or Te%t and it specifies if strin"sp are to be compared using binary or te%t comparison operations. )ption -trict1 The default is 'ff. *n e%ample, 4f value of one data type is assigned to another then /isual 0asic will consider that as an error. 4f you want to assign a value of one Type to another then you should set it to 'n and use the conversion functions.

E%ample using the 'ption (tatement. The following code does not perform any special function but will show where to place an )ption statement.
4ption Strict 4<< Imports System Mo ule Mo ule C Su) Main (' ,onsole.+rite=ine (>3sing 4ption@' "n Su) "n Mo ule

15

What are attri1 tes in 3is a) 7asi# .NET?


*ttributes are items that hold information about items we are using in /0.NET. They are used when /0.NET needs to know more than what standard synta% can specified. *ttributes are enclosed in angle bracketsZY. E%ample, To call a )indows *&4 functions you have to include a dynamic link library #D!!$ reference that the function you are calling resides in. This is done using the D!!4mport attribute as follows,
#u)lic S*are :unctionFDllImport""user32. ll"'TMessage%o&(%yval..'

Aou can also use an attribute like Z*ttributeY or pass itJs value to a parameter as you can do with procedures like Z*ttribute#OhelloO$Y.

What are En merations in 37.NET and how are the$ sed?


Enumerations are new in /0.Net #*s apposed to /0#i$$ and they are used to group related sets of constants. To create a Enumeration you use the En#m statement. E*ample #sin" a En#meration
Mo ule Mo ule C "num Mont*s Aanuary$C :e)urary$2 Marc*$3 April$B May$D Aune$U Auly$V August$P Septem)er$W 4cto)er$C. 1ovem)er$CC Decem)er$C2 "n "num

Su) Main(' System.,onsole.+rite=ine(>Decem)er is > Y Mont*s.Decem)er Y@ t* Mont*@' "n "n Su) Mo ule

)hen using constant;s declared in an Enumeration, you need to refer to it like so,
Mont*s.Decem)er.

The output of the above code displays December is the E?th Month.

15

%ow do I #on+ert te9t &rom )ower #ase to #ase in 37.NET?

((er

The following code shows how te%t can be converted from lower case to upper.
Mo ule Mo uleC Su) Main (' Dim strC as String$@+elcome to String@ Dim str2 as String Str2$3,ase(strC' 4r Str2$StrC.-o3pper System.,onsole.+rite=ine(str2' "n Su)

%ow do I hand)e Math & n#tions in 37.NET?


9igher Mathematical functions in /0.NET are in the methods of the -'stem.Math namespace. alculation of a hyperbolic cosecant value and so on is possible by using the methods in this namespace. E*ample #sin" a Math 4#nction
Imports System.Mat* Mo ule Mo uleC Su) Main(' System.,onsole.+ite=ine(>#i $ > Y B H Atan('' "n Su) "n Mo ule

%ow do I hand)e ,ate and Time in 37.NET?


)orking with Dates is one to think about. Especially if your data needs to be spread accross time5ones *lso there are different date formats to take in to consideration. /0.NET 9as some good Date#$ Functions, one of which is demonstrated below, E*ample
Imports System.Mat* Mo ule Mo uleC Su) Main (' Dim Dts as Date Dts $ \ C.KCDK2..C System.,onsole.+rite=ine(>1e5 Date6 Y DateA "n Su) "n Mo ule

(DateInterval.Mont*! 22! Dts''

The above code adds ?? months to the date we declared in the &rogram.

%ow do I #reate /ro#ed re ,e)e'ates?


Delegates are used to work with the address of procedures. This is much like pointers in and 22. (ometimes itJs useful to pass the location of a procedure to other procedures.

15

E*ample workin" with (ele"ates1


Mo ule Mo uleC Delegate Su) Su)DelegateC(%ySal str as String' Su) Main(' Dim Mess as Su)DelegateC MessMA ress4< Display Mess.Invo/e(>?ello <rom Delegates@' "n Su)

Su) Display(%ySal str as String' System.,onsole.+rite=ine(Str-e&t' "n "n Su) Mo ule

The above code displays U9ello from DelegatesV 3ust like a normal program but it uses (ele"ates to do it.

%ow do I

se the In( t7o9 F n#tion?

*n 2np#tBo* function is much like a K1ava(cript prompt window which allows the input of te%t. To work with the 4nput0o%, drag a ommand 0utton and a Te%t0o% from the Toolbar. 'pon clicking the ommand 0utton the 4nput0o% prompts asks for a name. 'nce entered, press '8. That te%t will now be displayed in the Te%tbo%. The sample code for the click event
#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySal e As System."ventArgs'N ?an les %uttonC.,lic/ Dim S*o5 As String S*o5 $ Input%o&(""nter your name"' -e&t%o&C.-e&t $ S*o5 "n Su)

%ow do I write data to a te9t &i)e in 37.NET?


The following code creates a te%t file and inserts some te%t.
Imports System.I4 #u)lic ,lass :ormC In*erits System.+in o5s.:orms.:orm #rivate Su) :ormCN=oa (%ySal sen er As System.4);ect! %ySal eN As System."ventArgs' ?an les My%ase.=oa Dim <s as 1e5 :ileStream("e&p.t&t"!:ileMo e.,reate!:ileAccess.+rite' Dim s as ne5 Stream+riter(<s' s.%aseStream.See/(.!See/4rigin."n ' s.+rite=ine("#rogrammers?eaven *as lot o< programming goo ies"' s.+rite=ine(" goo resource <or most popular programming languages"' s.,lose(' "n Su) "n ,lass

15

What is "n#horin' and ,o#kin'?


The /0 terms (ockin" and Anchorin" are used to make sure that a control covers the whole client area of a form. @pon OdockingO a window, it adheres to the edges of itJs container #the Form$. To OdockO a particular control, select the (ock property of the control from the properties window. (electing the (ock property opens up a small window like structure where you can select towards which side on the Form should the control be docked. Aou can use Anchorin" to OanchorO a control to the edges of it;s container #the Form$. (electing this property in the properties window opens up a small window from where you can select what edge to OanchorO the control to.

%ow to 'et #om( ter name and I/ address?


The following code uses the -'stem.NET.(N- namespace to access the Ocomputer nameO and itJs 4& address.
4ption Strict 4<< Imports system Imports System.1et.D1S #u)lic ,lass IetI#

S*are

:unction IetI#A

ress(' As String ress

Dim sam As System.1et.I#A Dim samC As String

+it* system.1et.D1S.Iet?ost%y1ame(system.1et.D1S.Iet?ost1ame('' sam $ 1e5 System.1et.I#A samC $ sam.-oString "n +it* ress(.A ress=ist(.'.A ress'

IetI#A

ress $ samC

"n

:unction

S*are

Su) main('

15

Dim s*ostname As String s*ostname $ system.1et.D1S.Iet?ost1ame console.5riteline("1ame o< t*e System is $ " Y s*ostname' console.5riteline("]our I# a "n Su) ress is$ " Y IetI#A ress'

"n

,lass

ompile the file as Ovbc getip.vb Br,system.net.dllO E%ecute the Ogetip.e%eO. The computerJs name and 4& address will be displayed in the onsole.

%ow to 'et the en+ironment in&ormation in 37.NET?


The -'stem.En&ironment namespace includes the functionality to get the environment information such as the @serName and '( /ersion.
:ile name is SystemIn<o.v)

Imports System

,lass SystemIn<o

S*are

Su) main('

,onsole.+rite=ine(""' ,onsole.+rite=ine(",urrent 3ser"' ,onsole.+rite=ine("nvironment.3ser1ame' ,onsole.+rite=ine(""'

,onsole.+rite=ine("1ame o< t*e Mac*ine"' ,onsole.+rite=ine("nvironment.Mac*ine1ame' ,onsole.+rite=ine(""'

15

,onsole.+rite=ine("4S version"' ,onsole.+rite=ine("nvironment.4SSersion' ,onsole.+rite=ine(""'

,onsole.+rite=ine("System Directory"' ,onsole.+rite=ine("nvironment.SystemDirectory' ,onsole.+rite=ine(""'

,onsole.+rite=ine("-M# :ol er"' ,onsole.+rite=ine("nvironment.Iet"nvironmentSaria)le("-M#"'' ,onsole.+rite=ine(""'

,onsole.+rite=ine(",lass #at*"'

,onsole.+rite=ine("nvironment.Iet"nvironmentSaria)le(",lass#at*"'' ,onsole.+rite=ine(""' ,onsole.rea =ine(' "n "n ,lass Su)

%ow do I read and write data to an =ML &i)e?


The following code demonstrates how to read and write to an +M! file.
FZ&ml version$"C.." stan alone$"yes"ZT

FDocumentT F,ustomerT F1ameTSan eepFK1ameT FAgeT23FKAgeT F4ccupationTDeveloperFK4ccupationT

16

FK,ustomerT FKDocumentT

Imports System ,lass +rite-oXM=

S*are Dim

Su) main(' set As 1e5 System.Data.DataSet('

Dim str As String $ "-est.&ml" O=oa t*e XM= <ile in t*e ata set

set.Rea Xml("-est.&ml"' ORea t*e XM= content on t*e console

,onsole.+rite( set.IetXml' OIetting ata <rom t*e user to )e save into t*e XM= <ile

,onsole.+rite(""nter 1ame 6 "' Dim name! age! occupation As String name $ ,onsole.Rea =ine ,onsole.+rite(""nter Age 6 "' age $ ,onsole.Rea =ine ,onsole.+rite(""nter 4ccupation 6 "' occupation $ ,onsole.Rea =ine ,onsole.+rite(name Y age Y occupation' Dim v(C' As String v(.' $ <name v(C' $ age v(2'$occupation set.-a)les(.'.Ro5s.A (v'

set.+riteXml("-est.&ml"' ,onsole.+rite( set.IetXml'

16

"n

)hen you run this code, the data from the +M! file will be displayed. *lso the data you enter will be updated into the +M! file.

%ow to work with an inter&a#e in 37.NET?


The following code demonstrates the ability to work with an interface. *n interface defines a methodJs name and not itJs contents.
Imports System Imports Microso<t.Sisual%asic

#u)lic Inter<ace 1e5Int

Su) Mysu)(' :unction My:un(' As String "n Inter<ace

,lass myclass Implements MyInt O Implementing t*e a)ove e<ine implements to use t*e inter<ace inter<ace! nee to use t*e /ey5or

S*are

Su) Main('

Dim mc As 1e5 myclass(' mc.Mysu)(' "n Su)

Su) Mysu)(' Implements 1e5Int.Mysu) Msg%o&("?ello <rom I1ter<aces"' "n Su)

:unction My:un(' As String Implements 1e5Int.My:un im str as string str$"*ello matey"

16

return (str' "n "n :unction ,lass

%ow to #on+ert the &ormat o& ima'es in 37.NET?


To convert the format of an image you need to use the -'stem.(rawin" namespace. @sing this code you can convert to a variety of graphic file formats, such as :4F or 1&:. The following e%ample converts a user prompted 0itmap image file into .:if format.
:ile Image,onverter.v)

Imports System Imports System.Dra5ing

,lass ,onvertImages S*are Su) main('

Dim str As String ,onsole.+rite("#at* o< t*e Image :ile to ,onvert 6"' str $ ,onsole.Rea =ine(' OInitiali8e t*e )itmap o);ect )y supplying t*e image <ile pat* Dim )mp As 1e5 %itmap(str' )mp.Save(str G ".gi<"! System.Dra5ing.Imaging.Image:ormat.Ii<' to " Y str Y ".gi<"'

,onsole.+rite("Image Sucess<ully ,onverte "n "n Su) ,lass

What is the #on#e(t o& destr #tors in 37.NET?


(estr#ctors are used to de<allocate resources i.e. to clean up after an ob3ect is no longer available. 4inali.e is the destructor which is normally used. 4inali.e is called automatically when the .NET runtime determines that the ob3ect is no longer being used. @sing the 4inali.e method in code looks like this,

16

#u)lic ,lass :ormC In*erits System.+in o5s.:orms.:orm

Dim o);C as ne5 ,lassC ('

"n

,lass

#u)lic ,lass Dest #rotecte overri es Su) :inali8e('

E calling t*e :inali8e met*o "n Su)

"n

,lass

%ow do I 'et 3ersion In&ormation From The "ssem1)$In&o Fi)e?


To get version information at "untime in /0 .NET, use the following code,
:unction Sersion(' As String +it* N

System.Diagnostics.:ileSersionIn<o.IetSersionIn<o(System.Re<lection.Assem)ly .Iet"&ecutingAssem)ly.=ocation' Return .:ileMa;or#art Y "." Y .:ileMinor#art Y "." Y .:ile%uil #art Y "." Y .:ile#rivate#art "n "n +it* :unction

:unction Display(' As String +it* System.Diagnostics.:ileSersionIn<o.IetSersionIn<o(System.Re<lection.Assem)ly .Iet"&ecutingAssem)ly.=ocation' Return .,omments "n "n +it* :unction

16

@pon running the version information of the *ssembly file is displayed.

What is mana'ed #ode and mana'ed data?


Managed code is the code that is written to target the services of the ommon !anguage "untime # !"$. 4n order to target these services, the code must provide a minimum level of information to the runtime. *ll of the ., /isual 0asic .NET and 1. .NET code is managed by default. losely related to managed code is managed data. This is the data that is allocated and de<allocated by the ommon !anguage "untimeJs "ar$a"e collector. *s said earlier ., /isual 0asic, and 1..NET data is managed by default. 22 data can, however, be marked as unmanaged through the use of special keywords. /isual (tudio .NET 22 data is unmanaged by default #even when using the B !" switch$, but when using Managed E%tensions for 22, a class can be marked as managed by using the ^^gc keyword. *s the name suggests this means that the memory used for instances of the class is managed by the garbage collector. 4n addition the class becomes a full participating member of the .NET Framework with the benefits and restrictions that it brings. *n e%ample of a benefit is proper interoperability with classes written in other languages #for e%ample, a managed 22 class can inherit from a /isual 0asic class$. *n e%ample of a restriction is that a managed class can only inherit from one base class.

What is an "ssem1)$?
*n Assem$l' is the building block of a /0.NET application. *n *ssembly is a complied and versioned collection of code and metadata. 'nce complete forms an OatomicO functional unit. *ssemblies come in the form of a Dynamic !ink !ibrary #D!!$ file or E%ecutable an program file#E+E$. They differ as they contain information found in a type libraries. *ll the .NET programs are constructed from these *ssemblies. *ssemblies are made of two parts. Firstly, the manifest which is similar to a Table 'f ontents#T' $. This holds the name and version of the assembly. (econdly, the mod#les which are internal files of 4ntermediate !anguage #4!$ code which are ready to run. )hen programming, developers donJt directly deal with assemblies as the and the .NET framework takes care of that behind the scenes. *n assembly includes, 4nformation for each public class or type used in the assembly 4nformation on all public methods in each class. For instance, the method name and return values #if any$ 4nformation on every public parameter for each method, such as the parameterJs name and type 4nformation on public enumerations including names and values 4nformation on the assembly version #each assembly has a specific version number$ !"

16

4ntermediate !anguage code to e%ecute "e-uired resources such as pictures, assembly metadata

%ow do I &ind the (ath &rom where the a(()i#ation is r nnin'?


To learn the path of your running application, do the following. Drag a Te%tbo% and a ommand /button from the Tool0ar and use the following code.
#u)lic ,lass :ormC In*erits System.+in o5s.:orms.:orm

\Region " +in o5s :orm Designer generate

co e "

\"n

Region

#rivate Su) %uttonCN,lic/(%ySal sen er As System.4);ect! %ySal e As System."ventArgs' ?an les %uttonC.,lic/ -e&t%o&C.-e&t $ Application."&ecuta)le#at* "n "n Su)

,lass

%ow do I 'et the s#reen reso) tion o& m$ workin' area?


To get the screen resolution of your current working area use the -'stem.Windows.4orms.-creen.<rimar'-creen.Bo#nds property

%ow #an I r n a .E=E &rom a 37.NET a(()i#ation?


To run a .E+E file from a /0.NET application you need to import the -'stem.(ia"nostics namespace. The following sample shows how to run Notepad from a /0.NET application.
Imports System Imports System.Diagnostics

Dim program As 1e5 #rocess('

16

program.StartIn<o.:ile1ame $ "1otepa .e&e" program.StartIn<o.Arguments $ " " program.Start('

What is Tr$> Cat#h ?Fina))$ E9#e(tion %and)in'?


E%ceptions are "untime errors that occur when an une%pected process causes the program to abort. (uch kind of situations can be kept at bay using E%ception 9andling. 0y looking for potential problems in the code B entity life cycle, we can handle most of the errors that may encountered. *s a result the application to continue to run without being dogged by errors. /0.NET supports (tructured e%ception handling by using Tr'... atch...4inall' The following code sample demonstrates how to use Tr'+ atch+4inall' e%ception handling.
Mo ule Mo uleC Su) Main(' Dim a$.! )$C! c As Integer -ry c$) K a Ot*e a)ove line t*ro5s an e&ception System.,onsole.+rite=ine(", is " Y c' ,atc* e As "&ception System.,onsole.+rite=ine(e' Ocatc*ing t*e e&ception "n -ry System.,onsole.Rea (' "n "n Su) Mo ule

The output of the above code displays a message stating the e%ception. The reason for the e%ception is because any number divided by 5ero is infinity.

%ow do I #on+ert one ,ataT$(e to other CT$(e F n#tion?


The Type is pretty generic conversion Function.

sin' the

The e%ample below demonstrates using a value to an 4nteger value.


Mo ule Mo uleC Su) Main(' Dim As Dou)le $ C32.3C223 Dim i As Integer

Type Function to convert a Double

16

i $ ,-ype( ! i' Ot5o arguments! type 5e are converting <rom! to type System.,onsole.+rite("Integer value is" Y i' "n "n Su) Mo ule

esire

16

You might also like