Common Language Runtime (CLR)
Common Language Runtime (CLR)
NET
The .NET Framework class Library is organized into namespaces. The namespace is a container for
functionality. Similar classes and constructs are grouped together in a namespace to define parent-
child relationships. Namespaces can be nested into namespaces.
All namespaces stem from the root namespace called System Namespace. It contains all data types
including the Object data type. Though all namespaces are subordinated to the System namespace,
User defined libraries can also coexist with the System namespace. They can have their own root
namespace which can be language focused namespaces such as Microsoft.Csharp,
Microsoft.VisualBasic.
The most significant feature of the .NET framework is the class Library collection of reusable types can
be integrated with CLR. The programmer can accomplish a range of common programming tasks, such
as string management; data collection; data base connectivity and file access using the .NET
framework class library. The developer can create console applications, Windows GUI applications,
ASP.NET applications, XML Web services or Windows services.
Microsoft Intermediate Language (MSIL)
MSIL are simple binary structures that are similar to the instruction sets of the CPU. Like the instruction
set, it encodes a wide spectrum of operations such as loading, storing, arithmetic and logical operations
and control flow. The similarity to the machine code enables the code to be compiled quickly in the Just
in time compiler. The type verification also becomes simpler because the DotNet binary contains tables
of metadata. The metadata defines each type and its signatures and also the other data that the
runtime locates and extracts from the file at the time of execution. The presence of the metadata makes
the module self descriptive and eliminates the need for IDL files and header files. However, unlike the
CPU instruction set, MSIL expresses object oriented concepts such as object creation, method
invocation, property access and exception handling.
It is the Microsoft Intermediate Language (MSIL) which makes applications language independent.
Applications may be created by programmers in any language of their choice—ASP.NET or VB.NET—
in a machine on which the .NET framework has been installed. The compiler then, gives an output in
the Microsoft Intermediate language. This language can be defined as a kind of assembly language at
a higher level of abstraction. The language is designed in a manner that makes it possible to convert it
into any kind of native machine code with ease. The CLR detects the Intermediate language and
invokes the Just-in-time compiler to convert the language into machine code.
In the next tutorial The .NET Framework Architecture Part 2 we will learn about Just-In-Time
(JIT) compilation, Assemblies, native assemblies, and the Global Assembly Cache (GAC).
Please let us know your feedback helps us to improve this training.
Just-In-Time (JIT) compilation
As stated above, the Just in time compiler is a facility that is invoked by the CLR to convert the IL into
machine code. The .NET framework assemblies (*.dll or *.exe) files cannot be executed by the target
processor unless it is converted into native code. When the Assembly is loaded the method calls are
invoked for compilation into native code. Since this is done just when the method needs to execute, it is
called Just in time compilation. When the JIT is invoked for the first time there is an overhead or
performance penalty, since the assembly is converted into its Native code or image using the Native
Image Generator (Ngen.exe). All subsequent calls will load faster as the Native image alone is invoked
thereafter from the Native image cache.
Significantly, the IL can coexist with the machine code in the application. This feature also enables the
developer modify the code or add to the code even when the application is actively deployed. This
functionality provided by JIT makes the .NET framework an efficient, agile and powerful means of
application development.
Assemblies, native assemblies, and the Global Assembly Cache (GAC)
The primary unit of deployment is the assembly. The assembly is used by the .NET CLR as the
smallest unit of deployment; version control; security; type grouping and code reuse. An assembly will
consist of a manifest and one or more modules or files. It can be defined as a logical DLL that contains
a manifest, type metadata, MSIL and resources. Assemblies can be application private or shared.
Private assemblies are restricted to use in a single application whereas shared assemblies can be used
across applications. Private applications also reside within the application folder while shared
assemblies reside in the common area-- GAC(Global Assembly Cache). They must have a globally
unique name.
The existence of the manifest within the assembly makes it self descriptive. It can be viewed by the IL
Disassembler (Ildasm.exe) which is part of the .NET framework SDK.
The assembly is identified by the manifest. It defines security requirements, lists other interdependent
assemblies and all the types and resources exposed by the assembly. Localized resources exposed by
assemblies and targeted by the application contain a default culture (language, currency, date/time
format etc).
The manifest contains several sections. Identity, Referenced Assemblies, file list and Custom Attributes
are some of the important sections of the manifest. The Identity section as the name suggests,
identifies the assembly. It contains a .assembly directive. The version directive specifies the version of
the assembly, so that the CLR identifies the different versions of an application. The Identity section
contains a strong name for shared assemblies and a public/private encryption key is used to distinguish
between assemblies of the same name. The Identity section also optionally contains the Culture which
defines the country and language of the assembly target. The .locale directive is used for this purpose
and the Culture-Neutral assemblies can be used by any assembly.
The Referenced Assemblies section of the manifest provides a reference to all the assemblies used in
an application.
Comparison of VB.NET, C#, and J#
The .NET framework architecture has made the language of coding immaterial to the final output. All
languages also have equal access to all development capabilities and revolve around the .NET
classes. The language syntax, operations etc look similar in all the languages of this group. Moreover,
code can be shared by all .NET languages and so a class made in C# or J# can be used in VB.NET
and vice versa.
In this context choice of language is no longer significant. Finally, all languages are transformed by the
compiler into Microsoft Intermediate language. It is the programmer’s familiarity with the language that
makes it material whether he is coding in VB.NET or C# or J#. However, the option settings in the
compiler will have to be set to the language of coding before the compiler is used.
The speed of performance of the compiler will also vary with the language being compiled. For instance
C# compiles faster than VB.NET. Subject to the above observation, the features of the languages will
be dicussed in the next tutorial.
Differences between VB.NET 1.0 and VB.NET 2.0
VB.NET 2005 comes with a number of enhancements. The IntelliSense Code snippets, the Windows
Forms designer updates, IntelliSense filtering, debugger data tips, exception Assistant etc make the
software a pleasure to work with. The language has been spruced up with generics, unsigned types,
Operator overloading etc.
The My Namespace is the most significant enhancement that provides a single reference to commonly
used functionalities within the .NET framework. It includes classes like Application, Computer, Forms,
Resources, Settings and Users. This enables users to ping a computer with a simple line of code or
play a audio file with a one line code.
Example:
My Computer Audio Play(“….\*(name of file).wav)
A number of mundane problems being faced by coders have been solved in the process. The
IntelliSense has taken away much of the pain of development by correcting errors and making
suggestions even during the process of development. This improves the quality of codes and reduces
the time taken to develop and debug large applications.
New Operators
A number of new operators have been introduced into the language to facilitate the coder. For instance
the IsNot operator facilitates comparisons with Nothing. This was not possible earlier.
Just My Code
This feature of VB.NET enables the coder to skip over all the code that was not written by him. This is
extremely useful when debugging custom code as all machine generated code is avoided. This feature
becomes enabled when “Enable Just My Code Stepping” option is activated. This feature is enabled by
default but can be disabled by the coder if he wishes to.
Support for Generics
The .NET framework has attempted to overcome some of the limitations of VB 6 with regard to
collections. Errors in object storage under a collection, which were detectable at compile time has been
resolved by providing the coder with many more types of collections. The coder can now import
Systems Collections namespace which gives access to BitArray, HashTable, Queue, StoredList and
Stack. In other words use of Generics has solved the problems in .NET Framework 2005.
Certain new concepts have been introduced in VB.NET 2005. The Operator overloading feature allows
the coder define the behavior of classes when used with intrinsic language operators such as +, -,<,>,=,
and <>. The appropriate outcome for operations are defined when applied to instances for user defined
classes.
The DotNet Framework architecture has revolutionized the process of application development. In the
lessons that follow we will be examining in greater detail how this framework helps the Visual Basic.
NET developer.
Introducing Windows Forms
Designing Windows Application is simpler and less time consuming with Visual Basic 2005. A number
of new facilities and enhancements have been made to assist the developer complete the project in
time and with lesser number of errors. Windows Form is the cynosure of the Windows Application.
Visual studio 2005 packs more features to the already enriched area of Windows Forms, both at design
and run time. Among the several features that have been added some standout as prominent. The
management of layout of the form is made easier by providing the snap lines that make it easy to align
controls with other controls as the layout is formed. A new deployment technology called ClickOnce for
forms is added.
Creating a Windows Application
1. Understanding Classes, Inheritance, and Namespaces
2. Using The System.Windows.Forms.Form class
3. Designing a Form using Windows Forms Designer
4. Exploring the Forms Designer generated code
5. Using the Application class
6. Using the MessageBox class
Setting and Adding Properties to a Windows Form
1. Using the Visual Designer to set Windows Form Properties
2. Setting Windows Forms Properties programatically
3. Adding new Property to a Windows Form
4. Using Visual Inheritance
Event Handling
1. Handling Events by attaching a delegate
2. Handling Events by overriding protected method of base class.
Building graphical interface elements
1. Understanding The Graphics Object
2. Understanding The Windows Forms Coordinate System
3. Drawing Text on a Form
4. Drawing Shapes
Implementing Class Library Object in VB.NET 2005
Class: Classical Object Oriented Concepts explain a class as a cookie cutter. A class allows you to
create objects of the class. As a programmer you define a class with data fields, properties, methods
and events. Then you can create objects based on that class that have state (fields, properties) and
behavior (methods, events). A class can be considered as a specification of how the object of the class
should look like and behave.
An object of the class is nothing other than a sequence of bytes at a specific memory location in the
memory heap. Thus we can understand that an object is an instance of the class. We can see an
illustration of a class.
Let's see an illustration of a class
Public Class Class1
Private VehicleType As String
Private VehicleModel As String
Private VehicleColor As String
Public Sub Accelerate()
' add code to Accelerate
End Sub
ReadOnly Property engineCapacity() As Decimal
Get
Return engineCapacity
End Get
End Property
End Class
Creating a Class Library project
1. On the File menu, select New Project.
2. On the Templates pane, in the New Project dialog box, click Class Library.
3. In the Name box, type DemoClass1 and then click OK.
4. A new Class Library project opens, and the Code Editor displays the Class module
Class1.vb.
5. In the Solution Explorer, right-click Class1.vb and select Rename, and then change the
name to DemoClass1.vb.
6. Note that the name in the Code Editor also changed to DemoClass.vb.
7. On the File menu, select Save All.
8. In the Save Project dialog box, click Save
Let us see the screen shots for doing this exercise:
The System.Object class serves as a common base class for all objects in the .NET framework, that
ensures interoperability of objects developed using Visual Studio .NET. New classes implicitly inherit
the System.Object class; therefore it is never necessary to explicitly name this class with an Inherits
statement. Among the methods that objects inherit from System.Object, one of the most useful is
Object.GetType, which is used to return the exact type of the current object.
VB.NET 2005 Free Training : Visual Studio.NET Namespaces
The .NET Framework class library has thousands of classes which are needed for developing and
deploying solutions. In order to organize all those classes for ease of use .NET Framework uses
namespaces. This Gives the Classes their own space and prevents conflicts between the various
names in these classes. For instance if two classes contain a method Paint(), then to avoid conflicts in
names we can place these classes in two different namespaces. Thus namespaces allow classes to be
grouped in a consistent, hierarchical manner.
The writing convention is that the word after the right–most dot is the name of the type and the string up
to the dot is the name of the namespace. We shall see an example of this in the following statement.
System.Windows.Forms.Button
In the above statement the name of the namespace is System.Windows.Form and the type name is
Button.
A namespace can contain classes, structures, enumerations, delegates, interfaces, and other
namespaces. Namespaces can be nested and can have any number of members. The typical
namespaces begin with Microsoft or System. The new namespace My is added in .NET 2005. If there
is a conflict in the namespace in such a way that even fully qualified Object name is also not usable,
then the classes cannot be used.
You can create a namespace by using the Namespace … End Namespace block. With in the
namespace Block, you can create classes, enumerations, structures, delegates, interfaces, or other
namespaces. It is not imperative that all the code should be kept in one single file. A namespace can
span multiple files and even multiple assemblies.
Namespace VBTutorial
Class Class1
…….
End Class
Namespace Lesson2
Class Class2
…..
Public Sub Teach()
End Sub
End Class
End namespace
End Namespace
In order to access the methods teach defined in class2 you have to instantiate the class Class2.
Dim lessonObj as new VBTutorial.Lesson2.Class2
lessonObj.Teach()
Alternatively you can use the following lines of code:
Imports VBTutorial.Lesson2
Dim lessonObj as new Class2
lessonObj.Teach()
Let us quickly see some of the namespaces defined in .NET
The identity of the code forms the basis for granting the runtime permissions, also the level of trust the
code is granted is determined by the security policy.
Code can demand that its callers have specific permissions. If you place a demand for certain
permission on your code, all code that uses your code must have that permission to run.
There are three kinds of permissions, each with a specific purpose
Code access permissions, which represent access to a protected resource or the ability to perform a
protected operation.
Identity permissions, which indicate that code has credentials that support a particular kind of identity.
Role-based security permissions, which provide a mechanism for discovering whether a user has a
particular identity or is a member of a specified role. Thus a very robust and well managed security is
provided in the .NET Framework.
Using Application Class
Visual Basic 2005 introduces a speedy way to access many important classes relating to the Computer
on which the application is running, the user running it, the application itself, its forms and any
associated web services. The best part of it all is that you can access it all using the new My object.
The new My object has added features that help the programmer to gain access to some functionality
that was really hard to achieve.
My.Application Object contains information about running application, such as the title, working
directory, version, and the common language runtime (CLR) version in use. It also gives access to
environment variables, allow you to easily write to the local application log or to a custom log, and so
on.
You can access the Application information easily as can be seen in the following lines of code
My.Application.AssemblyInfo.DirectoryPath
My.Application.AssemblyInfo.ProductName
My.Application.Log.WriteEntry(“Application Starting”, EventLogEntryType.Information,
Nothing)
The above lines of code will retrieve this information from the assembly which can used by the
application on run time.
The following table gives the properties and methods of the My.Application Object
ApplicationContext Gives access to the context associated with the current thread.
AssmblyInfo Allows easy access to data from the AssemblyInfo.vb file, including CompanyName,
ProductName, Title and Version.
ChangeCurrentCulture Allows Change the culture in which the current thread is running, which affects
such things as string manipulation and formatting
ChangeCurrentUICulture Allows changing the culture that the current thread uses for retrieving
culture-specific resources
CommandLineArgs Return a collection of command-line arguments
CurrentCulture Returns a collection of command-line arguments
CurrentDirectory Returns the folder where the application resides
CurrentUICulture Returns the culture that the current thread is using for retrieving culture-specific
resources
DoEvents Causes all messages in the message queue to be processed
GetEnvironmentVariable Returns a specific environment variable on the local maching\e
IsNetWorkDeployed Returns True if the application was network-deployed else returns False.
Log Allows writing to application log on the local machine
MainForm A read-write property that allows setting or getting the form that the application will use as
its main form
Run Sets up and starts the VB Startup/Shutdown Application model
SplashScreen Lets setting or getting the application's splash screen
Using the MessageBox class
Message boxes are often used objects. They are derived form Form Class, displayed modally and used
to take user’s acknowledgement and also inform the user or alert the user of any thing that needs to be
informed or alerted.
You cannot create a new instance of the System.Windows.Forms.MessageBox class. To display a
message box, call the static method System.Windows.Forms.MessageBox.Show. The title, message,
buttons, and icons displayed in the message box are determined by parameters that you pass to this
method.
The following example shows how to use a System.Windows.Forms.MessageBox to inform the user
of a missing entry in a System.Windows.Forms.TextBox.
This example assumes that the method is called from an existing form with a
System.Windows.Forms.Button and a System.Windows.Forms.TextBox on it.
OKOnly 0
Displays OK button only.
MsgBoxSetForeground 65536 Specifies the message box window as the foreground window.
MsgBoxRtlReading 1048576
Specifies text should appear as right-to-left reading on Hebrew and
Arabic systems.
The first group of values (0–5) describes the number and type of buttons displayed in the dialog box;
the second group (16, 32, 48, 64) describes the icon style; the third group (0, 256, 512) determines
which button is the default; the fourth group (0, 4096) determines the modality of the message box, and
the fifth group specifies whether or not the message box window is the foreground window, along with
the alignment and direction of the text. When adding numbers to create a final value for the Buttons
argument, use only one number from each group.
Setting and Adding Properties to a Windows Form
In this tutorial we wil leran about Setting and Adding Properties to a Windows Form, Using the Visual
Designer to set Windows Form Properties, Setting Windows Forms Properties programatically and
Using Visual Inheritance along with the sample project and screen shots.
Using the Visual Designer to set Windows Form Properties
The properties of the Widows properties can be edited in the properties window visually. Both the
inherited properties and also those added in the current class can be edited using the property window.
If this window is not visible, you can click on the menu view and choose property window. Alternatively
you can click F4 to invoke this window.
This window can be docked to a side and can be hidden or pinned to the desk. If it is hidden then if the
mouse hovers over the title bar of the property window it then becomes visible. We and see how the
properties of a text box and a grid control can be edited in the illustration:
In the above screen shot, see the button titled OK and all the properties of the button are available so
that it can changed.
We can also see another illustration involving grid box control: The screen shot below displays
properties that can be changed.
Setting Windows Forms Properties programmatically
You may have a clear idea of value of the properties and the controls at design time and they can be
edited using the method explained above. However most of the time the value of the property of several
items cannot be identified at design time and they have to be set at run time based on several
considerations. Visual Basic provides facility to edit and initialize or substitute the value of the
properties programmatically. Le us see an illustration.
Start a new project and add a form to the project. This form will be the starting form by default. Add two
text boxes and a command button to the form and place them as shown below:
Now you can proceed to add the codes for the program by double clicking the form. You will see the
controls.vb file opened. Add the following codes to the form as given below:
We have added two labels to the form class. These classes are merely declared in the class. The
Contols_Load Sub contains the codes to edit the properties and to add them. The visible property of the
form is set to true so these controls will be visible on the form. Now let us look at the value for the labels
lblFirstNm and lblSeconNm which are initially assigned a value "Enter your First Name" and "Enter your
Last Name".
Now take a look at the sub addNames. This sub takes two arguments, viz firstNm and SecondNm. The
sub assigns the value of firstNm to lblFirstNm and the value of SeconNm to lblSecondNm. We also
make some cosmetic change by making the font bold.
The action comes from the sub btnOk_click. Here we declare two string variables firstNm and
secondNm. The value of the text from the two text box are captured and assigned to these variables in
the respective order. Then the sub addNames is called here with the two names as arguments and the
result can be seen in the two graphics that are given below:
See the screenshot below after the “Enter” button is clicked: You will also see that the value in the text
boxe have been reset to null values.
Using Visual Inheritance
Inheritance allows you to derive one class from another class. Visual Basic provides a facility by which,
while deriving a class from another class, you can also inherit the visual aspects of the class.
To derive a form from a Form1 which will inherit all aspects of Form1, including the controls on the
form. Let us create a new project VisualInheritance and add a form Form1 to it. Now add a button
botton1 to the form. Now click on the Build menu and click on Build VisualInheritance. This will enable
the form to be available for being inherited.
Now right click on the project and you choose Add Inherited Form. You will see a window named
inheritance picker. Choose the form Form1 in the window. The new inherited form will have the controls
that were placed on the base form Form1.
Introduction to Event Handling
One of the most useful capabilities of the OOP Languages is their inbuilt ability to be aware of a
large number of events like MouseOver, MouseClick, and so on so that we can write codes to react
to any event that we are interested. This is made possible by the rich set of classes that have been
built in the .NET Framework
The events handling is very simple as we have seen in the previous example where buttonClicked
event is handled by the following code:
Private Sub btnOk_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
Handles btnOk.Click
The Handles keyword is used to tell the program to look for the specific event. The sub or the
function that handles the event will be called immediately when the event occurs. This is a simple
implementation. In some cases you may have to raise an application event which will be caught by
the event handler. Please see the following code fragment to understand this.
Public Event TimeExpired(ByVal Status As String)
RaiseEvent TimeExpired("Your time has run out")
The first line declares the event Time expired and the second statement raises the event. In order
that this code works you need to make a reference to the System namespace. The Event statement
should be located outside any procedure or Sub and at the class level. The RaiseEvent statement
should be available inside some procedure in the application. Events must be raised within the
scope of the class or module or structure where they are declared. Thus you cannot raise an event
declared in the base class from within a derived class. The object that raised the event is the
sender or the source of the event. Some of the examples of these kinds of objects are forms,
controls etc.
An event handler can be any procedure that is called when the corresponding event occurs. You
cannot use a function as an event handler as it would necessitate the function to return a value to
the source object. The event handler cannot be made use of unless you first associate the
procedure with the event by using the keyword Handles or AddHandler statement.
While handles clause is used with design time activity AddHandler and RemoveHandler statements
are more flexible and they allow you to dynamically connect or disconnect the events with one or
more event handlers at run time. You are also relieved from adding one more line of code using
withEvents.
Let us see an example of event handling using Handles clause.
Dim withEvents AnEvent as new EventRaised()
Sub EventEgs()
AnEvent.RaiseEvents()
End Sub
Sub AnEvent_EventHandler() Handles AnEvent.EventOne, AnEvent.EventTwo
MsgBox(“Received Event”)
End Sub
Class EventRaised
Public Event EventOne()
Public Event EventTwo()
Sub RaiseEvents()
RaiseEvent EventOne()
RaiseEvent EventTwo()
End Sub
End Class
There are some limitations in using this kind of solution as listed below:
• You cannot use a WithEvents variable as a object variable. That is, you cannot declare it as
Object — you must specify the class name when you declare the variable.
• You cannot use WithEvents to declaratively handle shared events, since they are not tied to an
instance that can be assigned to a WithEvents variable. Similarily, you cannot use WithEvents or
Handles to handle events from a Structure. In both cases, you can use the AddHandler statement
to handle those events.
• You cannot create arrays of WithEvents variables.
• WithEvents variables allow a single event handler to handle one or more kind of event, or one or
more event handlers to handle the same kind of event.
The other method is employing the AddHandler and RemoveHandler clause. We shall see this in the
next section
A delegate is kind of OO function pointer that permits a function to be invoked indirectly by making
reference to the function. They are employed to attach to event handlers and pass a procedure
from on procedure to another. However delegates can also be used for other tasks not related to
events like free threading or procedures that need to call different versions of functions at compile
time. An illustration on the use of delegates is given by the following codes:
Click here for Sample Code
The output is given below:
Sub EventHandler()
' This procedure handles events raised by the object Obj.
MsgBox("EventHandler caught event.") ' Handle the event.
End Sub