Professional Documents
Culture Documents
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,
! 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.
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.
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%
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.
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.
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.
*t runtime, the .NET assembly #compiled 4! code$ is translated to native machine code and e%ecuted by the !".
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&.
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.
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.
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 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.
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
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
Main('
".1"-"! . ';
15
2 2
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
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
array
,onsole.+rite=ine(;agge [2([I('
2 2
18
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.
*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;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.
21
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.
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
inserts a record to emp table and set its empno field to EFE and its ename field to I1ohn :uttag;
updates the record whose empno field is EFE by setting its ename field to IEric :amma;
deletes the record whose empno field is EFE from the emp table
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 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.
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 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
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 $;"
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'
C0 3ersion
4leD),onnection conn $ ne5 4leD),onnection(connectionString';
37.Net 3ersion
Dim conn As 1e5 4leD),onnection(connectionString'
For 'D0
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"
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
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.
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"'
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
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
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
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
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
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
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 $
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('
ata-a)le $
s.-a)les("prog"'
40
: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.
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,
42
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.
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.
C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[2(["lines"( $ U..;
37.Net 3ersion
Dim t $ s.-a)les("Article"' t.Ro5s(2'("lines"' $ V..
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..;
37.Net 3ersion
Dim t $ s.-a)les("Article"' t.Ro5s(2'("lines"' $ V..
9ere Ida; and Ids; are the references of the Data*dapter and Data(et ob3ects respectively.
C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[2(["lines"( $ U..;
37.Net 3ersion
Dim t $ s.-a)les("Article"' t.Ro5s(2'("lines"' $ V..
46
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';
37.Net 3ersion
Dim t As Data-a)le t $ s.-a)les("Article"'
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
C0 3ersion
Data-a)le t $ s.-a)les["Article"(; t.Ro5s[3(; KK Delete DataRo5 r $ r.Delete(';
37.Net 3ersion
Dim t As Data-a)le t $ s.-a)les("Article"'
r.Delete('
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('
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';
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'
+*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('
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';
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
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
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
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
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
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";
conn.4pen('; 2
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 ,onst IetSalue,m -e&t As String $"S"=",- value :R4M My-a)le +?"R" name $ O"
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 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.
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.
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.
9ere we have used only one parameter as to delete a record you only need its primary key value.
58
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
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$.
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"';
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/
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('
"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
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(';
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
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('
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
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
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.
(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
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 $ "";
37.Net 3ersion
Dim connStr As String
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$
C0 3ersion
string connStr $ "";
KK ...
KK Rea
37.Net 3ersion
Dim connStr As String $ ""
70
O ...
O Rea
C0 3ersion
string connStr $ "";
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
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 +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
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 $ "";
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
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
(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;
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.
SLl,omman ("spNmyNstore Nproce ure"!my,onn'; my,m .,omman -ype $ ,omman -ype.Store #roce ure;
79
(ne5 SLl#arameter("9cust1ame"!
SLlDataA apter
$ my,m ;
s $ ne5 DataSet(';
80
"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
,onn.,lose('
@pon running the above code, TableE from the a OTestO database will be displayed in a Data:rid.
81
Message%o&.S*o5(icount' O isplays num)er o< recor s inserte ,atc* "n "n -ry Su)
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
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
*(&.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.
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.
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
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
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.
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
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.
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
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.
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%.
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.
93
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.
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,
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.
>. 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 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
t*is.,ontrols.A )tn"&it2'; 2
pu)lic voi {
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
"n
,lass
#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..'
(l)lIreeting'
,lass
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..'
(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
10
"n
Su)
"n
,lass
#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/
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('
10
O :orm Me.-e&t $ "My :irst +in o5s Application" Me.Si8e $ 1e5 Si8e(3..! 3..'
O =a)el
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/
#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
t*is.,ontrols.A )tn"&it2'; 2
pu)lic voi
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
"n
,lass
11
#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/
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
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/
#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$
11
! 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
! Version
my:orm.Sisi)le $ :alse;
VB.NET Version
my:orm.Sisi)le $ :alse
! 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
11
! Version
my:orm.S*o5(';
VB.NET Version
my:orm.S*o5('
! 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.
! 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...';
-*rea .Sleep(2...';
11
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/
-*rea .Sleep(2...'
-*rea .Sleep(2...'
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.
! 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.
! Version
Application."&it(';
VB.NET Version
Application."&it('
! 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"!
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<
"n
I<
! Version
MySecon :orm <rm2 $ ne5 MySecon :orm(';
12
<rm2.S*o5(';
KK <rm2.S*o5Dialog(';
VB.NET Version
Dim <rm2 As 1e5 MySecon :orm(' <rm2.S*o5(' O 5ill present t*e nonMmo al <orm
O <rm2.S*o5Dialog('
! 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
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)
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 (re+ent a
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
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.
12
12
%ow to
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
-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)
#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
@pon running the application,click on the Te%t on the !ink!abel. The website, Aahoo.com will open in a new browser.
#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@'
13
"n
Su)
To sort the items alpahbetically, select the .-orted property and set it to True.
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)
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
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.
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 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
14
Aou can also define your own regions using the .regionM.end region block with your code.
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 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 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
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 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.
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.
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.
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
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
array
,onsole.+rite=ine(;agge [2([I('
15
2 2
15
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.
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
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
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.
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
((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)
The above code adds ?? months to the date we declared in the &rogram.
15
The above code displays U9ello from DelegatesV 3ust like a normal program but it uses (ele"ates to do it.
%ow do I
*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)
15
S*are
:unction IetI#A
+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.
Imports System
,lass SystemIn<o
S*are
Su) main('
15
,onsole.+rite=ine(",lass #at*"'
16
FK,ustomerT FKDocumentT
S*are Dim
Dim str As String $ "-est.&ml" O=oa t*e XM= <ile in t*e ata set
,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'
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.
,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('
16
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<"'
16
"n
,lass
"n
,lass
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
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
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
16
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.
sin' the
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