modern programming tools_and techniques iii - shrivastava - ibrg

362
 www.lpude.in DIRECTORATE OF DISTANCE EDUCATION MODERN PROGRAMMING TOOLS & TECHNIQUES-III

Upload: michael

Post on 07-Oct-2015

61 views

Category:

Documents


1 download

DESCRIPTION

Modern Prommaming Tools and Techniques

TRANSCRIPT

  • www.lpude.in

    DIRECTORATE OF DISTANCE EDUCATION

    MODERN PROGRAMMING TOOLS & TECHNIQUES-III

  • Copyright 2013, Varun BhardwajAll rights reserved.

    Produced & Printed byFRANK BROTHERS & CO. (PUBLISHERS) LIMITED

    B-41, Sector-4, NOIDA - 201301, Gautam Budh Nagarfor

    Directorate of Distance EducationLovely Professional University

    Phagwara

  • Directorate of Distance Education

    LPU is reaching out to the masses by providing an intellectual learning environment that is academically rich with most affordable fee structure. Supported by the largest University1 in the country, LPU, the Directorate of Distance Education (DDE) is bridging the gap between education and the education seekers at a fast pace, through the usage of technology which significantly extends the reach and quality of education. DDE aims at making Distance Education, a credible and valued mode of learning, by providing education without a compromise.

    DDE is a young and dynamic wing of the University, filled with energy, enthusiasm, compassion and concern. Its team strives hard to meet the demands of the industry, to ensure quality in curriculum, teaching methodology, examination and evaluation system, and to provide the best of services to its students. DDE is proud of its values, by virtue of which, it ensures to make an impact on the education system and its learners.

    Through affordable education, online resources and a network of Study Centres, DDE intends to reach the unreached.

    1. in terms of no. of students in a single campus

  • SYLLABUS

    Modern Programming Tools & Techniques-III

    Objectives: To impart the skills needed to implement Network enabled technologies. To enable the student to understand dot net framework classes.

    To enable the student to develop multi-language support applications.

    To enable the student to develop platform independent applications.

    To enable the student to develop console and windows applications.

    To enable the student to implementing Object oriented concepts in dot net.

    To enable the student to learn file handling using dot net.

    To enable the student to understand Database application development using dot net and data transmission technology.

    S. No. Topics

    1. Introduction: What is VB.NET, Characteristics of VB.NET, VB.NET as a language in .NET Framework.

    2. Variables and Data Types: Variables and Data Types. Decision Making and Looping: If, If else if. While, do while, for loop, Declaring Arrays. System. Array class

    3. In Built Functions: String Class, Conversion functions, other Miscellaneous Functions, Subroutines and Functions

    4. Classes & Object in VB.NET: Using Classes, object, methods. Constructors. Creating Properties and indexers. Using Inheritance in classes.

    5. Namespaces: Meaning and its working. Using System Namespace and Object class. Exception Handling: Using Try and Catch blocks, The Finally Section

    6. Using System. Collections: Array List, Stack, Queue, Sorted List etc.

    7. Windows Programming: Using Controls- textboxes, listbox, buttons, datetime picker, comboboxes etc.

    8. Common Dialog Boxes: OpenFileDialog, SaveFileDialog, ColorDialog, MessageBox Class and DialogResult Class.

    9. File Input Output: Working with Files and Directories. System.IO.

    10. ADO.NET: Accesing Database with ADO.NET. Executing Insertion, deletion, updation and select command with databases. XML Basics: What is XML? Data Representation through XML. Working with XMLReader and XMLWriter Classes.

    COURSE CONTENTS:

  • CONTENTS

    Unit 1: Introduction to Visual Basic 1

    Unit 2: Variables and Data Types 35

    Unit 3: Decision Making and Looping 55

    Unit 4: Array 74

    Unit 5: In Built Functions 89

    Unit 6: Classes and Object in VB.NET 110

    Unit 7: Namespaces 135

    Unit 8: Exception Handling 163

    Unit 9: Using System.Collections 178

    Unit 10: Windows Programming 204

    Unit 11: Common Dialog Boxes 234

    Unit 12: File Input Output 262

    Unit 13: ADO.NET 301

    Unit 14: XML 323

  • 6 LOVELY PROFESSIONAL UNIVERSITY

    Corporate and Business Law

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 1

    NotesUnit 1: Introduction to Visual Basic

    CONTENTSObjectivesIntroduction

    1.1 Element of Visual Basic

    1.1.1 The Visual Element

    1.1.2 The Language Element

    1.2 Object Oriented Programming in VB.NET

    1.3 Visual Basic.NET

    1.3.1 The Common Language Runtime

    1.3.2 Managed Execution

    1.3.3 Microsoft Intermediate Language (MSIL)

    1.3.4 The Just-In-Time Compiler

    1.3.5 Executing Code

    1.3.6 Assemblies

    1.3.7 Assembly Manifest

    1.3.8 An End to DLL Hell

    1.3.9 Global Assembly Cache (GAC)

    1.4 The Common Type System

    1.4.1 Classes

    1.4.2 Interfaces

    1.4.3 Value Types

    1.4.4 Delegates

    1.5 Feature of VB.NET

    1.5.1 Powerful Windows-based Applications

    1.5.2 Building Web-based Applications

    1.5.3 SimplifiedDeployment

    1.5.4 Powerful,Flexible,SimplifiedDataAccess

    1.5.5 Improved Coding

    1.5.6 Direct Access to the Platform

    1.5.7 Full Object-Oriented Constructs

    1.5.8 XML Web Services

    1.5.9 Mobile Applications

    1.5.10 COM Interoperability

    1.5.11 Reuse Existing Investments

    1.5.12 Upgrade Wizard

    1.6 NET Framework

    1.6.1 Visual Basic in .Net Framework

  • Modern Programming Tools & Techniques-III

    2 LOVELY PROFESSIONAL UNIVERSITY

    Notes1.7 VB.NET as a Language in .NET Framework

    1.7.1 Source Files

    1.7.2 Identifiers

    1.7.3 Keywords

    1.7.4 Literals

    1.7.5 Types

    1.8 Summary

    1.9 Keywords

    1.10 Review Questions

    1.11 Further Reading

    Objectives

    After studying this unit, you will be able to:

    Explaintheelementofvisualbasic

    DescribetheobjectorientedprogramminginVB.NET

    Discusstheframeworkofvisualbasic.net

    Definecommontypesystem

    ExplainthefeatureofVB.NET

    Define.NETframework

    DiscusstheVB.NETasalanguagein.NETframework

    Introduction

    Before we begin Visual Basic programming, let us understand some basic concepts of programming. A computer program is an organized list of instructions that, when executed, causes the computer to behave in a predetermined manner. Without programs, computers are useless. Therefore, programming means designing or creating a set of instructions for the computer to carry out certain tasks at much faster rate than human beings. A lot of people think that computer CPU is a very intelligent thing, which in actual fact it is a dumb and inanimate object that can do nothing without human assistance. The microchips of a CPU can only understand two distinct electrical states, namely, the on and off states, or 0 and 1 codes in the binary system. So, the CPU only understands combinations of 0 and 1 code, a language whichwecalledmachinelanguage.Machinelanguageisextremelydifficulttolearnandit isnot for us laymen to master it easily. Fortunately, we have many smart programmers who wrote interpreters and compilers that can translate human languagelike programs such as BASIC into machine language so that the computer can carry out the instructions entered by the users. Machine language is known as the primitive language while Interpreters and compilers like Visual Basic are called high-level language. Some of the high-level computer languages beside Visual Basic are FORTRAN, COBOL, Java, C, C++, Turbo Pascal, and etc.

    Therefore, programming means designing or creating a set of instructions to ask the computer to carry out certain jobs which normally are very much faster than human beings can do.

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 3

    NotesIn order to do programming, we need to use certain computer language to communicate with the computer. There are many computer languages out there, some of the examples are Visual Basic, FORTRAN, COBOL, Java, C++, Turbo Pascal, Assembly language and etc. Among them, Visual Basic is the easiest to learn because it uses a language very similar to natural human language. It involves using words such as If, Then, Else, Goto, Select and so on, so beginners can pick up the language very quickly.

    In 2001, Microsoft released the .NET (pronounced dot net) platform. Visual Basic .NET, or VB.NET, is an upgrade to the last version of VB (version 6.0) that conforms to the .NET platform. As we will see in subsequent chapters, the changes in VB.NET allow programmers to write Web or desk-top applications within the same language. In addition, VB.NET is fully object-oriented as opposed to prior versions that had many, but not all, of the elements of an object-oriented language. This topic is based on VB.NET. We will sometimes refer to Visual Basic as VB, omitting .NET.

    Visual Basic is a highly popular language in the commercial world because it allows for the rapid development of Windows based programs. VB is particularly strong at creating front ends for databases. This can be done in amazing time through the use of wizards. This page does not cover all aspects of VB, it does not show how to do the basics like layout a form, neither does it cover all the built in functions, as there is already plenty of help provided for these, and a lot of it is self-evident.

    Visual Basic is a high level programming language which was evolved from the earlier DOS version called BASIC. BASIC means Beginners All-purpose Symbolic Instruction Code. It is a very easy programming language to learn. The codes look a lot like English Language. In the past there were many different versions of BASIC however most people today use Microsoft Visual Basic today. It is a well developed programming language and supporting resources are available everywhere.

    On the other hand, because the user may click on certain object randomly, so each object has to be programmed independently to be able to response to those actions (events). Therefore, a VB Program is made up of many subprograms, each has its own program code, and each can be executed independently and at the same time each can be linked together in one way or another. A computer program is an organized list of instructions that, when executed, causes the computer to behave in a predetermined manner. Without programs, computers are useless automatons.

    What you can do with Visual Basic: We can program practically everything from educational software to teach science, mathematics, language, and history, geography to financial andaccounting software to games. Indeed, there is no limit to what we can program!

    Event Driven: Visual Basic is a Visual and events driven Programming Language. These are the main divergence from the old BASIC. In BASIC, programming is done in a text-only environment and the program is executed sequentially. In VISUAL BASIC, programming is done in a graphical environment. In the old BASIC, we have to write program codes for each graphical object we wish to display it on screen, including its position and its color. However, in Visual Basic, we just need to drag and drop any graphical object anywhere on the form, and we can change its color any time using the properties windows.

    Programs and Subprograms: Because users may click on a certain object randomly, so each object has to be programmed independently to be able to response to those actions (events). Therefore, a VISUAL BASIC Program is made up of many subprograms, each has its own program codes, and each can be executed independently and at the same time each can be linked together in one way or another.

  • Modern Programming Tools & Techniques-III

    4 LOVELY PROFESSIONAL UNIVERSITY

    Notes Visual Basic was initially introduced in 1991 as the first programming language that directly supported programmable graphical user interfaces using language-supplied objects.

    1.1 Element of Visual Basic

    From a programming viewpoint, Visual Basic is an object-oriented language that consists of two fundamental parts: a visual part and a language part. The visual part of the language consists of a set of objects, while the language part consists of a high-level procedural programming language. These two elements of the language are used together to create applications. An application is simply a Visual Basic program that can be run under the Windows Operating System. The term application is preferred to the term program for two reasons: one, it is the term selected by Microsoft to designate any program that can be run under its Windows Operating System (all versions) and two, it is used to avoid confusion with older procedural programs that consisted entirely of only a language element.

    Thus, for our purposes we can express the elements of a Visual Basic application as:

    Visual Basic Application = Object-Based Visual Part +

    Procedural-Based Language Part

    Thus, learning to create Visual Basic applications requires being very familiar with elements, visual and language.

    1.1.1 The Visual ElementFrom a users standpoint, the visual part of an application is provided within a window. This is the graphical interface that allows the user to see the input and output provided by the application. This user interface is referred to as the graphical user interface (GUI). From a programmers perspective the GUI is constructed by placing a set of visual objects on a blank window, or form, when the program is being developed. For example, consider Figure 1.1, which shows how a particular application would look to the user. From a programmers viewpoint, the application shown in Figure 1.1 is based on the design form shown in Figure 1.2. The points displayed on the form are a design grid used to arrange objects on the form and are only displayed during design time.

    Figure 1.1: A Users View of an Application

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 5

    NotesFigure 1.2: The Design Form on which Figure 1.1 is Based

    Design Form(Initial Form Window)

    Design Window

    The programmer can place various objects on this form, which is itself a Visual Basic object. When an application is run, the form becomes a window that provides the background for the various objects placed on the form by the programmer. The objects on the window become the controls used to direct program events. Let us take a moment to look at the objects provided in the Visual Basic Toolbox. The standard object Toolbox, which is illustrated in Figure 1.3, contains the objects we will use in constructing each graphical user interface.

    Figure 1.3: The Standard Visual Basic Toolbox

  • Modern Programming Tools & Techniques-III

    6 LOVELY PROFESSIONAL UNIVERSITY

    Notes A majority of applications can be constructed using a minimal set of objects provided by the standard object Toolbox. This minimal set consists of the Label, TextBox, and Button objects. The next set of objects that are more frequently found in applications include the CheckBox, RadioButton, ListBox, and ComboBox. Finally, the Timer and PictureBox can be used for constructing interesting moving images across the window. Table 1.1 lists this object types and describes what each object is used for. The remaining sections of the text will describe the use of objects in the toolbox, with special emphasis on the four objects (Label, TextBox, Button and ListBox) that we will use in almost every application that we develop.

    In addition to the basic set of controls provided in VB, a great number of objects can be purchased either for special purpose applications or to enhance standard applications.

    Table 1.1: Fundamental Object Types and Their Uses

    Object Type UseLabel Create text that a user cannot directly change.TextBox Enter or display data.Button Initiate an action, such as a display or calculation.CheckBox Select one option from two mutually exclusive options.RadioButton Select one option from a group of mutually exclusive options.ListBox Display a list of items from which one can be selected. ComboBox Display a list of items from which one can be selected, as well as

    permit user to type the value of the desired item.Timer Create a timer to automatically initiate program actions.PictureBox Display text or graphics.

    Do not be overwhelmed by all of the available controls. At a minimum, we will always have the objects provided by the standard Toolbox available to us, and these are the ones we will be working with. Once we learn how to place the basic control objects on a form, we will also understand how to place the additional objects, because every object used in a Visual Basic application, whether it is selected from a standard or purchased control, is placed on a form in the same simple manner. Similarly, each and every object contains two basic characteristics: properties and methods.

    Anobjectspropertiesdefineparticularcharacteristicsoftheobject.Forexample,thepropertiesof a text box include the location of the text box on the form, the color of the box (the background color), the color of text that will be displayed in the box (the foreground color), and whether it is read-only or can also be written to by the user.

    Methodsarepredefinedproceduresthataresuppliedwiththeobjectforperformingspecifictasks.For example, we can use a method to move an object to a different location or change its size.

    Additionally, each object from the Toolbox recognizes certain actions. For example, a button recognizes when the mouse pointer is pointing to it and the left mouse button is clicked. These types of actions are referred to as events. In our example, we would say that the button recognizes the mouse-click event. However, once an event is activated, we must write our own procedures to do something in response to the event. This is where the language element of Visual Basic comes into play.

    1.1.2 The Language ElementBefore the advent of GUIs, computer programs consisted entirely of a sequence of instructions. Programming was the process of writing these instructions in a language to which the computer

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 7

    Notescould respond. The set of instructions and rules that could be used to construct a program were called a programming language. Frequently, the word code was used to designate the instructions contained within a program. With the advent of graphical user interfaces the need for code (program instructions) has not gone away rather, it forms the basis for responding to the events taking place on the GUI. Figure 1.4 illustrates the interaction between an event and a program code.

    As illustrated in Figure 1.4, an event, such as clicking the mouse on a button, sets in motion a sequence of actions. If code has been written for the event, the code is executed; otherwise the event is ignored. This is the essence of GUIs and event-driven applicationsthe selection of executed code depends on what events occur, which ultimately depends on what the user does. The programmer must still write the code that performs the desired action.

    Figure 1.4: An Event Triggers the Initiation of a Procedure

    Public Class Form1

    Inherits System.Windows.Forms.Form

    Windows form Designer generated code

    Private Sub ByVal As ObjectButton1_Click ( sender , _

    TextBox1.Text = Hello World !

    End Sub

    End Class

    ByVal As Handlese System.EventArgs) Buton1.Click

    Visual Basic is a high-level programming language that supports all of the procedural programming features found in other modern languages. These include statements to perform calculations, permit repetitive instruction execution, and allow selection between two or more alternatives.

    Visual Basic is a visual programming environment for developing Windows (also Web now) applications.

    1.2 Object Oriented Programming in VB.NET

    Information hiding is the concept of exposing only essential information and hiding the inner logic. It is used mostly in hiding of design decisions that are most likely to change. Information hiding also manifests in Encapsulation and Polymorphism. The term Encapsulation is used interchangeably with information hiding Encapsulation results in encapsulating the data and the processes into a module or other construct which presents an interface.

    Polymorphism is where multiple procedures of the same name perform different tasks; Polymorphism is the process of using a function or a procedure in different ways for different setofinputsgiven.PolymorphisminVB.NETisthroughthedefinitionandimplementationofa common interface. We can use polymorphism to hide logic from the programmer.

    Inheritance helps we create new objects from existing objects for example we can inherit one form from another form. One common reason to use inheritance is to create specializations of existing classes or objects. For example, a Bank Account class might have data for an account number, owner, and balance. An Interest Bearing Account class might inherit Bank Account and then add data for interest rate and interest accrued along with behavior for calculating interest earned.

  • Modern Programming Tools & Techniques-III

    8 LOVELY PROFESSIONAL UNIVERSITY

    Notes Programming object mimics the behavior of a real-world object, for example when a Button on a form perform a task when clicked some objects are visible to the user while others are not Objects are created from classes Multiple objects can be created from the same class. For Example TheclassofDogdefinesallpossibledogsbylistingthecharacteristicsandbehaviorstheycanhave; the object Snoopy is one particular dog, with particular versions of the characteristics. A Dog has fur; Snoopy has white fur.

    AClass defines the abstract characteristics of an object, including the things characteristics(itsattributes,fieldsorproperties)andtheobjectsbehaviors(thethingsitcando,ormethods,operations or features). One might say that a class is a blueprint or factory that describes the nature of something. For example, the class Dog would consist of traits shared by all dogs, such as breed and fur color (characteristics), and the ability to bark and sit (behaviors). Classes provide modularity and structure in an object-oriented computer program. A class should typically be recognizable to a non-programmer familiar with the problem domain, meaning that the characteristics of the class should make sense in context.

    The code for a class should be relatively self-contained (generally using encapsulation).Collectively, thepropertiesandmethodsdefinedbya classare called members.

    1.3 Visual Basic.NET

    Manypeoplehave lookedatVB.NETandgrumbledabout thechanges.Therearesignificantchanges to the language: a new optional error handling structure, namespaces, true inheritance, free threading, and many others. Some see these changes as merely a way that Microsoft can place a check mark next to a certain feature and is able to say, Yeah, we do that. However, there are good reasons for the changes in VB.NET.

    The world of applications is changing. This is merely a continuation of what has occurred over the past several years. If we took a Visual Basic 1.0 developer and showed him an ntier application with an ASP front end, a VB COM component middle tier, and a SQL Server back end full of stored procedures, it would look quite alien to him. Yet, over the past few years, the vast majority of developers have been using Visual Basic to create COM components, and they have become quite versed in ADO as well. The needs for reusability and centralization (a way to avoid distributing components to the desktop) have driven this move to the ntier model.

    The move to the Web revealed some problems. Scalability was an issue, but more complex applications had other requirements, such as transactions that spanned multiple components, multiple databases, or both. To address these issues, Microsoft created Microsoft Transaction Services (MTS) and COM+ Component Services. MTS (in Windows NT 4) and Component Services (an updated MTS in Windows 2000) acted as an object-hosting environment, allowing us to gain scalability and distributed transactions with relative ease. However, VB components could not take full advantage of all that Component Services had to offer, such as object pooling, because VB did not support free threading.

    In the ASP/VB6 model, Microsoft had developers building a component and then calling it via an ASP. Microsoft realized that it would be a good idea to make the component directly callable over HTTP, so that an application anywhere in the world could use that component. Microsoft threw their support behind SOAP, Simple Object Access Protocol, which allows developers to call a component over HTTP using an XML string, with the data returning via HTTP in an XML string. Components sport URLs, making them as easy to access as any other Web item. SOAP has the advantage of having been a cross-industry standard, and not just a Microsoft creation.

    At this point, we might be tempted to think that SOAP is all we need, and that we can just stick with VB6. Therefore it is important to understand what VB.NET gives us, and why it

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 9

    Notesmakes sense for we, and many other developers, to upgrade to .NET. For example, we create components and want them to be callable via SOAP, but how do we let people know that those componentsexist? .NET includesadiscoverymechanismthatallowswe tofindcomponentsthatareavailabletoweb.Wewillfindoutmoreaboutthismechanism,includingthediscofile,BuildingWebServiceswithVB.NET. .NETalsoprovidesmanyotherfeatures,suchasgarbagecollectionforfreeingupresources,trueinheritanceforthefirsttime,debuggingthatworks across languages and against running applications, and the ability to create Windows services and console applications.

    Before proceeding, it is important to understand a little bit more about what is meant by .NET. There are many .NETs here. There is VB.NET, which is the new version of Visual Basic. There is Visual Studio.NET, an Integrated Development Environment that hosts VB.NET, C#, and C++.NET. Underlying all this is the .NET Framework and its core execution engine, the Common Language Runtime.

    In the .NET model, we write applications that target the .NET Framework. This gives them automatic access to suchbenefits as garbage collection (whichdestroys objects and reclaimsmemory for we), debugging, security services, inheritance, and more. When we compile the code from any language that supports the .NET Framework, it compiles into something called MSIL, orMicrosoftIntermediateLanguage.ThisMSILfileisbinary,butitisnotmachinecode;instead,it is a format that is platform independent and can be placed on any machine running the .NET Framework. Within the .NET Framework is a compiler called the Just-In-Time, or JIT, compiler. ItcompilestheMSILdowntomachinecodespecifictothathardwareandoperatingsystem.

    In looking at the fundamental changes, it is important to understand that the number one feature request from Visual Basic developers, for years, has been inheritance. VB has had interface inheritance since VB4, but developers wanted real or implementation inheritance. Why? What arethebenefits?Themainbenefitofinheritanceistheabilitytocreateapplicationsmorequickly.This is an extension of the promise of component design and reusability. With implementation inheritance, we build a base class and can inherit from it, using it as the basis for new classes. For example, we could create a Vehicle class that provides basic functionality that could be inherited in both a Bicycle class and a Car class. The important point here is that Bicycle and Car inherit the functionality, or the actual code, from the Vehicle class. In VB4, the best we could do was inheriting the structure, minus any implementation code. In VB.NET, the functionality in that base class is available to your other classes as is, or we can extend and modify it as necessary.

    The .NET provides us with integrated debugging tools. If we have ever debugged an ASP application that had VB COM components, we know that we had to use Visual InterDev to debug the ASPs and VB to debug the components. If we also had C++ components in the mix, we had to use the C++ debugger on those components. With .NET, there is one debugger. Any language that targets the .NET Framework can be debugged with that single debugger, even if one part of your application is written in VB.NET and calls another part written in C# (pronounced C-Sharp), or any other language built to target the .NET Framework.

    The .NET supplies a standard security mechanism, available to all parts of your application. .NET provides a possible solution to DLL Hell, and removes much of the complexity of dealing with COM and the registry. .NET allows us to run components locally, without requiring the callingapplicationtogototheregistrytofindcomponents.

    There are also things that VB.NET can do that we cannot do today in VB. For example, Web Applications are a new form of project. Gone is Visual InterDev with its interpreted VBScript code. Instead, we now build your ASP.NET pages with VB.NET (or C# or C++), and they are truly compiled for better performance. VB.NET lets we create Windows services natively for the firsttimebyprovidingaWindowsServicesprojecttype.Andyes,VB.NETletsVBdevelopersbuildtrulyfree-threadedcomponentsandapplicationsforthefirsttime.

  • Modern Programming Tools & Techniques-III

    10 LOVELY PROFESSIONAL UNIVERSITY

    Notes Finally, we need to realize that the new language is actually going to have a version number onit,althoughthefinalnameisundecided.ItmightwellbecalledVB.NET2002.Thisimpliesthat at some point, there will be new versions of VB.NET, just as there were new versions of VB. References to previous versions of VB will be either VB or VB6. References to VB.NET 2002 will be just VB.NET.

    WehavedecidedweneedtomovefromVisualBasic6toVB.NET,andwepickeduptofindout about the changes. .NET Framework why starts with the .NET Framework? The truth is that we cannot understand VB.NET until we understand the .NET Framework. We see the .NET Framework and VB.NET are tightly intertwined; many of the services we will build into your applications are actually provided by the .NET Framework and are merely called into action by your application.

    The .NET Framework is a collection of services and classes. It exists as a layer between the applications we write and the underlying operating system. This is a powerful concept: The .NET Framework need not be a Windows-only solution. The .NET Framework could be moved to any operating system, meaning your .NET applications could be run on any operating system hosting the .NET Framework. This means that we could achieve true cross-platform capabilities simply by creating VB.NET applications, provided the .NET Framework was available for other platforms. Although this promise of cross-platform capability is a strong selling point to .NET, therehasnotyetbeenanyofficialannouncementabout.NETbeingmovedtootheroperatingsystems.

    In addition, the .NET Framework is exciting because it encapsulates much of the basic functionality that used to have to be built into various programming languages. The .NET Framework has the code that makes Windows Forms work, so any language can use the built-in code in order to create and use standard Windows forms. In addition, Web Forms are part of the framework, so any .NET language could be used to create Web Applications. Additionally, this means that various programming elements will be the same across all languages; a Long data type will be the same size in all .NET languages. This is even more important when it comes to strings and arrays. No longer will we have to worry about whether or not a string is a BStr or a CStr before we pass it to a component written in another language.

    The drag and drop design for creating the user interface in Visual Basic, is derived from a prototype form generator developed by Alan Cooper and his company called Tripod.

    1.3.1 The Common Language RuntimeOne of the major components of the .NET Framework is the Common Language Runtime, or CLR. TheCLRprovides a number of benefits to the developer, such as exception handling,security,debugging,andversioningandthesebenefitsareavailabletoanylanguagebuiltforthe CLR. This means that the CLR can host a variety of languages, and can offer a common set of tools across those languages. Microsoft has made VB, C++, and C# premier languages for the CLR, which means that these three languages fully support the CLR. In addition, other vendors have signed up to provide implementations of other languages, such as Perl, Python, and even COBOL.

    When a compiler compiles for the CLR, this code is said to be managed code. Managed code is simply code that takes advantage of the services offered by the CLR. For the runtime to work with managed code, that code must contain metadata. This metadata is created during the compilation process by compilers targeting the CLR. The metadata is stored with the compiled code and contains information about the types, members, and references in the code. Among other things, the CLR uses this metadata to:

    Locateclasses

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 11

    Notes Loadclasses

    Generatenativecode

    Providesecurity

    The runtime also handles object lifetimes. Just as COM/COM+ provided reference counting for objects; the CLR manages references to objects and removes them from memory when all the references are gone, through the process known as garbage collection. Although garbage collection actually gives us slightly less control than we had in VB, we gain some important benefits.Forexample,yourerrorsshoulddecreasebecausethenumberofobjectsthatenduphanging around due to circular references should be reduced or completely eliminated. In addition, garbage collection ends up being much faster than the old way of destroying objects in VB. Instances of objects we create that are managed by the runtime are called managed data. We can interact with both managed and unmanaged data in the same application, although manageddatagivesweallthebenefitsoftheruntime.

    TheCLRdefinesastandardtypesystemtobeusedbyallCLRlanguages.ThismeansthatallCLR languages will have the same size integers and longs, and they will all have the same type of string no more worrying about BStrs and CStrs! This standard type system opens up the door for some powerful language interoperability. For example, we can pass a reference of a class from one component to another, even if those components are written in different languages. We also can derive a class in C# from a base class written in VB.NET, or any other combination of languages targeted to the runtime. Do not forget that COM had a set of standard types as well, but they were binary standards. This meant that with COM, we had language interoperability at run time. With .NETs type standard, we have language interoperability at design time.

    After it is compiled, managed code includes metadata, which contains information about the component itself, and the components used to create the code. The runtime can check to make sure that resources on which we depend are available. The metadata removes the need to store component information in the registry. That means moving a component to a new machine does not require registration (unless it will be a global assembly, Building Classes and Assemblies with VB.NET), and removing components is as simple as deleting them.

    Aswecansee,theCommonLanguageRuntimeprovidesanumberofbenefitsthatarenotonlynew,butshouldenhancetheexperienceofbuildingapplications.Otherbenefits thatwewillsee in more detail include some of the new object-oriented features to VB.NET. Many of these new features are not so much additions to the language as they are features of the runtime that are simply being exposed to the VB.NET.

    1.3.2 Managed ExecutionTo understand how your VB.NET applications work, and just how much the code differs from the VB code that Dorothy wrote in Kansas, it is important to understand managed code and how itworks.TousemanagedexecutionandgetthebenefitsoftheCLR,wemustusealanguagethat was built for, or targets, the runtime.

    Fortunately for we, this includes VB.NET. In fact, Microsoft wanted to make sure that VB.NET was a premier language on the .NET platform, meaning that Visual Basic could no longer be accused of being a toy language. The runtime is a language-neutral environment, which means that any vendor can create a language that takes advantage of the runtimes features. Different compilers can expose different amounts of the runtime to the developer, so the tool we use and the language in which we write might still appear to work somewhat differently. The syntax of each language is different, of course, but when the compilation process occurs, all code should be compiled into something understandable to the runtime.

  • Modern Programming Tools & Techniques-III

    12 LOVELY PROFESSIONAL UNIVERSITY

    Notes 1.3.3 Microsoft Intermediate Language (MSIL)One of the more interesting aspects of .NET is that when we compile your code, we do not compile to native code. Before we VB developers panic and fear that we are returning to the days of interpreted code, realize that the compilation process translates your code into something called Microsoft intermediate language, which is also called MSIL or just IL. The compiler also creates the necessary metadata and compiles it into the component. This IL is CPU independent.

    AftertheILandmetadataareinafile,thiscompiledfileiscalledthePE,whichstandsforeitherportable executable or physical executable, depending on whom we ask. Because the PE contains your IL and metadata, it is therefore self-describing, eliminating the need for a type library or interfacesspecifiedwiththeInterfaceDefinitionLanguage(IDL).

    1.3.4 The Just-In-Time CompilerYourcodedoesnot stay IL for long,however. It is thePEfile, containing the IL that canbedistributed and placed with the CLR running on the .NET Framework on any operating system for which the .NET Framework exists, because the IL is platform independent. When we run the IL, however, it is compiled to native code for that platform. Therefore, we are still running native code; we are not going back to the days of interpreted code at all. The compilation to native code occurs via another tool of the .NET Framework: the Just-In-Time (JIT) compiler.

    With the code compiled, it can run within the Framework and take advantage of low-level features such as memory management and security. The compiled code is native code for the CPU, on which the .NET Framework is running, meaning that we are indeed running native code instead of interpreted code. A JIT compiler will be available for each platform on which the .NET Framework runs, so we should always be getting native code on any platform running the .NET Framework. Remember, today this is just Windows, but this could change in the future.

    1.3.5 Executing CodeInterestingly,theJITcomplierdoesnotcompiletheentireILwhenthecomponentisfirstcalled.Instead,eachmethodiscompiledthefirsttimeitiscalled.Thiskeepswefromhavingtocompilesections of code that are never called. After the code is compiled, of course, subsequent calls use the compiled version of the code. This natively compiled code is stored in memory in Beta 2. However, Microsoft has provided a PreJIT compiler that will compile all the code at once and store the compiled version on disk, so the compilation will persist over time. This tool is called ngen.exeandcanbeused toprecompile theentire IL. If theCLRcannotfindaprecompiledversionofthecode,itbeginstoJITcompileiton-the-fly.

    Afterthecodestartsexecuting,itcantakefulladvantageoftheCLR,withbenefitssuchasthesecuritymodel,memorymanagement,debuggingsupport,andprofilingtools.

    1.3.6 AssembliesOne of the new structures we will create in VB.NET is the assembly. An assembly is a collection ofoneormorephysicalfiles.Thefilesaremostoftencode,suchastheclasseswebuild,buttheycouldalsobeimages,resourcefiles,andotherbinaryfilesassociatedwiththecode.Suchassemblies are known as static assemblies because we create them and store them on disk. Dynamic assemblies are created at runtime and are not normally stored to disk (although they can be).

    An assembly represents the unit of deployment, version control, reuse, and security. If this sounds like the DLLs we have been creating in Visual Basic for the past six years, it is similar. Just as a standard COM DLL has a type library, the assembly has a manifest that contains the metadata for the assembly, such as the classes, types, and references contained in the IL. The

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 13

    Notesassembly often contains one or more classes, just like a COM DLL. In .NET, applications are built using assemblies; assemblies are not applications in their own rights.

    Perhaps the most important point of assemblies is this: All runtime applications must be made up of one or more assemblies.

    1.3.7 Assembly ManifestThe manifest is similar in theory to the type library in COM DLLs. The manifest contains all the information about the items in the assembly, including what parts of the assembly are exposed to the outside world. The manifest also lists the assemblys dependencies on other assemblies. Each assembly is required to have a manifest.

    ThemanifestcanbepartofaPEfile,oritcanbeastandalonefileifyourassemblyhasmorethanonefileinit.Althoughthisisnotanexhaustivelist,amanifestcontains:

    Assemblyname

    Version

    Filesintheassembly

    Referencedassemblies

    In addition, a developer can set custom attributes for an assembly, such as a title and a description.

    1.3.8 An End to DLL HellOneof thegreatbenefitsofCOMwassupposed tobeanend toDLLHell. Ifwe thinkbackfor a moment to the days of 16-bit programming, we will remember that we had to distribute a number of DLLs with a Windows application. It seemed that almost every application had to install the same few DLLs, such as Ctrl3d2.dll. Each application we installed might have a slightly different version of the DLL, and we ended up with multiple copies of the same DLL, but many were different versions. Even worse, a version of a particular DLL could be placed in the Windows\System directory that then broke many of your existing applications.

    TheCOMwas supposed to fix all that.No longer did applications search around forDLLsby looking in their own directories, and then search the Windows path. With COM, requests for components were sent to the registry. Although there might be multiple versions of the same COM DLL on the machine, there would be only one version in the registry at any time. Therefore, all clients would use the same version. This meant, however, that each new version of the DLL had to guarantee compatibility with previous versions. This led to interfaces being immutable under COM; after the component was in production, the interface was never supposed to change. In concept that sounds great, but developers released COM components that broke binarycompatibility;inotherwords,theircomponentsmodified,added,orremovedpropertiesandmethods.Themodifiedcomponents thenbrokeallexistingclients.ManyVBdevelopershave struggled with this exact problem.

    The .NET Framework and the CLR attempt to address this problem through the use of assemblies. Even before .NET, Windows 2000 introduced the capability to have an application look in the local directory for a DLL, instead of going to the registry. This ensured that we always had the correct version of the DLL available to the application.

    The runtime carries this further by allowing components to declare dependencies on certain versions of other components. In addition, multiple versions of the same component can be run simultaneously in what Microsoft calls side-by-side instancing or side-by-side execution.

  • Modern Programming Tools & Techniques-III

    14 LOVELY PROFESSIONAL UNIVERSITY

    Notes 1.3.9 Global Assembly Cache (GAC)Even though components in .NET do not have to be registered, there is a similar process if we have an assembly that is to be used by multiple applications. The CLR actually has two caches within its overall code cache: the download cache and the global assembly cache (GAC). An assembly that will be used by more than one application is placed into the global assembly cache by running an installer that places the assembly in the GAC. If an assembly is not in the localdirectoryandnot in theGAC,wecanhaveacodebasehint inaconfigurationfile.TheCLR then downloads the assembly, storing it in the download cache and binding to it from there. This download cache is just for assemblies that have to be downloaded, and will not be discussed further.

    The GAC is where we place a component if we want multiple applications to use the same component. This is very similar to what we have with registered COM components in VB6.

    Placing assemblies in the GAC has several advantages. Assemblies in the GAC tend to perform better because the runtime locates them faster and the security does not have to be checked each time that the assemblies are loaded. Assemblies can be added to or removed from the GAC only by someone with administrator privileges.

    Where things get interesting is that we can actually have different versions of the same assembly in the GAC at the same time.

    1.4 The Common Type System

    TheCommonTypeSystemspecifies the typessupportedbytheCLR.Thetypesspecifiedbythe CLR include

    ClassesThedefinitionofwhatwillbecomeanobject;includesproperties,methods,andevents.

    InterfacesThedefinitionofthefunctionalityaclasscanimplement,butdoesnotcontainany implementation code.

    Value TypesUser-defineddatatypesthatarepassedbyvalue.

    DelegatesSimilar to function pointers in C++, delegates are often used for event handling and callbacks.

    The type system sets out the rules that language compilers must follow to produce code that is cross-language compatible. By following the type system, vendors can produce code that is guaranteed to work with code from other languages and other compilers because all languages are consistent in their use of types.

    1.4.1 ClassesMostVisualBasicdevelopersarefamiliarwithclasses.Classesaredefinitionsorblueprintsofobjectsthatwillbecreatedatruntime.Classesdefinetheproperties,methods,fields,andeventsofobjects.Ifthetermfieldsarenewtous,itsimplymeanspublicvariablesexposedbytheclass;fieldsarethelazywaytodoproperties.Together,properties,methods,fields,andeventsaregenerically called members of the class.

    If a class has one or more methods that do not contain any implementation, the class is said to be abstract. In VB.NET, we cannot instantiate abstract classes directly; instead, we must inherit fromthem.InVB6,itwaspossibletocreateaclassthatwasjustmethoddefinitionsandthentouse the Implements keyword to inherit the interface. We could actually instantiate the interface in VB6, but because it did not have any implementation code, there was no point in doing so.

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 15

    NotesIn VB.NET, we can create a class that has implementation code instead of just the interface, and then mark the class as abstract. Now, other classes can inherit from that abstract class and use the implementation in it or override the implementation as needed. These are new concepts to VB developers. In the past, VB had only interface inheritance, but VB.NET has real inheritance, known as implementation inheritance.

    In VB.NET, interfaces are separate from classes. In VB6, we created interfaces by creating classeswithmethod definitions, but no implementation code inside thosemethods. Classeshave a number of possible characteristics that can be set, and that are stored in the metadata. In addition, members can have characteristics. These characteristics include such items as whether or not the class or member is inheritable.

    1.4.2 Interfaces

    InterfacesinVB.NETareliketheinterfacesinpreviousversionsofVB:Theyaredefinitionsofa class without the actual implementation. Because there is no implementation code, we cannot instantiate an interface, but must instead implement it in a class.

    There is one exception to the no implementation code in an interface rule: In VB.NET, we can definewhatarecalledstaticmembers.Thesecanhaveimplementationcode.

    1.4.3 Value Types

    In .NET languages, a standard variable type, such as an integer, is native to the language, and it is passed by value when used as an argument. Objects, on the other hand, are always passed byreference.However,avaluetypeisauser-definedtypethatactsmuchlikeanobject,butispassed by value. In reality, value types are stored as primitive data types, but they can contain fields,properties,events,andbothstaticandnonstaticmethods.Valuetypesdonotcarrytheoverhead of an object that is being held in memory.

    If this seems confusing, think about enums. Enumerations are a special type of value type. An enumsimplyhasanameandasetoffieldsthatdefinevaluesforaprimitivedatatype.Enums,however, cannot have their own properties, events, or methods.

    1.4.4 Delegates

    Delegates are a construct that can be declared in a client. The delegate actually points to a method on a particular object. The method to be pointed and the object can be set when the instance of thedelegate is createdatdeclaration.Thisallowsus todefinecalls tovariousmethods indifferent objects based on logic in your code. Delegates are most often used to handle events. Using delegates, we can pass events to a centralized event handler.

    Make the list of data types in VB.NET.

    Self Assessment QuestionsMultiple Choice Questions

    1. Visual Basic is an object-oriented language that consists of two fundamental parts:

    (a) Visual part and language part (b) Visual part and even part

    (c) Even part and language part (d) Even part and program part

  • Modern Programming Tools & Techniques-III

    16 LOVELY PROFESSIONAL UNIVERSITY

    Notes 2. Polymorphism is the process of using a .. or a procedure in different ways for different set of inputs given.

    (a) language (b) program

    (c) function (d) variable

    3. Windows Forms in Visual Basic .NET . provide a robust container for existing ActiveX controls.

    (a) 2000 (b) 2001

    (c) 2002 (d) 2003

    4. Visual Basic .NET provides the easiest, most productive language and tool for rapidly building Windows and ..

    (a) Web applications (b) Web programming

    (c) Web language (d) Web design

    5. TheCLRdefinesastandardtypesystemtobeusedbyallCLR.

    (a) languages (b) program

    (c) function (d) variable

    1.5 Feature of VB.NET

    Visual Basic .NET provides the easiest, most productive language and tool for rapidly building Windows and Web applications. Visual Basic .NET comes with enhanced visual designers, increased application performance, and a powerful integrated development environment (IDE). It also supports creation of applications for wireless, Internet-enabled hand-held devices. The following are the features of Visual Basic .NET with .NET Framework 1.0 and Visual Basic .NET 2003 with .NET Framework 1.1.

    1.5.1 Powerful Windows-based ApplicationsVisual Basic .NET comes with features such as a powerful new forms designer, an in-place menu editor, and automatic control anchoring and docking. Visual Basic .NET delivers new productivity features for building more robust applications easily and quickly. With an improved integrated development environment (IDE)anda significantly reduced startup time,VisualBasic .NEToffers fast, automatic formatting of code as we type, improved IntelliSense, an enhanced object browser and XML designer, and much more.

    1.5.2 Building Web-based ApplicationsWith Visual Basic .NET we can create Web applications using the shared Web Forms Designer and the familiar drag and drop feature. We can double-click and write code to respond to events. Visual Basic .NET 2003 comes with an enhanced HTML Editor for working with complex Web pages. We can also use IntelliSense technology and tag completion, or choose the WYSIWYG editor for visual authoring of interactive Web applications.

    1.5.3 Simplified Deployment

    With Visual Basic .NET we can build applications more rapidly and deploy and maintain them withefficiency.VisualBasic.NET2003and.NETFramework1.1makesDLLHellathingofthe past. Side-by-side versioning enables multiple versions of the same component to live safely onthesamemachinesothatapplicationscanuseaspecificversionofacomponent.XCOPY-

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 17

    Notesdeployment and Web auto-download of Windows-based applications combine the simplicity of Web page deployment and maintenance with the power of rich, responsive Windows-based applications.

    1.5.4 Powerful, Flexible, Simplified Data Access

    WecantackleanydataaccessscenarioeasilywithADO.NETandADOdataaccess.Theflexibilityof ADO.NET enables data binding to any database, as well as classes, collections, and arrays, and provides true XML representation of data. Seamless access to ADO enables simple data access for connected data binding scenarios. Using ADO.NET, Visual Basic .NET can gain high-speed access to MS SQL Server, Oracle, DB2, Microsoft Access, and more.

    1.5.5 Improved CodingWe can code faster and more effectively. A multitude of enhancements to the code editor, including enhanced IntelliSense, smart listing of code for greater readability and a background compiler for real-time notification of syntax errors transforms into a rapid application development (RAD) coding machine.

    1.5.6 Direct Access to the PlatformVisual Basic developers can have full access to the capabilities available in .NET Framework 1.1. Developers can easily program system services including the event log, performance counters and filesystem.ThenewWindowsServiceprojecttemplateenablestobuildrealMicrosoftWindowsNT Services. Programming against Windows Services and creating new Windows Services is not available in Visual Basic .NET Standard, it requires Visual Studio 2003 Professional, or higher.

    1.5.7 Full Object-Oriented ConstructsWe can create reusable, enterprise-class code using full object-oriented constructs. Language features include full implementation inheritance, encapsulation, and polymorphism. Structured exception handling provides a global error handler and eliminates spaghetti code.

    1.5.8 XML Web ServicesXML Web services enable us to call components running on any platform using open Internet protocols. Working with XML Web services is easier where enhancements simplify the discovery andconsumptionofXMLWebservicesthatarelocatedwithinanyfirewall.XMLWebservicescan be built as easily as we would build any class in Visual Basic 6.0. The XML Web service project template builds all underlying Web service infrastructure.

    1.5.9 Mobile ApplicationsVisual Basic .NET 2003 and the .NET Framework 1.1 offer integrated support for developing mobile Web applications for more than 200 Internet-enabled mobile devices. These new features give developers a single, mobile Web interface and programming model to support a broad range of Web devices, including WML 1.1 for WAPenabled cellular phones, compact HTML (cHTML) for i-Mode phones, and HTML for Pocket PC, handheld devices, and pagers. Please note, Pocket PC programming is not available in Visual Basic .NET Standard, it requires Visual Studio 2003 Professional, or higher.

    1.5.10 COM InteroperabilityWe can maintain your existing code without the need to recode. COM interoperability enables us to leverage your existing code assets and offers seamless bi-directional communication between Visual Basic 6.0 and Visual Basic .NET applications.

  • Modern Programming Tools & Techniques-III

    18 LOVELY PROFESSIONAL UNIVERSITY

    Notes 1.5.11 Reuse Existing InvestmentsWe can reuse all your existing ActiveX Controls. Windows Forms in Visual Basic .NET 2003 provide a robust container for existing ActiveX controls. In addition, full support for existing ADO code and data binding enable a smooth transition to Visual Basic .NET 2003.

    1.5.12 Upgrade WizardWe upgrade your code to receive all of the benefits of Visual Basic .NET 2003. The VisualBasic .NET Upgrade Wizard, available in Visual Basic .NET 2003 Standard Edition, and higher, upgrades up to 95% of existing Visual Basic code and forms to Visual Basic .NET with new support for Web classes and UserControls.

    1.6 .NET Framework

    The programming languages in Visual Studio run in the .NET Framework. The Framework provides for easier development of Web-based and Windows-based applications, allows objects from different languages to operate together, and standardizes how the languages refer to data and objects. Several third-party vendors have announced or have released versions of other programming languages to run in the .NET Framework, including .NET versions of APL by Dyalog, FORTRAN by Lahey Computer Systems, COBOL by Fujitsu Software Corporation, Pascal by the Queensland University of Technology (free), PERL by ActiveState, RPG by ASNA, and Java, known as IKVM.NET. The .NET languages all compile to (are translated to) a common machine language, called Microsoft Intermediate Language (MSIL). The MSIL code, called managed code, runs in the Common Language Runtime (CLR), which is part of the .NET Framework.

    1.6.1 Visual Basic in .Net FrameworkMicrosoft Visual Basic comes with Visual Studio. We also can purchase VB by itself (without the other languages but with the .NET Framework). VB is available in an Express Edition, a Standard Edition, a Professional Edition, and a Team System Edition. Anyone planning to do professional application development that includes the advanced features of database management should use theProfessionalEditionor theTeamSystemEdition.Wecanfindamatrix showing thefeatures of each edition in Help. The Professional Edition is available to educational institutions through the Microsoft Academic Alliance program and is the best possible deal. When a campus department purchases the Academic Alliance, the school can install Visual Studio on all classroom and lab computers and provide the software to all students and faculty at no additional charge.

    The .NET Framework encompasses the following:

    A new way to expose operating system and other APIs. For years, the set of Windows functionality that was available to developers and the way that functionality was invoked were dependent on the language environment being used. For example, the Windows operating system provides the ability to create windows (obviously). Yet, the way this feature was invoked from a C++ program was dramatically different from the way it was invoked from a Visual Basic program. With .NET, the way that operating system services are invoked is uniform across all languages (including code embedded in ASP.NET pages).

    This portion of .NET is commonly referred to as the .NET Framework class library.

    A new infrastructure for managing application execution. To provide a number of sophisticated new operating-system services including code-level security, cross-language class inheritance, cross-language type compatibility, and hardware and operating-system independence, among othersMicrosoft developed a new runtime environment known as the Common Language Runtime (CLR). The CLR includes the Common Type System

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 19

    Notes(CTS) for cross-language type compatibility and the Common Language Specification(CLS) for ensuring that third-party libraries can be used from all .NET-enabled languages.

    To support hardware and operating-system independence, Microsoft developed the Microsoft Intermediate Language (MSIL, or just IL). IL is a CPU-independent machine language-style instruction set into which .NET Framework programs are compiled. IL programs are compiled to the actual machine language on the target platform prior to execution (known as just-in-time, or JIT, compiling). IL is never interpreted.

    A new web server paradigm. To support high-capacity web sites, Microsoft has replaced its Active Server Pages (ASP) technology with ASP.NET. While developers who are used to classicASPwillfindASP.NETfamiliaronthesurface,theunderlyingengineisdifferent,and far more features are supported. One difference, already mentioned, is that ASP.NET web page code is now compiled rather than interpreted, greatly increasing execution speed.

    A new focus on distributed-application architecture. Visual Studio .NET provides top-notch tools for creating and consuming web services-vendor-independent software services that can be invoked over the Internet.

    The .NET Framework is designed top to bottom with the Internet in mind. For example, ADO.NET, the next step in the evolution of Microsofts vision of universal data access, assumes that applications will work with disconnected data by default. In addition, the ADO.NET classes provide sophisticated XML capabilities, further increasing their usefulness in a distributed environment.

    An understanding of the .NET Framework is essential to developing professional Visual Basic .NET applications.

    Search more about the features of VB.NET.

    1.7 VB.NET as a Language in .NET Framework

    The syntax of the Visual Basic .NET language, including basic concepts such as variables, operators,statements,classes,etc.Somematerialthatwedidexpecttofindinherewewillseemtobemissing.Forexample,mathematicalfunctions,fileI/O,andformdeclarationsareallverymuch a part of developing Visual Basic .NET applications, yet they are not introduced because they are not intrinsic to the Visual Basic .NET language.

    1.7.1 Source FilesVisualBasic.NETsourcecodeissavedinfileswitha.vb extension. The exception to this rule iswhenVisualBasic .NETcode isembedded inASP.NETwebpagefiles.Suchfileshavean.aspx extension.

    Sourcefilesareplain-textfilesthatcanbecreatedandeditedwithanytexteditor,includingouroldfriend,Notepad.Sourcecodecanbebrokenintoasmanyorasfewfilesasdesired.WhenweuseVisualStudio.NET,sourcefilesarelistedintheSolutionExplorerwindow,andallsourceisincludedfromthesefileswhenthesolutionisbuilt.Whenwearecompilingfromthecommandline, all sourcefilesmust appearas command-linearguments to the compile command.Thelocationofdeclarationswithinsourcefilesisunimportant.Aslongasallreferenceddeclarationsappearsomewhereinasourcefilebeingcompiled,theywillbefound.

    UnlikepreviousversionsofVisualBasic,nospecialfileextensionsareusedtoindicatevariouslanguage constructs (e.g., .cls for classes, .frm for forms, etc.). Syntax has been added to the

  • Modern Programming Tools & Techniques-III

    20 LOVELY PROFESSIONAL UNIVERSITY

    Notes language to differentiate various constructs. In addition, the pseudo language for specifying the graphicallayoutofformshasbeenremoved.Formlayoutisspecifiedbysettingpropertiesofform objects explicitly within code. Either this code can be written manually, or the WYSIWYG form designer in Visual Studio .NET can write it.

    1.7.2 Identifiers

    Identifiersarenamesgiventonamespaces, types (enumerations,structures,classes,standardmodules, interfaces, and delegates), type members (methods, constructors, events, constants, fields, and properties), and variables. Identifiers must begin with either an alphabetic orunderscore character (_),may be of any length, and after the first charactermust consist ofonly alphanumeric and underscore characters. Namespace declarations may be declared either withidentifiersorqualifiedidentifiers.Qualifiedidentifiersconsistoftwoormoreidentifiersconnectedwiththedotcharacter(.).Onlynamespacedeclarationsmayusequalifiedidentifiers.

    Consider this code fragment:

    Imports System

    Namespace ORelly.ProgVBNet

    Public Class Hello

    Public Shared Sub SayHello( )

    Console.WriteLine(hello, world)

    End Sub

    End Class

    End Namespace

    Thiscode fragmentdeclares three identifiers:OReilly.ProgVBNet (anamespacename),Hello(a class name), and SayHello (a method name). In addition to these, the code fragment uses threeidentifiersdeclaredelsewhere:System(anamespacename),Console(aclassname),andWriteLine (a method name).

    Although Visual Basic .NET is not case sensitive, the case of identifiers is preserved whenapplications are compiled. When using Visual Basic .NET components from case-sensitive languages, the caller must use the appropriate case.

    Ordinarily,identifiersmaynotmatchVisualBasic.NETkeywords.Ifitisnecessarytodeclareoruseanidentifierthatmatchesakeyword,theidentifiermustbeenclosedinsquarebrackets([ ]). Consider this code fragment:

    Public Class [Public]

    Public Shared Sub SayHello( )

    Console.WriteLine(hello, world)

    End Sub

    End Class

    Public Class SomeOtherClass

    Public Shared Sub SomeOtherMethod( )

    [Public].SayHello( )

    End Sub

    End Class

    This code declares a class named Public and then declares a class and method that use the Public class. Public is a keyword in Visual Basic .NET. Escaping it with square brackets lets it isusedasanidentifier, inthiscasethenameofaclass.Asamatterofstyle,usingkeywords

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 21

    Notesasidentifiersshouldbeavoided,unlessthereisacompellingneed.ThisfacilityallowsVisualBasic .NET applications to use external components that declare identifiersmatchingVisualBasic .NET keywords.

    1.7.3 KeywordsKeywords are words with special meaning in a programming language. In Visual Basic .NET, keywords are reserved; that is, they cannot be used as tokens for such purposes as naming variables and subroutines. The keywords in Visual Basic .NET are shown in Table 1.2.

    Table 1.2: Keywords in Visual Basic .NET

    ElseIf Used in the If Else ElseIf End If constructEnd Used to terminate a variety of statementsEndIf Used in the If Else ElseIf End If constructEnum Visual Basic .Net statementErase Visual Basic .Net statementError Used in the Error and on Error compatibility statementsEvent Visual Basic .Net statementExplicit Used in the Option Explicit statementFalse Boolean LiteralFor Used in the For Next and For Each Next constructsFinally Visual Basic .Net statementFor Visual Basic .Net statementFriend StatementandaccessmodifierFunction Visual Basic .Net statementGet Used in the Property constructGetType Visual Basic .Net operatorGoTo Visual Basic .Net statement, used with the On Error statementHandles DefinesaneventhandlerinaproceduredeclarationCall Visual Basic .Net statementCase Used in the Select Case constructCatch Visual Basic .Net statementCBool Data-conversion functionCByte Data-conversion functionCChar Data-conversion functionCDate Data-conversion functionCDec Data-conversion functionCDb1 Data-conversion functionChar Used in variable declaration (intrinsic data type)CInt Data-conversion functionClass Visual Basic .Net statementCLng Data-conversion functionCObj Data-conversion functionCompare Used in the Option Compare statementCShort Data-conversion functionCSng Data-conversion function

    Contd...

  • Modern Programming Tools & Techniques-III

    22 LOVELY PROFESSIONAL UNIVERSITY

    NotesCStr Data-conversion functionCType Data-conversion functionDate Used in variable declaration (intrinsic data type)Decimal Used in variable declaration (intrinsic data type)Declare Visual Basic .NET statementDefault Used in the Property statementDelegate Visual Basic .NET statementDim Variable declaration statementDo Visual Basic .NET statementDouble Used in variable declaration (intrinsic data type)Each Used in the For Each Next constructElse Used in the If Else ElseIf End If constructElseIf Used in the If Else Elself End If constructEnd Used to terminate a variety of statementsEndIf Used in the If Else ElseIf ... End If constructEnum Visual Basic .NET statementErase Visual Basic .NET statementError Used in the Error and On Error compatibility statementsEvent Visual Basic .NET statementExplicit Used in the Option Explicit statementFalse Boolean literalFor Used in the For Next and For Each Next constructsFinally Visual Basic .NET statementFor Visual Basic .NET statementFriend StatementandaccessmodifierFunction Visual Basic .NET statementGet Used in the Property constructGetType Visual Basic .NET operatorGoTo Visual Basic .NET statement, used with the On Error statementHandles DefinesaneventhandlerinaproceduredeclarationIf Visual Basic .NET statementImplements Visual Basic .NET statementImports Visual Basic .NET statementIn Used in the For Each Next constructInherits Visual Basic .NET statementInput Used in the FileOpen functionInteger Used in variable declaration (intrinsic data type)Interface Visual Basic .NET statementIs Object comparison operatorLet Reserved but unused in Visual Basic .NETLib Used in the Declare statementLike Visual Basic .NET operatorLock Function nameLong Used in variable declaration (intrinsic data type)

    Contd...

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 23

    NotesLoop Used in a Do loopMe Statement referring to the current object instanceMid String-manipulation statement and functionMod Visual Basic .NET operatorModule Visual Basic .NET statementMustInherit Used in the Class constructMustOverride Used in the Sub and Function statementsMyBase Statement referring to an objects base classMyClass Statement referring to the current object instanceNamespace Visual Basic .NET statementNew Object-creation keyword, constructor nameNext Used in the For Next and For Each Next constructsNot Visual Basic .NET operatorNothing Used to clear an object referenceNotInheritable Used in the Class constructNotOverridable Used in the Sub, Property, and Function statementsObject Used in variable declaration (intrinsic data type)Off Used in Option statementsOn Used in option statementsOption Used in Option statementsOptional Used in the Declare, Function, Property, and Sub statementsOr Boolean operatorOrElse Boolean operatorOutput Used in the FileOpen functionOverloads Used in the Sub and Function statementsOverridable Used in the Sub and Function statementsOverrides Used in the Sub, Property, and Function statementsParamArray Used in the Declare, Function, Property, and Sub statementsPreserve Used with the ReDim statementPrivate StatementandaccessmodifierProperty Visual Basic .NET statementProtected StatementandaccessmodifierPublic StatementandaccessmodifierRaiseEvent Visual Basic .NET statementRandom Used in the FileOpen functionRead Used in the FileOpen functionReadOnly Used in the Property statementReDim Visual Basic .NET statementRem Visual Basic .NET statementRemoveHandler Visual Basic .NET statementResume Used in the On Error and Resume statementsReturn Visual Basic .NET statementSeek File-access statement and functionSelect Used in the Select Case construct

    Contd...

  • Modern Programming Tools & Techniques-III

    24 LOVELY PROFESSIONAL UNIVERSITY

    NotesSet Used in the Property statementShadows Visual Basic .NET statementShared Used in the Sub and Function statementsShort Used in variable declaration (intrinsic data type)Single Used in variable declaration (intrinsic data type)Static Variable declaration statementStep Used in the For Next constructStop Visual Basic .NET statementString Used in variable declaration (intrinsic data type)Structure Visual Basic .NET statementSub Visual Basic .NET statementSyncLock Visual Basic .NET statementText Used in the Option Compare statementThen Used in the If Then Else EndIf constructThrow Visual Basic .NET statementTo Used in the For Next and Select Case constructsTrue Boolean literalTry Visual Basic .NET statementTypeOf Used in variations of the If Then EndIf constructUnicode Used in the Declare statementUntil Used in the For Next constructVariant Reserved but unused in Visual Basic .NETWhen Used with the Try Catch Finally constructWhile Used with the Do Loop and While End While constructs With Visual Basic .NET statementWithEvents Used in variable declaration (Dim, Public, etc.)WriteOnly Used in the Property statementXOr Visual Basic .NET operator

    1.7.4 LiteralsLiterals are representations of values within the text of a program. For example, in the following line of code, 10 is a literal, but x and y is not:

    x = y * 10

    Literals have data types just as variables do. The 10 in this code fragment is interpreted by the compiler as type Integer because it is an integer that falls within the range of the Integer type.

    Numeric Literals

    Any integer literal that is within the range of the Integer type (-2147483648 through 2147483647) is interpreted as type Integer, even if the value is small enough to be interpreted as type Byte or Short. Integer literals that are outside the Integer range but are within the range of the Long type (9223372036854775808 through 9223372036854775807) are interpreted as type Long. Integer literals outside the Long range cause a compile-time error.

    Numeric literalscanalsobeofoneof thefloatingpoint typesSingle,Double,andDecimal.For example, in this line of code, 3.14 is a literal of type Double:

    z = y * 3.14

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 25

    NotesIntheabsenceofanexplicitindicationoftype,VisualBasic.NETinterpretsfloatingpointliteralsas type Double. If the literal is outside the range of the Double type (1.7976931348623157E308 through 1.7976931348623157E308), a compile-time error occurs.

    Visual Basic .NET allows programmers to explicitly specify the types of literals. Table 1.2 lists VisualBasic.NETsintrinsicdatatypes,alongwiththemethodforexplicitlydefiningaliteralof each type. Note that for some intrinsic types, there is no way to write a literal.

    String Literals

    Literals of type String consist of characters enclosed within quotation-mark characters. For example, in the following line of code, hello, world is a literal of type String:

    Console.WriteLine(hello, world)

    String literals are not permitted to span multiple source lines. In other words, this is not permitted:

    Wrong

    Console.WriteLine(hello,

    World)

    To write a string literal containing quotation-mark characters, type the character twice for each time it should appear. For example:

    Console.WriteLine(So then Dave said, hello, world.)

    This line produces the following output:

    So then Dave said, hello, world.

    Character Literals

    Visual Basic .NETs Char type represents a single character. This is not the same as a one-character string; Strings and Chars are distinct types. Literals of type Char consist of a single character enclosed within quotation-mark characters, followed by the character c. For example, in the following code, Ac is a literal of type Char:

    Dim MyChar As Char

    MyChar = Ac

    To emphasize that this literal is of a different data type than a single-character string, note that this code causes a compile-time error if Option Strict is On:

    Wrong

    Dim MyChar As Char

    MyChar = A

    The error is:

    Option Strict On disallows implicit conversions from String to Char.

    Date Literals

    Literals of type Date are formed by enclosing a date/time string within number-sign characters. For example:

    Dim MyDate As Date

    MyDate = #11/15/2001 3:00:00 PM#

    Date literals in Visual Basic .NET code must be in the format m/d/yyyy, regardless of the regional settings of the computer on which the code is written.

  • Modern Programming Tools & Techniques-III

    26 LOVELY PROFESSIONAL UNIVERSITY

    Notes Boolean Literals

    The keywords True and False are the only Boolean literals. They represent the true and false Boolean states, respectively (of course!). For example:

    Dim MyBoolean As Boolean

    MyBoolean = True

    Nothing

    There is one literal that has no type: the keyword Nothing. Nothing is a special symbol that represents an uninitialized value of any type. It can be assigned to any variable and passed in any parameter. When used in place of a reference type, it represents a reference that does not reference any object. When used in place of a value type, it represents an empty value of that type. For numeric types, this is 0 or 0.0. For the String type, this is the empty string (). For the Boolean type, this is False. For the Char type, this is the Unicode character that has a numeric codeof0.Forprogrammer-definedvaluetypes,nothingrepresentsaninstanceofthetypethathas been created but has not been assigned a value.

    Summary of Literal Formats

    Table 1.3 shows all of Visual Basic .NETs intrinsic types, as well as the format for writing literals of those types in programs.

    Note the following facts about forming literals in Visual Basic .NET:

    ThereisnowaytorepresentaliteraloftypeByte.However,thisdoesnotmeanthatliteralscannot be used in situations where type Byte is expected. For example, the following code isfine:

    Dim MyByte As Byte = 100

    EventhoughtheVisualBasic .NETcompilerconsiders100tobeof typeInteger inthisexample,itrecognizesthatthenumberissmallenoughtofitintoavariableoftypeByte.

    TypesnotshowninTable1.3cannotbeexpressedasliterals.

    1.7.5 TypesTypes in Visual Basic .NET are divided into two categories: value types and reference types. Value types minimize memory overhead and maximize speed of access, but they lack some features of a fully object-oriented design (such as inheritance). Reference types give full access to object-oriented features, but they impose some memory and speed overhead for managing and accessing objects. When a variable holds a value type, the data itself is stored in the variable. When a variable holds a reference type, a reference to the data (also known as a pointer) is stored in the variable, and the data itself is stored somewhere else. Visual Basic .NETs primitive types include both value types and reference types. For extending the type system, Visual Basic .NET providessyntaxfordefiningbothnewvaluetypesandnewreferencetypes.

    All reference types derive from the Object type. To unify the type system, value types can be treated as reference types when needed. This means that all types can derive from the Object type.

    Arrays

    Array declarations in Visual Basic .NET are similar to those in Visual Basic 6 and other languages. Forexample,hereisadeclarationofanIntegerarraythathasfiveelements:

    Dim a(4) As Integer

    Theliteral4inthisdeclarationspecifiestheupperboundofthearray.AllarraysinVisualBasic.NEThavealowerboundof0,sothisisadeclarationofanarraywithfiveelements,havingindexes 0, 1, 2, 3, and 4.

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 27

    NotesThe previous declaration is of a variable named a, which is of type array of Integer. Array types implicitly inherit fromthe .NETFrameworksArraytype(defined in theSystemnamespace)and,therefore,haveaccesstothemethodsdefinedinthattype.Forexample,thefollowingcodedisplays the lower and upper bounds of an array by calling the Array classs GetLowerBound and GetUpperBound methods:

    Dim a(4) As Integer

    Console.WriteLine(LowerBound is & a.GetLowerBound(0).ToString( ))

    Console.WriteLine(UpperBound is & a.GetUpperBound(0).ToString( ))

    The output is:

    LowerBound is 0

    UpperBound is 4

    Note that the upper bound of the array is dynamic: it can be changed by methods available in the Array type.

    Array elements are initialized to the default value of the element type. A types default value is determined as follows:

    Fornumerictypes,thedefaultvalueis0.

    FortheBooleantype,thedefaultvalueisFalse.

    FortheChartype,thedefaultvalueisthecharacterwhoseUnicodevalueis0.

    Forstructure types, thedefaultvalue isan instanceof thestructure typewithallof itsfieldssettotheirdefaultvalues.

    Forenumerationtypes,thedefaultvalueisaninstanceoftheenumerationtypewithitsinternal representation set to 0, which may or may not correspond to a legal value in the enumeration.

    Forreferencetypes(includingString),thedefaultvalueisNothing.

    Wecanaccessarrayelementsbysuffixingthearraynamewiththeindexofthedesiredelementenclosed in parentheses, as shown here:

    For i = 0 To 4

    Console.WriteLine(a(i))

    Next

    Arrays can be multidimensional. Commas separate the dimensions of the array when used in declarations and when accessing elements. Here is the declaration of a three-dimensional array, where each dimension has a different size:

    Dim a(5, 10, 15) As Integer

    As with single-dimensional arrays, array elements are initialized to their default values.

    Initializing arrays

    Arrays of primitive types can be initialized by enclosing the initial values in curly brackets ({}). For example:

    Dim a( ) As String = {First, Second, Third, Fourth, Fifth}

    Notice that when arrays are initialized in this manner, the array declaration is not permitted to specify an explicit size. The compiler infers the size from the number of elements in the initialize.

  • Modern Programming Tools & Techniques-III

    28 LOVELY PROFESSIONAL UNIVERSITY

    Notes To initialize multidimensional arrays, include the appropriate number of commas in the array-name declaration and use nested curly brackets in the initializer. Here is a declaration of a two-dimensional array having three rows and two columns:

    Dim a(,) As Integer = {{1, 2}, {3, 4}, {5, 6}}

    This declaration produces the following array:

    a(0,0)=1 a(0,1)=2

    a(1,0)=3 a(1,1)=4

    a(2,0)=5 a(2,1)=6

    When initializing multidimensional arrays, the innermost curly brackets correspond to the rightmost dimension.

    Dynamically allocating arrays

    Use the New keyword to allocate arrays of any type. For example, this code creates an array of fiveIntegersandinitializestheelementsasshown:

    Dim a( ) As Integer

    a = New Integer(4) {1, 2, 3, 4, 5}

    If the array elements would not be initialized by the allocation, it is still necessary to include the curly brackets:

    Dim a( ) As Integer

    allocatesanuninitializedarrayoffiveIntegers

    a = New Integer(5) {}

    Curly brackets are required so the compiler would not confuse the array syntax with constructor syntax.

    Note also the meaning of this declaration by itself:

    Dim a( ) As Integer

    This is the declaration of a reference that could point to a single-dimensional array of Integers, but does not yet. Its initial value is Nothing.

    Collections

    AcollectionisanytypethatexposestheICollectioninterface(definedintheSystem.Collectionsnamespace). An interface is an agreement in which the type will expose certain methods, properties, and other members. By exposing the ICollection interface, a type ensures that it can be used anywhere a collection is expected.) In general, collections store multiple values and provide a way for iterating through those values. Specialized collection types may also provide othermeansforaddingandreadingvalues.Forexample,theStacktype(definedintheSystem.Collections namespace) provides methods, such as Push and Pop, for performing operations that are appropriate for the stack data structure.

    The Visual Basic .NET runtime provides a type called Collection (defined in theMicrosoft.VisualBasic namespace) that mimics the behavior of Visual Basic 6 collections and exposes the ICollection interface.

    Using the Collection type

    Create a new collection object.

    Dim col As New Collection( )

    Add some items to the collection.

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 29

    Notes col.Add(Some value)

    col.Add(Some other value)

    col.Add(A third value)

    Iterate through the collection and output the strings.

    Dim obj As Object

    For Each obj In col

    Dim str As String = CType(obj, String)

    Console.WriteLine(str)

    Next

    The Collection types Add method adds items to the collection. Although strings are added to thecollection,theAddmethodisdefinedtotakeitemsoftypeObject,meaningthatanytypecan be passed to the method. After items are added to the collection, they can be iterated using theForEachstatement.BecausetheCollectionclassisdefinedtostoreitemsoftypeObject,theloop variable in the for each statement must be of type Object. Because the items are actually strings, the code in example converts the Object references to String references using the CType function. The output of the code in example is:

    Some value

    Some other value

    A third value

    The items in a Collection object can also be iterated using a numerical index. The Collection object has a Count property, which indicates the number of items in the collection. The next example is precisely the same as above example, except that it iterates through the Collection object using a numerical index and a standard for loop.

    Using a numerical index on a collection object

    Create a new collection object.

    Dim col As New Collection( )

    Add some items to the collection.

    col.Add(Some value)

    col.Add(Some other value)

    col.Add(A third value)

    Iterate through the collection and output the strings.

    Dim i As Integer

    For i = 1 To col.Count

    Dim str As String = CType(col(i), String)

    Console.WriteLine(str)

    Next

    Note that to access an item by index, the index number is placed within parentheses following the name of the Collection reference variable, as shown again here:

    col(i)

    The syntax of the Add method is:

    Public Sub Add( _

    ByVal

  • Modern Programming Tools & Techniques-III

    30 LOVELY PROFESSIONAL UNIVERSITY

    Notes Item As Object, _

    Optional ByVal

    Key As String = Nothing, _

    Optional ByVal

    Before As Object = Nothing, _

    Optional ByVal

    After As Object = Nothing _

    )

    The parameters are:

    Item

    The item to add to the collection.

    Key

    An optional string value that can be used as an index to retrieve the associated item. For example, the following code adds an item to a collection and then uses the key value to retrieve the item:

    Dim col As New Collection( )

    col.Add(Some value, Some key)

    ...

    Dim str As String = CType(col(Some key), String)

    Console.WriteLine(str)

    The output is:

    Some value

    Before

    The item before which the new item should be added.

    After

    The item after which the new item should be added.

    Very Busy (VB) Mail Server

    We can place an order and ship it to us. We also help with shopping for gifts; your order can be gift wrapped and sent anywhere you wish.The company title will be shortened to VB Mail Order. Include this name on the titlebarofthefirstformofeachprojectthatwecreateforthiscasestudy.

    Werfirstjobistocreateaprojectthatwilldisplaythenameandtelephonenumberforthecontact person for the customer relations, marketing, and order processing, and shipping departments.

    Include a button for each department. When the user clicks on the button for a department, display the name and telephone number for the contact person in two labels. Also include identifying labels with Text Department Contact and Telephone Number.

    Be sure to include a button for Print and one for Exit. Include a label at the bottom of the form that holds your name.

    Contd...

  • Unit 1: Introduction to Visual Basic

    LOVELY PROFESSIONAL UNIVERSITY 31

    NotesTest Data

    Department Department Contact Telephone NumberCustomer Relations Tricia Mills 500-1111Marketing Michelle Rigner 500-2222Order Processing Kenna DeVoss 500-3333Shipping Eric Andrews 500-4444

    Valley Bou