Tuesday, June 3, 2008

.NET General

.NET GENERAL

What is Microsoft.NET platform?
Microsoft .NET is a software development platform based on virtual machine based architecture. Dot net is designed from the scratch to support programming language independent application development. The entire .NET programs are independent of any particular operating system and physical hardware machine. They can run on any physical machine, running any operating system that contains the implementation of .NET Framework. The core component of the .NET framework is its Common Language Runtime (CLR), which provides the abstraction of execution environment (Physical machine and Operating System) and manages the overall execution of any of the .NET based program.




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



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

What is the VB.NET and C# language comparisons?
VB.NET and C# both are integral part of the .NET framework. Both of the languages have a lot of similarities in language constructs and language design with minor differences in the syntax. C# is more like C++ and Java in its syntax while VB.NET lends its syntax from VB6 a great deal; although VB.NET can not be seen as the successor of Visual Basic at the level of overall language design and the vision of its creators.

The general conception is that most of the VB6 developers will upgrade to VB.NET while developers coming from Java or C++ to .NET are likely to go for C#. Since web developers for Windows using ASP are familiar with VB and VB Scripts, therefore, most of the web development with ASP.NET at the start is likely to be dominated by VB.NET; but after sometime C# will be able to attract at least half of these developers. Keeping technical side away, C++ and thus C# developers are generally paid more than those of VB developers. So, this might also be the factor for making C# the language of choice on .NET framework.

What is the difference between Console, Windows, Web applications and Web services?
Console applications are light weight programs run inside the command prompt (DOS) window. They are commonly used for test applications.

Windows Applications are form based standard Windows desktop applications for common day to day tasks. Microsoft word is an example of a Windows application.

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

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

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

In Microsoft.Net, the code written in any programming language is compiled to the same Intermediate Language (Microsoft Intermediate Language - MSIL or Common Intermediate Language – CIL) and to same component standard (assembly). Hence, it is possible for developers to employ the language interoperability by using and extending the solution implemented by other developers which might be using different programming language provided developers at both end are using.Net compliant programming languages.

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

There are two kind of assemblies in .NET; private and shared. Private assemblies are simple and copied with each calling assemblies in the calling assemblies folder. Shared assemblies (also called strong named assemblies) are copied to a single location (usually the Global assembly cache). For all calling assemblies within the same application, the same copy of the shared assembly is used from its original location. Hence, shared 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 mix with each other.

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

What are the differences between a .NET Assembly, a Windows DLL and a COM Component?
A Windows DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries.

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

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

What are the differences between a .NET Assembly, a Windows DLL and a COM Component?
A Windows DLL contains library code to be used by any program running on Windows. A DLL may contain either structured or object oriented libraries.

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

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

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

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

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

What is meant by un-safe code?
By un-safe code, it means that the managed program can access the memory address using pointers. There are two points to remember here;

Un-safe code is different from un-managed as it is still managed by the CLR
You still can not perform pointer arithmetic in un-safe code.

What is the difference between Unmanaged and Unsafe code?
Un-managed code runs outside the Common Language Runtime (CLR) control while the unsafe code runs inside the CLR’s control. Both un-safe and un-managed codes may use pointers and direct memory addresses.

What about the MS.NET standardization?
Microsoft has secured certification for both C# and CLI from ECMA and ISO/IEC as Industry standards. This is a very important step for Microsoft and .Net platform because this enhances the credibility of the newer .Net platform and allures a larger portion of technology industry into adopting .Net as their development platform. Several companies and government organizations only utilize ISO certified technologies; for example, in Australia anything ISO certified is also considered Australian standard according to the rules of the Australian government. Several academic institutions will now be interested in teaching standard C#. Another major outcome of having an open industry standard specification is .Net platform could be getting ported to other platforms like Linux and UNIX; best example is the Mono Project by Ximian- it is an open source implementation of .Net platform for UNIX and Linux based on ECMA approved Public Domain Specification of C# and CLI.

Microsoft submitted the specifications to ECMA, which in turn fast-tracked them through ISO. In doing so, Microsoft released all intellectual property in the core C#/CLI platform to the public domain. No one needs a license to implement C#/CLI. This will also help everybody in better understanding the implementations of C# and CLI which are at the core of .Net platform. However, the whole of .Net platform is not a Public domain standard- Microsoft still owns complete Intellectual property rights to several class libraries and API within the .Net platform.

What about the implementation of .NET other than Microsoft.Net on Windows Operating System?
Microsoft has implemented .NET framework for all of its operating system suits (excluding MS Windows 95 and earlier) on all supported hardware platforms. For handheld and small devices, Microsoft has released a compact framework of .NET (http://msdn.microsoft.com/vstudio/device/compact.aspx ). But, there are various other implementations being developed on platforms other than Microsoft Windows. You can read the discussion on the portability of .NET at (See http://zdnet.com.com/2100-1107-960049.html)

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

Microsoft has released almost all the source code of their .NET framework for FreeBSD and Mac OS under the title of Shared Source Common Language Infrastructure (SSCLI). Check out the SSCLI 1.0 release - which already builds on WindowsXP, FreeBSD, and Mac OS X 10.2, released under Microsoft's Shared Source Initiative. http://msdn.microsoft.com/net/sscli/ http://www.microsoft.com/resources/sharedsource/default.mspx

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



In the presence of dot net framework, a program is not compiled to the native machine executable code; rather it gets compiled to an intermediate language code called Microsoft Intermediate Language (MSIL) or Common Intermediate Language (CIL). The Dot Net Common Language Runtime (CLR) then converts this intermediate code at runtime to the machine executable code. The optimization is carried out at runtime. A program also does not call the operating system APIs directly; rather it delegates this task to the CLR which performs the desired operations on behalf of the program and returns the results of the operations back to the program. The CLR also performs the memory management, garbage collection, security and thread management on behalf of the program. Dot NET framework is shipped with the supporting object oriented framework of common code libraries, called the .NET Framework Class Library (FCL), to facilitate the common operations. Hence the .Net manages the overall execution of an application. This is the reason why the code running on .Net framework is sometimes called the managed code. The complete process is depicted in the following Figure. Note that only the CLR (and thus the .Net framework and not the user application) is interacting and coupled with the platform and operating system.





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

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



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



Just In Time Compilers (JITers)
When our IL compiled code needs to be executed, CLR invokes JIT compilers which compile the IL code to native executable code (.exe or .dll) for the specific machine and OS. JITers in many ways are different from traditional compilers as they, as their name suggests, compile the IL to native code only when desired e.g., when a function is called, IL of function’s body is converted to native code; just in time of need. So, the part of code that is not used by particular run is not converted to native code. If some IL code is converted to native code then the next time when its needed to be used, the CLR uses the same copy without re-compiling. So, if a program runs for sometime, then it won’t have any just in time performance penalty. As JITers are aware of processor and OS exactly at runtime, they can optimize the code extremely efficiently resulting in very robust applications. Also, since JITer knows the exact current state of executable code, they can also optimize the code by in-lining small function calls (like replacing body of small function when its called in a loop, saving the function call time). Although, Microsoft stated that C# and .Net are not competing with languages like C++ in efficiency, speed of execution, JITers can make your code even faster than C++ code in some cases when program is run over extended period of time (like web-servers).

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

Common Language Specification (CLS)
Earlier we used the term ‘.NET Compliant Language’ and stated that all the .NET compliant languages can make use of CLR and FCL. But what makes a language ‘.NET compliant language’? The answer is Common Language Specification (CLS). Microsoft has released a small set of specification that each language should meet to qualify as a .NET Compliant Language. As IL is a very rich language, it is not necessary for a language to implement all the IL functionality, rather it meets the small subset of it, CLS, to qualify as a .NET compliant language, which is the reason why so many languages (procedural and OO) are now running under .Net umbrella. CLS basically addresses to language design issues and lays certain standards like there should be no global function declaration, no pointers, no multiple inheritance and things like that. The important point to note here is that if you keep your code within CLS boundary, your code is guaranteed to be usable in any other .Net language.

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

Garbage Collector (GC)
CLR also contains Garbage Collector (GC) which runs in a low-priority thread and checks for un-referenced dynamically allocated memory space. If it finds some data that is no more referenced by any variable/reference, it re-claims it and returns the occupied memory back to the Operating System; so that it can be used by other programs as necessary. The presence of standard Garbage Collector frees the programmer from keeping track of dangling data.


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



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

How is MS.NET compared with Java based platforms (J2EE)?
At root level architecture and components, MS.NET and J2EE platforms are very similar. Both are virtual machine based architecture having CLR and Java Virtual Machine (JVM) as the underlying virtual machine for the management and execution of programs. Both provide memory, security and thread management on behalf of the program and both try to decouple the applications with the execution environment (OS and physical machine). Both, basically, target the Web based applications and especially the XML based web services. Both provide managed access to memory and no direct access to memory is allowed to their managed applications.
However, there are few contrasts in the architecture and design of the two virtual machines. Microsoft .NET framework’s architecture is more coupled to the Microsoft Windows Operating System which makes it difficult to implement it on various operating systems and physical machines. Java, on the other hand, is available on almost all major platforms. At the darker side, J2EE architecture and JVM is more coupled to the Java programming language while Microsoft.NET has been designed from the scratch to support language independence and language integration. Microsoft.NET covers the component development and integration in much more detail than Java. The versioning policy of .NET is simply the best implemented versioning solution in the software development history. Java has got the support of industry giants like Sun, IBM, Apache and Oracle while the Microsoft.NET is supported by giants like Microsoft, Intel, and HP.

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

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

How true it is that .NET and Java programs are quite in-efficient when compared to C++?
The startup of managed .NET and Java programs is definitely slower than the traditional C++ programs as it involves the hosting of CLR into managed application process in .NET and starting the JVM in a new process in case of Java. The execution also is a bit slower during the initial period of program execution as the intermediate code is translated to the machine code on the fly at runtime. But as the program runs various parts repeatedly, the execution gets pace too. Since, the CLR and JVM optimizes the code more efficiently than the static C++ compilers, the execution speed of the program may actually be faster after sometime of the program startup when most of the code is translated. Hence, in the longer run, the .Net and Java based programs should not be in-efficient when compared to C++. We used ‘should’ here as the actual performance depends on the particular implementation and implementation strategy.

What are XML Doc comments (comments start with three slashes ///)?
The XML Doc comments are special kind of comments that can be recognized by Document utility to automatically generate the documentation of your methods, types and regions.

Using COM components in .NET and How to add a reference to a COM component?
The .NET does not encourage the use of COM component directly inside the managed application! Although, the .NET framework contains utilities that enable COM components to be used inside the .Net applications seamlessly. How it is done? The .NET utilities like TlbImp generates the wrapper .NET assembly for the COM component which provides the same calling interface to the client as exposed by the COM component. Inside the wrapper methods, it calls the actual methods of the COM component and returns the result back to the caller. The generated wrapper .NET assembly is called the ‘Runtime Callable Wrapper’ or RCW.
To use a COM component in your Visual Studio.NET project, you need to add a reference of the COM component in the Reference node of the project node of the solution inside the solution explorer window. The great thing about Visual Studio.Net is that it allows you to add a reference to the COM component in exactly the similar way as you add the reference to the .NET assembly. The Visual Studio.NET automatically creates the runtime callable wrapper assembly for the referenced COM component.
To add a reference to a COM component, right click the ‘Reference’ node under the project node inside the solution explorer and select the ‘Add Reference…’ option. It will show you a user interface screen where you browse for the target COM component. When you have selected the component, press the ‘Select’ button and then press OK. This will add a new reference node in the Reference sub tree of the project. By selecting the added reference node, you can edit its properties from the properties window.
Note: The process of importing a COM component into .NET is called ‘COM interoperability with .NET’

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

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

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

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

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

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

What is MSIL / IL? What is JIT (Just In Time)?
When compiling the source code to managed code, the compiler translates the source into Microsoft intermediate language (MSIL). This is a CPU-independent set of instructions that can efficiently be converted to native code. Microsoft intermediate language (MSIL) is a translation used as the output of a number of compilers. It is the input to a just-in-time (JIT) compiler. The Common Language Runtime includes a JIT compiler for the conversion of MSIL to native code.

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

What is Code Access Security (CAS)? How does CAS work? Who defines the CAS code groups?
Code Access Security (CAS) is part of the .NET security model. CAS determines whether or not a piece of code is allowed to run and also what resources to use. For example, CAS will prevent malicious code from entering your system and causing havoc.

The CAS 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. An example: Using the default security policy, a control downloaded from a web site belongs to the 'Zone - Internet' code group which complies to the permissions defined by the 'Internet' named permission set.

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

What is serialization in .NET and what are the ways to control serialization?
Serialization is the process of converting an object into a stream of bytes. On the other hand Deserialization is the process of creating an object from a stream of bytes. Serialization/Deserialization is used to transport or to persist objects. Serialization can be defined as the process of storing the state of an object to a storage medium. During this process, the public and private fields of the object and the name of the class, including the assembly are converted to a stream of bytes. Which is then written to a data stream. Upon the object's subsequent deserialized, an exact clone of the original object is created.

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

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

As XML is an open standard, it is an attractive choice for sharing data across the Web. SOAP is also an open standard, which makes it an attractive choice too. There are two separate mechanisms provided by the .NET class library - XmlSerializer and SoapFormatter/BinaryFormatter. Microsoft uses XmlSerializer for Web Services, and uses SoapFormatter/BinaryFormatter for remoting. Both are available for use in your own code.

What is Active Directory? What namespace should I use to use Active Directories?
Active Directory Service Interfaces (ADSI) is a programmatic interface for the Microsoft Windows Active Directory. It enables your applications to interact with different directories on a network using a single interface.

Visual Studio .NET and the .NET Framework make it easy to add ADSI functionality with the DirectoryEntry and DirectorySearcher components. Using ADSI you can create applications that perform common administrative tasks, such as backing up databases, accessing printers and managing user accounts. ADSI allows:

1) Log on once to work with diverse directories. The DirectoryEntry component class provides username and password properties that can be entered at Runtime and are passed to the Active Directory object you are bound to.

2) Use of an Application-Programming Interface (API) to perform tasks on multiple directory systems. This includes multi protocol support. The DirectoryServices namespace provides the classes to perform most administrative functions such as creating users.

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

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

5) Integrate directory information with databases such as  ?SQL Server. The DirectoryEntry path may be used as an ADO.NET connection string.

Name space to be imported when working with Active Directories:
System.DirectoryServices

Can I use the Win32 API from a .NET Framework program?
Using platform invoke it's possible. .NET Framework programs can access native code libraries by means of static DLL entry points.
Here is an example of C# calling the Win32 MessageBox function:

using System;
using System.Runtime.InteropServices;

class MainApp
{
[DllImport("user32.dll", EntryPoint="MessageBox")]
public static extern int MessageBox(int hWnd, String
strMessage, String strCaption, uint uiType);
public static void Main()
{
MessageBox(0, "This is PInvoke in operation!",
".NET", 0 );
}
}
How do I send an attachment in an email?
The following code shows how to add an attachment to an email.

Using System.IO;
Using System.Web.Mail;

MailAttachment ma=new MailAttachment("c:\sample.txt");
MailMessage mm=new MailMessage();
mm.To ="xyz@programmersheaven.com";
mm.From="abc@yahoo.com";
mm.Body ="Attachment";
mm.Subject="Check out the attached text file";

mm.Attachments.Add(ma);

SmtpMail.SmtpServer="mail.programmersheaven.com";
SmtpMail.Send(mm);

ADO .NET

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



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

What does it mean by disconnected data access architecture of ADO.Net?
ADO.Net introduces the concept of disconnected data architecture. In traditional data access components, you make a connection to the database system and then interact with it through SQL queries using the connection. The application stays connected to the DB system even when it is not using DB services. This commonly wastes the valuable and expensive database resource as most of the time applications only query and view the persistent data. ADO.Net solves this problem by managing a local buffer of persistent data called data set. Your application automatically connects to the database server when it needs to pass some query and then disconnects immediately after getting the result back and storing it in dataset. This design of ADO.Net is called disconnected data architecture and is very much similar to the connection less services of http over the internet. It should be noted that ADO.Net also provides the connection oriented traditional data access services.

Traditional Data Access Architecture



ADO.Net Disconnected Data Access Architecture



Another important aspect of the disconnected architecture is that it maintains the local repository of data in the dataset object. The dataset object stores the tables, their relationship and different constraints. The user performs operations like update, insert, delete to this dataset locally and finally the changed dataset is stored in actual database as a batch when needed. This greatly reduces the network traffic and results in the better performance.

What does it mean by connected data access architecture of ADO.Net?
In the connected environment, it is your responsibility to open and close the database connection. You first establish the database connection, perform the interested operations to the database and when you are done, close the database connection. All the changes are done directly to the database and no local (memory) buffer is maintained.

What's the difference between accessing data with dataset or data reader?
The dataset is generally used when you like to employ the disconnected architecture of the ADO.Net. It reads the data into the local memory buffer and perform the data operations (update, insert, delete) locally to this buffer.

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

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

What are the performance considerations when using dataset?
Since no memory buffer is maintained by the data reader, it takes up fewer resources and 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. All the updates are done in the local memory and are updated to the database in a batch. Since database connection remains open for the short time, the database management system does not get flooded with the incoming requests.
However, since the dataset stores the records in the local buffer in the hierarchical form, it does take up more resources and may affect the overall performance of the application.

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

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

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

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

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

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



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

Class & Description
DataSet
The DataSet is a local buffer of tables or a collection of disconnected record sets

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

DataRow
Represents a single record or row in DataTable

DataColumn
Represents a column or field of DataTable

DataRelation
Represents the relationship between different tables in a data set.

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

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

The core objects that make up a data provider are:

Class & Description

Connection
Represents a connection to the database system

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

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

DataReader
A stream that reads data from the database in connected design

Parameter
Represents a parameter to a stored procedure


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

What is a data adapter?
A data adapter is the component that exists between the local repository (dataset) and the physical database. It contains the four different commands (SELECT, INSERT, UPDATE and DELETE). It uses these commands to fetch the data from the DB and fill into the dataset and to perform updates done in the dataset to the physical database. It is the data adapter that is responsible for opening and closing the database connection and communicates with the dataset.

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

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

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

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

SELECT empno, ename from emp
selects the fields empno and ename of all records from the table name ‘emp’

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

SELECT * from article, author where article.authorId = author.authorId
selects all those records from the table name ‘article’ and ‘author’ that have same value of the field authorId

SQL INSERT Statement
This query is used to insert a record to a database table.

INSERT INTO emp(empno, ename) values(101, ‘John Guttag’)
inserts a record to emp table and set its empno field to 101 and its ename field to ‘John Guttag’

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

UPDATE emp SET ename =‘Eric Gamma’ WHERE empno = 101
updates the record whose empno field is 101 by setting its ename field to ‘Eric Gamma’

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

DELETE FROM emp WHERE empno = 101
deletes the record whose empno field is 101 from the emp table

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

How do different components of ADO.Net interact with each other in disconnected architecture?
The Data Adapter contains in it the Command and Connection object. It uses the connection object to connect to the database, execute the containing command, fetch the result and update the DataSet.



How do different components of ADO.Net interact with each other in connected architecture?
Here, the Command object contains the Connection object. The Command object uses the containing connection (that must be opened) to execute the SQL query and if the SQL statement is SELECT, returns the DataReader object. The data reader object is the stream to the database which reads the resulting records from the DB and passes them to the application



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

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

Class & Description

Connection
Represents a connection to the database system

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

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

DataReader
A stream that reads data from the database in connected design

Parameter
Represents a parameter to a stored procedure


What are the standard dot net framework data providers that are shipped with the Dot Net Framework 1.1?
The Dot Net Framework 1.1 is shipped with four different data providers:
Dot Net Framework data provider for Microsoft SQL Server DBMS
Dot Net Framework data provider for Oracle DBMS (available only in Framework 1.1)
Dot Net Framework data provider for OLEDB supporting DBMS
Dot Net Framework data provider for ODBC supporting data sources (available only in Framework 1.1)

Why should one use a specialized data provider when the data can be accessed with general data providers?
The specialized data providers (e.g., SQL Server and Oracle) are built specially for a particular kind of DBMS and works much more efficiently than the general data providers (e.g., OLEDB and ODBC). In practice, the specialized data providers are many times efficient than the general data providers.

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

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

What is the Dot Net Framework data provider for OLEDB?
The dot net framework data provider for OLEDB provides connectivity with the OLEDB supported database management systems. It is the recommended middle tier for the SQL Server 6.5 or earlier and Microsoft Access Database. It is a general data provider. You can also use it to connect with the SQL Server or Oracle Database Management Systems. The classes for this provider are present in the System.Data.OleDBClient namespace.

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

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

Data access using ADO.Net involves the following steps:

Defining the connection string for the database server
Defining the connection (SqlConnection, OleDbConnection, etc) to the database using the connection string
Defining the command (SqlCommand, OleDbCommand, etc) or command string that contains the query
Defining the data adapter (SqlDataAdapter, OleDbDataAdapter, etc) using the command string and the connection object
Creating a new DataSet object
If the command is SELECT, filling the dataset object with the result of the query through the data adapter
Reading the records from the DataTables in the datasets using the DataRow and DataColumn objects
If the command is UPDATE, INSERT or DELETE, then updating the dataset through the data adapter
Accepting to save the changes in the dataset to the database

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

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

Data Provider & Namespace

MS SQL Server
System.Data.SqlClient

Oracle Database
System.Data.OracleClient

OLE DB Databases
System.Data.OleDBClient

ODBC Data Sources
System.Data.ODBCClient


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

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

C# Version
// for Sql Server
string connectionString = "server=P-III; database=programmersheaven;" +_
"uid=sa; pwd=;";
VB.Net Version
' for Sql Server
Dim connectionString As String = "server=P-III; database=programmersheaven;" + _ "uid=sa; pwd=;"
First of all we have defined the instance name of the server, which is P-III on my system. Next we defined the name of the database, user id (uid) and password (pwd). Since my SQL server doesn't have a password for the System Administrator (sa) user, I have left it blank in the connection string. (Yes I know this is very dangerous and is really a bad practice - never, ever use a blank password on a system that is accessible over a network)

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

C# Version
string connectionString = "Data Source=Oracle8i;User Id=username;" +
"Password=pwd; Integrated Security=no;";
VB.Net Version
Dim connectionString As String = "Data Source=Oracle8i;User Id=username;" + _
"Password=pwd; Integrated Security=no;"

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

C# Version
// for MS Access
string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" +
"data source = c:\\programmersheaven.mdb";
VB.Net Version
' for MS Access
Dim connectionString As String = "provider=Microsoft.Jet.OLEDB.4.0;" + _
"data source = c:\programmersheaven.mdb"
First we have defined the provider of the access database. Then we have defined the data source which is the address of the target database.

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

C# Version
string connectionString = "Driver={SQL Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;";
VB.Net Version
Dim connectionString As String = "Driver={SQL Server};Server=FARAZ;Database=pubs;Uid=sa;Pwd=;"


How do I find the connection string for the database server?
Usually the connection string options are provided in the documentation, you can also find the connection strings on the internet. A good website for the connections strings is http://www.connectionstrings.com

How do I define the connection to database?
A connection is defined using the connection string. The Connection object is used by the data adapter or data reader to connect to and disconnect from the database.

For SQL Server used with SQL Server data provider, the connection is created like this:

C# Version
SqlConnection conn = new SqlConnection(connectionString);
VB.Net Version
Dim conn As New SqlConnection(connectionString)

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

C# Version
OracleConnection conn = new OracleConnection(connectionString);
VB.Net Version
Dim conn As New OracleConnection(connectionString)

For OLE DB provider, the connection is created like this:

C# Version
OleDbConnection conn = new OleDbConnection(connectionString);
VB.Net Version
Dim conn As New OleDbConnection(connectionString)

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

C# Version
OdbcConnection conn = new OdbcConnection(connectionString);
VB.Net Version
Dim conn As New OdbcConnection(connectionString)

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

How do I create a command and supply the SQL query to ADO.Net? (Command object and command string)
First of all, you create a command object (SqlCommand, OracleCommand, OleDbCommand, OdbcCommand) using the connection object (SqlConnection, OracleConnection, OleDbConnection, OdbcConnection) and set its CommandText property to the SQL query to execute.

C# Version
OdbcCommand cmd = conn.CreateCommand();
cmd.CommandText = "select * from authors";
VB.Net Version
Dim cmd As OdbcCommand
cmd = conn.CreateCommand()
cmd.CommandText = "select * from authors"


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

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

1.by supplying the command string (SQL Select command) and connection string
2.by supplying the command string (SQL Select command) and a connection object
3.by supplying the command object (SqlCommand, OracleCommand, OleDbCommand, OdbcCommand)

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

C# Version
// for Sql Server
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, conn);
VB.Net Version
Dim da As New SqlDataAdapter(commandString, conn)

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

For Access, the data adapter is created like

C# Version
// for MS Access
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(commandString, connectionString);
VB.Net Version
Dim da As New OleDbDataAdapter(commandString, connectionString)

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

How do I get the result of my command and fill it to the dataset?
DataSet is a local and offline container of the data. The DataSet object is created simply like

C# Version
DataSet ds = new DataSet();
VB.Net Version
Dim ds As New DataSet()

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

C# Version
dataAdapter.Fill(ds, "prog");
VB.Net Version
da.Fill(ds, "prog")

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

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

C# Version
DataTable dataTable = ds.Tables["prog"];
VB.Net Version
Dim dataTable As DataTable
dt = ds.Tables("prog")

The indexer we have used takes the name of the table in dataset and returns the corresponding DataTable object. Now we can use the tables Rows and Columns collection to access the data in the table.

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

C# Version
DataTable dt = ds.Tables["student"];
string stId = dt.Rows[0]["StudentID"].ToString();
string stName = dt.Rows[0]["StudentName"].ToString();
string stDateOfBirth = dt.Rows[0][2].ToString();
VB.Net Version
Dim dt As DataTable
dt = ds.Tables("student")
Dim stId As String
stId = dt.Rows(0)("StudentID").ToString()
Dim stName As String
stName = dt.Rows(0)("StudentName").ToString()
Dim stDateOfBirth As String
stDateOfBirth = dt.Rows(0)(2).ToString()

Here we have retrieved various fields of the first record of the student table read in the dataset. As you can see, we can either specify the column name in string format or we can specify the column number in integer format. Also note that the field value is returned in the form of Object, so we need to convert it to the string before using it. Similarly, you need to cast variables of other data types before using them.

C# Version
int stAge = int.Parse(dt.Rows(0)("Age").ToString());
VB.Net Version
Dim stage As Integer
stAge = Integer.Parse(dt.Rows(0)("Age").ToString())


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

C# Version
dataAdapter.Update(ds, "student");
ds.AcceptChanges();
VB.Net Version
da.Update(ds, "student")
ds.AcceptChanges()

Here ‘da’ is the reference to the data adapter object, ‘ds’ is the reference to the dataset, and ‘student’ is the name of table we want to update.

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

Field Name, Type & Description
artId (Primary Key)
Integer
The unique identity of article

Title
String
The title of the article

Topic
String
Topic or Series name of the article like ‘Multithreading in Java’ or ‘C# School’

authorId (Foreign Key)
Integer
Unique identity of author

Lines
Integer
No. of lines in the article

dateOfPublishing
Date
Date of publishing of the article

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

Field Name, Type & Description

authorId (Primary Key)
Integer
The unique identity of author

name
String
Name of author


How do I make my first “Hello, ADO.Net” Application in C#?
Let’s now create a demonstration application for accessing data. First create a windows form application and make the layout like the following snapshot



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

We have also defined three variables in the Form class as

public class ADOForm : System.Windows.Forms.Form
{
DataTable dataTable;
int currRec=0;
int totalRec=0;

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

Loading table
For LoadTable button, we have written the following event handler
private void btnLoadTable_Click(object sender, System.EventArgs e)
{
// for Sql Server
string connectionString = "server=P-III; database=programmersheaven;" +
"uid=sa; pwd=;";
// for MS Access
/*string connectionString = "provider=Microsoft.Jet.OLEDB.4.0;" +
"data source = c:\\programmersheaven.mdb";*/
// for Sql Server
SqlConnection conn = new SqlConnection(connectionString);
// for MS Access
//OleDbConnection conn = new OleDbConnection(connectionString);
string commandString = "SELECT " +
"artId, title, topic, " +
"article.authorId as authorId, " +
"name, lines, dateOfPublishing " +
"FROM " +
"article, author " +
"WHERE " +
"author.authorId = article.authorId";
// for Sql Server
SqlDataAdapter dataAdapter = new SqlDataAdapter(commandString, conn);
// for MS Access
//OleDbDataAdapter dataAdapter = new OleDbDataAdapter(commandString, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "prog");
dataTable = ds.Tables["prog"];
currRec = 0;
totalRec = dataTable.Rows.Count;
FillControls();
btnNext.Enabled = true;
btnPrevious.Enabled = true;
}
In the start, we have created the connection, data adapter and filled the dataset object which we have discussed earlier. It should be noted that we have commented the code for OleDb provider (MS-Access) and are using the SQL Server specific code. If you like to use Access database, you can simply comment the SQL server code and de-comment the Access code.

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

dataTable = ds.Tables["prog"];
currRec = 0;
totalRec = dataTable.Rows.Count;

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

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

private void FillControls()
{
txtArticleId.Text = dataTable.Rows[currRec]["artId"].ToString();
txtArticleTitle.Text = dataTable.Rows[currRec]["title"].ToString();
txtArticleTopic.Text = dataTable.Rows[currRec]["topic"].ToString();
txtAuthorId.Text = dataTable.Rows[currRec]["authorId"].ToString();
txtAuthorName.Text = dataTable.Rows[currRec]["name"].ToString();
txtNumOfLines.Text = dataTable.Rows[currRec]["lines"].ToString();
txtDateOfPublishing.Text = dataTable.Rows[currRec]["dateOfPublishing"].ToString();
}

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

DataRow row = dataTable.Rows[currRec]; // getting current row
object data = row["artId"]; // getting data in the artId field
string strData = data.ToString(); // converting to string
txtArticleId.Text = strData; // display in the text box

which is equivalent to

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

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



How do I make my first “Hello, ADO.Net” Application in VB.Net?
Let's now create a demonstration application for accessing data. First create a windows form application and make the layout shown the following snapshot.



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

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

Private dataTable As dataTable
Private currRec As Integer = 0
Private totalRec As Integer = 0 ...

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


Private Sub btnLoadTable_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnLoadTable.Click
' for Sql Server
Dim connectionString As String = "server=P-III; database=programmersheaven;" + _ "uid=sa; pwd=;"

' for MS Access
'Dim connectionString As String = "provider=Microsoft.Jet.OLEDB.4.0;" +
' "data source = c:\\programmersheaven.mdb"

' for Sql Server
Dim conn As New SqlConnection(connectionString)

' for MS Access
'Dim conn As New OleDbConnection(connectionString)

Dim commandString As String = "SELECT " + _
"artId, title, topic, " + _
"article.authorId as authorId, " + _
"name, lines, dateOfPublishing " + _
"FROM " + _
"article, author " + _
"WHERE " + _
"author.authorId = article.authorId"

' for Sql Server
Dim dataAdapter As New SqlDataAdapter(commandString, conn)
' for MS Access
'Dim dataAdapter As New OleDbDataAdapter(commandString, conn)
Dim ds As New DataSet()
dataAdapter.Fill(ds, "prog")
dataTable = ds.Tables("prog")
currRec = 0
totalRec = dataTable.Rows.Count
FillControls()
btnNext.Enabled = True
btnPrevious.Enabled = True
End Sub

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

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

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

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

Private Sub FillControls()
txtArticleId.Text=dataTable.Rows(currRec)("artId").ToString()
txtArticleTitle.Text=dataTable.Rows(currRec)("title").ToString()
txtArticleTopic.Text=dataTable.Rows(currRec)("topic").ToString()
txtAuthorId.Text=dataTable.Rows(currRec)("authorId").ToString()
txtAuthorName.Text=dataTable.Rows(currRec)("name").ToString()
txtNumOfLines.Text=dataTable.Rows(currRec)("lines").ToString()
txtDateOfPublishing.Text=dataTable.Rows(currRec)("dateOfPublishing").ToString()
End Sub

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

Dim row As DataRow = dataTable.Rows(currRec) ' getting current row
Dim data As Object = row("artId") ' getting data in the artId field
Dim strData As String = data.ToString() ' converting to string
txtArticleId.Text = strData ' display in the text box
which is equivalent to

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

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



How do I navigate through the records?
Navigating through the records is again very easy. For the Next button, we have written the following simple event handler

Private Sub btnNext_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnNext.Click
currRec += 1
If currRec >= totalRec Then
currRec = 0
End If
FillControls()
End Sub

Here we first increment the integer variable currRec and check if it has crossed the last record (using the totalRec variable) in the table. If it has, then we move the current record to the first record. We then call the FillControls() method to display the current record on the form. Similarly the event handler for the Previous button looks like this:

Private Sub btnPrevious_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnPrevious.Click
currRec -= 1
If currRec < totalRec Then
currRec = totalRec - 1
End If
FillControls()
End Sub

Here we decrement the currRec variable and check if has crossed the first record and if it has then we move it to the last record. Once again, we call the FillControls() method to display the current record. Now you can navigate through the records using the Next and Previous buttons.

How do I update tables in the dataset?
Updating a table in ADO.Net is very interesting and easy. You need to follow these steps to update, insert and delete records:

The Data Adapter class (SqlDataAdapter) has properties for each of the insert, update and delete commands. First of all we need to prepare the command (SqlCommand) and add it to the data adapter object. The commands are simple SQL commands with parameters. You may use the Visual Studio .Net designer to easily create these commands.

Secondly we need to add parameters to these commands. The parameters are simply the names of the data table fields involved in the particular command. Visual Studio .Net also build it for you in its Data Adapter configuration wizard.

The two steps described above are done only once in the application. For each insert, update and delete; we insert, update and delete the corresponding data row (DataRow) of the data table (DataTable) object.

After any update we call the Update() 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 AcceptChanges() method of the dataset object to store the changes in the dataset to the physical database.

How do I use a CommandBuilder object to prepare the update commands in my dataset?
Each data provider has a command builder object that prepares the update, insert and delete commands for you. You can use these (SqlCommandBuilder, OracleCommandBuilder, OleDbCommandBuilder, OdbcCommandBuilder) objects to generate commands automatically using the Select command you specified when defining the data adapter. In the following code, we have created and set the update, insert and delete commands using the SqlCommandBuilder object

C# Version
SqlConnection conn = new SqlConnection("server=FARAZ; database=programmersheaven; uid=sa; pwd=;");
string cmdStr = "select * from article";
SqlDataAdapter da = new SqlDataAdapter(cmdStr, conn);

DataSet ds = new DataSet();
da.Fill(ds, "Article");

SqlCommandBuilder cmdBuilder = new SqlCommandBuilder(da);
da.InsertCommand = cmdBuilder.GetInsertCommand();
da.UpdateCommand = cmdBuilder.GetUpdateCommand();
da.DeleteCommand = cmdBuilder.GetDeleteCommand();
VB.Net Version
Dim conn As New SqlConnection("server=FARAZ; database=programmersheaven; uid=sa; pwd=;")

Dim cmdStr As String
cmdStr = "select * from article"
Dim da As New SqlDataAdapter(cmdStr, conn)
Dim ds As New DataSet
da.Fill(ds, "Article")

Dim cmdBuilder As New SqlCommandBuilder(da)
da.InsertCommand = cmdBuilder.GetInsertCommand()
da.UpdateCommand = cmdBuilder.GetUpdateCommand()
da.DeleteCommand = cmdBuilder.GetDeleteCommand()

What are the general steps for updating the records in dataset?
The Data Adapter class (SqlDataAdapter) has properties for each of the insert, update and delete commands. First of all we need to prepare the command (SqlCommand) and add it to the data adapter object.

Secondly 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 delete; we insert, update and delete the corresponding data row (DataRow) of the data table (DataTable) object.

After any update we call the Update() 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 AcceptChanges() method of the dataset object to store the changes in the dataset to the physical database.

How do I update the dataset with the updates in records?
You can update the dataset by calling the Update() method of the data adapter.

C# Version
DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;
da.Update(ds, "Article");
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
da.Update(ds, "Article")

Here ‘da’ and ‘ds’ are the references of the DataAdapter and DataSet objects respectively.

How do I update the physical database with the changes in the dataset?
You can update the physical database by calling the AcceptChanges() method of the data set.

C# Version
DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
da.Update(ds, "Article")
ds.AcceptChanges()

Here ‘da’ and ‘ds’ are the references of the DataAdapter and DataSet objects respectively.

How do I update a record in the table using ADO.Net dataset?
Once you have the UpdateCommand prepared in the data adapter, you can update individual records simply by updating the field values in the data table’s rows. The above code demonstrate how we can update the ‘lines’ field of the third record of the table ‘Article’

C# Version
DataTable dt = ds.Tables["Article"];
dt.Rows[2]["lines"] = 600;
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt = ds.Tables("Article")
dt.Rows(2)("lines") = 700
da.Update(ds, "Article")
ds.AcceptChanges()

How do I insert a record in the table using ADO.Net dataset?
To insert a record in the data table, you create an object of the DataRow using the DataTable object. Then you set the appropriate field values and finally add it to the DataTable’s Rows collection.

C# Version
DataTable dt = ds.Tables["Article"];

// Insert
DataRow dr = dt.NewRow();
dr[0] = 4;
dr[1] = "MFC Programming";
dr[2] = "VC++ MFC Library";
dr[3] = 3;
dr[4] = 3000;
dr[5] = DateTime.Parse("8/14/1999");
dt.Rows.Add(dr);
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt As DataTable
dt = ds.Tables("Article")
' Insert
Dim dr As DataRow
dr = dt.NewRow()
dr(0) = 4
dr(1) = "MFC Programming"
dr(2) = "VC++ MFC Library"
dr(3) = 3
dr(4) = 3000
dr(5) = DateTime.Parse("8/14/1999")
dt.Rows.Add(dr)
da.Update(ds, "Article")
ds.AcceptChanges()

How do I delete a record in the table using ADO.Net dataset?
To delete a record, you first get the DataRow object from the DataTable object. Then you simply call the Delete() method of the data row object to delete a record from the data table.

C# Version
DataTable dt = ds.Tables["Article"];

// Delete
DataRow dr = dt.Rows[3];
dr.Delete();
da.Update(ds, "Article");
ds.AcceptChanges();
VB.Net Version
Dim dt As DataTable
dt = ds.Tables("Article")
' Delete
Dim dr As DataRow
dr = dt.Rows(3)
dr.Delete()
da.Update(ds, "Article")
ds.AcceptChanges()

What is the architecture of connected environment of data access in ADO.Net?
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 required to manage the connection with the database. You can only perform database operations when, there exists an open connection to the database. Hence, 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 objects for working in the connected environment are:

Connection (SqlConnection, OleDbConnection, etc): It represents a connection to the database. All the connection objects in the ADO.Net implement the System.Data.IDbConnection interface.

Command (SqlCommand, OleDbCommand, etc): It represents the SQL command sent to the database, e.g., SELECT, UPDATE, INSERT, DELETE. All commands in ADO.Net implements IDbCommand interface

DataReader (SqlDataReader, OleDbDataReader, etc): It represents a data stream that can be used to read the result of your query returned by the database server. Using this object, you read the individual records and their fields returned as a result of your query to the database server. All the data readers in ADO.Net implement the System.Data.IDataReader interface.

How do I read data (or records) from database using data reader?
To read data from the database, you first make a connection object (SqlConnection, etc) and open it.

C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
conn.Open();
VB.Net Version
Dim connString As String = "server=siraj; database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
conn.Open()

Then you create a command using this connection and the command text.

C# Version
string cmdString = "select * from author";
SqlCommand cmd = new SqlCommand(cmdString, conn);
VB.Net Version
Dim cmdString As String = "select * from author"
Dim cmd As New SqlCommand(cmdString, conn)

Then you execute the command with the command object’s ExecuteReader() method. The ExecuteReader method returns the object of type IDataReader

C# Version
SqlDataReader reader = cmd.ExecuteReader();
VB.Net Version
Dim reader As SqlDataReader = cmd.ExecuteReader()

Now you read the individual records using this data reader. To advance to the next record, you call its Read() method which returns Boolean to indicate if there exists a next row. If the DataReader’s Read() method returns true then the DataReader acts as a database row (record). Now you can access the fields of this particular row specifying the column names (or integral indexes) in its indexers.

C# Version
while(reader.Read())
{
txtData.Text += reader["authorId"].ToString();
txtData.Text += ", ";
txtData.Text += reader["name"].ToString();
txtData.Text += "\r\n";
}
VB.Net Version
While reader.Read()
txtData.Text += reader("authorId").ToString()
txtData.Text += ", "
txtData.Text += reader("name").ToString()
txtData.Text += vbCrLf
End While

Finally, you need to close the database connection opened before performing the database operation (SELECT, in our case)

C# Version
conn.Close();
VB.Net Version
conn.Close()

Let’s look at the complete code now for review

C# Version
string connString = "server=siraj; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);
string cmdString = "select * from author";
SqlCommand cmd = new SqlCommand(cmdString, conn);
conn.Open();
SqlDataReader reader = cmd.ExecuteReader();
while(reader.Read())
{
txtData.Text += reader["authorId"].ToString();
txtData.Text += ", ";
txtData.Text += reader["name"].ToString();
txtData.Text += "\r\n";
}
conn.Close();
VB.Net Version
Dim connString As String = "server=siraj; database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
Dim cmdString As String = "select * from author"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
txtData.Text += reader("authorId").ToString()
txtData.Text += ", "
txtData.Text += reader("name").ToString()
txtData.Text += vbCrLf
End While
conn.Close()

How do I insert records using data reader?
The procedure for updating records using INSERT commands is very similar to the one we presented in the previous example (of SELECT) except that here the command does not return anything and thus the method to call on the SqlCommand object is called ExecuteNonQuery().

C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);

// INSERT Query
string cmdString ="INSERT INTO Author " +
"(authorId, name) " +
"VALUES(3, 'Anders Hejlsberg')";

SqlCommand cmd = new SqlCommand(cmdString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
VB.Net Version
Dim connString As String = "server=FARAZ; database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
' INSERT Query
Dim cmdString As String = "INSERT INTO Author " + _
"(authorId, name) " + _
"VALUES(3, 'Anders Hejlsberg')"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()

How do I update records using data reader?
The procedure for updating records using INSERT commands is very similar to the one we presented in the previous example (of SELECT) except that here the command does not return anything and thus the method to call on the SqlCommand object is called ExecuteNonQuery().

C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);

// UPDATE Query
string cmdString = "UPDATE Author " +
"SET name = 'Grady Booch' " +
"WHERE authorId = 3";
SqlCommand cmd = new SqlCommand(cmdString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
VB.Net Version
Dim connString As String = "server=FARAZ; database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
' UPDATE Query
Dim cmdString As String = "UPDATE Author " + _
"SET name = 'Grady Booch' " + _
"WHERE authorId = 3"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()

How do I delete records using data reader?
The procedure for updating records using INSERT commands is very similar to the one we presented in the previous example (of SELECT) except that here the command does not return anything and thus the method to call on the SqlCommand object is called ExecuteNonQuery().

C# Version
string connString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=";
SqlConnection conn = new SqlConnection(connString);

// DELETE Query
string cmdString = "DELETE FROM Author " +
"WHERE authorId = 3";
SqlCommand cmd = new SqlCommand(cmdString, conn);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
VB.Net Version
Dim connString As String = "server=FARAZ; database=programmersheaven;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
' DELETE Query
Dim cmdString As String = "DELETE FROM Author " +
"WHERE authorId = 3"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
cmd.ExecuteNonQuery()
conn.Close()

How do I write common code for different dot net framework data providers?
The System.Data namespace contains the interfaces implemented by different dot net framework data providers, such as:

IDbConnection implemented by SqlConnection, OracleConnection, OleDbConnection, OdbcConnection classes represents a connection with the database server

IDbCommand implemented by SqlCommand, OracleCommand, OleDbCommand, OdbcCommand classes represents an SQL command passed to the database server

IDbDataAdapter implemented by SqlDataAdapter, OracleDataAdapter, OleDbDataAdapter, OdbcDataAdapter classes represents a data adapter used to fill the data set in the disconnected environment of the ADO.Net

IDataReader implemented by SqlDataReader, OracleDataReader, OleDbDataReader, OdbcDataReader classes represents a data reader used to read records from the database server, analogous to read only, forward only cursor

IDbTransaction implemented by SqlTransaction, OracleTransaction, OleDbTransaction, OdbcTransaction classes represents a transaction established with the database server

We strongly recommend the readers to use the references of these interface type to perform the database operations wherever possible. Using these, you can write a code that is data provider independent. Consider 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

C# Version
internal class DataAccessModule
{
private IDbConnection conn;
private IDbCommand cmd;
private const string GetValueCmdText ="SELECT value FROM MyTable WHERE name = '";
public DataAccessModule(IDbConnection conn)
{
this.conn = conn;
cmd = conn.CreateCommand();
conn.Open();
}
public string GetValue(string name)
{
cmd.CommandText = GetValueCmdText + name + "'";
IDataReader reader = cmd.ExecuteReader();
if(reader.Read())
{
return reader["value"].ToString();
}
else
{
return null;
}
}
// more functions...
}
VB.Net Version
Friend Class DataAccessModule
Private conn As IDbConnection
Private cmd As IDbCommand
Private Const GetValueCmdText As String ="SELECT value FROM MyTable WHERE name = '"
Public Sub New(ByVal conn As IDbConnection)
Me.conn = conn
cmd = conn.CreateCommand()
conn.Open()
End Sub
Public Function GetValue(ByVal name As String) As String
cmd.CommandText = GetValueCmdText + name + "'"
Dim reader As IDataReader = cmd.ExecuteReader()
If (reader.Read()) Then
Return reader("value").ToString()
Else
Return Nothing
End If
End Function
' More Functions....
End Class

What is a stored procedure?
A stored procedure is a precompiled executable object that contains one or more SQL statements. A stored procedure may be written to accept inputs and return output.

What is the advantage of using stored procedure over the SQL queries?
Writing the SQL statements inside our code is usually not a good idea. In this way you expose your database schema (design) in the code which may be changed. Hence most of the time programmers use stored procedures instead of plain SQL statements. A stored procedure is a precompiled executable object that contains one or more SQL statements. Hence you can replace your complex SQL statements with a single stored procedure. Since, stored procedures are precompiled objects they execute faster at the database server. Most of the time, stored procedures contain more than one command; in this case, the time to pass the individual commands to the database server from the program is saved. The database is issued just one command (to execute the stored procedure) and the DB server executes all the commands and returns the result in the end. Hence, the overall interaction time with the DB server reduces in a great deal. This can result in a huge optimization in case where the DB server is accessed via a slow network.

How do stored procedure look like, can you provide some sample stored procedures?
Here we are presenting a brief review of four basic type of stored procedure for SELECT, INSERT, UPDATE and DELETE operations. In SQL Server, you can create and add stored procedures to your database using the SQL Server Enterprise Manager.

UPDATE Stored Procedure
A simple stored procedure to update a record is
CREATE PROCEDURE UpdateProc (
@artId as int,
@title as varchar(100),
@topic as varchar(100),
@authorId as int,
@lines as int,
@dateOfPublishing as datetime)
AS
UPDATE Article SET
title=@title, topic=@topic, authorId=@authorId,
lines=@lines, dateOfPublishing=@dateOfPublishing
WHERE artId=@artId
GO

The name of stored procedure is UpdateProc and it has the input parameters for each of the fields of our Article table. The query to be executed when the stored procedure is run updates the record with the supplied primary key (@artId) using the supplied parameters. It is very similar to the code we have written to initialize command in the previous example and we hope you don’t have any problem in understanding this even you are not familiar with stored procedure.

INSERT Stored Procedure
A simple stored procedure to insert a record is
CREATE PROCEDURE InsertProc (
@artId as int,
@title as varchar(100),
@topic as varchar(100),
@authorId as int,
@lines as int,
@dateOfPublishing as datetime)
AS
INSERT INTO article (artId, title, topic, authorId, lines, dateOfPublishing)
VALUES(@artId, @title, @topic, @authorId, @lines, @dateOfPublishing)
GO

The stored procedure above is named InsertProc and is very similar to the UpdateProc except that here we are using the INSERT SQL statement instead of the UPDATE command.

DELETE Stored Procedure
A simple stored procedure to delete a record is
CREATE PROCEDURE DeleteProc (@artId as int)
AS
DELETE FROM article WHERE artId = @artId
GO

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

SELECT Stored Procedure
A simple stored procedure to delete a record is
CREATE PROCEDURE SelectProc
AS
SELECT * FROM Article
GO

This probably is the simplest of all. It does not take any parameter and only selects all the records from the Article table.

All the four stored procedures presented above are kept extremely simple so that the reader does not find any difficulty in understanding the use of stored procedure in his C#/VB.Net code. The real world stored procedures are much more complex and off course useful than these!

How do I call a stored procedure from my application using ADO.Net?
Using stored procedures with ADO.Net in C# is extremely simple, especially when we have developed the application with SQL commands. All we need is:

Create a command object (SqlCommand, etc) and specify the stored procedure name

Set the CommandType property of the command object to the CommandType.StoredProcedure enumeration value. This tells the runtime that the command used here is a stored procedure.

That’s it! The sample code to use with data adapter is:
C# Version
// Preparing Insert SQL Command
SqlCommand insertCommand = new SqlCommand("InsertProc", conn);
insertCommand.CommandType = CommandType.StoredProcedure;
dataAdapter.InsertCommand = insertCommand;
insertCommand.UpdatedRowSource = UpdateRowSource.None;
...
VB.Net Version
' Preparing Insert SQL Command
Dim insertCommand = New SqlCommand("InsertProc", conn)
insertCommand.CommandType = CommandType.StoredProcedure
dataAdapter.InsertCommand = insertCommand
insertCommand.UpdatedRowSource = UpdateRowSource.None


How do I make my first application to call stored procedure using ADO.Net?
Please download the attached source code for the sample application using the stored procedures to access the data with ADO.Net in VB and C#.

What are the important points when developing a data access app with ADO.Net?
Always try to use the base interfaces for connection, command, data reader and other objects.

Always try to use the SqlClient, SqlServerCe and OracleClient to connect with the Sql Server, Sql Server CE and Oracle Database servers as they are specialized and optimized for the specific database servers.

Still remember to reference the data provider specific objects (SqlConnection, OracleCommand) to reference with the base interface (IDbConnection, IDbCommand)

C# Version
IDbConnection conn = new SqlConnection();
...
IDbCommand cmd = new OracleCommand();
VB.Net Version
Dim conn As IDbConnection
conn = New SqlConnection();
...
Dim cmd As IDbCommand
cmd = new OracleCommand();

Do not write the connection string in your code as it may change. Either write it in a text file or an xml file and read it on the application startup. For security purposes, you may also write the encrypted connection string in the text/xml file

Try to use the stored procedures wherever possible especially when you are to write a series of queries whose individual results are not required to be used in the code in between this series of queries.

Do not use the complex queries in the source code. If the query is getting complex, try to make the views inside the database server and use the views instead.

Practice using the transactions when it makes sense, especially with error handling codes

Put special consideration in the error handling code. The database operation may fail due to various reasons such as invalid connection string, invalid table/field name in the query, database server failure, connection failure, too many connections on the server or the server busy, invalid query, etc You need to consider all these while writing the code for error handling.

Using Visual Studio.Net’s debugger is a very good and useful practice to find the possible errors. Remember, Ado.Net exception messages are not much useful (or quite vague) in general for debugging; hence the use of watch and quick watch debugger windows is extremely useful and helpful in when debugging the code.

When using dataset and disconnected architecture, we don’t update the data source (by calling DataAdapter’s Update() method and DataSet’s AcceptChanges() method) for each update. Instead we make the changes local and update all these changes later as a batch. This provides optimized use of network bandwidth. BUT, this off course is not a better option when multiple users are updating the same database. When 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 (UPDATE, INSERT and DELETE) by calling the ExecuteNonQuery() method of your command (SqlCommand or OleDbCommand) object.

Disconnected data access is suited most to read only services. In common practice clients are often interested in reading and displaying data. In this type of situation, the disconnected data access excels 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. On the down side, disconnected data access architecture is not designed to be used in the networked environment where multiple users are updating data simultaneously and each of them needs to be aware of current state of database at any time (e.g., Airline Reservation System).

What is data grid and what is the use of it?
Data Grid is the standard control for viewing data in .Net environment. A data grid control is represented in .Net by System.Windows.Forms.DataGrid class. The data grid control can display the data from a number of data sources e.g. data table, dataset, data view and array.

How can I make my first application with DataGrid using the data from ADO.Net?
Let’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 Visual Studio toolbox. We have set the Name property of data grid to ‘dgDetails’ and its CaptionText property to ‘ProgrammersHeaven Database’. The name of button is ‘btnLoadData’. The event handler for button is:
C# Version
private void btnLoadData_Click(object sender, System.EventArgs e)
{
string connectionString = "server=FARAZ; database=programmersheaven;" +
"uid=sa; pwd=;";
SqlConnection conn = new SqlConnection(connectionString);
string cmdString = "SELECT * FROM article";
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdString, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "article");
dgDetails.SetDataBinding(ds, "article");
}
VB.Net Version
Private Sub btnLoadData_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnLoadData.Click
Dim connectionString As String = "server=P-III; database=programmersheaven;" + _
"uid=sa; pwd=;"
Dim conn As New SqlConnection(connectionString)
Dim cmdString As String = "SELECT * FROM article"
Dim dataAdapter As New SqlDataAdapter(cmdString, conn)
Dim ds As New DataSet()
dataAdapter.Fill(ds, "article")
dgDetails.SetDataBinding(ds, "article")
End Sub

Here 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 “article” table to the data grid control which is done by calling the SetDataBinding() method of the DataGrid class. The first parameter of this method is the dataset while the second parameter is the name of table in the dataset.

C# Version
dgDetails.SetDataBinding(ds, "article");
VB.Net Version
dgDetails.SetDataBinding(ds, "article")

When you execute this program and select the Load button you will see the output presented in the previous figure.

How can I make my data grid to view data from multiple related tables?
Let’s see how we can use Data Grid control to show multiple related tables. When 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 example in our ProgrammersHeaven database, table Author is the parent table of the Article table as the Article table contains ‘AuthorId’ as foreign key which is a primary key in the Author table.

In this example, we will use data grid to show the related records from article and author table. In order to specify the relationship between the two tables we need to use the DataRelation class as:

C# Version
dgDetails.SetDataBinding(ds, "article")
DataRelation relation = new DataRelation("ArtAuth",
ds.Tables["author"].Columns["authorId"],
ds.Tables["article"].Columns["authorId"]
);
VB.Net Version
Dim relation As New DataRelation("ArtAuth", _
ds.Tables("author").Columns("authorId"), _
ds.Tables("article").Columns("authorId") _
)

Here the first argument of DataRelation 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. After creating this relationship we need to add it to the Relations collection of the dataset.

C# Version
ds.Relations.Add(relation);
VB.Net Version
ds.Relations.Add(relation)

Hence the modified code for the Load Data button is:

C# Version
private void btnLoadData_Click(object sender, System.EventArgs e)
{
string connectionString = "server=P-III; database=programmersheaven;" +
"uid=sa; pwd=;";
SqlConnection conn = new SqlConnection(connectionString);
string cmdString = "SELECT * FROM article";
SqlDataAdapter dataAdapter = new SqlDataAdapter(cmdString, conn);
DataSet ds = new DataSet();
dataAdapter.Fill(ds, "article");
cmdString = "SELECT * FROM author";
dataAdapter = new SqlDataAdapter(cmdString, conn);
dataAdapter.Fill(ds, "author");
DataRelation relation = new DataRelation("ArtAuth",
ds.Tables["author"].Columns["authorId"],
ds.Tables["article"].Columns["authorId"]
);
ds.Relations.Add(relation);
DataView dv = new DataView(ds.Tables["author"]);
dgDetails.DataSource = dv;
}
VB.Net Version
Private Sub btnLoadData_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles btnLoadData.Click
Dim connectionString As String = "server=P-III; database=programmersheaven;" + _
"uid=sa; pwd=;"
Dim conn As New SqlConnection(connectionString)
Dim cmdString As String = "SELECT * FROM article"
Dim dataAdapter As New SqlDataAdapter(cmdString, conn)
Dim ds As New DataSet()
dataAdapter.Fill(ds, "article")
cmdString = "SELECT * FROM author"
dataAdapter = New SqlDataAdapter(cmdString, conn)
dataAdapter.Fill(ds, "author")
Dim relation As New DataRelation("ArtAuth", _
ds.Tables("author").Columns("authorId"), _
ds.Tables("article").Columns("authorId") _
)
ds.Relations.Add(relation)
Dim dv As New DataView(ds.Tables("author"))
dgDetails.DataSource = dv
End Sub

In the above code we first filled the dataset with the two tables, defined the relationship between them and then added it to the dataset. In the last two lines, we created an instance of DataView class by supplying the parent table in its constructor call and then set the DataSource property of data grid to this data view.

When we compile and execute this application, the data grid will show the records of parent table with ‘+’ button on the left of each record



When you press the ‘+’ button on the left of the record, it will expand 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



Still you can see the parent record at the top of all the rows of the child table. You can go back to the parent table using the back arrow button (ç) at the title bar of the data grid.

What are the issues related to the deployment of data access application?
Some of the basic issues related to the deployment of the data access applications are:
Can we suppose the required database exists at the target location?

If the database does exist then how can we get the connection string of it? Should we get it at the installation time? Or at the first run?

If the database does not exist then how it can be created? Is it the responsibility of human installing our application? Or the application should create it at the time of installation?

If the database is to be created by the application installation, then how does the installation setup know where (on which machine) to create the database? And what user name and password the setup should use to create the database?

Once, 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 execution)?

What if the database address (connection string) is changed during the application life cycle then what should be the application behavior? How can the application be aware of the new connection string?

If the database schema is hard-coded in the code (like table and field names) and the DB schema is changed (table/field name or data type is changed or new field/table added or some fields/tables deleted) because of any reason, then how to fix this problem?

You 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) should be handled without any change in the code or any update patch installation

How do I solve the deployment issues (mentioned in the previous FAQ)?
Ok, let’s discuss some of the issues and their solution briefly. The specific detail of these solutions is given in the next FAQs.

The easiest and very sound solution is to provide the database script to create necessary database and tables along with the installation and ask your user to run the script on the target database server to create the required database. Then ask the user to supply the connection string at the installation setup time.

You can create the database with the installation by executing the database creation script with the installation. But before this, you have to ask the user the location (the computer on the network) where the database server exists, and the user name, password to login to the database.

The connection string should be stored in a text or binary or xml file. You can also encrypt the connection string before writing it to the file. The application, thus, is required to decrypt and load the connection string in the memory at each startup.

The application should load the connection string at each startup and attempt to connect to the database. If the connection attempt fails then it should inform the user that the database is not available and ask the user to setup the database and try again. The application should also allow the user to change the database connection string any time and, it the application logic permits, let the user specify to work without database. If the user specifies a new connection string during the application startup or regular execution, the application should save it for later use.

One solution to the schema changed problem is to use views and stored procedure wherever possible. But if this is not done or the change is too big to be catered by the views and/or stored procedure then you can supply a new data access module update (a new DLL may be). For this reason, it is advised to separate the data access code in a separate physical and logical module (or assembly in .Net language) so you can change it without affecting the overall application. But when using this, the interface (the method signatures) should be made that abstract that they does not exactly map to the physical database schema but to the logical schema. Finally, if the database schema change is major (which is not a very good sign for the application overall design) then there is no solution but to change the code and ship the installation again!!!

How do I set the connection string at installation :specific data provider?
Well this is quite tricky and interesting. Connection strings are database dependent and different database servers allow connection strings in different formats.
If you are using the database specific provider classes (like those from System.Data.SqlClient or System.Data.OracleClient) then you can generate the connection string easily by taking the specific inputs from the user. For example, if you are using SQL Server and the classes from the System.Data.SqlClient namespace then we can ask user the SQL Server instance name, the user name, password of if he/she is using the Windows Authentication to log in and the database name.

How do I set the connection string at installation :general data provider?
The problem arises when you are using the general data providers such as classes from System.Data.OleDb and System.Data.Odbc namespaces. You can’t make a general GUI to generate the connection string for all the database servers. Then what to do now? The solution is the DataLink Dialog. You must have seen the dialog which looks like this in many windows applications:



So how you can use this dialog in your program? For this you need add a reference to COM component ‘Microsoft OLE DB Service Component 1.0 Type Library’ which should be available if you have installed Microsoft ActiveX Data Components. Once you have added the component, you can show the Data Link Properties dialog box by making an object of type MSDASC.DataLink class and calling its PromptNew() method.

C# Version
MSDASC.DataLinks udl = new MSDASC.DataLinksClass();
udl.PromptNew();
VB.Net Version
Dim udl As MSDASC.DataLinks
udl = New MSDASC.DataLinksClass
udl.PromptNew()

The above code will show the Data Link Properties dialog box. But how can we get the connection string generated by the dialog box? The PromptNew() method returns a connection type object which can be captured in an object of type ADODB.Connection. Hence for this, add a reference to ‘adodb’ .Net assembly in your project, and get the connection string using the ConnectionString property of this object. The following code snippets demonstrate this:

C# Version
string connStr = "";
MSDASC.DataLinks udl = new MSDASC.DataLinksClass();
ADODB.Connection conn = (ADODB.Connection) udl.PromptNew();
if(conn != null)
{
connStr = conn.ConnectionString;
}
VB.Net Version
Dim connStr As String
Dim udl As MSDASC.DataLinks
udl = New MSDASC.DataLinksClass
Dim conn As ADODB.Connection = udl.PromptNew()
If Not conn Is Nothing Then
connStr = conn.ConnectionString
End If

You can use this code in the overrided Install() method of your project’s installer class (the class derived from System.Configuration.Install.Installer class), and add the project output in the ‘Custom Actions’ of the setup project.

How do I supply the connection string during first run or during the regular execution?
Well that should be very simple Just add the Data Link Properties dialog box at the start of the application or during the regular execution of the application whenever you need it. Alternatively, you can also provide your own designed user interface for connection string related properties, if your application supports specific .Net data providers (like System.Data.SqlClient or System.Data.OracleClient)

How do I store / retrieve the connection string in / from a text file?
You can store the connection string in the text file or an xml file and later retrieve it. Let’s see some example code to write a connection string to the text file and read it back

C# Version
string connStr = "";
// get connection string in the connStr variable
// Write connection string to text file
StreamWriter sw = new StreamWriter(@"C:\ConnectionString.txt");
sw.WriteLine(connStr);
// ...
// Read connection string from the text file
StreamReader sr = new StreamReader(@"C:\ConnectionString.txt");
connStr = sr.ReadLine();
VB.Net Version
Dim connStr As String = ""
' get connection string in the connStr variable
' Write connection string to text file
Dim sw As New StreamWriter("C:\ConnectionString.txt")
sw.WriteLine(connStr)
' ...
' Read connection string from the text file
Dim sr As New StreamReader("C:\ConnectionString.txt")
connStr = sr.ReadLine()

How do I store / retrieve the connection string in / from an XML file?
Once you get the connection string, you can store the connection string in the text file or an xml file and later retrieve it. Let’s see some example code to write a connection string to an XML file and read it back

C# Version
string connStr = "";
// get connection string in the connStr variable
// Write connection string to xml file
XmlDocument xmlDoc = new XmlDocument();
XmlNode xn = xmlDoc.CreateNode(XmlNodeType.Element, "ConnectionString", "");
xn.InnerText = connStr;
xmlDoc.AppendChild(xn);
xmlDoc.Save(@"C:\ConnectionString.xml");
// ...
// Read connection string from the text file
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\ConnectionString.xml");
XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString");
connStr = xn.InnerText;
VB.Net Version
Dim connStr As String = ""
' get connection string in the connStr variable
' Write connection string to xml file
Dim xmlDoc As New XmlDocument
Dim xn As XmlNode
xn = xmlDoc.CreateNode(XmlNodeType.Element, "ConnectionString", "")
xn.InnerText = connStr
xmlDoc.AppendChild(xn)
xmlDoc.Save("C:\ConnectionString.xml")
' ...
' Read connection string from the xml file
Dim xmlDoc As New XmlDocument
xmlDoc.Load("C:\ConnectionString.xml")
Dim xn As XmlNode
xn = xmlDoc.SelectSingleNode("ConnectionString")
connStr = xn.InnerText

How do I make my first “Hello, Data Access Application Deployment” setup program?
We will start with the assumption that you have a data access application. Note that we are only providing here the C# example. The VB.Net example is exactly similar. Why we didn’t include the VB.Net example? Because, the intent here is not to explain the code but the procedure of how to create the data accessing application’s deployment project which is independent of the language being used. All the code we will present here has already been presented in the previous FAQs and explained in much detail.

The first step, then, is to add an installer class. The easiest way to do is to right click the project icon in the solution explorer and select ‘Add New Item…’ and in the pop-up window, select Installer class, name it appropriately and select ‘Open’ button to add it. Now right click the newly added installer class and select view code. You will notice that this new class is automatically inherited from the System.Configuration.Install.Installer class

public class Installer1 : System.Configuration.Install.Installer

The only thing you need to do now in this class is to override the Install() method of the base class, write the code you want to execute when the installation setup is executed. We have written the code to display the Data Link Properties dialog box and save the resulted connection string into an xml file, so later the application can use it.

public override void Install(IDictionary stateSaver)
{
base.Install (stateSaver);
string connStr = "";
MSDASC.DataLinks udl = new MSDASC.DataLinksClass();
ADODB.Connection conn = (ADODB.Connection) udl.PromptNew();
if(conn != null)
{
connStr = conn.ConnectionString;
}
// Write connection string to xml file
XmlDocument xmlDoc = new XmlDocument();
XmlNode xn = xmlDoc.CreateNode(XmlNodeType.Element, "ConnectionString", "");
xn.InnerText = connStr;
xmlDoc.AppendChild(xn);
xmlDoc.Save(@"C:\ConnectionString.xml");
}

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 box. It retrieves the connection string from the xml file generated by the installation setup program.

private void btnShowConnStr_Click(object sender, System.EventArgs e)
{
string connStr = "";
// Read connection string from the xml file
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\ConnectionString.xml");
XmlNode xn = xmlDoc.SelectSingleNode("ConnectionString");
connStr = xn.InnerText;
MessageBox.Show(connStr, "Connection String from XML file");
}

Now the application is ready. We will start building our setup project. For this, add a new ‘Setup and Deployment’ project to the solution by right clicking the solution and selecting ‘Add New Project…’ in the pop-up window, selecting the ‘Setup Project’ from the ‘Setup and Deployment Projects’ section. Once the setup project is added to the solution, right click it in the solution explorer and select View-->File System. Here right click the application folder icon and select Project Output --> Primary Out put of your data access project. This will automatically add the project dependencies. Now right click the ‘Primary Output of your project’ and create its short cut. Copy this shortcut to the Desktop folder and the User Program Menu and rename shortcut appropriately.



Now to ask the setup project run our custom installation code (we have written in the Installer class in the data access application), we need to add the primary output of our project to the custom actions of the setup project. To do this, right click the setup project in the solution explorer, and select View --> Custom Actions. Here right click ‘Install’ and select ‘Add Custom Action’. In the popup window, select the primary output of the database access application from the application folder and click OK.



This is all we need to do! Rebuild the solution and remove any minor bugs (if they do popup). When your setup project will be built, it will generate a Setup.exe file in its debug (or release folder depending on the project configuration). Run this setup.exe to install this application. The setup will ask you the connection string and save it in the xml file.



After installation is complete, run the application using its desktop icon. When you will click the button on the form, it will read the connection string from the xml file and display it in the message box.



How to use relation objects in a dataset?
DataSet's that contain multiple DataTable objects can use DataRelation objects to relate one table to another. Adding a DataRelation to a DataSet adds by default a UniqueConstraint to the parent table and a ForeignKeyConstraint to the child table.

The code sample below creates a DataRelation using two DataTable objects in a DataSet. Each DataTable contains a column named CustID which serves as a "relation" between two the DataTable objects. The example adds a single DataRelation to the Relations collection of the DataSet. The first argument in the sample specifies the name of the DataRelation being created. The second argument sets the parent DataColumn and the third argument sets the child DataColumn.

custDS.Relations.Add("CustOrders",
custDS.Tables["Customers"].Columns["CustID"],
custDS.Tables["Orders"].Columns["CustID"]);

OR

private void CreateRelation()
{
DataColumn parentCol;
DataColumn childCol;
parentCol = DataSet1.Tables["Customers"].Columns["CustID"];
childCol = DataSet1.Tables["Orders"].Columns["CustID"];
DataRelation relCustOrder;
relCustOrder = new DataRelation("CustomersOrders",
parentCol, childCol);
DataSet1.Relations.Add(relCustOrder);

DataReader Vs DataSet?
The ADO.NET DataReader is used to retrieve "read-only" / "forward-only" data from a database. Using the DataReader increases application performance and reduces system overheads. This is due to one row at a time is stored in memory. You create a DataReader by calling Command.ExecuteReader after creating an instance of the Command object.

The following line of code is used to retrieve rows from a data source.

SqlDataReader myReader = myCommand.ExecuteReader();

The Read method of the DataReader object is used to obtain a row from the results of the query, like so.

(myReader.Read()) Console.WriteLine("\t{0}\t{1}",
myReader.GetInt32(0), myReader.GetString(1));
myReader.Close();

The DataSet is a in-memory representation of data that provides a consistent relational programming model regardless of the data source. It can be used with multiple data sources. The DataSet represents a complete set of data including related tables, constraints, and relationships among the tables. The methods and objects in a DataSet are consistent with those in the relational database model. The DataSet can also persist and reload its contents as XML and its schema as XML Schema definition language (XSD) schema.

The DataAdapter acts as a bridge between a DataSet and a data source for retrieving and saving data. The DataAdapter provides this bridge by "mapping Fill". Which changes the data in the DataSet to match the data in the data source. Upon this an Update occurs, which changes the data in the data source to match the data in the DataSet.

On connecting to a Microsoft  ?SQL Server database, an increase in overall performance can be obtained by using the SqlDataAdapter along with its associated SqlCommand and SqlConnection. For other OLE DB-supported databases, use the DataAdapter with its associated OleDbCommand and OleDbConnection.

How do I access a SQL stored procedure?
You can access SQL stored procedures the same way as executing other SQL commands.

Set the query string as the name of the stored procedure and then set the CommandType to be CommandType.StoredProcedure. Below is an example of one input and one output parameter.

if(myConn.State == ConnectionState.Closed)myConn.Open();
SqlCommand myCmd = new
SqlCommand("sp_my_stored_procedure",myConn);
myCmd.CommandType = CommandType.StoredProcedure;
SqlParameter parm;
parm = myCmd.Parameters.Add(new SqlParameter("@custid",
SqlDbType.VarChar,50));
parm.Direction = ParameterDirection.Input;
myCmd.Parameters["@custid"].Value = OrderID;
parm = myCmd.Parameters.Add(new SqlParameter("@custName",
SqlDbType.VarChar,50));
parm.Direction = ParameterDirection.Output;
SqlDataAdapter da = new SqlDataAdapter();
da.TableMappings.Add("your mapping","your mapping");
da.SelectCommand = myCmd;
DataSet ds = new DataSet();
da.Fill(ds);
DataTable resultTable = ds.Tables[0];

Methods of the Command Objects with databases?
The Command object is represented by two corresponding classes: SqlCommand and OleDbCommand. Command objects are used to execute statements (commands) to a database via a data connection. The Command objects can be used to execute stored procedures on the Database, SQL statements, or return complete tables directly.
Command objects provide three methods that are used to execute commands on the database:

ExecuteNonQuery. Executes direct SQL commands, such as INSERT, UPDATE or DELETE.

ExecuteScalar. Returns a single value from a Database Query.

ExecuteReader. Returns a result set by way of a DataReader object.

How do I display a data table in a data grid?
The following code queries an MS Access Table, then displays all the columns of that table in a Data Grid.

'Establish a connection to the data source.
Dim ConnString As String
ConnString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=C:\Test.mdb"
Dim Conn As New System.Data.OleDb.OleDbConnection(ConnString)
Conn.Open()
Dim dapt As New System.Data.OleDb.OleDbDataAdapter("Table1", Conn)
Dim dst As New DataSet
dapt.Fill(dst, "Table1")
DataGrid1.SetDataBinding(dst, "Table1")
Conn.Close()

Upon running the above code, Table1 from the a "Test" database will be displayed in a DataGrid.

How do I insert data entered in a textbox into the database?
The data you enter in the textboxes will be inserted into the database when of the click of a Button.

The working senario is a database called "Emp" with a table named "Table1" with three columns. Also a Form with three TextBoxes and one Command Button.

Imports System.Data.OleDb
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles_ Button2.Click

Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\emp.mdb;Persist Security_ Info=False")
cn.Open()

str = "insert into table1 values(" & CInt(TextBox1.Text) & ",'" & TextBox2.Text & "','" & TextBox3.Text & "')" 'string stores the command
'and CInt is used to convert number, to string

cmd = New OleDbCommand(str, cn)
icount = cmd.ExecuteNonQuery

MessageBox.Show(icount) 'displays number of records inserted
Catch

End Try

End Sub

How do I access SQL server in VB.NET?
To access data from a table in  ?SQL Server you need to import the namespace System.Data.SqlClient and establish a connection from the application to the server.
The following code demonstrates how to connect to a  ?SQL Server and display data from the "Discounts" table in the sample database "PUBS".

Imports System.Data.SqlClient

Public Class Form1 Inherits System.Windows.Forms.Form

Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()

'declaring the objects need
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_

System.EventArgs) Handles MyBase.Load

myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection

Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)

'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()

While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While

dr.Close()
myConnection.Close()

Catch e As Exception
End Try

End Sub
End Class

How to insert an image in Access Database?
The following code asks for a path of a Gif image. Then inserts the Gif image to an Access database.

File name is Image.vb

Imports System
Imports System.IO
Imports System.Data

Public Class SaveImage
Shared Sub main()

Dim o As System.IO.FileStream
Dim r As StreamReader
Dim gifFile As String

Console.Write("Enter a Valid .Gif file path")
gifFile = Console.ReadLine

If Dir(gifFile) = "" Then
Console.Write("Invalid File Path")
Exit Sub
End If

o = New FileStream(gifFile, FileMode.Open, FileAccess.Read, FileShare.Read)
r = New StreamReader(o)

Try

Dim FileByteArray(o.Length - 1) As Byte
o.Read(FileByteArray, 0, o.Length)
Dim Con As New _ System.Data.OleDb.OleDbConnection("Provider=Microsoft.Jet.OLEDB.3.51;Persist Security Info=False;Data

Source=Test.mdb")

Dim Sql As String = "INSERT INTO Images (Pic,FileSize) VALUES (?,?)"
Dim Cmd As New System.Data.OleDb.OleDbCommand(Sql, Con)
Cmd.Parameters.Add("@Pic", System.Data.OleDb.OleDbType.Binary, o.Length).Value = FileByteArray
Cmd.Parameters.Add("@FileSize", System.Data.OleDb.OleDbType.VarChar, 100).Value = o.Length

Con.Open()
Cmd.ExecuteNonQuery()
Con.Close()
Catch ex As Exception
Console.Write(ex.ToString)

End Try
End Sub
End Class

A file will be inserted in the Database each time the code is executed.

ASP.NET

What is the difference between ASP and ASP.NET?
Web application development in .NET with ASP.NET has evolved a great deal. The overall architecture of web applications in .Net is much more improved and robust. The enhanced features in ASP.NET make it the best available technology for web application development. The code behind the ASP.Net scripts can be in written in any .Net compliant programming language.

The script (ASP.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 amazingly useful data grid controls. The ASP.Net web applications can now use .NET assemblies and COM components to serve the client requests. ASP.NET pages are now compiled contrary to the ASP pages which are interpreted by the ISA server. Truly speaking, there is no comparison between ASP and ASP.NET... ASP.NET simply rules!

What is ASP.NET?
ASP.NET is a powerful programming platform for developing web-based applications and services. It comes with rich set of web controls to create dynamic, fast and interactive web pages. Web pages built using ASP.NET are called ASP.NET web pages or web forms. ASP.NET simplifies web development by using WYSIWYG (what you see is what you get) editors. ASP.NET helps to build complex web applications with the use of drag and drop control support. Visual Studion.NET helps us to build web applications (ASP.NET) using either the C# or VB programming language. The following features are making developers choose ASP.NET over other technologies:

ASP.NET applications can be designed and developed using RAD (Rapid Application Development) tools.

ASP.NET web forms support a variety of controls and also support user created and third party controls.

Any .NET FrameWork language can be used to develop ASP.NET applications.

ASP.NET uses the Common Language Runtime (CLR) resource and benefits from it's features.

What is the use of Web.config file?
ASP.NET configuration files are XML-based text files. Each "web.config" file applies configuration settings to the directory it is located in and to all virtual sub directories under it.

Settings in sub directories can optionally override or modify settings specified in main directories. The root configuration file "WinNT\Microsoft.NET\Framework\\config\machine.config" provides default configuration settings for the entire machine.

ASP.NET configures IIS to prevent direct browser access to "web.config" files. This ensures that their values cannot become public (Attempts to access them will cause ASP.NET to return 403: Access Forbidden). At run time, ASP.NET uses these "web.config" configuration files to hierarchically compute a unique collection of settings for each incoming URL target request. These settings are calculated only once and then cached across subsequent requests. ASP.NET automatically watches for file changes and will invalidate the cache if any of the configuration files change.

What are Web Services and the underlying protocol used with it?
Web Services are applications that provide services on the internet. Web services allow for programmatic access of business logic over the Web. Web services typically rely on XML-based protocols, messages, and interface descriptions for communication and access.

Web services are designed for use by other programs or applications rather than directly by end user. Programs invoking a Web service are called clients. SOAP over HTTP is the most commonly used protocol for invoking Web services.

There are three main uses of Web services. Application integration Web services within an intranet are commonly used to integrate business applications running on different platforms. For example, a .NET client running on Windows 2000 can easily invoke a Java Web service running on a mainframe or Unix machine to retrieve data from a legacy application.

Business integration Web services allow trading partners to engage in e-business allowing them to leverage the existing Internet infrastructure. Organizations can send electronic purchase orders to suppliers and receive electronic invoices. Doing e-business with Web services means a low barrier to entry because Web services can be added to existing applications running on any platform without changing legacy code.

Commercial Web services focus on selling content and business services to clients over the Internet similar to familiar Web pages. Unlike Web pages, commercial Web services target applications as their direct users.

Example, Continental Airlines exposes flight schedules and status Web services for travel Web sites and agencies to use in their applications. Like Web pages, commercial Web services are valuable only if they offer services that are needed. It makes sense to sell real-time weather information or stock quotes as a Web service. Technology can help you add value to your services and explore new markets. However ultimately customers pay for contents and/or business services, not for technology.

How to generate a WebService proxy? What are SOAP, WSDL, and UDDI?
SOAP is an XML-based messaging protocol designed for exchanging formatted data (messages) over the Internet. Using SOAP you can send request and reply messages. SOAP is simple, easy to use, light weight and completely neutral with respect to operating systems, programming languages, and distributed computing platforms. After SOAP came into existence as a mechanism for exchanging XML messages among enterprises, a function was needed to describe the messages and how they are exchanged.

The Web Services Description Language (WSDL) is a particular form of an XML Schema. Developed by Microsoft and IBM for the purpose of defining the XML message, operation, and protocol mapping of a web service accessed using SOAP or other XML protocol. WSDL defines web services in terms of "endpoints" that operate on XML messages. The WSDL syntax 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 WSDL specification describes how to map messages and operations to SOAP 1.1, HTTP GET/POST and MIME. WSDL creates web service definitions by mapping a group of endpoints into a logical sequence of operations on XML messages. The same XML message can be mapped to multiple operations (or services) and bound to one or more communications protocols using "ports".

The "Universal Description, Discovery, and Integration" (UDDI) defines a data model (in XML). Also SOAP API's for registration and searching business information, web services that a business exposes to the Internet are also covered. UDDI is an independent consortium of vendors founded by Microsoft, IBM and Ariba. This project purpose of developing an Internet standard for web service description registration and discovery.

Microsoft, IBM and Ariba also are hosting the initial deployment of the UDDI service. This is conceptually patterned after DNS (the Internet service that translates URLs into TCP addresses).

UDDI uses a private agreement profile of SOAP (UDDI doesn't use the SOAP serialization format because it's not well suited to passing complete XML documents (it's aimed at RPC style interactions). The main idea is that businesses use SOAP APIs to register themselves with UDDI. Other businesses search the UDDI when they want to discover a trading partner.

The information in UDDI is categorized according to industry type and geographical location, allowing UDDI subscribers to search through lists of potentially matching businesses. Once a specific business is chosen, another call to UDDI is made to obtain the specific contact information for that business. The contact information includes a pointer to the target business's WSDL or other XML schema file describing the web service that the target business publishes.

What is the trace utility used for?

Using the SOAP Trace Utility
The Microsoft Simple Object Access Protocol (SOAP) Toolkit 2.0 includes a TCP/IP trace utility, MSSOAPT.EXE. You use this trace utility to view the SOAP messages sent by HTTP between a SOAP client and a service on a server. In order to use the Trace Utility, perform the following steps on the server. Open the Web Services Description Language (WSDL) file.

1) In the WSDL file, locate the element that corresponds to the service and change the location attribute for this element to port 8080.

For example, change

to

.
2) Run MSSOAPT.exe.
3) File menu, New, Click "Formatted Trace" (if you don't want to see HTTP headers) or click Unformatted Trace (if you want to see HTTP headers). 4) In the Trace Setup dialog box, click OK to accept the default values.

Using the Trace Utility on Client

To see all send/receive messages from a service, do the following steps on the client.
1) Copy the WSDL file from the server to the client.
2) Modify location attribute of the element in the local copy of the WSDL document to direct the client to

localhost:8080
Make a note of the current host and port.

For example, Change

to

and make note of "MyServer". 3) On the client, run MSSOPT.exe.
4) File menu, New, and either click Formatted Trace (if you don't want to see HTTP headers) or click Unformatted Trace (if you do want to see HTTP headers).
5) In the Destination host box, enter the host specified in Step 2.
6) In the Destination port box, enter the port specified in Step 2.
7) Click OK.

How do I upload a file from my ASP.NET page?
To upload a file with your ASP.NET page, you need the use of two classes: System.Web.UI.HtmlControls.HtmlInputFile class and the System.Web.HttpPostedFile.

The HtmlInputFile class represents an HTML input control that the user will use on the client to select a file to upload.

The HttpPostedFile class represents the uploaded file. This is obtained from the .PostedFile property of the HtmlInputFile control.

In order to use the HtmlInputFile control, you need to add the enctype attribute to your form tag as follows:

Note: Please replace (,) with < , > in the following code.

(form id="upload" method="post" runat="server" enctype="multipart/form-data")

Below is a simple example of how to upload a file via an ASP.NET page using C#.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.UI.HtmlControls" %>
<%@ Import Namespace="System.IO" %>
<%@ Import Namespace="System.Drawing" %>
(html)
(head)
(title)upload_cs(/title)
(/head)
(script language="C#" runat="server")
public void UploadFile(object sender, EventArgs e)
{
if (loFile.PostedFile != null)
{
try
{
String strFileName, strFileNamePath, strFileFolder;
strFileFolder = Context.Server.MapPath(@"data\");
strFileName = loFile.PostedFile.FileName;
strFileName = Path.GetFileName(strFileName);
strFileNamePath = strFileFolder + strFileName;
loFile.PostedFile.SaveAs(strFileNamePath);
lblFileName.Text = strFileName;
lblFileLength.Text = loFile.PostedFile.ContentLength.ToString();
lblFileType.Text = loFile.PostedFile.ContentType;
pnStatus.Visible = true;
}
catch (Exception x)
{
Label lblError = new Label();
lblError.ForeColor = Color.Red;
lblError.Text = "Exception occurred: " + x.Message;
lblError.Visible = true;
this.Controls.Add(lblError);
}
}
}
(/script)
(body)
(form id="upload_cs" method="post" runat="server" enctype="multipart/form-data")
(P)
(INPUT type="file" id="loFile" runat="server")
(/P)
(P)
(/P)
(P)

uploaded

bytes



(/form)
(/body)
(close HTML tag)

Tip
The /data 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 /data directory or one of its subdirectories.

How do I send an email from my ASP.NET page?
Include the System.Web.Mail.MailMessage and the System.Web.Mail.SmtpMail classes to send email from ASPX pages.

Below is a sample of sending email using said classes in C#.
<%@ Import Namespace="System" %>
<%@ Import Namespace="System.Web" %>
<%@ Import Namespace="System.Web.Mail" %>
(Open html tag)
(head)
(title)Mail Test(/title)
(/head)
(script language="C#" runat="server")
private void Page_Load(Object sender, EventArgs e)
{
try
{
MailMessage mailObj = new MailMessage();
mailObj.From = "xyz@programmersheaven.com";
'mail from address
mailObj.To = "abc@hotmail.com";
'mail to address
mailObj.Subject = "New Article Suggestion";
'mail subject
mailObj.Body = "I am sending a link to this article which is really very interesting";
'mail body
mailObj.BodyFormat = MailFormat.Text;
SmtpMail.SmtpServer = "mail.programmersheaven.com";
'specify mail server name depending on your mail server
SmtpMail.Send(mailObj);
Response.Write("Mail sent successfully");
}
catch (Exception x)
{
Response.Write("Your message was not sent: " + x.Message);
}
}
(/script)
(body)
(form id="mail_test" method="post" runat="server")
(/form)
(/body)
(Close /HTML tag)

Tip
In order to send email through your mail server, you should set the static SmtpServer property of the SmtpMail class to mail-fwd.

IIS with Windows Server 2003 benefits?
Below are the benefits of using IIS 6.0 with Windows Server 2003.
1.Faster sites without the need for high spec hardware for Web sites, intranets, and Web-based applications.
2.You can check your site's potential speed improvement with real-time Compression Check tool provided by Port80 Software.
3.Reduces total response time per page request. Using HTTP compression helps end users experience a 50% reduction in download time.
4.HTTP compression reduces the size of files sent from your Web server to the Web browser by an average of 30 to 50 percent which is a dramatic decrease in bandwidth.
5.Using IIS 6.0 compression feature you can have savings in monthly bandwidth charges.
6.You can reduce bandwidth by enabling compression, and serve more users with the same hardware.
7.You can delay or eliminate the need to add more Web servers by enabling IIS 6.0 compression, even when your site gets more traffic.
8.Management code for compression is now part of core IIS 6.0 Web server for speed and stability.
9.Server-side compatibility issues are resolved.
10.Granular compression allows turning compression on/off at the global, site, folder, and file levels.

What is State Management and what are the different ways to maintain a state in .Net?
Web pages are recreated each time a page is posted to a server. In traditional Web 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 Web programming, the ASP.NET page framework includes various options to help you preserve changes when Managing the State. The page framework includes a facility called view state that automatically preserves property values of the page and all controls on it between round trips.

However, you will probably also have application-specific values that you want to preserve. This can be done using state management options.

Client-Based State Management Options: View State Hidden Form Fields Cookies Query Strings
Server-Based State Management Options: Application State Session State Database Support

What server controls come with ASP.NET?
Server controls are supplied with ASP.NET. Server controls in ASP.NET are different to the normal windows controls as they work within the .NET FrameWork. The different types of server controls in ASP.NET are:

HTML Server Controls: These controls refer to the HTML elements that can be used in server code. The HTML elements can be converted into HTML server controls.
ASP.NET Server controls: ASP.NET server controls are the general controls like textbox, buttons, tables etc.
Validation Controls: these controls are used to validate user input. Normally these controls are attached with textboxes, checkboxes and radio buttons to check the values entered or selected.
USER Controls: These controls are those controls that are created by the user and are used just like all other controls.

What is the AdRotator control and it's uses?
AdRotator is a special control in ASP.NET used to display flashing banner advertisments. The control can display advertisments randomly or sequentially as set by the developer.

Using the AdRotator control
To use the control, drag it from the toolbox. In the properties window you will there are three key properties:

.AdvertisementsFile .KeywordFilter .Target

The advertisement file is an XML file which contains information about the image to be displayed and the page to which the user should be redirected on click.

The following example assumes there are two images named one.gif and two.gif. Below is the XML to correspond with our
example:




one.gif


http://www.codepedia.com


The Web's fastest growing technical encyclopdia


1


Visual Basic




two.gif


http://www.programmersheaven.com


Where the pro's are


1


Programming




The above tags are explained below:

: The image URL that presents the advertisement image.
: The on click redirect URL.
: Image description/name thats show when the mouse is over the image ( Optional use ).
: Optional parameter that specifies the keyword (category) like books, programming etc.
: A 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. Again, this is optional.

What is a Calendar control and how do I use it?
The Calendar control is used to display the calendar year on a web page. You can view dates or select a specific day, week or month. The default event of the Calendar control is Selection Changed event that is called when a selection is made on the control.

Drag a calendar control and a textbox from the toolbox. We will display the date selected from the calendar control in the textbox.
The sample code for that is:

Private Sub Calendar1_SelectionChanged (ByVal sender As System.Object, ByVal_
e As System.EventArgs) Handles Calendar1.SelectionChanged
TextBox1.Text = Calendar1.SelectedDat

End Sub

In Runtime Mode - Select a date from the calendar control. That date will now be the .Text Value of the textbox.

What is a RequiredFieldValidator control?
The RequiredFieldValidator is a control that checks whether the value of an assigned input control is different from its initial value.

To work with this control drag a RequiredFieldValidator control, Command Button and two TextBoxes from the Toolbox. The intention is to display the text entered in TextBox1 in TextBox2 when the Command Button is clicked. If there is no value in TextBox1, an error message ("Saying Textbox1 needs a value") will be spawned.

All you have to make the RequiredFieldValidator work is to open the properties of the control. Looking at two properties; ErrorMessage and ControltoValidate specifically. The ErrorMessage property should be completed with a warning that the field needs to be completed. Secondly, the ControltoValidate property is used to tag which control is to be validated.

The sample code for that is:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal_
e As System.EventArgs) Handles Button1.Click
TextBox2.Text = TextBox1.Text

End Sub

What is a CompareValidatorControl?
CompareValidator is used to make sure that a value matches a specified value. This control is often used when validating passwords. Important properties of this control are .ControlToValidate and .ControlToCompare.

.ControlTovalidate property is used to set the control to be validated and the
.ControlToCompare property is used to identify the control to be compared.

To work with this control drag a CompareValidatorControl, a Command Button and two TextBoxes from the ToolBox. The intention is to enter two values the textboxes. If the two values do not match, an error is generated denoting that the values are not alike.

Set the following control properties in CompareValidatorControl; .ControlToCompare property as TextBox1 and .ControltoValidate property as TextBox2.

Run the code and enter some text in both the textboxes and click the button. If both the TextBox values are the same then no error message will arise else an error.

What is a RangeValidator control?
A RangeValidator control is used to determine whether a control value falls within a specified range. The RangeValidator checks whether the value passed to the control is within the range specified. This type of watch dog is generally used when buying products online like tickets etc.

To work with the RangeValidator control, drag a TextBox and a RangeValidator Control from the toolbox. Open the RangeValidator control properties and enter a value of 8 in the MaximumValue field, 3 in the MinimumValue field and set TextBox1 as the control to be validated.

Run the code and try entering some values in the TextBox. If the value entered is within the specified range ( 8 High, 3 Low ) then nothing happens else an error message is displayed.

What is a RegularExpressionValidator?
RegularExpressionValidator control is used to check a value against a regular expression. It checks whether the value of the associated input control matches the pattern of the regular expression. This Control generally used to check whether the entered phone number or email address matches a set format. A notable property of this control is the ValidationExpression property, which is used to set the validation criteria and which comes with some predefined formats.

To work with a RegularExpressionValidator control; Drag a TextBox and a Command Button from the ToolBox. Our intention is to check for the format of an email address and display an error message if the input format is not correct. An example of a correctly formated inpput would be "xyz@programmersheaven.com". To implement format definition. In the properties window of the Regularexpression click on the ellipse button for ValidationExpression and select Internet E-mail Address from the pop-up window. When you run the program and enter a value not in the format of abc@xyz.com the error message is displayed.

What is the difference between a Web User Control and a Web Custom Control?
Web 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 ASP.NET server controls, including full support for Visual Studio design features such as the Properties window, the visual designer, and the Toolbox. There are several ways to create Web custom controls:

You can compile a control that combines the functionality of two or more existing controls. For example, if you need a control that encapsulates a button and a text box. You can create it by compiling the existing controls together.

If an existing server control almost meets your requirements but lacks some required features, you can customize the control by deriving from it and overriding its properties, methods, and events. If none of the existing Web server controls (or their combinations) meet your requirements, you can create a custom control by deriving from one of the base control classes. These classes provide all the functionality like other Web server controls. You only need to write the logic for the programming features you require.

If none of the existing ASP.NET server controls meet the specific requirements of your applications, you can create either a Web user control or a Web custom 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. Web user controls are easy to make, but they can be less convenient to use in advanced scenarios. Web user controls can be developed almost exactly the same way that you develop Web Form pages.

Like Web Forms, user controls can be created in the visual designer or they can be written with code separate from the HTML. They can also support execution events. However, since Web user controls are compiled dynamically at run time they cannot be added to the Toolbox and they are represented by a simple placeholder when added to a page.

This makes Web user controls harder to use if you are accustomed to full Visual Studio .NET design-time support, including the Properties window and Design view previews. Also 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.

Web custom controls are compiled code, which makes them easier to use but more difficult to create. Web custom controls must be authored in code. Once you have created the control you can add it to the Toolbox and display it in a visual designer with full Properties window support and all the other design-time features of ASP.NET server controls. In addition you can install a single copy of the Web custom control in the global assembly cache and share it between applications, which make maintenance easier.

Windows Forms

What are windows form applications?
Windows form applications are standard applications for Windows operating system having a user interface. A windows form application usually has one or more forms containing menus and other user interface controls like buttons, text boxes, tree view, etc. Windows form applications are like any other application on Windows except that it has its own Graphical User Interface (GUI). Common examples of windows form applications include Microsoft Word, Adobe Photoshop and Winamp. Windows form applications are event based, i.e., they perform certain operations on user action. For example, Microsoft Word saves the document into disk file only when you ask the application to do so (selecting File > Save).

How are the Windows form applications different from the Console Applications?
Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.

How are the Windows form applications different from the Console Applications?
Windows applications are facilitated with the Windows standard user interface controls (like button, text box, list box, picture box and etc) and the standard events of Windows operating system. On the other hand, the Console Application can only take user input and output from/to the Console, command or a shell window. Windows form applications are more responsive and may use a lot of features like shortcut and icons. On the other hand, console applications are light weight and are used for testing and background service type applications. Several Java based web servers are implemented on Windows using Console application.

What support does the Visual Studio.NET provide for the development of .NET win form applications?
Visual Studio.NET provides an enormous support for the development of Win Form applications. The key features of Visual Studio.NET IDE include:
The form designer allows you to design the User Interface (UI) of the applications by simple drag and drop of the controls.
The Properties window allows you to set different properties for form and a number of windows controls
The Intellisense (help completing the syntax as you place dot (.) with objects, enumeration and namespace and when you create new objects)
Project and solution management with solution explorer that helps manage applications consisting of multiple files, which is what usually happens
Standard debugger that allows you to debug your program by putting break points for observing run-time behavior of the variables and objects in the program
Hot compiler that checks the syntax of your code as you type it and report any errors present
Dynamic Help on number of topics using Microsoft Development Network (MSDN) Library
Compilation and building applications
Execution of your application with/without debugger
Deploying your .NET application over the Internet or on CDs

How do I make my first “Hello, WinForm” .NET form application using VS.NET and Visual C#?
C# Version Using Visual Studio.NET to build the “Hello WinForm” Application So we have had a lot of Visual Studio.NET introduction. Now, let’s use Visual Studio.NET IDE to build the “Hello WinForm” application which we created earlier in the lesson.
Creating a new Project First of all, we need to create a new C# Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen
[IMAGE1]
From the above screen, select ‘Visual C# Projects’ in Project types and ‘Windows Application’ in Templates. Write the name of the new project (‘LearningWinForm’ in the above figure) in the text box labeled Name. Select the disk path where you wish to store the project using Browse… Button and click OK. It will show you an empty form in the designer view similar to the figure below
[IMAGE2]
The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other windows may not be visible. You can change these settings using View menu as described earlier in the lesson.
Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pan, select View -> Properties Window). Now change the title of the form and the name of the form’s class in the code using Text and Form’s Name property respectively as shown in the following figure.
IMAGE3]
Adding Controls to the Form Now select the Label control from toolbox and place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to “Hello WinForm” and the Name property to ‘lblGreeting’. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from toolbox and place it on the form and resize it appropriately. Select (click) the button and set its Name property as ‘btnExit’ and Text property as ‘Exit’ from the properties window. The form should now look like
[IMAGE4]
Adding Event Handling Now, we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer. It will create a new event handler for the Exit button’s Click event and take you to the source code as shown in the following figure
[IMAGE5]
Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button’s Click event.
Executing the application That is it! The ‘Hello WinForm’ application is complete. To compile and execute the application, select Build -> Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5).
Author’s Note: Unfortunately, my copy of Visual Studio.NET 2001 does not change the name of form (from Form1 to MyForm in our case) in the call to Application.Run() method in the Main() method. I have to explicitly change the Main() method like this
static void Main()
{
Application.Run(new MyForm());
}
If you are also experiencing the same problem with your copy of Visual Studio.NET, make sure to change the name of the form in Main() method also whenever you change its name in the Properties Window in order to avoid the compilation error
This will compile and start the ‘Hello WinForm’ application in a new window as shown below
[IMAGE6]
To close the application, click the Exit button or the close button at the title bar of the window.
The code generated by the Form Designer You can toggle between Form Designer and Code using View -> Designer and View -> Code. After 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.

How do I make my first “Hello, WinForm” .NET form application using VS.NET and
Visual Basic.NET?

VB.NET Version Using Visual Studio.NET to build the "Hello WinForm" Application Let's use the Visual Studio.NET IDE to build the "Hello WinForm" application. Creating a new Project First of all, we need to create a new VB.NET Windows Application Project. For this, start Visual Studio.NET and click File -> New -> Project. It will show the following screen:
[IMAGE7]
From the above screen, select 'Visual Basic Projects' in Project types and 'Windows Application' in Templates. Write the name of the new project ('LearningWinForm' in the above figure) in the text box labeled Name. Select the location where you wish to store the project using the Browse... Button and click OK. It will show you an empty form in the designer view similar to the figure below: [IMAGE8]
The layout of the form designer screen may be somewhat different from the one shown above. Your toolbox and properties window may be visible and some other windows may not be visible. You can change these settings using the View menu as described earlier in the lesson.
Setting various properties of the form You can change the default properties of the form using the Properties window. For this, select (click) the form and select the properties window (If the properties window is not visible in the right hand pane, select View -> 'Properties Window). Now change the title of the form and the name of the form's class in the code by changing the Text and Name properties, as shown in the following figure.
[IMAGE9]
Adding Controls to the Form Now select the Label control from the toolbox, place it on the form and resize it as appropriate. Select (click) the label on the form and from the properties window, set its Text property to "Hello WinForm" and the Name property to 'lblGreeting'. The name of a control is the name of its corresponding instance in the source code. Now select the Button control from the toolbox, place it on the form and resize it appropriately. Select (click) the button and set its Name property to 'btnExit' and its Text property to 'Exit' using the properties window. The form should now look like this:
[IMAGE10] Adding Event Handling Now we need to add the event handling code for the Exit button. For this, simply double click the Exit button in the designer. This will create a new event handler for the Exit button's Click event and take you to the source code as shown in the following figure:
[IMAGE11] Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button's Click event. Executing the application That is it! The 'Hello WinForm' application is complete. To compile and execute the application, select Build ->Build Solution (or press Ctrl+Shift+B) and then select Debug -> Start Without Debugging (or press Ctrl+F5). This will compile and start the 'Hello WinForm' application in a new window as shown below:
[IMAGE12] To close the application, click the Exit button or the close button on the title bar of the window. The code generated by the Form Designer You can toggle between the Form Designer and Code using View -> Designer and View -> Code. After switching to the code, you will find the code generated by the form designer to be very similar to that we have written earlier in the lesson. To understand the code better, we recommend removing all the comments and region boundaries.

What is the architecture of .NET win form applications?

C# Version
WinForm Architecture As stated earlier, .NET provides WinForm and other controls through base classes in the System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .NET. In order to design a windows application, we need: 1. Create a Windows Application project in Visual Studio.NET or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use /reference option of the command line compiler to add these assemblies. 2. Write a new class to represent the WinForm and derive it from System.Windows.Forms.Form class as

class MyForm : System.Windows.Form
{
...
}

3. Instantiate various controls, set their appropriate properties and add these to MyForm’s Controls collection. 4. Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method by supplying it an instance of MyForm.

class Test
{
static void Main()
{
Application.Run(new MyForm());
}
}

The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.
VB.NET Version
WinForm Architecture As stated earlier, .NET provides the WinForm and other controls through base classes in the System.Windows.Forms namespace. The class System.Windows.Forms.Form is the base class of all WinForms in .NET. In order to design a windows application, we need to: 1.Create a Windows Application project in Visual Studio.NET, or add references to System.Windows.Forms and System.Drawing to your current project. If you are not using Visual Studio at all, use the /reference option of the command line compiler to add these assemblies. 2. Write a new class to represent the WinForm and derive it from the
System.Windows.Forms.Form class:

Public Class MyForm
Inherits System.Windows.Forms.Form

End Class

3. Instantiate various controls, set their appropriate properties and add these to MyForm's Controls collection. 4. Write another class containing the Main() method. In the Main() method, call the System.Application.Run() method, supplying it with an instance of
MyForm.

Class Test
Public Sub Main()
Application.Run(New MyForm())
End Sub
End Class

The Application.Run() method registers your form as a windows application in the operating system so that it may receive event messages from the Windows Operating System.


How do I make my first “Hello, WinForm” .NET form application without VS.NET in Visual C#?

C# Version
Building the “Hello WinForm” Application Let’s now build our first windows application called “Hello WinForm”. The application will present a simple window with “Hello WinForm” greeting at the center. The source code of the program is:

using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
class Test
{
static void Main()
{
Application.Run(new MyWindow());
}
}
class MyWindow : Form
{
public MyWindow() : base()
{
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);

Label lblGreeting = new Label();
lblGreeting.Text = "Hello WinForm";
lblGreeting.Location = new Point(100, 100);
this.Controls.Add(lblGreeting);
}
}
}

Understanding the Code
In the start, we included three namespaces to our application
using System;
using System.Windows.Forms;
using System.Drawing;
The System namespace, as we stated in the first lesson, is the necessary ingredient of all C# applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls like Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the useful classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in System.Drawing namespace.

Later, we derived a new class ‘MyWindow’ from the Form class defined in

System.Windows.Forms
class MyWindow : Form
{
...
}

In the constructor of MyWindow, we specified the size and title of the form. The size is defined using the System.Drawing namespace’s Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.

public MyWindow() : base()
{
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);

Next in the constructor, we created a text label and added it to the Controls collection of the Form. A text label is used to write some text on the form. The System.Windows.Forms.Label class is used to create a text label in windows applications. We set the text of the Label using its Text property which is of string type. All the controls contained by a form must be added to its Controls collection; hence we have also added our label to this collection.

public MyWindow() : base()
{
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);
Label lblGreeting = new Label();
lblGreeting.Text = "Hello WinForm";
lblGreeting.Location = new Point(100, 100);
this.Controls.Add(lblGreeting);
}

Finally, we have created a Test class containing the Main() method. In the Main() method, we have instantiated the MyWindow class and passed its reference to the Application.Run() method so it may receive messages from the Windows Operating System.

When we execute the above code, the following screen is presented as output
To close the application, press the close button on the title bar.

Adding Event Handling Let’s now add a button labeled ‘Exit’ to the form. The ‘Exit’ button will close the application when it is clicked. In .NET, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application

using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
class Test
{
static void Main()
{
Application.Run(new MyWindow());
}
}
class MyWindow : Form
{
public MyWindow() : base()
{
// Form
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);
this.StartPosition = FormStartPosition.CenterScreen;

// Label
Label lblGreeting = new Label();
lblGreeting.Text = "Hello WinForm";
lblGreeting.Location = new Point(100, 100);
// Button
Button btnExit = new Button();
btnExit.Text = "Exit";
btnExit.Location = new Point(180, 180);
btnExit.Size = new Size(80, 30);
btnExit.Click += new EventHandler(BtnExitOnClick);
// Adding controls to Form
this.Controls.AddRange(new Control[] {lblGreeting, btnExit});
}
public void BtnExitOnClick(object sender, EventArgs e)
{
Application.Exit();
}
}
}

In the constructor of MyWindow, first we have set certain properties of the Form. In this code, we have also used the StartPosition 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 ‘FormStartPosition’. We have set the start position of the form to the center of the screen.

The new inclusion in the code is the Exit button called ‘btnExit’. We have created the button using the base class System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection. Note that this time we have used AddRange() method of form class to add an array of controls to the Controls collection of form. This method takes an array of type Control as its parameter.

The output of the code will be
Now you can press either the Exit Button or the close button at title bar to exit the application.

How do I make my first “Hello, WinForm” .NET form application without VS.NET in Visual Basic.NET?

VB.NET Version
Building the "Hello WinForm" Application Let's build our first windows application, which we will call "Hello WinForm". The application will present a simple window with a "Hello WinForm" greeting at the center. The source code of the program is:

Imports System
Imports System.Windows.Forms
Imports System.Drawing
Class Test
Public Sub Main()
Application.Run(New MyForm())
End Sub
End Class
Class MyForm
Inherits Form
Public Sub New()
MyBase.new()
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)
Dim lblGreeting As New Label()
lblGreeting.Text = "Hello WinForm"
lblGreeting.Location = New Point(100, 100)
Me.Controls.Add(lblGreeting)
End Sub
End Class

Understanding the Code At the start, we included three namespaces in our application:

Imports System
Imports System.Windows.Forms
Imports System.Drawing

The System namespace, as we stated in the first lesson, is the necessary ingredient of all VB.NET applications. In fact, the Application class that we used later in the Main() method is defined in this namespace. The System.Windows.Forms namespaces contains the base classes for windows controls, e.g. Form, Label and Button. Finally, including the System.Drawing namespace is necessary as it contains the classes related to the drawing of controls. The Size and Point classes used later in the program are actually defined in the System.Drawing namespace. The System.Windows.Forms and System.Drawing namespaces can not be added to a project just by writing Imports statement for them. We also need to add references to the assemblies (for now take assemblies as Windows DLL’s or library files for .NET) that contain the code of types these namespaces. For this we need to add reference to System.Windows.Forms.dll and System.Drawing.dll. To add a reference write click the ‘Reference’ folder under the current project in the solution explorer and select Add Reference… It will show the following window
From the '.NET' tab of the Add Reference Dialog box, select the System.Windows.Forms.dll and System.Drawing.dll and select OK. This completes the process of adding references to assemblies in your project. Lets go back to our sample application. Later, we derived a new class, 'MyForm', from the Form class defined in

System.Windows.Forms.
Class MyForm
Inherits Form
...
End Sub
End Class

In the constructor of MyForm, we specified the size and title of the form (by setting the size and text properties). The size is defined using the System.Drawing namespace's Size class. We passed two integers to the constructor of Size to specify the width and the height of the form.

Public Sub New()
MyBase.new()
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)

Next in the constructor, we created a text label and added it to the Controls collection of the Form. A text label is used to write some text on the form. The System.Windows.Forms.Label class defines a text label in a Windows application. We set the text of the Label using its Text property, which is of the string type. All the controls contained by a form must be added to its Controls collection; hence we have also added our label to this collection.

Public Sub New()
MyBase.new()
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)
Dim lblGreeting As New Label()
lblGreeting.Text = "Hello WinForm"
lblGreeting.Location = New Point(100, 100)
Me.Controls.Add(lblGreeting)
End Sub

Finally, we have created a Test class containing the Main() method. In the Main() method, we have instantiated the MyForm class and passed its reference to the Application.Run() method so it may receive messages from the Windows Operating System. When we execute the above code, the following screen is displayed: To close the application, press the close button on the title bar.

Adding Event Handling Let's now add a button labeled 'Exit' to the form. The 'Exit' button will close the application when it is clicked. In .NET, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button's Click event. Below is the code for this application.

Imports System
Imports System.Windows.Forms
Imports System.Drawing
Class Test
Public Sub Main()
Application.Run(New MyForm())
End Sub
End Class
Class MyForm
Inherits Form
Public Sub New()
MyBase.new()
' Form
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)
' Label
Dim lblGreeting As New Label()
lblGreeting.Text = "Hello WinForm"
lblGreeting.Location = New Point(100, 100)
' Button
Dim btnExit As New Button()
btnExit.Text = "Exit"
btnExit.Location = New Point(180, 180)
btnExit.Size = New Size(80, 30)
AddHandler btnExit.Click, AddressOf BtnExitOnClick
Me.Controls.AddRange(New Control() {lblGreeting, btnExit})
End Sub
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs)
Application.Exit()
End Sub
End Class

In the constructor of MyForm, first we have set certain properties of the Form. In this code, we have also used the StartPosition 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 'FormStartPosition'. We have set the start position of the form to the center of the screen. The new inclusion in the code is the Exit button called 'btnExit'. We have created the button using the base class System.Windows.Forms.Button. Later, we have set various properties of the button, specifically its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also subscribed this event handler to the btnExit's Click event (To understand the event handling in VB.Net, see lesson 10 of the VB.Net school). In the end, we have added both the label and the button to the form's Controls collection. Note that this time we have used the AddRange() method of form class to add an array of controls to the Controls collection of form. This method takes an array of type Control as its parameter. When the code is run, the following window will be displayed: Now you can press either the Exit Button or the close button at title bar to exit the application.

Alternate procedure for Event Handling – Using the ‘Handles’ Keyword Note that in the previous code, we subscribed Exit buttons event handler using the ‘AddHandler’ keyword. We can also do this using the ‘Handles’ keyword with the Event Handler method. But to use the ‘Handles’ keyword, the Exit button needs to be instance variable of the form class defined with the ‘WithEvents’ keyword. The complete source code of the MyForm class is

Class MyForm
Inherits Form
' Form controls are usually private
' instance members of the form class
Private WithEvents btnExit As New Button()
Private lblGreeting As New Label()
Public Sub New()
MyBase.new()
' Form
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)
' Label
lblGreeting.Text = "Hello WinForm"
lblGreeting.Location = New Point(100, 100)
' Button
btnExit.Text = "Exit"
btnExit.Location = New Point(180, 180)
btnExit.Size = New Size(80, 30)
'AddHandler btnExit.Click, AddressOf BtnExitOnClick
Me.Controls.AddRange(New Control() {lblGreeting, btnExit})
End Sub
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
End Class

This procedure of event handling (using the ‘Handles’ keyword) is usually followed by Visual Studio.NET standard code for Form based applications (Windows and Web Applications)

How do I provide the event handling for my form and controls using VS.NET?

Adding Event Handling You 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. If you want to implement a default event handler of the form or control, simply double click it.

For example, to add the event handling code for the Exit button in the Hello WinForm application (demonstrated in FAQ 5), simply double click the Exit button in the designer. It will create a new event handler for the Exit button’s Click event and take you to the source code as shown in the following figure

C# Version
Write the code to close the application (Application.Exit()) in the event handler. The IDE in fact has not only created the event handler but also has registered it with the Exit button’s Click event.

How event handling is implemented in win form and .NET form controls with C#?C# Version
Adding Event Handling A control exposes an event by defining its delegate. We can add our own event handler for the event by writing an event handler method and adding it to the event’s delegate.

For example, add a button labeled ‘Exit’ to the form of FAQ 8. The ‘Exit’ button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button’s Click event. Following is the code for this modified application

using System;
using System.Windows.Forms;
using System.Drawing;
namespace CSharpSchool
{
class Test
{
static void Main()
{
Application.Run(new MyWindow());
}
}
class MyWindow : Form
{
public MyWindow() : base()
{
// Form
this.Text = "My First Windows Application";
this.Size = new Size(300, 300);
this.StartPosition = FormStartPosition.CenterScreen;
// Label
Label lblGreeting = new Label();
lblGreeting.Text = "Hello WinForm";
lblGreeting.Location = new Point(100, 100);
// Button
Button btnExit = new Button();
btnExit.Text = "Exit";
btnExit.Location = new Point(180, 180);
btnExit.Size = new Size(80, 30);
btnExit.Click += new EventHandler(BtnExitOnClick);
// Adding controls to Form
this.Controls.AddRange(new Control[] {lblGreeting, btnExit});
}
public void BtnExitOnClick(object sender, EventArgs e)
{
Application.Exit();
}
}
}

We have highlighted the interested parts in the above code by bold formatting. We have created the Exit button called ‘btnExit’ using the class
System.Windows.Forms.Button. Later, we set various properties of the button like its text label (Text), its Location and its Size. Finally, we have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also registered this event handler to the btnExit’s Click event (To understand the event handling in C#, see lesson 10 of the C# school). In the end, we have added a label and button to the form’s Controls collection.

The output of the code will be
Now you can press either the Exit Button or the close button at title bar to exit the application.

How event handling is implemented in win form and .NET form controls with VB.NET?

VB.NET Version
Adding Event Handling A control exposes an event by defining its ‘delegate’. We can add our own event handler for the event by writing an event handler method and adding it to the event's delegate. Let's add a button labeled 'Exit' to the form. The 'Exit' button will close the application when it is clicked. In .Net, Push Buttons are instances of the System.Windows.Forms.Button class. To associate some action with the button click, we need to create an event handler and register (or add) it to the Button's Click event. Below is the code for this application.

Imports System
Imports System.Windows.Forms
Imports System.Drawing
Class Test
Public Sub Main()
Application.Run(New MyForm())
End Sub
End Class
Class MyForm
Inherits Form
Public Sub New()
MyBase.new()
' Form
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)
' Label
Dim lblGreeting As New Label()
lblGreeting.Text = "Hello WinForm"
lblGreeting.Location = New Point(100, 100)
' Button
Dim btnExit As New Button()
btnExit.Text = "Exit"
btnExit.Location = New Point(180, 180)
btnExit.Size = New Size(80, 30)
AddHandler btnExit.Click, AddressOf BtnExitOnClick
Me.Controls.AddRange(New Control() {lblGreeting, btnExit})
End Sub
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs)
Application.Exit()
End Sub
End Class

The interesting lines defining the event handler for the button is highlighted with bold formatting. We have created an event handler method for this button called BtnExitOnClick(). In the BtnExitOnClick() method, we have written the code to exit the application. We have also subscribed this event handler to the btnExit's Click event (To understand the event handling in VB.NET, see lesson 10 of the VB.NET school). Now you can press either the Exit Button or the close button at title bar to exit the application. Alternate procedure for Event Handling – Using the ‘Handles’ Keyword Note that in the previous code, we subscribed Exit buttons event handler using the ‘AddHandler’ keyword. We can also do this using the ‘Handles’ keyword with the Event Handler method. But to use the ‘Handles’ keyword, the Exit button needs to be instance variable of the form class defined with the ‘WithEvents’ keyword. The complete source code of the MyForm class is
Class MyForm
Inherits Form
' Form controls are usually private
' instance members of the form class
Private WithEvents btnExit As New Button()
Private lblGreeting As New Label()
Public Sub New()
MyBase.new()
' Form
Me.Text = "My First Windows Application"
Me.Size = New Size(300, 300)
' Label
lblGreeting.Text = "Hello WinForm"
lblGreeting.Location = New Point(100, 100)
' Button
btnExit.Text = "Exit"
btnExit.Location = New Point(180, 180)
btnExit.Size = New Size(80, 30)
'AddHandler btnExit.Click, AddressOf BtnExitOnClick
Me.Controls.AddRange(New Control() {lblGreeting, btnExit})
End Sub
Public Sub BtnExitOnClick(ByVal sender As Object, ByVal e As EventArgs) Handles btnExit.Click
Application.Exit()
End Sub
End Class

Note that the button is now instantiated with the ‘WithEvents’ keyword and the event handler is specifically marked with the ‘Handles’ keyword to qualify it as an event handler method. This procedure of implementing event handling (using the ‘Handles’ keyword) is usually followed by Visual Studio.NET standard code for Form based applications (Windows and Web Applications)

What are the lifetime events of a form?
Some important lifetime events of a form include:
Load: This event is fired when the form is first loaded in the program. It is called when the Form.Show() or Form.ShowDialog() method is called for the first time.
Activated: This event is triggered whenever the form gets the application focus. It is fired when the form is first loaded (along with Load event), when the form is brought in front, or when the form is restored from the minimized state.
VisibleChanged: It is called whenever the Visible property of the form is changed or the form is hidden or shown.
Deactivated: This event is triggered whenever the form loses the application focus. It is fired when the form is closed, when the form is brought into background, or when the form is minimized.
Closing: It is fired when the application wishes to be closed, or the application is in the process of close but has not yet closed.
Closed: It is raised when the application is finally closed.

How do I change the title of my window?
Use the Text property of the Form to change the title of the form.

How do I change the application name?
To change the application name, change the name of the startup project by right clicking the project node in the solution explorer and selecting properties. It will show the property pages for the project. Here in the Common Properties -> General, you can change the assembly name to change the resulting executable (.exe) file name.

How do I set the startup position of the form?
To change the startup position of the form, select the form in the designer and change its StartPosition property. The StartPosition is an enumeration and has the following useful properties:

CenterScreen: The form should be displayed at the center of the screen
WindowsDefaultLocation: The form's startup position should be selected by the Windows Operating System
CenterParent: The form should be displayed at the center of the parent form. This option is useful when you are building an MDI (Multiple Document Interface) application. The MDI child form can be set, in this way, to be displayed at the center of the MDI parent form.

How do I set the initial (startup) size of the form?
The size property can be used to set the startup size of the form. The data type of the size property is System.Drawing.Size. The size can be set as:

C# Version
myForm.Size = new System.Drawing.Size(400, 300);
VB.NET Version
myForm.Size = New System.Drawing.Size(400, 300)
What does it mean by Startup Window State of the form? How do I set the startup

window state of the form?
The startup window state specifies whether the form should be displayed in normal, maximized or minimized state. It can be set using the WindowState property of the form. The data type of this property is System.Windows.Forms.FormWindowState enumeration, which has three members; Maximized, Minimized and Normal.

C# Version
myForm.WindowState = FormWindowState.Maximized;
VB.NET Version
myForm.WindowState = FormWindowState.Maximized

How do I hide my form?
You can hide your form or any other control by setting its Visible property to False.

C# Version
myForm.Visible = False;
VB.NET Version
myForm.Visible = False

How do I show my form?
You can show your hidden form or any other control by setting its ‘Visible’ property to True.

C# Version
myForm.Visible = True;
VB.NET Version
myForm.Visible = True

You can also display your form for the first time using the Show() or the ShowDialog() methods of the form class. The Show() method displays the form in Non-Modal fashion, while the ShowDialog() method displays the form in Modal mode. See the following FAQs for the description of Modal and Non-Modal forms

What is the difference between modal and non-modal dialogs?
The modal form, when displayed on the screen, does not allow you to go and select any other form of the window. The typical example of the Modal form is the Message Box; you must select OK (or other appropriate) button to go back to other forms of the applications.

The Non modal form, on the other hand, does not prevent you from accessing other form windows of the application, when they are present on the screen using the Show() method of the form.

C# Version
myForm.Show();
VB.NET Version
myForm.Show()

By default, all the forms are Non-modal.

How do I show my form as a modal dialog?
To show your form as the Modal dialog, call the ShowDialog() method of the form to display it on the screen.

C# Version
myForm.ShowDialog();
VB.NET Version
myForm.ShowDialog()

It 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.

How do I minimize, maximize and restore my form programmatically?
You can minimize, maximize and restore the form by setting the WindowState property of the form. The following code example will minimize the form, wait for 2 seconds, restore the form, wait for 2 seconds and then maximize the form. I have written this code on the a button’s Click event.

C# Version
private void button1_Click(object sender, System.EventArgs e)
{
// Minimize the form window
this.WindowState = FormWindowState.Minimized;
Thread.Sleep(2000); // wait for 2 seconds
// Restore the form window
this.WindowState = FormWindowState.Normal;
Thread.Sleep(2000); // wait for 2 seconds
// Maximize the form window
this.WindowState = FormWindowState.Maximized;
}
VB.NET Version
Private Sub Button1_Click(ByVal sender As System.Object, _
ByVal e As System.EventArgs) _
Handles Button1.Click
' Minimize the form window
Me.WindowState = FormWindowState.Minimized
Thread.Sleep(2000) ' wait for 2 seconds
' Restore the form window
Me.WindowState = FormWindowState.Normal
Thread.Sleep(2000) ' wait for 2 seconds
' Maximize the form window
Me.WindowState = FormWindowState.Maximized
End Sub

Note that the above code snippet is using the System.Threading.Thread class’ Sleep method to suspend the form for 2 seconds. Hence, you would be required to include the System.Threading namespace to your form class source code.

C# Version
Using System.Threading;
VB.NET Version
Imports System.Threading

How do I hide maximize, minimize and close box at the form title bar?
To disable the maximize box at the form title bar, set the Maximize property of the form to false.
To disable the minimize box at the form title bar, set the Minimize property of the form to false.
You can not hide only the close box from the form title bar using the form’s property.

Similarly, you can not only hide maximize or minimize boxes from the title window.
You can hide maximize and minimize boxes from the title bar by setting the FormBorderStyle property of the form to the FixedToolWindow or the SizableToolWindow. But remember that with FormBorderStyle set to the FixedToolWindow or SizableToolWindow, the form will not be displayed in the Windows task bar or in the window that appears when the user presses ALT+TAB.

You can hide the Control box from the title bar of the form by setting the ControlBox property of the form to false. This will hide the control box and system menu from the form window.

How do I make my form non-resizable or fixed length?
You can make your form non-resizable or fixed length by setting its FormBorderStyle property to Fixed3D or FixedSingle or FixedDialog

How do I change the icon of my form to be displayed at title bar?
You can change the icon of the form by changing its icon property. Remember that this property will only change the icon of the form and not of the application. To change the icon of the application or assembly, change the icon from the property pages of the project. The property pages for the project are displayed when you right click the project and select properties.

How do I make my form not to appear in the task bar?
To make your form not to appear in the task bar, set the ShowInTaskbar property of the form to false.

How do I make and display a form without title bar?
To display your from without the title bar, set the FormBorderStyle property of the form to None

How do I close the form programmatically?
To close the form programmatically, call the Close() method of the form.

C# Version
myForm.Close();
VB.NET Version
myForm.Close()

Remember that this will only close the form and not the application. To close or exit the application, call the Application.Exit() method.

How do I exit my win form application programmatically?
To exit the win form application programmatically, call the Application.Exit() method.

C# Version
Application.Exit();
VB.NET Version
Application.Exit()

How do I display a message box in my form application?
To show the message box, call the MessageBox class’ Show() method. The message box is the modal form that notifies the user about certain event in the application and optionally takes the user feedback. The Show() is an static (C#) / Shared (VB.NET) method of the System.Windows.Forms.MessageBox class. It has a number of overloaded versions. The simplest one take the message text and display it in the message box.

C# Version
MessageBox.Show("Welcome to Win Form");
VB.NET Version
MessageBox.Show("Welcome to Win Form")

To add the title to the message box, call the MessageBox.Show() like:
C# Version
MessageBox.Show("Welcome to Win Form", "Greeting");
VB.NET Version
MessageBox.Show("Welcome to Win Form", "Greeting")

The following example code shows the message box with Yes, No, Cancel button to confirm application close and closes the application if the user selects the Yes button

C# Version
DialogResult dlgRes = null
dlgRes = MessageBox.Show(
"Are you sure you want to close without saving the document",
"Confirm Document Close",
MessageBoxButtons.YesNoCancel,
MessageBoxIcon.Question);
if(dlgRes == DialogResult.Yes)
{
Application.Exit();
}
VB.NET Version
Dim dlgRes As DialogResult
dlgRes = MessageBox.Show( _
"Are you sure you want to close without saving the document", _
"Confirm Document Close", _
MessageBoxButtons.YesNoCancel, _
MessageBoxIcon.Question)

If dlgRes = DialogResult.Yes Then
Application.Exit()
End If

How do I add another form into my win form application?
To add and design a new form at design time, right click the target project node in the Solution Explorer and select AddàAdd Windows Form… This will add a new form; design it by placing controls and setting necessary properties.

To show the new form at run time, instantiate the new form and call its Show() or ShowDialog() method.

Let we name the new form as ‘MySecondForm’, then on the click event of the button of our first (startup) form, we can write the following code:

C# Version
MySecondForm frm2 = new MySecondForm();
frm2.Show(); // will present the non-modal form

// frm2.ShowDialog(); // will present the modal form
VB.NET Version
Dim frm2 As New MySecondForm()
frm2.Show() ' will present the non-modal form

' frm2.ShowDialog() 'will present the modal form

How do I set the first form to be loaded at application startup?
The first form to be loaded at the application startup is called the startup or main form of the application. You can set the startup form of the application by right clicking the target project node and selecting properties. It will show you the property pages for the project. Here in the Common PropertiesàGeneral, you can set the startup form by selecting its name from the drop down list of ‘Startup Object’.

C# Note
Remember that only those forms that have a valid Main() method can be selected as the startup object.

What does it mean by scrollable forms in .NET? How can make my own form scrollable?
.NET introduces with it a concept of scrollable forms. A scrollable form is just like an html page that can be scrolled. You can access its controls by scrolling it down or right; if the contents (controls) don’t fit in the form display area.
You can make a form scrollable by setting its AutScroll property to true

How do I make a splash screen in my win form application?
There is no built-in support for the splash screen in the Microsoft.NET win form applications. However, you can create a splash screen by creating a form with no title bar (by setting its FormBorderStyle to None), making it not appear in the taskbar (by setting its ShowInTaskbar property to false), making it the top most form (by setting) its TopMost property to true, and making it appear on the center of the screen (by setting its StartupPosition as CenterScreen).

You can now show this splash form when the main application is loading.

C# Version
private void Form1_Load(object sender, System.EventArgs e)
{
this.Hide();
Form2 frmSplash = new Form2();
frmSplash.Show();
frmSplash.Update();
Thread.Sleep(5000);
frmSplash.Close();
this.Visible = true;
}
VB.NET Version
Private Sub Form1_Load(ByVal sender As System.Object, _
yVal e As System.EventArgs) Handles MyBase.Load

Me.Hide()
Dim frmSplash As New Form2
frmSplash.Show()
frmSplash.Update()
Thread.Sleep(5000)
frmSplash.Close()
Me.Visible = True
End Sub

What basics should be remembered while developing win form apps?
Some Important Points for designing Windows Applications
Make your form layout simple and easy to understand. It is important that the user of your application finds it familiar. The behavior should be expected and should not surprise the user.

The Format menu of the Visual Studio.NET IDE is very useful when designing the form layout. It provides a number of useful options for alignment and size of the controls.

Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard.

Usually we don't change the Name property of labels as we don’t need to use the label variable in our code most of the time.

The controls should be named so that their purpose can be recognized, e.g., you may name the ‘Purchase’ button as btnPurchase, text box for entering email may be txtEmail and so on.

Although now it is not a standard convention, but it is useful to add a three letter prefix to the name of your controls so that they are recognizable with their name. Most of the developers used to follow the convention like prefixing Label with lbl (lblGreeting), TextBox with txt (txtComments), Button with btn (btnPurchase), CheckBox with cbx (cbxProgCS), RadioButton with rbn (rbnFullPayment) and GroupBox with gbx (gbxPaymentMode).

How do I change the icon of the application I am working with?
Changing the Icon of your application is simple. Select Project->Properties. In the windows "style" section click on the "Icon" Button. Then make your choice.

How do I prevent a user from resizing a form?
The following code shows how a Form's size can be restricted at runtime.
Place the following code in the load event of the form.

Public Class Form2
Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
Private Sub Form2_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Me.MaximizeBox = False
End Sub
End Class

Controls

What are win form controls? How they are represented in .NET framework class library?
A form may contain various user interface (UI) controls. The controls represent the visual components that allow user to interact with the application and perform the desired task. All the controls, in .Net, are represented by subclasses of System.Windows.Forms.Control class. Each form has a collection (named ‘Controls’) to store the constituent controls of the form. In fact, a form itself is a special type of control called Container Control, i.e., the Form class itself is derived from the ContainerControl class which is a subclass of the Control class. A container control, as the name suggests, may contain other controls. Other examples of the Container control include Panel and Tab Control.

Each control, and thus form, exposes a number of events that can be triggered on certain user action or application behavior. For example, a button raises Click event whenever it is clicked and the text box raises the TextChanged event whenever its text is changed. The application developer can write even handler to catch these events and perform corresponding action. Beside these, a form also has certain set of events called the form life cycle events. These events are triggered during the life cycle of form to indicate the current state of the form.

What are the fundamental and common properties of .NET controls?
Almost all the controls have some similar properties like Location, Size, Enabled, Visible, TabIndex, Name, Text, BacKColor, ForeColor, Font, etc. The TabIndex property is very important. It describes the sequence followed by the windows focus when the user presses the Tab button of keyboard

How do I set the tab order of the controls on the form?
To set the tab order of the controls on the form, select View -> Tab Order. This will start a wizard for setting the tab order. You can set the order of tab for the control by just clicking it in the same sequence as of required tab order.

What does it mean by anchoring of controls?
An anchoring is the property of the control to keep a specific distance with a particular edge of the window (or other containing control). You can anchor a control to any edge or side of the window, e.g., left, top, right, bottom, left and top, etc. If a control is anchored to the left of the window, it will keep the constant distance from the left side of the window; even when the window is resized. The constant distance that the control will keep with the window is the distance it has at the form startup or defined by its Location property. In the figure below, the button is anchored to the top edge of the window.

When the window is resized, it shifts itself on the form to keep the same distance from the top, see the figure below:

If we have defined the top and bottom anchoring and the form is resized, the control will resize itself to have the same distance from top and bottom. Consider the figure below; here the button is anchored top and bottom

When the form is resized, the button resizes itself to keep the same distance from top and bottom

The default anchoring of a control is left and top.

How do I set the anchoring property of my controls?
To change the anchoring property of the control, set the Anchor property of the control from the properties window. When you click the Anchor property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to anchor the control

What does it mean by docking of controls?
Docking is the property of the control to attach itself to a particular edge of the window (or other containing control). You can either dock a control to an edge or to fill the available space in the parent control or window. Common examples of docking includes menu bar and toolbars which dock themselves at the top of the window so that they may remain at top regardless of the size and of the window.

When the control is resized, the control remains stuck to the top of the window

(Does it remind you the famous outlook bar?)

You can define a control to have a fill dock property so that it may fill all the available space in the parent window or parent control. In the figure below, we have docked the tree view control at left and the list view control with fill docking property

When the form is resized, the tree view will remain at left (changing only its height and not width) while the list view will expand itself to the rest of the available space on the form

(Does it remind you the famous Windows Explorer?)

A control is not docked to any edge, by default.

How do I set the docking property of my controls?
To change the docking property of the control, set the Dock property of the control from the properties window. When you click the Dock property of the control in the properties window, Visual Studio.NET will show you a tab to set the edges with which you wish to dock the control

How do I set the width of a ComboBox to fit the contents?
Move through the index items to find the longest item by character length using the MeasureString function. Use the this value as the ComboBox width.
System.Drawing.Graphics g = comboBox1.CreateGraphics();

float maxWidth = 0f;

foreach(object o in comboBox1.Items)

{

float w = g.MeasureString(o.ToString(), comboBox1.Font).Width;
'checking the combobox for the longest text
if(w > maxWidth)
maxWidth = w;
'setting the width by checking the longest text
}
g.Dispose();
comboBox1.Width = (int) maxWidth

How do I set the color and font in a RichEditBox?
Use the SelectionFont and SelectionColor properties to set the font and color of a RichEditBox. The following code will set the "selected text" to a blue-italic-verdana font set.

Note. If no text is selected then any all new text will be blue-italic-verdana within the RichEditBox.

RichTextBox1.Focus();

RichTextBox1.SelectionColor = Color.Blue;

RichTextBox1.SelectionFont = new Font ("Verdana", 12, FontStyle.Italic);

How do I browse and read a text file into a TextBox?
You use the OpenFileDialog to implement this functionailty.

using System.Text;
using System.IO;
private void button1_Click(object sender, System.EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open the text file you wish" ;
ofd.InitialDirectory = "c:\" ;
ofd.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;

if(ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = File.OpenText(ofd.FileName);
string s = sr.ReadLine();
StringBuilder sb = new StringBuilder();
while (s != null)
{
sb.Append(s);
s = sr.ReadLine();
}
sr.Close();
textBox1.Text = sb.ToString();
}
}

How to use the Splitter control?
The Splitter control is used to resize 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).

How do I place restriction when entering some text in a textbox?
You can restrict a user from entering text against a set pattern. Or you can request the user only to enters certain type of
characters. E.g. Only a single digit number or a double digit number and so on. To control the input, use the KeyPress event like below:

Private Sub TextBox1_KeyPress(ByVal sender As Object,ByVal e As _ System.Windows.Forms.KeyPressEventArgs) Handles
TextBox1.KeyPress
If(e.KeyChar < "10" Or e.KeyChar > "100") Then
MessageBox.Show("Enter Double Digits")
End If
End Sub

How do I access controls on another Form?
To access controls on other WinForms follow the example. This example reads the text in a textbox from other form and displays it in the textbox on the current form.

Open two forms (form1 and form2), add a Command Button and a Textbox to Form1 and a Textbox to Form2.

The following code relates to form1.

Public Class Form1
Inherits System.Windows.Forms.Form
Dim NewWindow As New Form2()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
NewWindow.Show()
End Sub

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
TextBox1.Text = NewWindow.TextBox1.Text
End Sub
End Class

When you run the code, Both

How can I access a Website/Webpage with a VB.NET LinkLabel control?
To access a Website or a Webpage using a VB.NET application. Drag a LinkLabel control and write the following code in it’s click event.

Private Sub LinkLabel1_LinkClicked(ByVal sender As System.Object, ByVal e As
System.Windows.Forms.LinkLabelLinkClickedEventArgs)Handles_
LinkLabel1.LinkClicked
System.Diagnostics.Process.Start("www.yahoo.com")
End Sub

Upon running the application,click on the Text on the LinkLabel. The website, Yahoo.com will open in a new browser.

How do I add items to a ComboBox and sort them?
The following code shows how to add items to a ComboBox.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
ComboBox1.Items.Add(“India”)
ComboBox1.Items.Add(“Australia”)
ComboBox1.Items.Add(“Sweden”)
ComboBox1.Items.Add(“Spain”)
ComboBox1.Items.Add(“England”)
ComboBox1.Items.Add(“United States”)
ComboBox1.Items.Add(“Russia”)
ComboBox1.Items.Add(“China”)
ComboBox1.Items.Add(“Japan”)
ComboBox1.Items.Add(“New Zeland”)
End Sub

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

How do I load a picture into the PictureBox control?
To load a Picture into the PictureBox control drag a PictureBox control and a Command Button from the Toolbox. When you click the Command Button, the picture you specified will be loaded into the Picturebox.

The following code is a demonstration.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
PictureBox1.Image=Image.FromFile("C:\images\image.gif")
'Assuming you have a folder named images in C: drive and a gif image in that
End Sub

How do I add a control to windows form at runtime?
To add a control to a Form at Runtime, firstly decide which control is needed. Set all relevent properties and finally use the Controls.Add(controlname) function.
An an example of how to add a TextBox:

Dim tb as TextBox = New TextBox()
'declaring a textbox
tb.Size = New Size(130, 25)
'setting the size for the textbox
tb.Location = New Point( 50, 70)
'setting the location
tb.Text = "Textbox1"
'setting the text
Me.Controls.Add(tb)
'adding the textbox to the form

How to create an "Explorer style" application in VB.NET?
Displaying all the drives, folders and files in an application like "Explorer" can be done easily in VB.NET. To do this follow these simple instructions:
Open a new project Add a Command Button to the Form. Place the following code in the click event of the command button.

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As _ System.EventArgs) Handles Button1.Click
Dim expl As New ExplorerStyleViewer()
expl.Show()
End Sub

What is a Tooltip control and how should I use it?
A Tooltip is a tag that displays some text when an ojects Mouse Over event is triggered. This is usually a decription of the object or the action that will follow if the object is say for example clicked.

Assume that there is a TextBox on a Form and we want to display a description when the mouse is over the TextBox.
Below is an example:

Private Sub Form5_Load(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles MyBase.Load
ToolTip1.SetToolTip(TextBox1, "Enter Some text")
'using the SetToolTip method to set the tip for the TextBox and the text that should appear
End Sub

XML

How do you test if an attribute exists in the xml document?

String Value="";
if (Node.Attributes["Attribute1"] == null)
{
// doesn't exist
Value="";
}
else
{
// exists
Value=Node.Attributes["Attribute1"].Value.ToString();
}


Visual studio .net

What is Visual Studio.NET?
Microsoft Visual Studio.NET is an integrated development environment which is the successor of Microsoft Visual Studio 6. It eases the development process of .NET Application to great deal for Visual C#.NET, Visual Basic.NET, Visual C++.NET, Visual JScript.NET, Visual J#.NET, ASP.NET, etc The revolutionary approach in this new Visual Studio.NET is that for all the Visual Studio.NET Compliant Languages there is a single IDE, debugger, project and solution explorer, class view, properties tab, tool box, standard menu and toolbars. The key features of Visual Studio.NET IDE include:

Keywords and syntax highlighting

Intellisense (help completing the syntax as you place dot (.) with objects, enumeration and namespace and when you create new objects)

Project and solution management with solution explorer that help manage applications consisting of multiple files, which is what usually happens

Help building user interface with simple drag and drop over the form window

Properties tab that allows you to set different properties on a number of windows and web controls

Standard debugger that allows you to debug your program by putting break points for observing run-time behavior of the variables and objects in the program

Hot compiler that checks the syntax of your code as you type it and report any errors present

Dynamic Help on number of topics using Microsoft Developer Network (MSDN) Library

Compilation and building applications

Execution of your application with/without debugger

Deploying your .Net application over the Internet or on CDs

Why use the IDE when we can develop a .NET application for free?
The basic purpose of using the Visual Studio.NET or any IDE is to manage the application code. As the requirements and thus application evolves, the size of code increases. It 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 required functionality. This is where the Integrated Development Environment (IDE) comes!

An IDE helps manage the application by assisting you to break your application into projects, separate files and grouping the files into folders. For example if you are developing an accounts management system, you may break it into three projects;

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 project to three folders;

first (Forms) containing user interface forms
second (AccountsAccessor) containing classes to interact with the accounts implementation project
third (StorageAccessor) containing classes to interact with the information storage project

Apart from this, an IDE also provide its support from the start of development to the creation of final installation. It provides an intelligent text editor that recognizes various parts of your code and also highlights the possible errors as you type it. It helps you in compiling and testing individual projects and also the complete application. It provides an integrated debugger to identify the bugs in your program and the possible cause of them. One of the most appealing features of an IDE like Visual Studio.Net is that it provides designers for various tasks like Windows Application User Interface designing, Web form designing and the database connection with simple drag and drop and setting a few properties. Once you have completed the application development and tested it through debugger, the IDE also helps you in building its installation program so that the application can be shipped to the client. Hence, an IDE supports developers throughout the life cycle of the application.

Is there any other IDE available for the development of .NET programs?
Fortunately, there are a number of IDE’s and source code editors available for the development of .Net programs. Some of these are introduced below:

Borland C#Builder for the Microsoft? .NET Framework http://www.borland.com/csharpbuilder/ Borland C# Builder is perhaps the second most popular IDE for development with C# programming language after Visual Studio.Net. According to Borland, “It is an integral component of the Borland solution for application lifecycle management, C#Builder accelerates the delivery of .NET Framework solutions with a design-driven approach to development that increases team productivity. C#Builder provides support for direct interoperability between the .NET Framework, the J2EE? platform, and CORBA? infrastructure, helping to simplify and reduce the cost of integrating .NET solutions with your existing software systems. And for faster, easier, and more flexible database development, C#Builder delivers high-performance native support for major enterprise-class databases.”

#develop (read as Sharp-Develop) http://www.icsharpcode.net/OpenSource/SD/ It is a free IDE for C# and VB.NET projects on Microsoft's .NET platform. It is open-source (GPL), and you can download both source code and executables from there site. In addition, you can find the latest information and changes on #develop, as well as get in touch with the team in the forum.



PrimalCode http://www.sapien.com/primalcode.htm PrimalCode is an innovative .NET development environment incorporating complete capability in a compact size that works with your existing hardware. Ideal for professional coders, PrimalCode streamlines every .NET project phase, from start-up to deployment. You can work faster, free from hours of repetitive and routine tasks. Best of all, PrimalCode needs only minimal drive space, so it runs full speed on your existing desktops or laptops.

What are the different parts and areas of Visual Studio.NET IDE's called?
The figure below highlights various parts of the Visual Studio.NET IDE.



You can see the toolbox window at the left hand side (#1) and the properties window at the right hand side (#2) of the above snapshot. The toolbox allows you to add different controls to your form. Once the control is placed on the form, you can change its various properties from the Properties window. You can also change the location and size of the controls using the mouse. Event properties can be changed by switching to the Event Properties panel (#3) in the Properties Window. The Toolbox, Properties Window, Help Window, Solution Explorer Window, Class View Window, Output Window and other helping windows in Visual Studio IDE can be set for Docking and Auto hiding. Windows 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. A window can be set for auto hide by the button marked #4 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 #5 in the above figure and has got the class view, help and solution explorer windows in the hidden state. If some of these windows are not visible in your visual studio IDE, you can make them visible from the View menu on the standard menu bar.

Solution Explorer

The solution explorer presents the hierarchical view of the projects included in the current solution. It presents the detailed view of the individual projects with the contained source code files (which may be grouped into some folders), the references to the assemblies (projects or library code) used by the project and any other resource files like icons, pictures, sounds, animation, etc.

The solution explorer does not only present the view of the solution hierarchy but also allows you to customize the solution or projects settings. It allows you to add and remove existing and new projects to the solutions, add and remove the references and resource files. It also allows you to change the name of the solution, projects, folders and files, their build options, output file names and things like that.



Toolbox, Properties and Class View Tabs
Now there is a single toolbox for all the Visual Studio.NET’s languages and tools. The toolbox (usually present on the left hand side) contains a number of common controls for windows, web and data applications like text box, check box, tree view, list box, menus, file open dialog, etc.

Properties Tab (usually present on the right hand side in IDE) allows you to set the properties on different controls and form without getting into code

Class View Tab shows all the classes that your project contains along with the methods and fields in tree hierarchy. This is similar to VC++ 6’s class view.

Menus in the Visual Studio .NET IDE
File Menu: Used to create, open, save and close the project, solution or individual source files.
Edit Menu: Used for text editing and searching in the Visual Studio source code editor.
View Menu: Provides options for setting the visibility of different Visual Studio windows and to switch between code and designer views.
Project Menu: Used for setting different properties of the Visual Studio Project. A Visual Studio project is a collection of files that make up a single assembly or a single object file (we will explore the concept of assemblies in coming lessons).
Build Menu: This menu is used to compile and build the source file, project or solution. The result of a build is an executable file or a code library.
Debug Menu: This menu provides various options related to the Visual Studio.Net Debugger. Debugging is the process of finding logical errors in the program, and a debugger helps make this proccess easier.
Data Menu: Provides various options for Data Access in .Net
Format Menu: Provides access to a set of useful operations for formatting the controls and their layout in the Form Designer view.
Tools Menu: Provides the access to various useful Visual Studio.NET tools.

Form Designer The Visual Studio.NET form designer allows you to design the windows and web forms for your application’s user interface. It simplifies the task by allowing you to just drag and drop the required controls from the toolbox to the designer’s emulated form. It even sets the default properties for your controls. You can then change the properties of the form and control through the Properties Tab of the Visual Studio.NET IDE. The form designer also allows you to attach the even handlers with the controls.

Code Editor
The Visual Studio.NET Code Editor supports you in writing the code for your application. The code editor is tightly integrated with the designers. As you change the properties and add controls, the designer puts the required code in you application source code files which can be viewed using the code editor. The code editor is quite smart; it highlights the various categories of the code like keyword, constant and even the syntax and semantic errors. It provides the code completion through its intellisense; when you place dot (in C# and VB.NET) with your object 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 VS.NET solutions and projects?
A Project is a combination of executable and library files that make an application or one of its modules (not a .NET assembly or VB.NET module; simply a separate part of the overall application). A project’s information is usually placed in a file with extension like ‘.vbproj’ where ‘vb’ represents Visual Basic (source programming language) and ‘proj’ stands for Project. Similarly C# projects are stored as ‘.csproj’ file where ‘cs’ stands for C Sharp. There are different kind of projects like Console Application, Windows application, ASP.Net Web Application, Class Library, Windows Control Library, Web Services and others.

A solution on the other hand is a placeholder for different logically related projects that make up an application. For example, a solution may consist of ASP.NET Web Application project and Windows Form project. The information for solution is stored in ‘.sln’ files while they can be managed using Visual Studio.NET’s Solution Explorer. Solutions are similar to VB 6’s Project Group and VC++ 6’s workspace.

A great thing about the Visual Studio.NET solutions is that it may contain projects built with any of the VS.NET compliant language. Hence, now your solution may consists of a database handling project in Visual C#, the GUI Application project in VB.NET and the protocol implementation project in VC++.NET!

What are the different types of projects that can be created with Visual Studio.NET?
Visual Studio.NET allows you to create projects of these types:
Console applications are light weight programs run inside the command prompt (DOS) window. They are commonly used for test applications.

Windows Applications are form based standard Windows desktop applications for common day to day tasks. Microsoft word is an example of a Windows application.
Web applications are programs that used to run inside some web server (e.g., IIS) to fulfill the user requests over the http. A typical example of web application is Hotmail and Google.

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

Class library contains components and libraries to be used inside other applications. A Class library can not be executed and thus it does not have any entry point.

Windows Control Library contains user defined windows controls to be used by Windows applications

Web Control Library contains user defined web controls to be used by web applications

How are projects different from the namespaces?
A Project is a physical grouping of the source code and resource files that make up an assembly and stored into some file. A namespace, on the other hand, is a logical grouping of related types which not necessarily reside into same assembly. A namespace may contain sub or child namespaces while there is not concept of child or sub projects. Finally, project is a Visual Studio.NET standard, while namespace is a .NET standard.

How are namespaces different from assemblies?
An assembly is a physical grouping of the source code and resource files that is stored into some file(s). A namespace, on the other hand, is a logical grouping of related types which not necessarily reside into same assembly. A namespace may contain sub or child namespaces while there is not concept of child or sub assemblies (module is something different from child namespace, as modules are integral and necessary parts of an assembly). An assembly not only contains the source code, it also contains manifest, version information (optional public key token) and culture information. A program may reference two or more assemblies with the same name (but with different versions) but a program can not contain two namespaces with the same name.

What does it mean by code folding in Visual Studio.NET?
The Visual Studio.NET automatically groups the code at various boundaries (method, property, class, structure, interface, and namespace bodies). It then allows you to expand/collapse the regions of these code body groups using the familiar plus/minus sign used in the tree-view control (e.g., in Windows Explorer) which allows you to fold (collapse)/unfold (expand) the code regions



You can also define your own regions using the #region…#end region block with your code.

What does it mean by syntax highlighting?
Visual Studio.NET Code Editor highlights the keywords and syntax errors in your code as you type it with different colors and waves. This is called the syntax highlighting.



What does it mean by VS.NET hot compilation?



The hot compiler highlights the syntax errors in your program as you type the code. The following figure shows an illustration of hot compiler in Visual Studio.NET

What are regions in Visual Studio.NET IDE’s code view?
A region is a part of the code that can be folded/un-folded in the Visual Studio.NET code editor. You can also define your own regions using the #region…#end region block with your code.

What is the difference between the Design View and the Code View of the Visual Studio.NET?
The design view opens the VS.NET form designer that allows you to place user interface controls on the form by simple drag and drop, resize them and set various properties in the convenient way. The designer automatically generates the required 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.

How can I compile and build a particular project and the whole solution?
To compile all the source files of the project and build the resulting assembly, right click the target project node in the solution explorer and select Rebuild project.
To compile all the source files of all the projects contained in a solution and build the resulting assemblies or the complete application, right click the solution node in the solution explorer and select Rebuild solution.

What features does the Visual Studio.NET debugger provide to the developers?
Visual Studio.NET provides an integrated debugger. The debugger allows you to debug your application from within the Visual Studio.NET IDE and code editor. You can use the code editor to specify the break points and see the runtime values of the variables of a program. You can control the execution of your program step by step; e.g. you can pause the execution of the program after each line, you can jump the control of execution to the next method in the execution sequence. You can even change the runtime values of the variables at runtime and re-execute it! It’s simply an amazing tool!

What is the difference between running an application with and without debugger?
When an application is run with debugger, the debugger will provide its services during the execution. This may slow down the execution of the program and is useful when the program is in the development and testing phase. When program is run without debugger, it is executed in the similar way as it will be executed at the client (user of the application) machine. The execution 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.

How can I run an application with and without debugger?
To run the application with debugger, select Debug > Run or press F5. To run the application without debugger, select Debug > Run without debugger or press Ctrl+F5

What are break points in context with the debugger?
A break point is the line of code at which you want your program to be paused (when running in debugger mode) and see the runtime values of different variables in the program. If the program control ever reaches this line during the execution of the program, it pause the execution and allows you to see and edit the values of the variables of your program.

How can I add a break point in my code? How can I remove a breakpoint?
To add a break point for some line, click at its left panel. You can also do this by right clicking the target line and selecting the 'Insert breakpoint'. To remove a break point from some line, click on its left pan. You can also do the same by right clicking on a target line and select 'Remove breakpoint'.

How can I see the runtime values of different variables of my code using debugger?
You can see the runtime value of a particular variable by just pointing a mouse over it when the program is running in debugger mode and is paused at some breakpoint. It will only show the value of any live variable. To see the runtime values of all the local variables of a method, see the 'Locals' debug window. This window is also accessible from Debug > Windows > Locals



How can I see the runtime values of the content of a class or structure?
A class or a structure is represented in ‘Locals’ and other debug windows with expandable tree. You can see its members by expanding its object node

What does it mean by 'watch' in context of the debugger?
Instead of pointing mouse pointer over a variable to show its value or using the Locals to view the values of all the local variables, you can also add only interested variables in the Debugger’s Watch Window (accessible through Debug -> Windows -> Watches -> Watch 1). The values in Watch window are always visible in the bottom of your VS.Net. To add any variable to Watch Window, right click on the variable and choose 'Add Watch' or drag it to the watch window.

When the execution of a program is paused at a breakpoint, how can I resume the execution?
You can resume the execution, either by selecting Debug > Continue (press F5) or using the various ‘Step’ options like Step Into (F11) or Step Over (F10).

How do I step into and step over the code with debugger? What do ‘stepping into’and stepping over’ actually mean?
The Step Into option (accessible through Debug -> Step Into or key F11) takes the execution control inside the calling method. For example, if the execution is paused at a line having code
int p = obj.GetInteger();
Then pressing F11, will take us to the body of the GetInteger() method and the execution control will pause at its first line.
The Step Over option (accessible through DebugàStep Over or key F10) executes the code in the line at which the debugger is paused and takes the execution control to the next line. For example, if the execution is paused at a line marked line 1 in the code below:
int p = obj.GetInteger(); // line 1
Console.WriteLine(p); // line 2
Then pressing F10, will execute the code at ‘line 1’ and will take the execution control to the line marked ‘line 2’ in the above code and the execution control will pause at the line // 2.

How are projects and solutions mapped to .NET assemblies?
In Visual Studio.NET, each project is compiled to a single assembly with references to the referenced assemblies and other code libraries. It is important to remember that up-till now Visual Studio.NET (2003) only supports single file assembly and not a multi-file assembly. It means that all the source code of a project is built to a single file representing the project’s assembly. Hence, if a solution contains five projects then when it (the solution) is built, it will emit five different assemblies each containing a single .dll or .exe file depending on the type of project selected.

A solution is a logical binding for the projects and it does not have any representation in the build files.

How much projects a solution may have?
There is no such limit; a solution may contain any number of projects. The projects can be coded in any VS.NET compliant programming language. A solution, basically, representation the raw application and it should contain only those projects which are the part of the application.

How to set the start application of a multi project solution?
You can specify the startup project of the application by selecting it from the startup project property of the solution which can be accessed by right clicking the solution and selecting the properties option from the pop up menu. It will show the property pages for the solution. You can change the startup project from Common Properties -> Startup project -> Single Startup project. Note that the startup project must represent an executable assembly (Console application, windows application or a web application) and not a library project.

How do I change the name of the resulting assembly files (.exe and .dll)?
Right click the project and select properties. It will show the property pages for the project. You can change the resulting assembly name from Common Properties> General > Assembly Name.

What is the difference between a debug and a release build?
The debug build is created with some embedded information which allows the debugger to debug the application and exposes the runtime behavior of the application. On the down side, the debug build is a bit slower and inefficient in execution and larger in size.

You may specify the build type of an assembly (project) by right clicking its project and selecting properties from the pop up menu. It will show the property pages for the project. You can select the build type by selecting Configuration Properties and then selecting the build type from the combo box at top labeled Configuration

What are references in context of the VS.NET projects?
A reference is the name and address of the .NET assembly or a COM component used inside some source files of the project. The Visual Studio.NET uses these added references when compiling your project assembly. A reference enables the language compiler to locate the referenced assemblies and COM component.

How many types of reference are there in the Visual Studio.NET?
There are basically three types of references that can be added to a project:
Reference to the .NET assembly (including components, library and controls)
Web reference to web services (see the succeeding question for details)
Reference to COM component (see the succeeding question for details)

What are web references in context of the VS.NET projects?
A web reference represents a reference to the web service, at its simplest. Getting inside, a web reference is a reference to the proxy classes to call the web service. These proxy classes are implemented for you by the VS.NET IDE for you through the Web Service Description Language (wsdl) file downloaded from the web service URL. These proxy classes provide the same calling interface to the clients of web service. When you call methods on a proxy class, it in turn calls the methods of the web service over the internet through SOAP (Simple Object Access Protocol) and returns the result back to your program.

How do I add a reference to a .NET assembly in my project?
To add a reference to a .NET assembly, right click the ‘Reference’ option under the project inside the solution explorer and select the ‘Add Reference…’ option. It will show you a user interface screen where you browse for the target assembly. When you have selected the assembly, press the ‘Select’ button and then press OK. This will add a new reference node in the Reference sub tree of the project. By selecting the added reference node, you can edit its properties from the properties window.
Index

What is Visual Studio.NET IDE and what is the importance of it?
The Visual Studio .NET IDE is the default Development Environment for all Microsoft .NET based applications. Its got a full set set of usefull features. The VS.NET IDE provides many options for developers and is packed with much funtionality that simplifies application development.

Important Features of Visual Studio .NET IDE.

One IDE for all .NET based Projects

Visual Studio .NET IDE provides a single environment for developing all types of .NET applications. Application’s range from single form applications to complex n-tier applications and also Rich Web Applications.

The option to choose from Multiple Programming Languages

You can customize the IDE based on your preferences. By use of "My Profile settings". With these settings you can set the IDE 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 IDE comes with a built-in browser that helps you navigate the Internet without launching another browser app.

What are the developing options in VS.NET? And what project templates are there?
Upon starting developing applications with Visual Studio .NET, Its possible to develop applications based on your choice. Here is a rundown of the different types of applications that can be developed using a vanilla install of VS.NET.
Opening a new project:

The following are the different options available in VS.NET and what they are used for.

Windows Applications: This template allows you to create standard windows based applications.

Class Library: Class libraries are those that provide functionality similar to Active X and DLL's by creating classes that that can be used from other applications.

Windows Control Library: This allows the creation of your own windows controls. These can also be added to the tool box to make it easier if you wish to use these resources in other projects.

ASP.NET Web Applications: Create web-based application using IIS. You can develop Web pages, Rich Web Applications and Web Services.
ASP.NET Web Service: For developing XML Web Services.

Web Control Library: Allows you to create User-defined controls for the Web. Similar to user defined windows controls but these are specifically for Web usage.

Console Application: Development of command line based applications. No GUI needed

Windows Service: Windows Services are background programs that run without promp. An example would eb an SMTP server.

Other: This template is to develop other kinds of applications such as enterprise applications, database applications etc.

How do I change the icon of my application?
Right click the startup project node in the solution explorer window and select the properties option. It will show the property pages for the project. You can change the application icon from Common Properties -> General -> Application Icon. Note that this is the icon for the application that will be attached with its executable file and shortcuts to it. To change the icon of the individual forms of your application, select the icon by editing the icon property of your form.

How do I make folders in the project?
To create a folder into a project, right click the target project node in the solution explorer and select ‘Add Folder…’ option. This will add a new folder to the project, specify the name of the folder and press Enter. The folders inside a project help you manage and separate source files for different purpose in the same project. For example, you may divide the windows form project to three folders;

first (Forms) containing user interface forms
second (Constants) containing constant values (enumerations and error codes) to be used in the project
third (StorageAccessor) containing classes for the database handling.

How do I add a new or existing file to a project or to a project folder?
To add a file to a project or to a project folder, right click its node in the solution explorer and select either ‘Add New Item…’ or ‘Add Existing Item…’ option. This will show you a user interface screen that allows you to add various kinds of items like report, icon, class file, windows form, etc. Select the appropriate item from here.

How do I add a new or existing project to a solution?
To add a project to a solution, right click the solution node inside the solution explorer and select the ‘Add Project…’ or ‘Add existing project’ option. It will show you a user interface screen where you can browse for the target project. This will add a new project node in the solution tree.

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

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

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

Sample C# Application

Using System
Class Sample
{
public static void main()
{
Console.WriteLine (“Hello World”)
}
}

What are Jagged Arrays in C#?
A special type of array is introduced in C#. A Jagged Array is an array of an array in which the length of each array index can differ.

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

The following code demonstrates the creation of a two-dimensional jagged array.
Class Jagged
{
public static void Main()
{
int [][] jagged=new int [3][];
jagged[0]=mew int[4]
jagged[1]=mew int[3]
jagged[2]=mew int[5]
int I;
‘Storing values in first array
for (I=0;I<4;I++)
jagged[0][I]=I;
‘Storing values in second array
for( I=0;I<3;I++)
jagged[1][I]=I;
‘Storing values in third array
for(I=0;I<5;I++)
jagged[2][I]=I;
‘Displaying values from first array
for (I=0;I<4;I++)
Console.WriteLine(jagged[0][I])
‘Displaying values from second array
for (I=0;I<3;I++)
Console.WriteLine(jagged[1][I])
‘Displaying values from third array
for(I=0;I<5;I++)
Console.WriteLine(jagged[2][I])
}
}
Run the code to see the output.

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

The RunTime supports two kinds of Value Types:
1 Built-in value types

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

2 User-defined value types
The language you are using will provide functionality to define your own Value Types. These user defined Types derive from System.ValueType. If you want to define a Type representing a value that is a complex number (two floating-point numbers), you might choose to define it as a value type. Why? Because you can pass the Value Type efficiently "By Value". If the Type you are defining could be more efficiently passed "By Reference", you should define it as a class instead. Variables of Reference Types are referred to as objects. These store references to the actual data.

The following are the Reference Types:
class
interface
delegate

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

VB.NET Frequenly Asked Questions

What is the difference between VB6 and VB.NET
There are quite a few differences in VB6 and VB.NET. We will highlight some of these here in points:

The greatest change in VB6 and VB.NET is of runtime environment. VB6 used the VB-Runtime while VB.NET uses the .Net Common Language Runtime (.Net CLR). The CLR is much better designed and implemented than VB-Runtime. The CLR uses better code translation through Just in Time compiler while VB-Runtime interprets the code. The CLR Garbage Collector is also more efficient than VB6 one as it may detect cyclic references too.

VB6 was interpreter based language while VB.NET is a compiled language

VB6 was not a type-safe language while VB.NET is a type safe language. There is no variant type in VB.NET and no magical type conversions happen in VB.NET

VB6 used ‘On Error Goto’ syntax to handle exceptions at runtime. VB.NET uses the Try…Catch…Finally syntax to handle exceptions at runtime.

A lot of code (like user interface code) in VB6 was hidden from developer. In VB.NET no code is hidden from developer and you can access and control each part of your application

VB.NET has much enhanced object oriented support than VB6

VB6 does not allow developing the multithreaded applications. In VB.NET you can create multithreaded applications.

VB6 was only considered good for desktop windows application. In VB.NET you can also develop web applications, distributed applications, create .NET windows and web controls and components, write windows and web services.

In VB.NET, you can also use reflections to read the meta-data of types and using reflection emit you can also generate code to define and invoke types at runtime.

VB.NET uses .NET framework class library along with specialized VB library (System.VisualBasic) as a standard library. As a result, the standard library for VB.NET is much enhanced and useful compared to VB6 standard library

VB.NET is platform independent because of .Net framework. Programs written in VB.NET can run on any platform where .Net framework is present. The platform include both hardware and software (operating system) platforms.

VB.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. Similarly the code written in VB.NET can also be used and enhanced by other .NET compliant languages. Although VB6 also provided this functionality through COM but it was limited and difficult to use and manage. VB.Net makes it easier because of the presence of Intermediate Language (IL) and Common Language Specification (CLS) of the .NET architecture.

VB6 uses COM (Component Object Model) as component architecture. VB.NET uses assemblies as its component architecture. The Assemblies architecture has removed a lot of problems with COM including DLL-Hell and versioning problem.

Components created in VB6 (COM) need to make and update registry entries. VB.NET does not require any registry entry making the deployment easier

VB6 used ASP to build web applications. VB.NET uses ASP.NET to build web applications.

VB6 used ADODB and record-sets to implement data access applications. VB.NET uses ADO.NET and datasets to build data access applications. The ADO.NET also supports the disconnected data access.

What are Console Applications in VB.NET?
Console Applications have only recently been introduced in VB (Excluding VB for DOS). They are command line based and run in within a DOS Shell (DOS Window). Unlike Windows Applications, Console Applications do not support Windows GUI's. Which means that you can't work with controls from the toolbox.

To work with Console Applications select File->New->Project and in selected "Console Application" from the template under Visual Basic or Visual C#.

Example (Sample.vb) of a Console Application.
Module Module 1
Sub Main ()
System.Console.WriteLine ("Hello World”)
End Sub
End Module
Run the program by pressing "F5" on the keyboard or by selecting Debug->Start.
The output of the program is “Hello World”.
Compilation of the program using the Visual Studio .NET Command Prompt is also possible. To compile the program using that type "vbc sample.vb" at the command prompt.

What are namespaces and what is the importance of them?
A namespace is a collection of different classes which are built into .NET. This very much like packages in Java. You need to import these namespaces to work with any .NET language. All the functionality of .NET is within these namespaces. The main namespace is the System namespace and all other namespaces are built into this System namespace.

Some of these namespaces and what they are used for are summarized below.

System: Includes essential classes and base classes that define commonly used Data Types, events, interfaces, attributes etc.
System.Data: Includes classes that make up ADO.NET and allows to build data-handling components.
System.Drawing: Provides access to graphics that gives access to drawing methods.
System.IO: Provides access to writing data streams and Files.
System.Net: Provides interface to many protocols used on the Internet.
System.Security: Includes classes to support the security system.
System.Threading: Includes classes that support threading.
System.Web.Services: Includes classes for creating and using Web Services.
System.Windows.Forms.: Includes classes for creating windows based applications.

What is the importance of the Option statement?
The Option statement is used to prevent syntax and logical errors in code. The possible suffixes of this statement are:

Option Explicit: Is the default abd is On. Option Explicit requires declaration of all variables before they are used.

Option Compare: This can be set to Binary or Text and it specifies if stringsp are to be compared using binary or text comparison operations.

Option Strict: The default is Off. An example: If value of one data type is assigned to another then Visual Basic will consider that as an error. If you want to assign a value of one Type to another then you should set it to On and use the conversion functions.

Example using the Option Statement.
The following code does not perform any special function but will show where to place an Option statement.
Option Strict Off
Imports System
Module Module 1
Sub Main ()
Console.WriteLine (“Using Option”)
End Sub
End Module

What are attributes in Visual Basic .NET?
Attributes are items that hold information about items we are using in VB.NET. They are used when VB.NET needs to know more than what standard syntax can specified. Attributes are enclosed in angle brackets<>.

Example: To call a Windows API functions you have to include a dynamic link library (DLL) reference that the function you are calling resides in. This is done using the DLLImport attribute as follows:

Public Shared Function (DllImport""user32.dll" ) MessageBox(Byval..)
You can also use an attribute like or pass it's value to a parameter as you can do with procedures like .

What are Enumerations in VB.NET and how are they used?
Enumerations are new in VB.Net (As apposed to VB(i)) and they are used to group related sets of constants. To create a Enumeration you use the Enum statement.

Example using a Enumeration
Module Module 1
Enum Months
January=1
Feburary=2
March=3
April=4
May=5
June=6
July=7
August=8
September=9
October=10
November=11
December=12
End Enum
Sub Main()
System.Console.WriteLine(“December is “ & Months.December &” th Month”)
End Sub
End Module
When using constant's declared in an Enumeration, you need to refer to it like so:
Months.December.
The output of the above code displays December is the 12th Month.

How do I convert text from lower case to upper case in VB.NET?
The following code shows how text can be converted from lower case to upper.

Module Module1
Sub Main ()
Dim str1 as String=”Welcome to String”
Dim str2 as String
Str2=UCase(str1)
Or
Str2=Str1.ToUpper
System.Console.WriteLine(str2)
End Sub

How do I handle Math functions in VB.NET?
Higher Mathematical functions in VB.NET are in the methods of the System.Math namespace. Calculation of a hyperbolic cosecant value and so on is possible by using the methods in this namespace.

Example using a Math Function
Imports System.Math
Module Module1
Sub Main()
System.Console.WiteLine(“Pi = “ & 4 * Atan())
End Sub
End Module

How do I handle Date and Time in VB.NET?
Working with Dates is one to think about. Especially if your data needs to be spread accross timezones Also there are different date formats to take in to consideration. VB.NET Has some good Date() Functions, one of which is demonstrated below:

Example
Imports System.Math
Module Module1
Sub Main ()
Dim Dts as Date
Dts = # 10/15/2001
System.Console.WriteLine(“New Date: & DateAdd(DateInterval.Month, 22, Dts))
End Sub
End Module
The above code adds 22 months to the date we declared in the Program.

How do I create Procedure Delegates?
Delegates are used to work with the address of procedures. This is much like pointers in C and C++. Sometimes it's useful to pass the location of a procedure to other procedures.

Example working with Delegates:
Module Module1
Delegate Sub SubDelegate1(ByVal str as String)
Sub Main()
Dim Mess as SubDelegate1
Mess-AddressOf Display
Mess.Invoke(“Hello from Delegates”)
End Sub
Sub Display(ByVal str as String)
System.Console.WriteLine(StrText)
End Sub
End Module
The above code displays “Hello from Delegates” just like a normal program but it uses Delegates to do it.

How do I use the InputBox Function?
An InputBox function is much like a  ?JavaScript prompt window which allows the input of text. To work with the InputBox, drag a Command Button and a TextBox from the Toolbar. Opon clicking the Command Button the InputBox prompts asks for a name. Once entered, press OK. That text will now be displayed in the Textbox.
The sample code for the click event
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles Button1.Click
Dim Show As String
Show = InputBox("Enter your name")
TextBox1.Text = Show
End Sub

How do I write data to a text file in VB.NET?
The following code creates a text file and inserts some text.

Imports System.IO
Public Class Form1 Inherits System.Windows.Forms.Form
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e_
As System.EventArgs) Handles MyBase.Load
Dim fs as New FileStream("exp.txt",FileMode.Create,FileAccess.Write)
Dim s as new StreamWriter(fs)
s.BaseStream.Seek(0,SeekOrigin.End)
s.WriteLine("ProgrammersHeaven has lot of programming goodies")
s.WriteLine(" good resource for most popular programming languages")
s.Close()
End Sub
End Class

What is Anchoring and Docking?
The VB terms Docking and Anchoring are used to make sure that a control covers the whole client area of a form.

Upon "docking" a window, it adheres to the edges of it's container (the Form). To "dock" a particular control, select the Dock property of the control from the properties window.

Selecting the Dock property opens up a small window like structure where you can select towards which side on the Form should the control be docked.

You can use Anchoring to "anchor" a control to the edges of it’s container (the Form). Selecting this property in the properties window opens up a small window from where you can select what edge to "anchor" the control to.

How to get computer name and IP address?
The following code uses the System.NET.DNS namespace to access the "computer name" and it's IP address.
Option Strict Off
Imports system
Imports System.Net.DNS
Public Class GetIP
Shared Function GetIPAddress() As String
Dim sam As System.Net.IPAddress
Dim sam1 As String
With system.Net.DNS.GetHostByName(system.Net.DNS.GetHostName())
sam = New System.Net.IPAddress(.AddressList(0).Address)
sam1 = sam.ToString
End With
GetIPAddress = sam1
End Function
Shared Sub main()
Dim shostname As String
shostname = system.Net.DNS.GetHostName
console.writeline("Name of the System is = " & shostname)
console.writeline("Your IP address is= " & GetIPAddress)
End Sub
End Class
Compile the file as "vbc getip.vb /r:system.net.dll"
Execute the "getip.exe". The computer's name and IP address will be displayed in the Console.

How to get the environment information in VB.NET?
The System.Environment namespace includes the functionality to get the environment information such as the UserName and OS Version.

File name is SystemInfo.vb
Imports System
Class SystemInfo
Shared Sub main()
Console.WriteLine("")
Console.WriteLine("Current User")
Console.WriteLine(Environment.UserName)
Console.WriteLine("")
Console.WriteLine("Name of the Machine")
Console.WriteLine(Environment.MachineName)
Console.WriteLine("")
Console.WriteLine("OS version")
Console.WriteLine(Environment.OSVersion)
Console.WriteLine("")
Console.WriteLine("System Directory")
Console.WriteLine(Environment.SystemDirectory)
Console.WriteLine("")
Console.WriteLine("TMP Folder")
Console.WriteLine(Environment.GetEnvironmentVariable("TMP"))
Console.WriteLine("")
Console.WriteLine("Class Path")
Console.WriteLine(Environment.GetEnvironmentVariable("ClassPath"))
Console.WriteLine("")
Console.readLine()
End Sub
End Class

How do I read and write data to an XML file?
The following code demonstrates how to read and write to an XML file.




Sandeep
23
Developer



Imports System
Class WriteToXML
Shared Sub main()
Dim dset As New System.Data.DataSet()
Dim str As String = "Test.xml"
'Load the XML file in the data set
dset.ReadXml("Test.xml")
'Read the XML content on the console
Console.Write(dset.GetXml)
'Getting data from the user to be saved into the XML file
Console.Write("Enter Name : ")
Dim name, age, occupation As String
name = Console.ReadLine
Console.Write("Enter Age : ")
age = Console.ReadLine
Console.Write("Enter Occupation : ")
occupation = Console.ReadLine
Console.Write(name & age & occupation)
Dim v(1) As String
v(0) = fname
v(1) = age
v(2)=occupation
dset.Tables(0).Rows.Add(v)
dset.WriteXml("Test.xml")
Console.Write(dset.GetXml)
End
When you run this code, the data from the XML file will be displayed. Also the data you enter will be updated into the XML file.

How to work with an interface in VB.NET?
The following code demonstrates the ability to work with an interface. An interface defines a method's name and not it's contents.

Imports System
Imports Microsoft.VisualBasic
Public Interface NewInt
Sub Mysub()
Function MyFun() As String
End Interface
Class myclass Implements MyInt
' Implementing the above defined interface, need to use the keyword implements to use the interface
Shared Sub Main()
Dim mc As New myclass()
mc.Mysub()
End Sub
Sub Mysub() Implements NewInt.Mysub
MsgBox("Hello from INterfaces")
End Sub
Function MyFun() As String Implements NewInt.MyFun
dim str as string
str="hello matey"
return (str)
End Function
End Class

How to convert the format of images in VB.NET?
To convert the format of an image you need to use the System.Drawing namespace. Using this code you can convert to a variety of graphic file formats, such as GIF or JPG.
The following example converts a user prompted Bitmap image file into .Gif format.

File ImageConverter.vb
Imports System
Imports System.Drawing
Class ConvertImages
Shared Sub main()
Dim str As String
Console.Write("Path of the Image File to Convert :")
str = Console.ReadLine()
'Initialize the bitmap object by supplying the image file path
Dim bmp As New Bitmap(str)
bmp.Save(str + ".gif", System.Drawing.Imaging.ImageFormat.Gif)
Console.Write("Image Sucessfully Converted to " & str & ".gif")
End Sub
End Class

What is the concept of destructors in VB.NET?
Destructors are used to de-allocate resources i.e. to clean up after an object is no longer available.

Finalize is the destructor which is normally used. Finalize is called automatically when the .NET runtime determines that the object is no longer being used. Using the Finalize method in code looks like this:

Public Class Form1 Inherits System.Windows.Forms.Form
Dim obj1 as new Class1 ()
End Class
Public Class Dest
Protected overrides Sub Finalize()
‘ calling the Finalize method
End Sub
End Class

How do I get Version Information From The AssemblyInfo File?
To get version information at Runtime in VB .NET, use the following code:

Function Version() As String With _
System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .FileMajorPart & "." & .FileMinorPart & "." & .FileBuildPart & "." & .FilePrivatePart
End With
End Function
Function Display() As String
With System.Diagnostics.FileVersionInfo.GetVersionInfo(System.Reflection.Assembly.GetExecutingAssembly.Location)
Return .Comments
End With
End Function
Upon running the version information of the Assembly file is displayed.

What is managed code and managed data?
Managed code is the code that is written to target the services of the Common Language Runtime (CLR). In order to target these services, the code must provide a minimum level of information to the runtime. All of the C#, Visual Basic .NET and J# .NET code is managed by default.

Closely related to managed code is managed data. This is the data that is allocated and de-allocated by the Common Language Runtime's garbage collector. As said earlier C#, Visual Basic, and J#.NET data is managed by default. C++ data can, however, be marked as unmanaged through the use of special keywords. Visual Studio .NET C++ data is unmanaged by default (even when using the /CLR switch), but when using Managed Extensions for C++, a class can be marked as managed by using the __gc keyword.

As the name suggests this means that the memory used for instances of the class is managed by the garbage collector. In addition the class becomes a full participating member of the .NET Framework with the benefits and restrictions that it brings. An example of a benefit is proper interoperability with classes written in other languages (for example, a managed C++ class can inherit from a Visual Basic class).

An example of a restriction is that a managed class can only inherit from one base class.

What is an Assembly?
An Assembly is the building block of a VB.NET application. An Assembly is a complied and versioned collection of code and metadata. Once complete forms an "atomic" functional unit.

Assemblies come in the form of a Dynamic Link Library (DLL) file or Executable an program file(EXE). They differ as they contain information found in a type libraries. All the .NET programs are constructed from these Assemblies. Assemblies are made of two parts. Firstly, the manifest which is similar to a Table Of Contents(TOC). This holds the name and version of the assembly. Secondly, the modules which are internal files of Intermediate Language (IL) code which are ready to run.

When programming, developers don't directly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes.

An assembly includes:
Information for each public class or type used in the assembly
Information on all public methods in each class. For instance, the method name and return values (if any)
Information on every public parameter for each method, such as the parameter's name and type
Information on public enumerations including names and values
Information on the assembly version (each assembly has a specific version number)
Intermediate Language code to execute
Required resources such as pictures, assembly metadata

How do I find the path from where the application is running?
To learn the path of your running application, do the following. Drag a Textbox and a Command Vbutton from the ToolBar and use the following code.

Public Class Form1 Inherits System.Windows.Forms.Form
#Region " Windows Form Designer generated code "
#End Region
Private Sub Button1_Click(ByVal sender As System.Object,
ByVal e As System.EventArgs)
Handles Button1.Click
TextBox1.Text = Application.ExecutablePath
End Sub
End Class

How do I get the screen resolution of my working area?
To get the screen resolution of your current working area use the System.Windows.Forms.Screen.PrimaryScreen.Bounds property

How can I run a .EXE from a VB.NET application?
To run a .EXE file from a VB.NET application you need to import the System.Diagnostics namespace. The following sample shows how to run Notepad from a VB.NET application.

Imports System
Imports System.Diagnostics
Dim program As New Process()
program.StartInfo.FileName = "Notepad.exe"
program.StartInfo.Arguments = " "
program.Start()

What is Try- Catch –Finally Exception Handling?
Exceptions are Runtime errors that occur when an unexpected process causes the program to abort. Such kind of situations can be kept at bay using Exception Handling. By looking for potential problems in the code / entity life cycle, we can handle most of the errors that may encountered. As a result the application to continue to run without being dogged by errors. VB.NET supports Structured exception handling by using Try...Catch...Finally

The following code sample demonstrates how to use Try-Catch-Finally exception handling.

Module Module1

Sub Main()
Dim a=0, b=1, c As Integer
Try
c=b / a
'the above line throws an exception
System.Console.WriteLine("C is " & c)
Catch e As Exception

System.Console.WriteLine(e)
'catching the exception

End Try
System.Console.Read()

End Sub
End Module

The output of the above code displays a message stating the exception. The reason for the exception is because any number divided by zero is infinity.

How do I convert one DataType to other using the CType Function?
The CType is pretty generic conversion Function.
The example below demonstrates using a CType Function to convert a Double value to an Integer value.

Module Module1

Sub Main()
Dim d As Double

d = 132.31223

Dim i As Integer

i = CType(d, i)
'two arguments, type we are converting from, to type desired
System.Console.Write("Integer value is" & i)

End Sub
End Module

2 Comments:

At June 11, 2008 at 11:29 PM , Blogger Anbarasan said...

Thank u Mr. NMK

 
At October 2, 2008 at 12:16 AM , Blogger Andrei Hetel said...

Article is excellent. My opinion is that you have to break it a little bit because is too long. Eventually detail even more topics of interest for readers. Keep up the good work.

 

Post a Comment

Subscribe to Post Comments [Atom]

Links to this post:

Create a Link

<< Home