News

Internet - .Net user group technical events, emerging .Net technologies;
General - Eco-travel, health and fitness, current events;
Community - Active volunteer with Hands On Miami, Non-Profit Ways;
.Net Framework - Detected 3.5 SP1 .NET Framework. No update needed ;
creative zen converter

Tweets













When a new version of your application is available

Users get notified as they run the older version. 

Now, when you investigate the files in the bin\release folder, you should find a copy of VBDemo.dll.

 It's this copy that your application will use, rather than the globally registered copy. At this point,

remove the net—that is, unregister VBDemo again. Run the application, and amazingly, it continues

 to work. This time, the application displays the current path, because the component is running

from within the current path. Because Visual Studio has copied the DLL locally, and because

of Reg-Free COM support, your application can use a local copy instead of the globally

registered copy.

Obviously, getting Reg-Free COM to work requires more effort than simply copying the COM

component locally. If you examine the files within the output folder, you'll also find

RegFreeCOMDemo.exe.manifest. If you open this file with a text editor, you'll see that the manifest

 file contains information about the COM component, and it's this file that makes Reg-Free COM work.

If you copy RegFreeCOMDemo.exe along the manifest file and the COM component to a new

computer running Windows XP, the application would continue to run. Combined with ClickOnce

deployment, it's easy to see how Reg-Free COM makes developers lives simpler—no more hassles

with registering COM components and no more DLL hell.

Reg-Free COM does have some limitations, as you might imagine. It requires Windows XP or later

 in order to run—if you attempt to deploy your application to an earlier version of Windows, you'll

see an error message indicating that you need a later version of Windows. Reg-Free COM is perfect

for deploying ActiveX controls, ActiveX DLLs, and other business objects, but it won't really work

 for all components. It only works for in-process components, so ActiveX EXEs are out.

It won't work for COM components that are part of the operating system. Reg-Free COM

also won't work for COM components that require a larger application—attempting to use

Reg-Free COM with the Microsoft Word or Microsoft Excel type libraries, for example,

wont' work, because these type libraries require a full copy of Word or Excel to be installed

on the target machine. For a large percentage of COM components that you'll want to deploy

with your applications, however, Reg-Free COM can make your life a lot easier. For more

information on Reg-Free COM, read

Simplify App Deployment with ClickOnce and Registration-Free COM.

Language Innovations

Continuing a tradition of balancing power and flexibility with ease of use, Visual Basic 2005 adds

a number of new features that keep Visual Basic in sync with the .NET Framework and make it the

premier language for business application development. The following sections outline some

of the new language features in Visual Basic 2005.

Operator Overloading

The .NET Framework has historically supported overloaded operators, and Visual Basic adds

 support for this feature in the 2005 release. This feature allows developers to consume operators

whose functionality has been overloaded by a particular class (a feature that wasn't available in previous

releases) and it also allows developers to overload the functionality for the standard language operators,

such as +, -, *, /, and so on.

You have most likely taken overloaded operator behavior for granted in classes where it's

already supported. Although it may not be common practice to write code like this, the code works

because of the overloaded + operator:

Dim inputString as String = "Hello, "
Dim outputString As String = inputString + " World!"

The + operator is generally only defined for numeric values, but the String class overloaded

the behavior of the operator so that it concatenates its two operands.

The operator overloading feature in Visual Basic 2005 consists of two distinct parts: consumption

 and declaration. Consumption is easy to demonstrate; take the Point structure, for example. You often

need to take an existing Point instance and add a Size structure to it, effectively offsetting the

Point by the values stored in the Size structure. The Point class includes code to handle addition

 and subtraction operations, using the standard + and – operators. That is, the following code

does just what you might expect:

Dim p1 As New Point(100, 100)
Dim s1 As New Size(20, 30)

Dim p2 As Point = p1 + s1
Dim p3 As Point = p1 – s1

After this code executes, p2 contains {120, 130} and p3 contains {80, 70}, as you might expect.

 At compile time, the compiler locates the correct special function, defined to handle addition or

subtraction of Point and Size structures, and turns the addition and subtraction operators into function

 calls to the special functions. The following code, required in previous versions of Visual Basic,

demonstrates how you might add Point and Size values without support for operator overloading:

Dim p2 As point = Point.op_Addition(p1, s1)

The developers who created the code for the Point structure provided the op_Addition function

(and the corresponding op_Subtraction, op_Equality, and so on). If these functions didn't exist,

the code wouldn't have compiled because the compiler must convert from the overloaded

operators into the appropriate function call at compile time. An expression like "p1 + s1" is,

in reality, simply a function call to the appropriate addition function, with two arguments, like this:

Point.op_Addition(p1, s1)

Because the addition function is simply a procedure, the compiler can determine which overloaded

version to use, based on the parameters. Because of the new operator overloading functionality

built into Visual Basic 2005, you can perform operations such as those shown here using standard

 mathematical operators on the Point and Size structures. (In previous versions of Visual Basic,

you were required to call the op_Addition method explicitly, for example, to add a Point and

 a Size structure.)

Although it's not likely a feature you'll need often, Visual Basic 2005 also adds support for

creating your own overloaded operators. The Visual Basic compiler allows you to overload

many operators, as shown in the following table:

+ + (unary)
- - (unary)
* \
/ ^
& Like
Mode And
Or Xor
Not <<
>> = (comparison)
<> <
<= >
>= CType
IsTrue IsFalse

Generics

Before looking at the concept of generics and how they can help you write better, more efficient,

and maintainable Visual Basic code, examine a common scenario. Let's say that you've created

a class as part of an application, and you'd like to create a collection containing instances of that class.

 For this example, you have created a simple class, named Customer, containing the following code:

Class Customer
    Public Name As String
    Public Age As Integer

    Public Sub New(ByVal Name As String, ByVal Age As String)
        Me.Name = Name
        Me.Age = Age
    End Sub
End Class

If you want to create a data structure that contains a collection of Customer objects, you could use the System.Collections.ArrayList class and could write code like this:

Dim customerList As New System.Collections.ArrayList
customerList.Add(New Customer("Tom", 48))
customerList.Add(New Customer("Peter", 45))
customerList.Add(New Customer("Jerry", 73))
customerList.Add("Hello, this won't work!")

For Each cust As Customer In customerList
    Console.WriteLine(cust.Name)
Next

Note the inconsistency in the data. Although the ArrayList class allows you to insert Customer

objects, it also is just as obliging when it comes to String, Integer, or any other object type.

The simplicity of the ArrayList class leads to its downfall—there's no way to easily restrict the type

 of data you add to it. Exposing a public ArrayList as a property of a class is a recipe for disaster,

 if you care about data integrity.

Creating your own collection class that derives from the System.Collections.CollectionBase

class provides a type-safe alternative. For example, the following class allows only Customer

objects to be added to its collection:

Class CustomerList
    Inherits CollectionBase

    Public Sub Add(ByVal cust As Customer)
        Me.List.Add(cust)
    End Sub
End Class

Given the CustomerList class, it would be impossible to add any object to your collection that

wasn't a Customer object. This solution is fine, as long as you only work with Customer objects.

 What happens when you also need a strongly typed collection class for working with Invoices?

 Or later, when you need a collection for Products, Orders, and so on? Creating and maintaining individual collection classes for each type could become a maintenance nightmare. Therein lies the motivation for the new language feature: generics.

Generics allow classes, structs, interfaces, and methods to be parameterized by the types of data

they store and manipulate. Generics are useful because many common classes and structures can be

parameterized in this way. These are called generic declarations. The .NET Framework provides

a group of generic collection classes as part of its System.Collections.Generic namespace.

For example, the System.Collections.Generic namespace provides a generic List class. To consume

the List class, you must supply the type for the items within the collection at the time you declare the

 instance of the list, like this (assuming that you've added an Imports statement for the System.Collections.Generic namespace to your code file):

Dim customerList As New List(Of Customer)

As you can probably guess, the "Of" keyword allows you to specify the type associated with

elements of the generic collection. To use the generic List class, you could write code like the following:

Dim customerList As New List(Of Customer)
customerList.Add(New Customer("Tom", 48))
customerList.Add(New Customer("Ken", 47))
customerList.Add(New Customer("Peter", 45))
customerList.Add(New Customer("Jerry", 73))

For Each cust As Customer In customerList
    Console.WriteLine(cust.Name)
Next

Of course, once you've created an instance of the List class with a Customer type as its type

argument (or any other type, for that matter), you are limited to storing only Customer objects

(or objects of a class derived from Customer). Generics provide strong typing, meaning you can no longer improperly store any other type into the list. Take, for example, this code:

Dim customerList As New List(Of Customer)
customerList.Add(New Customer("Tom", 48))
customerList.Add("Hello there!")
Dim c As Customer = customerList(0)

Notice two important things:

  • Unless you remove the third line, the code won't compile. The compiler checks to verify
  •  that you're using the object created by the generic class definition correctly.
  • In the final line, there's no need to cast the value returned from the List object. Each element
  •  contained within the List instance is always of the type specified when you declare the instance of the List class.

Besides the List class, the System.Collections.Generic namespace also provides generic versions of the Dictionary, SortedDictionary, LinkedList, Queue, and Stack classes. Because the .NET Framework

 includes so many generic collection classes, it's unlikely that you'll need to create your own generic class.

 If you find a need to create your own, however, Visual Basic 2005 makes it possible.

For example, if you needed to create a class that contained a one-dimensional array of a single

data type (often called a vector), you might create a class like the following:

Public Class TypedVector(Of T)
    ' Create a one-dimensional array of 
    ' the specified type.
    Private arrayValue() As T

    Public Sub New(ByVal Size As Integer)
        ReDim arrayValue(Size - 1)
    End Sub

    Default Public Property Item(ByVal Index As Integer) As T
        Get
            Return arrayValue(Index)
        End Get
        Set(ByVal Value As T)
            arrayValue(Index) = Value
        End Set
    End Property
End Class

When you use the generic class declaration TypedVector, as in the example that follows, you can

specify the actual type to be used by the generic class. In this case, the code instructs the TypedVector

class to use the Integer type by specifying it as a type argument with the "(Of Integer)" syntax after

the class name. This example creates an array containing five integers:

Dim myVector As New TypedVector(Of Integer)(4)
myVector(0) = 73
myVector(1) = 27
' Fill the rest of the items...

To create a TypedVector instance that could contain only instances of some specific business type,

 perhaps Customer objects, you could use code like the following:

Dim myVector As New TypedVector(Of Customer)(11)
myVector(0) = someCustomerObject

It's clear that you won't need generics for every application you write. When you do need to create a

strongly typed collection, there's no better solution than to take advantage of either the built-in classes from the System.Collections.Generic namespace or to create your own generic collection class.

IsNot Keyword

Although it hasn't been a terrible burden in the past, determining whether an object reference is not the

same as another object reference has historically involved a somewhat clumsy construct:

If Not (obj Is Nothing) Then

Visual Basic 2005 adds the IsNot keyword, making it possible to rewrite the previous example:

If obj IsNot Nothing Then

Sometimes, it's the little things that make a big difference.

Using Keyword

Many classes in the .NET Framework provide a Dispose method as a standard mechanism for

releasing resources used by the object. In general, it's a good rule of thumb to call the Dispose method

of an object you're using when you're done with the object. When you're working with managed

wrappers around unmanaged or limited resources, as is the case when you work with a database

connection or a Windows font or brush, you should always explicitly call the Dispose method if the

object provides it, in order to release the unmanaged resource. Imagine a form that draws text in

a specific font and brush in its Paint event handler. In previous versions of Visual Basic, you were required

to write code something like the following:

Private Sub Form1_Paint( _
 ByVal sender As Object, ByVal e As PaintEventArgs) _
 Handles MyBase.Paint

    Dim myFont As Font
    Dim myBrush As Brush
    Try
        myFont = New Font("Verdana", 12)
        myBrush = New SolidBrush(Color.FromArgb(123, 0, 123))
        e.Graphics.DrawString( _
         "Hello, World!", myFont, myBrush, 0, 0)

    Finally
        If myFont IsNot Nothing Then
            myFont.Dispose()
        End If

        If myBrush IsNot Nothing Then
            myBrush.Dispose()
        End If
    End Try
End Sub

Visual Basic 2005 adds the Using keyword, which creates a block of code that disposes of an object

for you at the end of the block, no matter how the block is exited. The previous code example can be

rewritten more efficiently, as in the following example:

Private Sub Form1_Paint( _
 ByVal sender As Object, ByVal e As PaintEventArgs) _
 Handles MyBase.Paint
    ' Create a new font.
    Using myFont As New Font("Verdana", 12)
        ' Create a new solid brush.
        Using myBrush As New SolidBrush( _
         Color.FromArgb(123, 0, 123))
            e.Graphics.DrawString( _
             "Hello, World!", myFont, myBrush, 0, 0)
        End Using
    End Using
End Sub

Unsigned Integer Types

Historically, Visual Basic has supported unsigned byte and signed integer types, but it hasn't supported

signed bytes or unsigned integers. In Visual Basic .NET 2002 and 2003, developers could create and

 use the .NET Framework's unsigned types, but they couldn't perform mathematical operations on

 these values. Visual Basic 2005 adds full support for these types, as well as the necessary

corresponding conversion methods. The following table lists the four new intrinsic types

(SByte has no type character because Byte has no type character):

VB Keyword Conversion Operator

Type Character

 

Range CLR Name
SByte (1 byte) CSByte(o) (None) -128 through 127 System.SByte
UShort (2 bytes) CUShort(o) US 0 through 65,535 System.UInt16
UInteger (4 bytes) CUInt(o) UI 0 through 4,294,967,295 System.UInt32
ULong (8 bytes) CULng(o) UL 0 through 18,446,744,073,709,551,615 (1.8...E+19) System.UInt64

Partial Classes

Partial classes allow a single class to be split into multiple files. Although this may seem like a feature that

won't affect your day-to-day development, it's a feature that will play a part in just about every

application you write. The most useful aspect of this feature is for code generators like Visual Studio

that can generate code into a different file than user-written code, but still provide functionality

within the same class as the user's code. In this manner, the visual designer can more easily parse

and regenerate its code without affecting the code the user has written.

The primary class is created just like a normal class, but the additional portions that the class

contains are declared using the Partial keyword. For example, you might see code like the following:

Public Class Form1
  Inherits Windows.Forms.Form
  ' Your Code
End Class

Partial Public Class Form1
  ' Designer code
  Sub InitializeComponent()
    ' Information about your controls goes here...
  End Sub
End Class

A single class can be broken up into multiple partial classes and all partial classes of the same name,

within the same namespace, are compiled into a single entity at compile time. This feature figures

prominently in the way Visual Studio manages your code, making it easy for tools provided by

the environment to update their code but leave yours intact. This is a feature you'll want to consider

when working on projects with multiple developers. Having classes split across multiple files makes it

far easier to manage source control with concurrent modification of the same class.

Background Worker Object

Handling asynchronous processing has always been a difficult area for many Visual Basic developers,

and ensuring that the callback procedure ran on the correct thread caused many headaches in previous

versions. Visual Basic 2005 developers can take advantage of the BackgroundWorker component

to handle these tasks automatically. By dragging this component onto any design surface, developers

 can easily run slow-running processes as background tasks.

By calling the RunWorkerAsync method of the BackgroundWorker component, developers can

execute code in the DoWork event handler of the component. This code runs in a separate thread

from the main user-interface thread, allowing the user interface to continue while the slower running

process executes without blocking the main thread. When the background task is complete,

the BackgroundWorker component raises its RunWorkerComplete event, allowing the caller

 to react to the fact that the task is completed. The RunWorkerComplete event handler also

 runs in the main thread, making it possible to update controls on the form containing the component.

If you've thought asynchronous processing was too difficult, or if you've fought with and never mastered

 the various intricacies of multi-threaded user interfaces, the BackgroundWorker component can make

 your life easier. You won't need to worry about the thread safety of your forms, and you'll be able

to simply add background processing to applications using this powerful new component.

Summary

As you can see from the few additions listed here, Visual Basic 2005 continues to build on the

success of Visual Basic .NET 2003, with its goal of providing the best environment and language

for creating applications quickly. With the new language features, IDE features, and productivity tools,

Visual Basic 2005 allows you to work more productively, using all the language features provided

 by the .NET Framework.

  • Share This Post:
  • Share on Twitter
  • Share on Facebook
  • Share on Technorati
Friday, June 02, 2006 3:36 PM

Feedback

No comments posted yet.


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: