Thursday, July 30, 2009

Finally! The Gold Medal, 1st Place

Finally! The Gold Medal, 1st Place, the highest award I can bestow goes to ...

TA DAH!

VB.NET is finally completely Object Oriented!

Now when you go to the beach, the C++ programmers won't kick sand in your face and steal your (girlfriend/boyfriend - pick one). And you can still code a complete General Ledger Trial Balance while they're trying to figure out which header files to include.

For the first time, you can code as close to the chip as you need to and access all the system internals your heart desires without having to resort to those nasty Win32 API calls. You've got inheritance, function overloading, asynchronous multithreading, garbage collection, and everything is an object. Can life get any better?

Did I hear someone say C++ has multiple inheritance and .NET still doesn't?

Burn the heretic!


from http://visualbasic.about.com/

The Bronze Award - 3rd Place

The Bronze Award - 3rd Place, goes to Arrays are 0 based instead of 1 based!

It's just one syntax change, but this change gets "medal podium" status because it is voted, "most likely to screw up your program logic". Remember, 3rd place IS "Award(2)" in our list. If you have counters and arrays in your VB6 program (and how many don't), this one will MESS YOU UP.

For ten years, People have been asking, "What was Microsoft smoking when they did it this way?" And for ten years, programmers have sort of universally ignored the fact that there was a myArray(0) element that just took up space and didn't get used for anything ... Except for those programmers who DID use it and their programs looked, I mean, just "weird".

For I = 1 to 5
MyArray(I - 1) = Whatever
Next

I mean, REALLY! ...

Probably no other single feature of Visual Basic "notNet"

The Silver Medal of 2nd Place goes to honor an old friend that was dropped into the bit bucket of programming with the passing of VB6! I speak of none other than, The Variant Datatype.

Probably no other single feature of Visual Basic "notNet" better represents the philosophy of "fast, cheap, and loose". This image dogged VB right up to the introduction of VB.NET. I'm old enough to remember the introduction of Visual Basic 3.0 by Microsoft: "Oh Wow! Lookee here! With the new, improved Variant data type, you don't have to declare variables or nothin'. You can just think 'em up and code 'em."

Microsoft changed their tune pretty fast on that one and recommended declaring variables with a specific datatype almost immediately, leaving many of us to wonder, "If you can't use Variants, why have them?"

But while we're on the subject of datatypes, I should mention that a lot of datatypes have changed in addition to dropping Variant into wet cement. There's a new Char datatype and a Long datatype that is 64 bits. Decimal is way different. Short and Integer aren't the same length anymore.

And there is a new "Object" datatype that can be anything. Did I hear someone say, "Son of Variant"?

In 4th Place, we have Changes to Procedure

In 4th Place, we have Changes to Procedure Calls!

This is the "goodness, purity, and wholesome virtue" award and represents a lot of hard campaigning by the "no more sloppy code" faction.

In VB6, if a procedure parameter variable is an intrinsic type, then it's ByRef, unless you have coded it ByVal explicitly, but if it's not coded ByRef or ByVal and it's not an intrinsic variable then it's ByVal. ... Got that?

In VB.NET, it's ByVal unless it's coded ByRef.

The ByVal VB.NET default, by the way, also prevents changes to parameter variables in procedures from being unintentionally propagated back into the calling code - a key part of good OOP programming.

Microsoft also "overloads" VB.NET with a change in the requirements for parentheses in procedure calls.

In VB6, parentheses are required around arguments when making function calls, but not when calling a subroutine when not using the Call statement but they are required when the Call statement is used.

In VB.NET, parentheses are always required around a nonempty argument list.

Award(5)", our 6th Place award goes to the C groupies

"Award(5)", our 6th Place award goes to the C groupies choice: C-like Syntax Changes!

Now you can code a += 1 instead of a = a + 1, saving THREE WHOLE KEYSTROKES!

Programmers of the World, Rejoice! VB has been raised up to C level, and a whole new generation trying to learn VB will get a little closer to the mass confusion that confronts students of C++.

But wait! There's more!

VB.NET now features "short circuit logic" that has introduced subtle bugs into C++ code for years to save precious nano-seconds of processor time. Short circuit logic only evaluates multiple conditions in a logical statement if necessary. For example:

Dim R As Boolean
R = Function1() And Function2()

In VB6, both functions are evaluated whether they need it or not. With VB.NET, if Function1() is false, Function2() is ignored since "R" can't be True. But, what if a global variable is changed in Function2() - just by chance (C++ programmers would say, "by poor programming".) Why does my code produce the wrong answer some of the time when it's translated to VB.NET? This might be it!

For Trying harder, VB.NET will Catch a little luck and Finally get recognized for "exceptional" error handling.

VB6 had the last holdout GoTo: "On Error GoTo". Even I have to admit that the C++ style "Try-Catch-Finally" structured exception handling is a vast improvement, not just a half vast improvement.

What, you say "On Error GoTo" is still in VB.NET? Wellll ... We try not to talk about that too much.

VB.NET no longer supports VarPtr, ObjPtr and StrPtr

5th Place selection is a group award: The Miscellaneous Command Changes! They have to share this award and there's a gazillion of 'em. Microsoft has been saving up for ten years and they really cut loose.
VB.NET no longer supports VarPtr, ObjPtr and StrPtr functions which retrieved the memory address of variables. And it doesn't support VB6 LSet which was used to convert one user defined type to another. (Not to be confused with VB6 LSet which does something completely different - see below.)
We also bid fond adieu to Let, Is Missing, DefBool, DefByte, DefLng, DefCur, DefSng, DefDbl, DefDec, DefDate, DefStr, DefObj, DefVar, and (my personal favorite!) GoSub.
Circle has morphed into GDI+ DrawEllipse. The same goes for Line to DrawLine. In calculation we now have Atan instead of Atn, Sign goes in for Sgn, and Sqrt suits up for the big game instead of Sqr.
In string processing, even though they're still available if you reference a Microsoft compatibility namespace, we have PadRight for VB6's LSet (again, totally different than VB6's LSet, of course) and PadLeft for RSet. (There goes the three keystrokes we saved with "+="!)
And of course, since we're OOP now, don't fret if Property Set, Property Let, and Property Get are not met in VB.NET, you bet!
Finally, Debug.Print becomes either Debug.Write or Debug.WriteLine. Only nerds print everything anyway.
This doesn't even touch all the NEW commands in VB.NET, but we've got to stop this nonsense somewhere.

.NET needed to do, Microsoft decided

In the meantime, Java, Python, and a whole lot of other programming languages that WERE object oriented started to appear. Visual Basic was getting passed up - big time! This is a situation Microsoft does not tolerate ... and they resolved to solve the problem once and for all. The solution is .NET.
But to do the things that .NET needed to do, Microsoft decided that they had to "break compatibility". That is, Visual Basic programs had been (with very minor exceptions) "upward compatible" from VB1 right up to VB6. A program written in that first version of VB would still compile and run in the next version. But with VB.NET, Microsoft found they just couldn't make the language completely OOP and maintain upward compatibily.
Once they made this fundamental decision, the flood gates opened on ten years of accumulated "wish list" changes and ALL of them went into the new VB.NET. As they say in Britain, "In for a penny, in for a pound."
Without further delay, here's my very personal list of the top five changes from VB6 to VB.NET in reverse order.
Wellllll .... just one further delay. Since we're changing from VB6, where an array declared as Dim myArray(5) has 6 elements, We have six of 'em. It's only fitting

The Top Five Changes between VB 6 and VB.NET

Visual Basic 1.0 was a major earthquake throughout programming. Before VB1, you had to use C, C++, or some other horrible development environment to create Windows applications. Programmers literally spent weeks just drawing windows on screens with picky, detailed, hard to debug code. (The same thing you can do by dragging a form from the toolbar in a few seconds.) VB1 was a hit and gazillions of programmers immediately started using it.
But to make the magic happen, Microsoft made some major architecture compromises. In particular, since VB1 created the forms and controls, they didn't allow the programmer access to the code that did it. You either let VB create everything, or you used C++.
VB 2 through 6 maintained this same architecture. Microsoft made some very clever updates which gave programmers a lot more control, but in the final analysis programmers still couldn't integrate their code with the VB code. It was a black box - and not in the good OOP way either. Another way of saying this was that the programmer didn't have access to the internal VB "objects" and another way of saying that was that VB6 still wasn't fully "object oriented".

The reason for the error this time is that when the VB 6

The reason for the error this time is that when the VB 6 code was pasted into VB.NET, Intellisense corrected another "error" and added the VB.NET default, ByVal. This doesn't allow the actual value of the argument to be changed, only the copy made for the subroutine. If this is changed to ByRef in the VB.NET program, all is well again. This is one thing the Upgrade Wizard does right, by the way. It's changed to ByRef automatically when the Wizard is run.

The explanation can be found in this note found buried pretty

The explanation can be found in this note found buried pretty deeply in the VB 6 documentation:
You are not required to use the Call keyword when calling a procedure. However, if you use the Call keyword to call a procedure that requires arguments, argumentlist must be enclosed in parentheses. If you omit the Call keyword, you also must omit the parentheses around argumentlist. If you use either Call syntax to call any intrinsic or user-defined function, the function's return value is discarded. Emphasis added.
The actual behavior of the code doesn't seem to quite follow the documentation. But one thing is clear, the result is discarded. Not knowing this interesting bit of non-obvious behavior could result in a hard to find bug in VB 6.
Because VB 6 didn't follow the conventions used by other languages and was generally confusing and inconsistent, Microsoft decided to scrap most of the procedure call syntax in VB 6 when they moved to VB.NET. In VB.NET, there is one way to do things and if you don't do it that way, an error results. Let's see what has to be done to convert this code to VB.NET.
One way to convert the VB 6 project is to use the Upgrade Wizard. Just open the VB 6 project in VB.NET and the wizard takes over. But the Upgrade Wizard often misses a lot of optimization and can't convert some things at all. So a lot of programmers just copy and paste the code from VB 6 to VB.NET and correct the errors that result. If you do this with the first code example at the top of the article, there's just one error to correct: the fact that the variable CallingArg isn't declared. When this is declared as String, the program runs! But it doesn't quite get the right result as shown below:

ByVal and ByRef: Passing Arguments in Visual Basic

There are two ways to pass arguments to a procedure in Visual Basic: ByVal and ByRef. This refers to whether a copy of the argument is passed to the procedure (ByVal - the value is passed) or whether the actual argument itself is passed (ByRef - a reference to the argument is passed). The default for VB 6 is to call ByRef.

There are also two types of procedures in Visual Basic: Function and Sub. The difference is that a Function returns the a value assigned to the function name and a Sub doesn't. So if you want to return a value to the calling routine, there are two ways to do it. In VB 6, the code that returns a value could look like this for a Sub:

Sub code to return a value from a procedure call

Public Sub CallingSub() CallingArg = "ABCDEF" CalledSub CallingArg MsgBox (CallingArg)End SubPublic Sub CalledSub(CalledArg) CalledArg = "987654"End Sub
Or the code could look like this for a Function:
Function code to return a value from a procedure call
Public Sub CallingSub() CallingArg = "ABCDEF" CalledFunc CallingArg MsgBox (CallingArg)End SubPublic Function CalledFunc(CalledArg) CalledArg = "987654" CalledFunc = "Any Return Value"End Function
The result of both is a messagebox that displays the value "987654" that is returned as a result of changing the value of the argument.
Note that the main difference is that the function has just one more statement to assign a return value to the function name. In VB 6, the difference was sometimes considered meaningless and programmers often used subroutines rather than functions out of habit or just to save a statement.
A few other "shortcuts" in VB 6 should be pointed out.
No variables are declared.This means that all of the variables are of type "Variant" - similar to "Object" in VB.NET.
No scoping or typing is done in the argument list.This means that everything uses the default settings.
The procedure call doesn't use any parentheses or a Call keyword.
This has some additional consequences. Let's look at those next. The illustration below shows an interesting result of simply changing whether parentheses are used or not in VB 6.

Sunday, July 26, 2009

Object Exchange

Object Exchange (OBEX) protocol - Windows CE .Net's support for OBEX works over Bluetooth and infra red data association (IrDA) protocols . Object Exchange (OBEX) is an efficient, compact binary protocol that enables a wide range of devices to exchange data spontaneously in a simple, efficient manner.

Media Sense - This feature improves the roaming experience for mobile devices users by notifying application of network status.

Real time collaboration and communication (RTC/SIP) - Real time communication (RTC) enables messaging, presence, and audio (voice over IP between any two IP-enabled devices .

Realiable core operating system services for demanding embedded designs : Windows CE .ET offers reliable core operating system services that enable the most demanding real time embedded designs across a breadth of devices .

New and enhanced operating system features include:

Small footprint: Continuing the effort to minimize the operating system footprint for embedded devices, Windows CE .NET provides granular Kernel componentization. Windows CE .NET supports a minimum configuration platform as small as 200 KB with minimum Kernel functions only.

Enterprise-scale - Network security enhancements include support for the Kerberos Security Protocol.

Wide selection of CPU'S- Windows CE .NET provides a high level of processor flexibility with support for the following four families of microprocessors and emulation technologies like ARM, MIPS, SHx, x 86 etc.

Real time - Real time processing support for the most demanding support for the most demanding deterministic applications with 256 priority levels and nested interrupt support.

Net- enabled for creating rich personalized experiences - Windows CE .NET enables you to build smart Microsoft .NET-enabled devices and create rich, personalized experiences.

XML - XML allows developers to easily describe and deliver rich, structured data from any application in a standard consistent way.

Net compact Framework :

Net compact Framework : The .NET Compact Framework supports all processors supported by windows CE .NET . For more information on how to develop application using the .NET Framework, please see .NET on the MSDN site. Look in the .NET Compact Framework Read me' for specific information about implementation issues in your embedded design.

Microsoft Direct3D API - Provides support for interactive three-dimensional (3-D) graphics applications by allowing device dependent access to 30d video-display hardware in devices-independent manner.

Windows Media 8 compressor/decompressor (codecs) and controls - Supports the latest Microsoft Windows Media 8 codes and controls ,which allows for the latest high-bandwidth encoded multimedia streams .

Easy-to-use end-to-end tool set: Windows CE .NET provides an integrated end-to-end tool set to help developers reduce both operating system and application development time, allowing them to get devices to market faster.

These tools include:

Emulation technology - Windows CE .NET include emulation technology to enable developers to build and test their designs on their Windows 2000 or Windows xp professional workstations without additional hardware investments.

New platform wizard - The new platform wizard provides a foundation for starting device designs for:

Cellophanes / Smart phones
Custom devices
Digital imaging devices
Industrial automation devices
Internet/media appliances
Personal digital assistants (PDA)/Mobile handhelds
Residential gateways
Retail point-of-sale
Set-top boxes
Tiny kernels
Web pads Windows thin clients
Support for managed and native code - To write applications for Windows CE .NET, Microsoft offers a rich set of languages for creating managed .NET-enabled or unmanaged (native) applications.

Windows CE .NET:

Windows CE .NET:

Window CE .NET is the successor to Windows CE 3.0 Designed from the ground up for the embedded marketplace, Window CE .NET aims to deliver a robust realtime operating system for rapidly building the next generation of smart mobile and small footprint devices.

With a complete operating system feature set and end-to-end development environment Windows CE-based devices that requires rich networking hard real time, and a small footprint , as well as rich multimedia and Web browsing capabilities.

Windows CE .NET offers :

Scalable wireless technologies : Windows CE.NET include scalable wireless technologies that enable mobile devices to flexibly connect into existing infrastructures . Supported wireless technologies include Bluetooth.

Windows CE .NET allows a devices to use a Bluetooth-enabled cellular phone as a data modem , and to use a Bluetooth-enabled local area network (LAN) access point to provide network connectivity .

802.1x/Zero Configuration - New features in window CE .NET i.e., 802.11 zero configuration, aim to simplify setup of 802.11 network and to enable seamless roaming from one 802.11 network to another. 801.1x and EAP enhance the security of 802.11 by enabling user/password, certificate, or original equipment manufacturer (OEM) specific authentication to log on to the network.

With Command Explained

Introduction
As mentioned above this tutorial focuses on the With command in Visual Basic 6.0, you can use it to control object on your forms and to set the properties like you can with the click of a mouse. I can hear you ask "Why use this when you can set properties with mouse clicks?". Well the answer is, in the programming world most people use this method and you can then easily change the property without going through any wizards or anything.

Requirements
For this tutorial you will need a Windows based operating system with a copy of Visual Basic 6.0 installed. Nothing else...

The With Command
I feel this command is sometimes underrated and most definantly underused in programs I have seen. People tend not to use this command as the Properties Window in Visual Basic allows you to do it much quicker without typing lines of code. In fact all you are doing is writing the code without typing (if that makes sense).

The syntax for this is really simple...

With objectname
'perform code
End With
Simply enough you replace the object name section with the name of your object e.g. dlgSplash. From here you can use the . (dot) to bring up the syntax suggest list of attributes to set. In our example we will load a splash dialog and then load the main program form.

So say we startup with a sub-routine called main. Using our with command we will show the dlgSplash form and refresh it.

Sub main()
'start with
With dlgSplash
'show form
.Show

'refresh form
.Refresh

End With
End Sub
Simple enough eh? All this does is shorten the dlgSplash.Show to what you see above in the example. Our final code example will have the code above and then load the new form for the main program and remove the splash dialog.
Sub main() 'start with With dlgSplash 'show form .Show 'refresh form .Refresh
'show program form frmMain.Show
'unload splash Unload dlgSplash
End WithEnd Sub
As you may have guessed by now we can shorten the frmMain.Show to this...
With frmMain .ShowEnd With
However if you have a property call in this in an if function for example you have to referenceit properly even though the With may already be where your object is.

Thursday, July 9, 2009

VB ScrollBar - Using ScrollBar Control In Visual Basic 6

The ScrollBar is a commonly used control, which enables the user to select a value by positioning it at the desired location. It represents a set of values. The Min and Max property represents the minimum and maximum value. The value property of the ScrollBar represents its current value, that may be any integer between minimum and maximum values assigned.

The HScrollBar and the VScrollBar controls are perfectly identical, apart from their different orientation. After you place an instance of such a control on a form, you have to worry about only a few properties: Min and Max represent the valid range of values, SmallChange is the variation in value you get when clicking on the scroll bar's arrows, and LargeChange is the variation you get when you click on either side of the scroll bar indicator. The default initial value for those two properties is 1, but you'll probably have to change LargeChange to a higher value. For example, if you have a scroll bar that lets you browse a portion of text, SmallChange should be 1 (you scroll one line at a time) and LargeChange should be set to match the number of visible text lines in the window.

The most important run-time property is Value, which always returns the relative position of the indicator on the scroll bar. By default, the Min value corresponds to the leftmost or upper end of the control:

' Move the indicator near the top (or left) arrow.
VScroll1.Value = VScroll1.Min
' Move the indicator near the bottom (or right) arrow.
VScroll1.Value = VScroll1.Max

While this setting is almost always OK for horizontal scroll bars, you might sometimes need to reverse the behavior of vertical scroll bars so that the zero is near the bottom of your form. This arrangement is often desirable if you want to use a vertical scroll bar as a sort of slider. You obtain this behavior by simply inverting the values in the Min and Max properties. (In other words, it's perfectly legal for Min to be greater than Max.)

There are two key events for scrollbar controls: the Change event fires when you click on the scroll bar arrows or when you drag the indicator; the Scroll event fires while you drag the indicator. The reason for these two distinct possibilities is mostly historical. First versions of Visual Basic supported only the Change event, and when developers realized that it wasn't possible to have continuous feedback when users dragged the indicator, Microsoft engineers added a new event instead of extending the Change event. In this way, old applications could be recompiled without unexpected changes in their behavior. At any rate, this means that you must often trap two distinct events:

' Show the current scroll bar's value.
Private VScroll1_Change()
Label1.Caption = VScroll1.Value
End Sub
Private VScroll1_Scroll()
Label1.Caption = VScroll1.Value
End Sub

The example shown in the following figure uses three VScrollBar controls as sliders to control the individual RGB (red, green, blue) components of a color. The three scroll bars have their Min property set to 255 and their Max property set to 0, while their SmallChange is 1 and LargeChange is 16. This example is also a moderately useful program in itself because you can select a color and then copy its numeric value to the clipboard and paste it in your application's code as a decimal value, a hexadecimal value, or an RGB function.



Use scrollbar controls to visually create colors.

Scrollbar controls can receive the input focus, and in fact they support both the TabIndex and TabStop properties. If you don't want the user to accidentally move the input focus on a scrollbar control when he or she presses the Tab key, you must explicitly set its TabStop property to False. When a scrollbar control has the focus, you can move the indicator using the Left, Right, Up, Down, PgUp, PgDn, Home, and End keys. For example, you can take advantage of this behavior to create a read-only TextBox control with a numeric value that can be edited only through a tiny companion scroll bar. This scroll bar appears to the user as a sort of spin button, as you can see in the figure below. To make the trick work, you need to write just a few lines of code:

Private Sub Text1_GotFocus()
' Pass the focus to the scroll bar.
VScroll1.SetFocus
End Sub
Private Sub VScroll1_Change()
' Scroll bar controls the text box value.
Text1.Text = VScroll1.Value
End Sub


Scrollbar controls are even more useful for building scrolling forms, like the one displayed in Figure 3-15. To be certain, scrolling forms aren't the most ergonomic type of user interface you can offer to your customers: If you have that many fields in a form, you should consider using a Tab control, child forms, or some other custom interface. Sometimes, however, you badly need scrollable forms, and in this situation you are on your own because Visual Basic forms don't support scrolling.

Fortunately, it doesn't take long to convert a regular form into a scrollable one. You need a couple of scrollbar controls, plus a PictureBox control that you use as the container for all the controls on the form, and a filler control—a CommandButton, for example—that you place in the bottom-right corner of the form when it displays the two scroll bars. The secret to creating scrollable forms is that you don't move all the child controls one by one. Instead, you place all the controls in the PictureBox control (named picCanvas in the following code), and you move it when the user acts on the scroll bar:

Sub MoveCanvas()
picCanvas.Move -HScroll1.Value, -VScroll1.Value
End Sub

In other words, to uncover the portion of the form near the right border, you assign a negative value to the PictureBox's Left property, and to display the portion near the form's bottom border you set its Top property to a negative value. It's really that simple. You do this by calling the MoveCanvas procedure from within the scroll bars' Change and Scroll events. Of course, it's critical that you write code in the Form_Resize event, which makes a scroll bar appear and disappear as the form is resized, and that you assign consistent values to Max properties of the scrollbar controls:

' size of scrollbars in twips
Const SB_WIDTH = 300 ' width of vertical scrollbars
Const SB_HEIGHT = 300 ' height of horizontal scrollbars

Private Sub Form_Resize()
' Resize the scroll bars along the form.
HScroll1.Move 0, ScaleHeight - SB_HEIGHT, ScaleWidth - SB_WIDTH
VScroll1.Move ScaleWidth - SB_WIDTH, 0, SB_WIDTH, _
ScaleHeight - SB_HEIGHT
cmdFiller.Move ScaleWidth - SB_WIDTH, ScaleHeight - SB_HEIGHT, _
SB_WIDTH, SB_HEIGHT

' Put these controls on top.
HScroll1.ZOrder
VScroll1.ZOrder
cmdFiller.ZOrder
picCanvas.BorderStyle = 0

' A click on the arrow moves one pixel.
HScroll1.SmallChange = ScaleX(1, vbPixels, vbTwips)
VScroll1.SmallChange = ScaleY(1, vbPixels, vbTwips)
' A click on the scroll bar moves 16 pixels.
HScroll1.LargeChange = HScroll1.SmallChange * 16
VScroll1.LargeChange = VScroll1.SmallChange * 16

' If the form is larger than the picCanvas picture box,
' we don't need to show the corresponding scroll bar.
If ScaleWidth < picCanvas.Width + SB_WIDTH Then
HScroll1.Visible = True
HScroll1.Max = picCanvas.Width + SB_WIDTH - ScaleWidth
Else
HScroll1.Value = 0
HScroll1.Visible = False
End If
If ScaleHeight < picCanvas.Height + SB_HEIGHT Then
VScroll1.Visible = True
VScroll1.Max = picCanvas.Height + SB_HEIGHT - ScaleHeight
Else
VScroll1.Value = 0
VScroll1.Visible = False
End If
' Make the filler control visible only if necessary.
cmdFiller.Visible = (HScroll1.Visible Or VScroll1.Visible)
MoveCanvas
End Sub

Working with scrollable forms at design time isn't comfortable. I suggest that you work with a maximized form and with the PictureBox control sized as large as possible. When you're finished with the form interface, resize the PictureBox control to the smallest area that contains all the controls, and then reset the form's WindowState property to 0-Normal.