NAVGUJARAT COLLEGE
OF COMPUTER APPLICATIONS
Subject:Advance visual and windows programming(BCA-205)
Subject Code :BCA-205
The .NET Framework
The .NET Framework is the next iteration of Microsoft's platform for developing component-based software. It provides fundamental advances in runtime services for application software. It also
supports development of applications that can be free of dependencies on hardware, operating system, and language compiler.
This chapter provides an overview of the architecture of the .NET Framework and describes the base features found in the core of its class library.
Common Language Infrastructure (CLI) and Common Language Runtime (CLR)
At the heart of the .NET Framework is a new mechanism for loading and running programs and managing their interactions. This mechanism is described in the Common
Language Infrastructure (CLI), a specification for a runtime environment that allows
software components to:
Pass data between each other without regard to the programming language in which each component is on paper
Execute on different operating systems and on different hardware platforms without having to recompile the high-level source code (a low-level compilation still automatically occurs on the target platform, as will be discussed in this chapter)
Although the CLI specification was created by Microsoft, it has since been submitted to the ECMA standards organization (http://www.ecma.ch), which now has responsibility and control over it.
The CLI is just a specification—it has to be implemented in order to be useful. An implementation of the CLI is known as a Common Language Runtime (CLR). Microsoft's CLR implementation on the Windows platform is not under ECMA's control, but it is Microsoft's intention that the CLR be a fully compliant implementation of the CLI. As of this writing, the CLI has not been implemented on non- Windows platforms, but Microsoft and others have announced intentions to do so.
The CLI specifies how executable code is loaded, run, and managed. The portion of the CLR that performs the tasks of loading, running, and managing .NET applications is called the virtual execution system (VES). Code run by the VES is called managed code .
The CLI greatly expands upon concepts that exist in Microsoft's Component Object
Model (COM). As its core feature, COM specifies how object interfaces are laid out in
memory. Any component that can create and consume this layout can share data with other components that do the same. COM was a big step forward when it was introduced (circa 1992), but it has its shortcomings.
Common Type System (CTS)
The CLI specification defines a rich type system that far surpasses COM's capabilities. It's called the Common Type System (CTS). The CTS defines at the runtime level how types are declared and used.
Previously, language compilers controlled the creation and usage of types, including their layout in memory. This led to problems when a component written in one language tried to pass data to a component written in a different language. Anyone who has written Visual Basic 6 code to call Windows API functions, for instance, or who has tried to pass a JavaScript array to a component written either in Visual Basic 6 or C++, is aware of this problem. It was up to the developer to translate the data to be understandable to the receiving component. The CTS obliterates this problem by providing the following features:
• Primitive types (Integer, String, etc.) are defined at the runtime level. Components can easily pass instances of primitive types between each other because they all agree on how that data is formatted.
• Complex types (structures, classes, enumerations, etc.) are constructed in a way that is defined at the runtime level. Components can easily pass instances of complex types between each other because they all agree on how complex types are constructed from primitive types.
• All types carry rich type information with them, meaning that a component that is handed an object can find out the definition of the type of which the object is an instance. This is analogous to type libraries in COM, but the CTS is different because the type information is
much richer and is guaranteed to be present.
Common Language Specification (CLS)
The CLI defines a runtime that is capable of supporting most, if not all, of the features found in modern programming languages. It is not intended that all languages that target the CLR will support all CLR features. This could cause problems when components written in different languages attempt to interoperate. The CLI therefore defines a subset of features that are considered compatible across language boundaries. This subset is called the Common Language Specification (CLS).
Vendors creating components for use by others need to ensure that all externally visible constructs (e.g., public types, public and protected methods, parameters on public and protected methods, etc.) are CLS-compliant. This ensures that their components will be usable within a broad array of languages, including Visual Basic .NET. Developers authoring components in Visual Basic .NET have an easy job because all Visual Basic .NET code is CLS-compliant (unless the developer explicitly exposes a public or protected type member or method parameter that is of a non-CLS-compliant type).
Because Visual Basic .NET automatically generates CLS-compliant components, this book does not describe the CLS rules. However, to give you a sense of the kind of thing that the CLS specifies, consider that some languages support a feature called operator overloading . This allows the developer to specify actions that should be taken if the standard operator symbols (+,
-, *, /, =, etc.) are used on user-defined classes. Because it is not reasonable to expect that all languages should implement such a feature, the CLS has a rule about it. The rule states that if a CLS-compliant component has public types that provide overloaded operators, those types must provide access to that functionality in another way as well (usually by providing a public method that performs the same operation).
Intermediate Language (IL) and Just-In-Time (JIT) Compilation
All compilers that target the CLR compile source code to Intermediate Language (IL), also known as Common Intermediate Language (CIL). IL is a machine language that is not tied to any specific machine. Microsoft designed it from scratch to support the CLI's programming concepts. The CLI specifies that all CLR implementations can compile or interpret IL on the machine on which the CLR is running. If the IL is compiled (versus interpreted), compilation can occur at either of two times:
• Immediately prior to a method in the application being executed
• At deployment time
compiled, subsequent calls bypass the compilation mechanism and call the compiled code directly. The compiled code is not saved to disk, so if the application is stopped and restarted, the compilation must occur again. This is known as just-in-time (JIT) compilation and is the most common scenario.
In the second case, the application is compiled in its entirety at deployment time. IL is saved to .exe and .dll files. When such a file containing IL is executed, the CLR knows how to invoke the JIT compiler and execute the resulting code. Note that on the Microsoft Windows platforms, IL is always compiled—never interpreted.
Metadata
Source code consists of some constructs that are procedural in nature and others that are declarative in nature. An example of a procedural construct is:
someObject.SomeMember = 5
This is procedural because it compiles into executable code that performs an action at runtime. Namely, it assigns the value 5 to the SomeMember member of the someObject object. In contrast, here is a declarative construct:
Dim someObject As SomeClass
This is declarative because it doesn't perform an action. It states that the symbol someObject is a variable that holds a reference to an object of type SomeClass.
In the past, declarative information typically was used only by the compiler and did not compile directly into the executable. In the CLR, however, declarative information is everything! The CLR uses type and signature information to ensure that memory is always referenced in a safe way. The JIT compiler uses type and signature information to resolve method calls to the appropriate target code at JIT compile time. The only way for this to work is for this declarative information to be included alongside its associated procedural information. Compilers that target the CLR therefore store both procedural and declarative information in the resulting .exe or .dll file. The procedural information is stored as IL, and the declarative information is stored as metadata. Metadata is just the CLI's name for declarative information.
Modules and Assemblies
A module is an .exe or .dll file. An assembly is a set of one or more modules that together make up an application. If the application is fully contained in an .exe file, fine—that's a one-module assembly. If the .exe is always deployed with two .dll files and one thinks of all three files as comprising an inseparable unit, then the three modules together form an assembly, but none of them does so by itself. If the product is a class library that exists in a .dll file, then that single .dll file is an assembly. To put it in Microsoft's terms, the assembly is the unit of deployment in .NET. An assembly is more than just an abstract way to think about sets of modules. When an assembly is deployed, one (and only one) of the modules in the assembly must contain the assembly manifest, which contains information about the assembly as a whole, including the list of modules contained in the assembly, the version of the assembly, its culture, etc.
Memory Management and Garbage Collection
In any object-oriented programming environment, there arises the need to instantiate and destroy objects. Instantiated objects occupy memory. When objects are no longer in use, the memory they occupy should be reclaimed for use by other objects. Recognizing when objects are no longer being used is called lifetime management, which is not a trivial problem. The solution the CLR uses has implications for the design and use of the components you write, so it is worth understanding.
In the COM world, the client of an object notified the object whenever a new object reference was passed to another client. Conversely, when any client of an object was finished with it, the client notified the object of that fact. The object kept track of how many clients had references to it. When that count dropped to zero, the object was free to delete itself (that is, give its memory back to the memory heap). This method of lifetime management is known as reference counting.
Basic compiler automatically generated the low-level code to perform this housekeeping. C++ developers had no such luxury.
Reference counting has some drawbacks:
• A method call is required every time an object reference is copied from one variable to another and every time an object reference is overwritten.
• Difficult-to-track bugs can be introduced if the reference-counting rules are not precisely followed.
• Care must be taken to ensure that circular references are specially treated (because circular references can result in objects that never go away).
The CLR mechanism for lifetime management is quite different. Reference counting is not used. Instead, the memory manager keeps a pointer to the address at which free memory (known as the heap) starts. To satisfy a memory request, it just hands back a copy of the pointer and then increments the pointer by the size of the request, leaving it in a position to satisfy the next memory request. This makes memory allocation very fast. No action is taken at all when an object is no longer being used. As long as the heap doesn't run out, memory is not reclaimed until the application exits. If the heap is large enough to satisfy all memory requests during program execution, this method of memory allocation is as fast as is theoretically possible, because the only overhead is incrementing the heap pointer on memory allocations.
If the heap runs out of memory, there is more work to do. To satisfy a memory request when the heap is exhausted, the memory manager looks for any previously allocated memory that can be reclaimed. It does this by examining the application variables that hold object references. The objects that these variables reference (and therefore the associated memory) are considered in use because they can be reached through the program's variables. Furthermore, because the runtime has complete access to the application's type information, the memory manager knows whether the objects contain members that reference other objects, and so on. In this way, the memory manager can find all of the memory that is in use. During this process, it consolidates the contents of all this memory into one contiguous block at the start of the heap, leaving the remainder of the heap free to satisfy new memory requests.
This process of freeing up memory is known as garbage collection (GC), a term that also applies to this overall method of lifetime management. The portion of the memory manager that performs garbage collection is called the garbage collector.
The benefits of garbage collection are:
• No overhead is incurred unless the heap becomes exhausted.
• It is impossible for applications to cause memory leaks.
• The application need not be careful with circular references.
Although the process of garbage collection is expensive (on the order of a fraction of a second when it occurs), Microsoft claims that the total overhead of garbage collection is on average much less than the total overhead of reference counting (as shown by their benchmarks). This, of course, is highly dependent on the exact pattern of object allocation and deallocation that occurs in any given program.
.NET Defined
Before getting deeply into the subject we will first know how Businesses are related to Internet, what .NET means to them and what exactly .NET is built upon. As per the product documentation from a Business perspective, there are three phases of the Internet. The First phase gets back to the early 1990's when Internet first came into general use and which brought a big revolution for Businesses. In the First phase of the Internet Businesses designed and launched their Website's and focused on the number of hits to know how many customers were visiting their site and interested in their products, etc. The Second phase is what we are in right now and in this phase Businesses are generating revenue through Online Transactions. We are now moving into the Third
effectively communicate with their customers and partners who are geographically isolated, participate in Digital Economy and deliver a wide range of services. How can that be possible? The answer, with .NET.
What is .NET ?
Many people reckon that it's Microsoft's way of controlling the Internet, which is
false. .NET is Microsoft's strategy of software that provides services to people any time, any place, on any device. An accurate definition of .NET is, it's an XML Web Services platform which allows us to build rich .NET applications, which allows users to interact with the Internet using wide range of smart devices (tablet devices, pocket PC's, web phones etc), which allows to build and integrate Web Services and which comes with many rich set of tools like Visual Studio to fully develop and build those applications.
What are Web Services?
Web Services are the applications that run on a Web Server and communicate with other applications. It uses a series of protocols to respond to different requests. The protocols on which Web Services are built are listed below:
UDDI: Stands for Universal Discovery and Description Integration WSDL: Stands for Web Services Description Language
SOAP: Stands for Simple Object Access Protocol
XML, HTTP and SMTP
EDITIONS OF VB .NET
Academic Edition
Professional Edition
Enterprise Developer Edition
Enterprise Architect Edition
Types Of Projects
Windows Applications
Class Libraries
Windows Control Libraries
Smart Device Applications
Asp .Net Web Applications
Asp .Net Web Services
Asp .Net Mobile Web Application
Web Control Library
Consol Application
TYPES OF FILES AND THEIR EXTENSIONS
.Suo Solution User Option File .Vb Any File From Following
A Basic Window Form A Code File
A Module File For Storing Functions A User Control
As Data Form A Custom Control An Inherited Form A Web Custom Control An Inherited User Control A Window Services An Assembly Info File
.Xsd An Xml Schema Provided To Create Datasets .Htm An Html Document .Txt A Text File .Rpt Crystal Report .Bmp Bitmap File .Js Jscript File .Vbs Vbscript File
.Wsf Windows Scripting File .Aspx A Web Form
.Asp An Active Server Page .Asmx Web Service Class
.Vsdisco A Dynamic Discovery Project .Web A We Configuration File
.Asax A Global Application Class
.Rex A Resource File To Store Resource Information .Sln Solution File
.Vbproj Vb Project File
.Vbproj.User Vb Project User Option File
VB .NET IDE
Start Page
Menu Bar
Toolbars
New Project Dilogbox Object Browser The Toolbox
Class View Window Property Window Dynamic Help Window Component Tray The Server Explorer
The Output Window
The Task List
The Command Window
Graphical Designers
Form Designers
Web Form Designers
Component Designer
Xml Designeres
Code Designers
MODES OF VB .NET
Design Time Mode
Runtime Mode
Break Time ModeVB Language
Visual Basic, the name makes me feel that it is something special. In the History of Computing world no other product sold more copies than Visual Basic did. Such is the importance of that language which clearly states how widely it is used for developing applications. Visual Basic is very popular for it's friendly working (graphical)
environment. Visual Basic. NET is an extension of Visual Basic programming language with many new features in it. The changes from VB to VB .NET are huge, ranging from the change in syntax of the language to the types of projects we can create now and the way we design applications. Visual Basic .NET was designed to take advantage of the .NET Framework base classes and runtime environment. It comes with power packed features that simplify application development.
Namespaces
A namespace is a collection of different classes. All VB applications are developed using classes from the .NET System namespace. The namespace with all the built-in VB functionality is the System namespace. All other namespaces are based on this System namespace
Some Namespaces and their use:
System: Includes essential classes and base classes for commonly used
System. Collections: Includes classes and interfaces that define various collection
of objects such as list, queues, hash tables, arrays, etc
System. Data: Includes classes which lets us handle data from data sources
System.Data.OleDb: Includes classes that support the OLEDB .NET provider System. Drawing: Provides access to drawing methods
System.IO: Includes classes for data access with Files
System. Threading: Includes classes and interfaces to support multithreaded System. Web: Includes classes and interfaces that support browser-server System.Windows.Forms: Includes classes for creating Windows based forms
Assemblies
An assembly is the building block of a .NET application. It is a self describing collection of code, resources, and metadata (data about data, example, name, size, version of a file is metadata about that file). An Assembly is a complied and versioned collection of code and metadata that forms an atomic functional unit. Assemblies take the form of a
dynamic link library (.dll) file or executable program file (.exe) but they differ as they contain the information found in a type library and the information about everything else needed to use an application or component. All .NET programs are constructed from these Assemblies. Assemblies are made of two parts: manifest, contains information about what is contained within the assembly and modules, internal files of IL code which are ready to run. When programming, we don't directly deal with assemblies as the CLR and the .NET framework takes care of that behind the scenes. The assembly file is visible in the Solution Explorer window of the project.
Data
Type
Size
Byte 1 8-bit System.Byte
Char 2 16-bit System.Char
Integer 4 32-bit System.Int32
Double 8 64-bit System.Double
Long 8 64-bit System.Int64
Short 2 16-bit System.Int16
Single 4 32-bit System.Single
String Varies Non-Numeric Type System.String
Date 8 System.Date
Boolean 2 Non-Numeric Type System.Boolean Object 4 Non-Numeric Type System.Object
Decimal 16 128-bit System.Decimal
Access specifiers let's us specify how a variable, method or a class can be used. The following are the most commonly used one's:
Public: Gives variable public access which means that there is no restriction on their accessibility
Private: Gives variable private access which means that they are accessible only within their declaration content
Protected: Protected access gives a variable accessibility within their own class or a class derived from that class
Friend: Gives variable friend access which means that they are accessible within the program that contains their declaration
Protected Friend: Gives a variable both protected and friend access
Static: Makes a variable static which means that the variable will hold the value even the procedure in which they are declared ends
Shared: Declares a variable that can be shared across many instances and which is not associated with a specific instance of a class or structure
Variables
Variables are used to store data. A variable has a name to which we refer and the data type, the type of data the variable holds. VB .NET now needs variables to be declared before using them. Variables are declared with the Dim keyword. Dim stands for Dimension.
Statements
A statement is a complete instruction. It can contain keywords, operators, variables, literals, expressions and constants. Each statement in Visual Basic should be either a declaration statement or a executable statement. A declaration statement is a statement that can create a variable, constant, data type. They are the one's we generally use to declare our variables. On the other hand, executable statements are the statements that perform an action. They execute a series of statements. They can execute a function, method, loop, etc.
Option Statement
The Option statement is used to set a number of options for the code to prevent
syntax and logical errors. This statement is normally the first line of the code. The Option values in Visual Basic are as follows.
Option Compare: You can set it's value to Text or Binary. This specifies if the
strings are compared using binary or text comparison operators.
Option Explicit: Default is On. You can set it to Off as well. This requires to
declare all the variables before they are used.
Option Strict: Default is Off. You can set it to On as well. Used normally when
working with conversions in code. If you want to assign a value of one type to another then you should set it to On and use the conversion functions else Visual Basic will consider that as an error.
When types cannot be implicitly converted you should convert them explicitly. This conversion is also called as cast. Explicit conversions are accomplished using CType function.
CType function for conversion
If we are not sure of the name of a particular conversion function then we can use the CType function. The above example with a CType function looks like this:
Imports System.Console 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 WriteLine("Integer value is" & i)
End Sub End Module
Explicit Conversions
CBool - use this function to convert to Bool data type CByte - use this function to convert to Byte data type CChar - use this function to convert to Char data type CDate - use this function to convert to Date type CDbl - use this function to convert to Double data type CDec - use this function to convert to Decimal data type CInt - use this function to convert to Integer data type CLng - use this function to convert to Long data type CObj - use this function to convert to Object type CShort - use this function to convert to Short data type CSng - use this function to convert to Single data type CString - use this function to convert to String data type
Operators
Visual Basic comes with many built-in operators that allow us to manipulate data. An operator performs a function on one or more operands. For example, we add two variables with the "+" addition operator and store the result in a third variable with the "=" assignment operator like this: int x + int y = int z. The two variables (x ,y) are called operands. There are different types of operators in Visual Basic and they are described below in the order of their precedence
Arithmetic Operators
Arithmetic operators are used to perform arithmetic operations that involve calculation of numeric values. The table below summarizes them:
Operator Use
^ Exponentiation
* Multiplication
/ Division
\ Integer Division
Mod Modulus Arithmetic
+ Addition
- Subtraction
Concatenation Operators
Concatenation operators join multiple strings into a single string. There are two concatenation operators, + and & as summarized below:
Operator Use
+ String Concatenation & String Concatenation Comparison Operators
A comparison operator compares operands and returns a logical value based on whether the comparison is true or not. The table below summarizes them:
Operator Use
= Equality
<> Inequality
< Less than
> Greater than
>= Greater than or equal to <= Less than or equal to Logical / Bitwise Operators
The logical operators compare Boolean expressions and return a Boolean result. In short, logical operators are expressions which return a true or false result over a conditional expression. The table below summarizes them:
Operator Use Not Negation And Conjunction AndAlso Conjunction Or Disjunction OrElse Disjunction Xor Disjunction
Arrays
Arrays are programming constructs that store data and allow us to access them by numeric index or subscript. Arrays helps us create shorter and simpler code in many situations. Arrays in Visual Basic .NET inherit from the Array class in the System
namespace. All arrays in VB as zero based, meaning, the index of the first element is zero and they are numbered sequentially. You must specify the number of array elements by indicating the upper bound of the array. The upper bound is the numder that specifies the index of the last element of the array. Arrays are declared using Dim, ReDim, Static,
Private, Public and Protected keywords. An array can have one dimension (liinear arrays) or more than one (multidimensional arrays). The dimensionality of an array refers to the number of subscripts used to identify an individual element. In Visual Basic we can specify up to 32 dimensions. Arrays do not have fixed size in Visual Basic.
The following code demonstrates arrays. Module Module1
Sub Main()
Dim sport(5) As String 'declaring an array sport(0) = "Soccer" sport(1) = "Cricket" sport(2) = "Rugby" sport(3) = "Aussie Rules" sport(4) = "BasketBall" sport(5) = "Hockey" 'storing values in the array
WriteLine("Name of the Sport in the third location" & " " & sport(2)) 'displaying value from array
End Sub End Module
STRING FUNCTIONS
Public Function Asc(ByVal String As Char) As Integer
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns an Integer representing the character code corresponding to the first letter in a string.
Public Function Chr(ByVal CharCode As Integer) As Char
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns the character associated with the specified character code as a Char data type.
Public Function Format(ByVal Expression As Object, Optional ByVal Style As String = "") As String
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns a String expression formatted according to instructions contained in a format String expression.
STRING FUNCTIONS
Public Function Mid(ByVal str As String, ByVal Start As Integer) As String Member of: Microsoft.VisualBasic.Strings
Summary:
Replaces a specified number of characters in a String variable with characters from another string.
Parameters:
str: Name of the String variable to modify.
Start: Integer data type. Character position in target where the replacement of text begins.
Start uses a one based index.
Public Function StrComp(ByVal String1 As String, ByVal String2 As String,
Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As Integer Member of: Microsoft.VisualBasic.Strings
Summary:
Returns -1, 0, or 1, based on the result of a string comparison. The strings are compared by alphanumeric sort values begining with the first character.
Parameters:
String1: Any valid String expression. String2: Any valid String expression.
Compare: Specifies the type of string comparison. If compare is omitted, the Option
Compare setting determines the type of comparison.
Public Function GetChar(ByVal str As String, ByVal Index As Integer) As
Char
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns the character at a specified position in a string
Parameters:
str: String to use as a source
Index: 1 based index of the character to return
Public Function InStr(ByVal Start As Integer, ByVal String1 As String, ByVal
String2 As String, Optional ByVal Compare As
Microsoft.VisualBasic.CompareMethod = 0) As Integer
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns an Integer specifying the start position of the first occurrence of one string within another.
Parameters:
Start: Numeric expression that sets the starting position for each search. If omitted,
search begins at the first character position. The start index is 1 based.
String1: String expression being searched. String2: String expression sought.
Public Function InStrRev(ByVal StringCheck As String, ByVal StringMatch As
String, Optional ByVal Start As Integer = -1, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As Integer
Summary:
Returns the position of the first occurrence of one string within another, starting from the right side of the string.
Parameters:
StringCheck: String expression being searched. StringMatch: String expression being searched for.
Start: Numeric expression that sets the one-based starting position for each search,
starting from the left side of the string. If Start is omitted, –1 is used, which means that the search begins at the last character position. Search then proceeds from right to left. Public Function Join(ByVal SourceArray() As Object, Optional ByVal Delimiter As String = " ") As String
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns a string created by joining a number of substrings contained in an array.
Parameters:
SourceArray: One-dimensional array containing substrings to be joined.
Delimiter: String used to separate the substrings in the returned string. If omitted, the
space character (" ") is used. If Delimiter is a zero-length string (""), all items in the list are concatenated with no delimiters.
Public Function LCase(ByVal Value As String) As String
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns a String or Char that has been converted to lowercase.
Parameters:
Value: Any valid String or Char expression.
Public Function Left(ByVal str As String, ByVal Length As Integer) As String
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns a String containing a specified number of characters from the left side of a string.
Parameters:
Str: String expression from which the leftmost characters are returned.
Length: Integer expression. Numeric expression indicating how many characters to
return. If 0, a zero-length string ("") is returned. If greater than or equal to the number of characters in Str, the entire string is returned.
Public Function Len(ByVal Expression As Byte) As Integer Member of: Microsoft.VisualBasic.Strings
Summary:
Returns an Integer containing either the number of characters in a string or the
number of bytes required to store a variable.
Parameters:
Expression: valid String expression or variable name. If Expression is of type
Object, the Len function returns the size as it will be written to the file.
Public Function Mid(ByVal str As String, ByVal Start As Integer) As String
Member of: Microsoft.VisualBasic.Strings
Replaces a specified number of characters in a String variable with characters from another string.
Parameters:
str: Name of the String variable to modify.
Start: Integer data type. Character position in target where the replacement of text begins.
Start uses a one based index.
Public Function Replace(ByVal Expression As String, ByVal Find As String,
ByVal Replacement As String, Optional ByVal Start As Integer = 1, Optional ByVal
Count As Integer = -1, Optional ByVal Compare As
Microsoft.VisualBasic.CompareMethod = 0) As String
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns a string in which a specified substring has been replaced with another substring a specified number of times.
Parameters:
Expression: String expression containing substring to replace. Find: Substring being searched for.
Replacement: Replacement substring.
Start: Position within Expression where substring search is to begin. If omitted, 1 is
assumed.
Count: Number of substring substitutions to perform. If omitted, the default value is –1,
which means make all possible substitutions.
Compare: Numeric value indicating the kind of comparison to use when evaluating
substrings. See Settings for values.
Public Function Split(ByVal Expression As String, Optional ByVal Delimiter As
String = " ", Optional ByVal Limit As Integer = -1, Optional ByVal Compare As Microsoft.VisualBasic.CompareMethod = 0) As String()
Member of: Microsoft.VisualBasic.Strings
Summary:
Returns a zero-based, one-dimensional array containing a specified number of substrings.
Parameters:
Expression: String expression containing substrings and delimiters. If Expression is a
zero-length string (""), the Split function returns an array with no elements and no data.
Delimiter: Single character used to identify substring limits. If Delimiter is omitted, the
space character (" ") is assumed to be the delimiter. If Delimiter is a zero-length string, a single-element array containing the entire Expression string is returned.
Limit: Number of substrings to be returned; the default, –1, indicates that all substrings
are returned.
Compare: Numeric value indicating the comparison to use when evaluating substrings.
See Settings for values. CONTROL STATEMENTS
IF condition THEN
ELSE END IF
SELECT CASE expr
CASE exprlst1 CASE exprlst2 …. …. CASE exprlstN END SELECT
SWITCH(expr-1,value-1,expr-2, value-2,..expr-N, value-N) CHOOSE(index,chice-1, chice-2, chice-3…. chice-N)
LOOPING CONSTUCTS
DO while/until condition
Stmt
Exit do LOOP
for index=start to end step
Statements Exit for NEXT WHILE condition Statements WEND WITH object Statements END WITH
Messagebox Function
MessageBox.Show(Arguments)Several choices for argument list
Introduces concept of Overloaded functions Multiple signatures to choose from
MessageBox.Show(TextMessage)
MessageBox.Show(TextMessage, TitlebarText) MessageBox.Show(TextMessage, TitlebarText, _
MessageBox.Show(TextMessage, TitlebarText, _ MessageBoxButtons, MessageBoxIcon)
MessageBox Icons and buttons Enumeration of constants
Menus,Sub Procedures,Sub Functions
Creating Menus and Menu Items Creating ContextMenus
Displaying Common Dialog Boxes Writing General Procedures
Menus
Create a menu by adding a MainMenu control to the component tray Great new Menu Designer replaces the Menu Editor
Menus
For Context menus, add a ContextMenu control
A ContextMenu uses the same Menu Designer as a MainMenu
Attach a context menu by setting the ContextMenu property of a control or the form
Sub Function
Arguments are passed ByVal (by default)
The Editor adds ByVal if you leave it out
New Return statement
Can still set function name to value Better to use the Return statement
Private Function CalculateSum( _ ByVal intNum1 As Integer, _
ByVal intNum2 As Integer) As Integer 'Calculate the sum of the numbers Return intNum1 + intNum2 End Function
CONTROLS
Button Control
One of the most popular control in Visual Basic is the Button Control (previously Command Control). They are the controls which we click and release to perform some action. Buttons are used mostly for handling events in code, say, for sending data entered in the form to the database and so on. The default event of the Button is the Click event and the Button class is based on the ButtonBase class which is based on the Control class.
Button Event
The default event of the Button is the Click event. When a Button is clicked it responds with the Click Event. The Click event of Button looks like this in code: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click
'You place the code here to perform action when Button is clicked End Sub
Important Properties of Button1
Appearance
BackColor and Background Image properties we can set a background color and
a background image to the button.
We set the font color and font style for the text that appears on button with
ForeColor and the Font property.
We change the appearance style of the button with the FlatStyle property. We can change the text that appears on button with the Text property with the TextAlign property we can set where on the button the text should
appear from a predefined set of options. Behavior
Notable Behavior properties of the Button are the Enabled and Visible properties. The Enabled property is set to True by default which makes the button enabled and setting it's property to False makes the button Disabled.
With the Visible property we can make the Button Visible or Invisible. The default value is set to True and to make the button Invisible set it's property to False.
Layout
Layout properties are about the look of the Button. Note the Dock property here. A control can be docked to one edge of its parent container or can be docked to all
edges and fill the parent container. The default value is set to none. If you want to dock the control towards the left, right, top, bottom and center you can do that by selecting from the button like image this property displays.
With the Location property you can change the location of the button.
With the Size property you can set the size of the button. Apart from the Dock
property you can set it's size and location by moving and stretching the Button on the form itself.
Creating a Button in Code
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 Button1 as New Button() 'declaring the button, Button1 Button1.Text="Creating a Button"
Button1.Location=New Point(100,50)
'setting the location for the Button where it should be created Button1.Size=New Size(75,23)
'setting the size of the Button Me.Controls.Add(Button1)
'adding the Button that is created to the form
'the Me keyword is used to refer to the current object, in this case the Form End Sub
End Class
Label
Labels are those controls that are used to display text in other parts of the application. They are based on the Control class.
Notable property of the label control is the text property which is used to set the text for the label.
Creating a Label in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load Dim Label1 As New Label() Label1.Text = "Label"
Label1.Location = New Point(135, 70) Label1.Size = New Size(30, 30) Me.Controls.Add(Label1) End Sub
TextBox Control
Windows users should be familiar with textboxes. This control looks like a box and accepts input from the user.
The TextBox is based on the TextBoxBase class which is based on the Control class. TextBoxes are used to accept input from the user or used to display text.
By default we can enter up to 2048 characters in a TextBox but if the Multiline property is set to True we can enter up to 32KB of text. The image below displays a Textbox
Some Notable Properties:
Behavior
Enabled: Default value is True. To disable, set the property to False.
Multiline: Setting this property to True makes the TextBox multiline which allows to accept multiple lines of text. Default value is False.
PasswordChar: Used to set the password character. The text displayed in the TextBox will be the character set by the user. Say, if you enter *, the text that is entered in the TextBox is displayed as *.
Read Only: Makes this TextBox readonly. It doesn't allow to enter any text. Visible: Default value is True. To hide it set the property to False Appearance section
TextAlign: Allows to align the text from three possible options. The default value is left and you can set the alignment of text to right or center.
Scrollbars: Allows to add a scrollbar to a Textbox. Very useful when the TextBox is multiline. You have four options with this property. Options are are None, Horizontal, Vertical and Both. Depending on the size of the TextBox anyone of those can be used. Code to Validate User Input
We can make sure that a TextBox can accept only characters or numbers which can restrict accidental operations. For example, adding two numbers of the form 27+2J cannot return anything. To avoid such kind of operations we use the KeyPress event of the TextBox.
Code that allows you to enter only double digits in a TextBox looks like this:
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
Creating a TextBox in Code
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 TextBox1 as New TextBox() TextBox1.Text="Hello Mate" TextBox1.Location=New Point(100,50) TextBox1.Size=New Size(75,23) Me.Controls.Add(TextBox1) End Sub End Class
CheckBox
CheckBoxes are those controls which gives us an option to select, say, Yes/No or True/False. A checkbox is clicked to select and clicked again to deselect some option. When a checkbox is selected a check (a tick mark) appears indicating a selection. The CheckBox control is based on the TextBoxBase class which is based on the Control class. Below is the image of a Checkbox.
Notable Properties
Important properties of the CheckBox in the Appearance section of the properties
window are:
Appearance: Default value is Normal. Set the value to Button if you want the
CheckBox to be displayed as a Button.
BackgroundImage: Used to set a background image for the checkbox.
CheckAlign: Used to set the alignment for the CheckBox from a predefined list.
as checked.
CheckState: Default value is Unchecked. Set it to True if you want a check to appear. When set to Indeterminate it displays a check in gray background.
FlatStyle: Default value is Standard. Select the value from a predefined list to set the style of the checkbox.
Important property in the Behavior section of the properties window is the ThreeState property which is set to False by default. Set it to True to specify if the Checkbox can allow three check states than two.
Code to check a CheckBox's state
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click
If CheckBox1.Checked = True Then TextBox1.Text = "Checked"
Else
TextBox1.Text = "UnChecked" End If
End Sub
Creating a CheckBox in Code
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles_ MyBase.Load
Dim CheckBox1 As New CheckBox() CheckBox1.Text = "Checkbox1"
CheckBox1.Location = New Point(100, 50) CheckBox1.Size = New Size(95, 45) Me.Controls.Add(CheckBox1) End Sub
ComboBox
ComboBox is a combination of a TextBox and a ListBox. The ComboBox displays an editing field (TextBox) combined with a ListBox allowing us to select from the list or to enter new text. ComboBox displays data in a drop-down style format. The ComboBox class is derived from the ListBox class. Below is the Image of a ComboBox.
Notable properties of the ComboBox
The DropDownStyle property in the Appearance section of the properties window
allows us to set the look of the ComboBox. The default value is set to DropDown which means that the ComboBox displays the Text set by it's Text property in the Textbox and displays it's items in the DropDownListBox below. Setting it to simple makes the ComboBox to be displayed with a TextBox and the list box which doesn't drop down. Setting it to DropDownList makes the ComboBox to make selection only from the drop down list and restricts you from entering any text in the textbox.
We can add items to the ComboBox with it's Items property.
Removing items from a ComboBox
You can remove all items or one particular item from the list box part of the ComboxBox. Code to remove a particular item by it's Index number looks like this: Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click
ComboBox1.Items.RemoveAt(4)
'removing an item by specifying it's index End Sub
Code to remove all items from the ComboBox
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As_ System.EventArgs) Handles Button1.Click
ComboBox1.Items.Clear()
'using the clear method to clear the list box End Sub
Handling Mouse Events in Forms
We can handle mouse events such as mouse pointer movements in Forms. The mouse events supported by VB .NET are as follows:
MouseDown: This event happens when the mouse pointer is over the form/control and is pressed
MouseEnter: This event happens when the mouse pointer enters the form/control MouseUp: This event happens when the mouse pointer is over the form/control and the
mouse button is released
MouseLeave: This event happens when the mouse pointer leaves the form/control
MouseMove: This event happens when the mouse pointer is moved over the form/control MouseWheel: This event happens when the mouse wheel moves while the form/control
has focus
MouseHover: This event happens when the mouse pointer hovers over the form/control
The properties of the MouseEventArgs objects that can be passed to the mouse event handler are as follows:
Button: Specifies that the mouse button was pressed
Clicks: Specifies number of times the mouse button is pressed and released X: The X-coordinate of the mouse click
Y: The Y-coordinate of the mouse click
Delta: Specifies a count of the number of detents (rotation of mouse wheel) the mouse
wheel has rotated
ListBox
The ListBox control displays a list of items from which we can make a selection. We can select one or more than one of the items from the list. The ListBox control is based on the ListControl class which is based on the Control class. The image below
displays a ListBox.
Notable Properties of the ListBox
In the Behavior Section
HorizontalScrollbar: Displays a horizontal scrollbar to the ListBox. Works when
the ListBox has MultipleColumns.
MultiColumn: The default value is set to False. Set it to True if you want the list box to display multiple columns.
ScrollAlwaysVisible: Default value is set to False. Setting it to True will display both Vertical and Horizontal scrollbar always.
SelectionMode: Default value is set to one. Select option None if you do not any item to be selected. Select it to MultiSimple if you want multiple items to be selected. Setting it to MultiExtended allows you to select multiple items with the help of Shift, Control and arrow keys on the keyboard.
Sorted: Default value is set to False. Set it to True if you want the items displayed in the ListBox to be sorted by alphabetical order.
Counting the number of Items in a ListBox
Add a Button to the form and place the following code in it's click event. Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _
As System.EventArgs) Handles Button1.Click TextBox1.Text = ListBox1.Items.Count
'counting the number of items in the ListBox with the Items.Count
End Sub When you run the code and click the Button it will display the number of items available in the ListBox.
Code to display the item selected from ListBox in a TextBox
Private Sub ListBox1_SelectedIndexChanged(ByVal sender As System.Object,_
ByVal e As System.EventArgs) Handles ListBox1.SelectedIndexChanged TextBox1.Text = ListBox1.SelectedItem
'using the selected item property
End Sub When you run the code and click an item in the Code to remove a particular item
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e _ As System.EventArgs) Handles Button1.Click
ListBox1.Items.RemoveAt(4)
'removing an item by specifying it's index End Sub
Code to Remove all items
Private Sub Button1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles Button1.Click
ListBox1.Items.Clear()
'using the clear method to clear the list box End Sub
Example
Code to add and remove data
Code to Shift single selected item from one listbox to another listbox Code to shift multiple items
Example-checkbox and option button Example-Calculator
Code for number buttons Code for Operators buttons Code for equals buttons
Common Dialogs
Visual Basic .NET comes with built-in dialog boxes which allow us to create our own File Open, File Save, Font, Color dialogs much like what we see in all other windows applications. To make a dialog box visible at run time we use the dialog box's
ShowDialog method. The Dialog Boxes which come with Visual Basic .NET are: OpenFileDialog, SaveFileDialog FontDialog ColorDialog PrintDialog PrintPreviewDialog and PageSetupDialog.
We will be working with OpenFile, SaveFile, Font and Color Dialog's in this section. The return values of all the above said dialog boxes which will determine which selection a user makes are: Abort, Cancel, Ignore, No, None, OK, Return, Retry and Yes.
OpenFileDialog
Properties of the OpenFileDialog are as follows:
AddExtension: Gets/Sets if the dialog box adds extension to file names if the user doesn't supply the extension.
CheckFileEixsts: Checks whether the specified file exists before returning from the dialog.
CheckPathExists: Checks whether the specified path exists before returning from the dialog.
DefaultExt: Allows you to set the default file extension. FileName: Gets/Sets file name selected in the file dialog box. FileNames: Gets the file names of all selected files.
Filter: Gets/Sets the current file name filter string, which sets the choices that appear in the "Files of Type" box.
FilterIndex: Gets/Sets the index of the filter selected in the file dialog box.
InitialDirectory: This property allows to set the initial directory which should open when you use the OpenFileDialog.
SaveFileDialog
Save File Dialog's are supported by the SaveFileDialog class and they allow us to save the file in a specified location.
Properties of the Save File Dialog are the same as that of the Open File Dialog. Please refer above. Notable property of Save File dialog is the OverwritePromopt
property which displays a warning if we choose to save to a name that already exists.
FontDialog
Properties of the FontDialog are as follows:
AllowSimulations: Gets/Sets whether the dialog box allows graphics device interface font simulations.
Color: Gets/Sets selected font color. Font: Gets/Sets the selected font.
FontMustExist: Gets/Sets whether the dialog box specifies an error condition if the user attempts to select a font or size that doesn't exist.
MaxSize: Gets/Sets the maximum point size the user can select. MinSize: Gets/Sets the mainimum point size the user can select.
ShowApply: Gets/Sets whether the dialog box contains an apply button. ShowColors: Gets/Sets whether the dialog box displays the color choice.
ShowEffects: Gets/Sets whether the dialog box contains controls that allow the user to specify to specify strikethrough, underline and text color options.
ShowHelp: Gets/Sets whether the dialog box displays a help button.
ColorDialogs
Properties of ColorDialog are as follows:
AllowFullOpen: Gets/Sets whether the user can use the dialog box to define custom colors.
AnyColor: Gets/Sets whether the dialog box displays all the available colors in the set of basic colons.
Color: Gets/Sets the color selected by the user.
CustomColors: Gets/Sets the set of custom colors shown in the dialog box.
FullOpen: Gets/Sets whether the controls used to create custom colors are visible when the dialog box is opened.
ShowHelp: Gets/Sets whether the dialog box displays a help button.
SolidColorOnly: Gets/Sets whether the dialog box will restrict users to selecting solid colors only.
The Windows Forms TreeView control displays a hierarchy of nodes, like the way files and folders are displayed in the left pane of Windows Explorer.
The Windows Forms TreeView control displays a hierarchy of nodes, like the way files and folders are displayed in the left pane of Windows Explorer. Each node might contain other nodes, called child nodes. Parent nodes, or nodes that contain child nodes, can be displayed as expanded or collapsed. A tree view can also be displayed with check boxes next to the nodes, if the tree view's CheckBoxes property is set to true. You can then programmatically select or clear nodes by setting the node's Checked property to true or
false. The key properties of the TreeView control are Nodes and SelectedNode. The Nodes property contains the list of top-level nodes in the tree view. The SelectedNode
property sets the currently selected node. Icons can be displayed next to the nodes; the images are taken from the ImageList control named in the tree view's ImageList
property. The ImageIndex property sets the default image for nodes in the tree view. For more information on displaying images
To add or remove nodes in the designer
1. Select the TreeView control or add one to the form.
2. In the Properties window, click the ellipsis ( ) button next to the Nodes property.
The TreeNode Editor appears.
3. To add nodes, a root node must exist; if one does not exist, you must first add a root by clicking the Add Root button. You can then add child nodes by selecting the root or any other node and clicking the Add Child button. To delete nodes, select the node to delete and then click the Delete button.
To add nodes programmatically
Use the Add method of the tree view's Nodes property.
Dim newNode As TreeNode = New TreeNode("Text for new node") TreeView1.SelectedNode.Nodes.Add(newNode)
To remove nodes programmatically
Use the Remove method of the tree view's Nodes property to remove a single node, or the Clear method to clear all nodes.
TreeView1.Nodes.Remove(TreeView1.SelectedNode) TreeView1.Nodes.Clear()
Use the EventArgs object to return a reference to the clicked node object.
Determine which node was clicked by checking the TreeViewEventArgs class, which contains data related to the event.
Private Sub TreeView1_AfterSelect(ByVal sender As System.Object, _ ByVal e As System.Windows.Forms.TreeViewEventArgs) Handles TreeView1.AfterSelect
.
MessageBox.Show(e.Node.Text) End Sub
LISTVIEW CONTROL
The Windows Forms ListView control displays a list of items with icons. You can use a list view to create a user interface like the right pane of Windows Explorer.
The Windows Forms ListView control displays a list of items with icons. You can use a list view to create a user interface like the right pane of Windows Explorer. The control has four view modes: LargeIcon, SmallIcon, List, and Details. The LargeIcon mode displays large icons next to the item text; the items appear in multiple columns if the control is large enough. The SmallIcon mode is the same except that it displays small icons. The List mode displays small icons but is always in a single column. The Details mode displays items in multiple columns.
The key property of the ListView control is Items, which contains the items displayed by the control. The SelectedItems property contains a collection of the items currently selected in the control. The user can select multiple items, for example to drag and drop several items at a time to another control, if the MultiSelect property is set to true. The
ListView control can display check boxes next to the items, if the CheckBoxes property
is set to true.
The Activation property determines what type of action the user must take to activate an item in the list: the options are Standard, OneClick, and TwoClick. OneClick activation requires a single click to activate the item. TwoClick activation requires the user to double-click to activate the item; a single click changes the color of the item text.
Standard activation requires the user to double-click to activate an item, but the item does not change appearance
1. In the Properties window, click the ellipsis button ( ) next to the Items property.
The ListViewItem Collection Editor appears.
2. To add an item, click the Add button. You can then set properties of the new item, such as the Text and ImageIndex properties. To remove an item, select it and click the Remove button.
To add items programmatically
ListView1.Items.Add("List item text", 3)
To add columns in the designer
1. Set the control's View property to Details.
2. In the Properties window, click the ellipsis button ( ) next to the Columns property.
The ColumnHeader Collection Editor appears.
3. Use the Add button to add new columns. You can then select the column header and set its text (the caption of the column), text alignment, and width.
To add columns programmatically
Set the control's View property to Details.
Use the Add method of the list view's Columns property. ListView1.View = View.Details
ListView1.Columns.Add("File type", 20, HorizontalAlignment.Left)
To display images in a list view
1. Set the appropriate property, SmallImageList, LargeImageList, or
StateImageList, to the existing ImageList component you wish to use.
These properties can be set in the designer with the Properties window, or in code. ' Visual Basic
2. Set the ImageIndex or StateImageIndex property for each list item that has an associated icon.
These properties can be set in code, or within the ListViewItem Collection
Editor. To open the ListViewItem Collection Editor, click the ellipsis button (
) next to the Items property on the Properties window. ' Visual Basic
' Sets the first list item to display the 4th image ListView1.Items(0).ImageIndex = 3
OOP-Concept
ObjectsVisual basic allows you to create object by defining class.Class may have properties and methods. Object is a thing which is properties and methods.
User defined class can be created in vb.and that classes can be incorporated to projects as a references.
Properties are the characteristic and methods are the operation that can be performed on an object. OOP-Terminology Encapsulation Inheritance Polymorphism CLASSES Instantiating an object New class name i.e
Dim c = new font(“arial”,12) Lblfnt.font=c
Creating your own classes
Create a new application of type class library Create properties of the class.
Property procedure
the way that your class allows its properties is to be accessed is through a property procedure. it may contain a get to retrieve a property value and a set to assign a value to the property.
Following is the example: Property op1() As Integer Get
op1 = no1 End Get
Set(ByVal Value As Integer) no1 = Value
End Set End Property
Creating your own classes
Create a new application of type class library Create properties of the class.
Property procedure
the way that your class allows its properties is to be accessed is through a property procedure. it may contain a get to retrieve a property value and a set to assign a value to the property.
Following is the example: Property op1() As Integer Get
op1 = no1 End Get
Set(ByVal Value As Integer) no1 = Value
End Set End Property
Creating new object using classes
Create new object using following statement in windows application Dim c as new class name
This class name must be add as a reference in a project.
Data Access Technologies
Most applications require some form of data access. If you are creating a new application, you have three excellent data access choices: ADO.NET, ADO, and OLE DB. If you need to modify the data access for an existing application, you might continue using the application's current data access technology for maintenance convenience. However, if you expect the application to have a long lifecycle, you should consider reengineering to use either ADO.NET for managed applications or ADO for native applications. In the
long run, the newer data access technologies typically reduce development time, simplify code, and provide excellent performance.
ADO.NET
ADO.NET is the strategic application-level interface for providing data access services in the Microsoft .NET Platform. You can use ADO.NET to access data sources using the new .NET Framework data providers. These data providers include:
• .NET Framework Data Provider for SQL Server.
• .NET Framework Data Provider for OLE DB.
• .NET Framework Data Provider for ODBC.
• .NET Framework Data Provider for Oracle.
These data providers support a variety of development needs, including middle-tier business objects using live connections to data in relational databases and other stores. ADO.NET is designed specifically for message-based Web applications while still providing preferable functionality for other application architectures. By supporting loosely coupled access to data, ADO.NET maximizes data sharing by reducing the number of active connections to the database — reducing the possibility of multiple users contending for limited resources on the database server.
ADO.NET provides several ways to access data. If your Web application or XML Web service requires data access from multiple sources, needs to interoperate with other applications (both local and remote), or can benefit from persisting and transmitting cached results, the dataset is an excellent choice. As an alternative, ADO.NET provides data commands and data readers to communicate directly with the data source. Direct database operations using data commands and data readers include running queries and stored procedures, creating
Advantages of ADO.NET over ADO
Interoperability
ADO.NET applications can take advantage of the flexibility and broad acceptance of XML. Because XML is the format for transmitting datasets across the network, any component that can read the XML format can process data. In fact, the receiving
component need not be an ADO.NET component at all: The transmitting component can simply transmit the dataset to its destination without regard to how the receiving
component is implemented. The destination component might be a Visual Studio application or any other application implemented with any tool whatsoever. The only requirement is that the receiving component be able to read XML. As an industry standard, XML was designed with exactly this kind of interoperability in mind.
Maintainability
In the life of a deployed system, modest changes are possible, but substantial, architectural changes are rarely attempted because they are so difficult. That is
unfortunate, because in a natural course of events, such substantial changes can become necessary. For example, as a deployed application becomes popular with users, the increased performance load might require architectural changes. As the performance load on a deployed application server grows, system resources can become scarce and
response time or throughput can suffer. Faced with this problem, software architects can choose to divide the server's business-logic processing and user-interface processing onto separate tiers on separate machines. In effect, the application server tier is replaced with two tiers, alleviating the shortage of system resources.
The problem is not designing a three-tiered application. Rather, it is increasing the
number of tiers after an application is deployed. If the original application is implemented in ADO.NET using datasets, this transformation is made easier. Remember, when you replace a single tier with two tiers, you arrange for those two tiers to trade information. Because the tiers can transmit data through XML-formatted datasets, the communication is relatively easy.
Programmability
ADO.NET data components in Visual Studio encapsulate data access functionality in various ways that help you program more quickly and with fewer mistakes. For example, data commands abstract the task of building and executing SQL statements or stored procedures.
Similarly, ADO.NET data classes generated by the tools result in typed datasets. This in turn allows you to access data through typed programming. For example, consider the following line of code that accesses a data member in an untyped dataset:
The equivalent line to access a data member in a typed dataset looks like the following: ' Visual Basic
Performance
For disconnected applications, ADO.NET datasets offer performance advantages over ADO disconnected recordsets. When using COM marshalling to transmit a disconnected recordset among tiers, a significant processing cost can result from converting the values in the recordset to data types recognized by COM. In ADO.NET, such data-type
conversion is not necessary.
Scalability
Because the Web can vastly increase the demands on your data, scalability has become critical. Internet applications have a limitless supply of potential users. Although an