Showing posts with label Simple. Show all posts
Showing posts with label Simple. Show all posts

Saturday, March 17, 2012

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

Wednesday, March 7, 2012

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

Monday, March 5, 2012

Simple Windows API Example

When developing Windows applications one of the most useful things a person can know is how to interact with the Win32 API. By understanding these functions and hooks that Microsoft provides we are able to unleash a vast array of extra capabilities that are not yet built into the VB.NET libraries. This tutorial walks through a simple example of how to call into the Windows API.

The Windows API is a set of code libraries (DLL files) containing numerous functions for working with all aspects of Windows (graphics, the file system, fonts, low-level memory access, etc.). These function libraries are available to programmers coding with any Windows development system (VB, C++, Delphi, etc.).

While using the API is often treated as an "advanced" programming topic (and to be sure, using the API allows you to delve as deep into the depths of Windows programming as you desire), the coding to actually set up and use an API function is relatively straightforward. The basic steps are:

Declare the API sub or function with the Declare statement. The Declare statement must be coded in the general declarations section of a form or module, and can be declared with either Public or Private scope (Private only in forms). If declared as Public, any form or module in your VB.NET application can use the function; if Private, only the form or module in which it is declared can use the function. Declare any variables and constants necessary to be used as parameters with the sub or function. Call the sub or function as you would any other sub or function. (Be advised that there are some differences between calling API functions versus regular VB.NET subs and functions.)

To find the declarations and documentation necessary to use any of the 1000+ Windows API functions available, you can consult any of the numerous API Help websites. Google is of course best for searching.

Sample Program

We will now build a simple program that demonstrates the use of API functions. We will call upon the "GetComputerName" function to access the name of your computer and display it in the console winodw.

Note: On Windows XP, the name of the computer can be found by right-clicking on the My Computer icon and choosing Properties, which then displays the System Properties screen shown below. The second tab, Computer Name, shows your computer name. In this case, the name of the computer is “toshiba-user” (shown circled in red below).

image

Following is the code for the sample console application to display the computer name:

Module Module1 Private Declare Function GetComputerName _Lib "kernel32.dll" Alias "GetComputerNameA" _ ByVal lpBuffer AsString, ByRef nSize AsInteger) AsInteger Sub Main() Dim strBuffer AsString Dim intCharCount AsInteger Dim intRetVal AsInteger Const MAX_COMPUTERNAME_LENGTH AsInteger = 31 Dim strMessage AsString intCharCount = MAX_COMPUTERNAME_LENGTH strBuffer = NewString(Chr(0), intCharCount + 1) intRetVal = GetComputerName(strBuffer, intCharCount) If intRetVal <> 0 Then strMessage = "Your computer name is: " _ & strBuffer.Substring(0, intCharCount) Else strMessage = "Computer name could not be determined." EndIf Console.WriteLine(strMessage) Console.WriteLine("") Console.WriteLine("(Press Enter to close this window.)") Console.ReadLine() EndSubEnd Module

A screen-shot of the run is shown below:

image

We can analyze the code as follows. First, an explanation of the Declare statement. The Declare statement has the following general syntax:

[Public | Private] Declare Function Name Lib LibraryName [Alias AliasName] ([parameter list]) As datatype

- or -

[Public | Private] Declare Sub Name Lib LibraryName [Alias AliasName] ([parameter list])

As discussed above, the Public or Private keyword establishes the scope of the function as it will be used in your program.

As in normal VB Subs and Functions, use the Function keyword (and the corresponding As datatype clause at the end of the declaration) if the API function returns a value (in most cases, the "Function" form will be used, and the return value (datatype) will be Integer). In other cases, where the API function does not return a value, use the Sub keyword and leave off the As datatype clause.

Name specifies the name of the function as it will be used in the VB program. When the internal name of the function within the library (DLL file) is different, use the Alias clause to specify the actual internal name within the DLL.

LibraryName specifies which DLL the function can be found in.

AliasName specifies the actual internal name of the function within the Windows DLL file. The Alias clause needs to be used if the name used for Name is different. The Alias clause is useful when an internal name conflicts with a keyword (but can be used if you simply want to use a different name to call the function).

Parameter list is the comma-separated list of arguments that the function expects.

As datatype specifies the data type returned by the function. In most cases, this is a 32-bit integer specified in VB.NET as Integer. (Note: In previous versions of VB, the Integer data type was a 16-bit integer and the Long was a 32-bit integer. Thus, the return value for API functions was typically specified as Long when declaring APIs in the previous VB versions. In VB.NET, the Integer data type is now a 32-bit integer and the Long is a 64-bit integer, so we must use Integer data type to specify the return value for API functions.)

In this example, our declaration looks like this:

Private Declare Function GetComputerName Lib _"kernel32.dll" Alias "GetComputerNameA" _(ByVal lpBuffer AsString, ByRef nSize AsInteger) AsInteger

This tells the system we are looking for the GetComputerName function located in the kernel32.dll Windows system file. (The Alias clause indicates that the actual name of the function in the dll is GetComputerNameA, however, declaring the function as above, we can refer to the function as GetComputerName in our VB code.)

The arguments to this particular function are lpBuffer, which is a string that will store the computer name, and nSize which is a number (integer) that will store the number of characters contained in the computer name. (Technically, the lpBuffer argument is a “null-terminated string”, which is a string in which the trailing character(s) are the null character (ASCII code 0). The characters up to but not including the first null character represents the value of the string.)

The As Integer specification at the end of our declaration indicates that the function will be returning a Integer value. In the case of many API functions, a 32-bit Integer value will be returned to indicate the success or failure of the call.

The crux of the processing occurs in these three lines. We are setting the variable intCharCount to the value of the constant MAX_COMPUTER_LENGTH, which is set to 31. The next statement pads the variable strBuffer with 32 null characters. The actual call to the API function follows, which causes the computer name to be stored in strBuffer (in our case the result will be the string “TOSHIBA-USER” followed by 20 null characters). This is because the string “TOSHIBA-USER” contains 12 characters, and since the total length of the string is 32 characters, 20 null characters will trail at the end of the string. The function will also store the value 12 in the variable intCharCount, representing the number of characters in the name that was retrieved. The result of the function (the return value) is stored in the variable intRetVal. If the result is non-zero, the function succeeded; if zero, the function failed.

intCharCount = MAX_COMPUTERNAME_LENGTH strBuffer = NewString(Chr(0), intCharCount + 1) intRetVal = GetComputerName(strBuffer, intCharCount)

The code that follows tests the return value. If the return value is non-zero, then the call was successful, and a message containing the computer’s name is stored in the variable strMessage (the Substring method is applied to the strBuffer variable to grab its 12 leftmost characters). Otherwise, we set strMessage to indicate that the function failed. In any case, the message is then displayed on the console.

If intRetVal <> 0 Then strMessage = "Your computer name is: " _ & strBuffer.Substring(0, intCharCount) Else strMessage = "Computer name could not be determined." EndIf  Console.WriteLine(strMessage)

Download the VB Project code for the example above: VB.NET API Example

NOTE : We can use the API functions in VB.NET using the steps covered in this article. However, it must be noted that most of the functionality of Windows API has been encapsulated in Object Oriented Classes of .NET framework and many more will be added to this list of classes and functions. Therefore, it is recommend that before using an API, we must check if the similar functionality is available in .NET classes.

This article was original written by The VB Programmer.


View the original article here

Sunday, March 4, 2012

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

Saturday, March 3, 2012

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

Friday, March 2, 2012

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here

Thursday, March 1, 2012

Simple Windows API Example

When developing Windows applications one of the most useful things a person can know is how to interact with the Win32 API. By understanding these functions and hooks that Microsoft provides we are able to unleash a vast array of extra capabilities that are not yet built into the VB.NET libraries. This tutorial walks through a simple example of how to call into the Windows API.

The Windows API is a set of code libraries (DLL files) containing numerous functions for working with all aspects of Windows (graphics, the file system, fonts, low-level memory access, etc.). These function libraries are available to programmers coding with any Windows development system (VB, C++, Delphi, etc.).

While using the API is often treated as an "advanced" programming topic (and to be sure, using the API allows you to delve as deep into the depths of Windows programming as you desire), the coding to actually set up and use an API function is relatively straightforward. The basic steps are:

Declare the API sub or function with the Declare statement. The Declare statement must be coded in the general declarations section of a form or module, and can be declared with either Public or Private scope (Private only in forms). If declared as Public, any form or module in your VB.NET application can use the function; if Private, only the form or module in which it is declared can use the function. Declare any variables and constants necessary to be used as parameters with the sub or function. Call the sub or function as you would any other sub or function. (Be advised that there are some differences between calling API functions versus regular VB.NET subs and functions.)

To find the declarations and documentation necessary to use any of the 1000+ Windows API functions available, you can consult any of the numerous API Help websites. Google is of course best for searching.

Sample Program

We will now build a simple program that demonstrates the use of API functions. We will call upon the "GetComputerName" function to access the name of your computer and display it in the console winodw.

Note: On Windows XP, the name of the computer can be found by right-clicking on the My Computer icon and choosing Properties, which then displays the System Properties screen shown below. The second tab, Computer Name, shows your computer name. In this case, the name of the computer is “toshiba-user” (shown circled in red below).

image

Following is the code for the sample console application to display the computer name:

Module Module1 Private Declare Function GetComputerName _Lib "kernel32.dll" Alias "GetComputerNameA" _ ByVal lpBuffer AsString, ByRef nSize AsInteger) AsInteger Sub Main() Dim strBuffer AsString Dim intCharCount AsInteger Dim intRetVal AsInteger Const MAX_COMPUTERNAME_LENGTH AsInteger = 31 Dim strMessage AsString intCharCount = MAX_COMPUTERNAME_LENGTH strBuffer = NewString(Chr(0), intCharCount + 1) intRetVal = GetComputerName(strBuffer, intCharCount) If intRetVal <> 0 Then strMessage = "Your computer name is: " _ & strBuffer.Substring(0, intCharCount) Else strMessage = "Computer name could not be determined." EndIf Console.WriteLine(strMessage) Console.WriteLine("") Console.WriteLine("(Press Enter to close this window.)") Console.ReadLine() EndSubEnd Module

A screen-shot of the run is shown below:

image

We can analyze the code as follows. First, an explanation of the Declare statement. The Declare statement has the following general syntax:

[Public | Private] Declare Function Name Lib LibraryName [Alias AliasName] ([parameter list]) As datatype

- or -

[Public | Private] Declare Sub Name Lib LibraryName [Alias AliasName] ([parameter list])

As discussed above, the Public or Private keyword establishes the scope of the function as it will be used in your program.

As in normal VB Subs and Functions, use the Function keyword (and the corresponding As datatype clause at the end of the declaration) if the API function returns a value (in most cases, the "Function" form will be used, and the return value (datatype) will be Integer). In other cases, where the API function does not return a value, use the Sub keyword and leave off the As datatype clause.

Name specifies the name of the function as it will be used in the VB program. When the internal name of the function within the library (DLL file) is different, use the Alias clause to specify the actual internal name within the DLL.

LibraryName specifies which DLL the function can be found in.

AliasName specifies the actual internal name of the function within the Windows DLL file. The Alias clause needs to be used if the name used for Name is different. The Alias clause is useful when an internal name conflicts with a keyword (but can be used if you simply want to use a different name to call the function).

Parameter list is the comma-separated list of arguments that the function expects.

As datatype specifies the data type returned by the function. In most cases, this is a 32-bit integer specified in VB.NET as Integer. (Note: In previous versions of VB, the Integer data type was a 16-bit integer and the Long was a 32-bit integer. Thus, the return value for API functions was typically specified as Long when declaring APIs in the previous VB versions. In VB.NET, the Integer data type is now a 32-bit integer and the Long is a 64-bit integer, so we must use Integer data type to specify the return value for API functions.)

In this example, our declaration looks like this:

Private Declare Function GetComputerName Lib _"kernel32.dll" Alias "GetComputerNameA" _(ByVal lpBuffer AsString, ByRef nSize AsInteger) AsInteger

This tells the system we are looking for the GetComputerName function located in the kernel32.dll Windows system file. (The Alias clause indicates that the actual name of the function in the dll is GetComputerNameA, however, declaring the function as above, we can refer to the function as GetComputerName in our VB code.)

The arguments to this particular function are lpBuffer, which is a string that will store the computer name, and nSize which is a number (integer) that will store the number of characters contained in the computer name. (Technically, the lpBuffer argument is a “null-terminated string”, which is a string in which the trailing character(s) are the null character (ASCII code 0). The characters up to but not including the first null character represents the value of the string.)

The As Integer specification at the end of our declaration indicates that the function will be returning a Integer value. In the case of many API functions, a 32-bit Integer value will be returned to indicate the success or failure of the call.

The crux of the processing occurs in these three lines. We are setting the variable intCharCount to the value of the constant MAX_COMPUTER_LENGTH, which is set to 31. The next statement pads the variable strBuffer with 32 null characters. The actual call to the API function follows, which causes the computer name to be stored in strBuffer (in our case the result will be the string “TOSHIBA-USER” followed by 20 null characters). This is because the string “TOSHIBA-USER” contains 12 characters, and since the total length of the string is 32 characters, 20 null characters will trail at the end of the string. The function will also store the value 12 in the variable intCharCount, representing the number of characters in the name that was retrieved. The result of the function (the return value) is stored in the variable intRetVal. If the result is non-zero, the function succeeded; if zero, the function failed.

intCharCount = MAX_COMPUTERNAME_LENGTH strBuffer = NewString(Chr(0), intCharCount + 1) intRetVal = GetComputerName(strBuffer, intCharCount)

The code that follows tests the return value. If the return value is non-zero, then the call was successful, and a message containing the computer’s name is stored in the variable strMessage (the Substring method is applied to the strBuffer variable to grab its 12 leftmost characters). Otherwise, we set strMessage to indicate that the function failed. In any case, the message is then displayed on the console.

If intRetVal <> 0 Then strMessage = "Your computer name is: " _ & strBuffer.Substring(0, intCharCount) Else strMessage = "Computer name could not be determined." EndIf  Console.WriteLine(strMessage)

Download the VB Project code for the example above: VB.NET API Example

NOTE : We can use the API functions in VB.NET using the steps covered in this article. However, it must be noted that most of the functionality of Windows API has been encapsulated in Object Oriented Classes of .NET framework and many more will be added to this list of classes and functions. Therefore, it is recommend that before using an API, we must check if the similar functionality is available in .NET classes.

This article was original written by The VB Programmer.


View the original article here

Wednesday, February 29, 2012

Simple and advanced Conditional Experssions

Conditional expressions are used for so many things in VB.NET including branching, selection, and repetition. We use Conditional expressions all the time in real life. They evaluate to being either true or false, and are important in programming because they can be used to signal the computer to take one action (or set of actions) if the condition is true and another set of actions if the condition is false. With selection, a set of actions is taken if a condition is true; an alternative set of actions is taken if the condition is false; with repetition, a set of actions is repeated as long as a certain condition prevails.

Conditional expressions in VB statements must be preceded by certain keywords, such as If or Do While. The conditional expression itself is formed as follows:

               

The expression on either side of the relational operator can be a constant (string or numeric), variable (string or numeric), or an expression using symbols like +, -, etc.

The relational operator can be one of six symbols (or pair of symbols):

            Relational Operator                    Meaning

                        <                                  less than

                        >                                  greater than

                        =                                  equal to

                        <>                                not equal to (same as ¹ in algebra)

                        >=                                greater than or equal to (same as ³ in algebra)

                        <=                                less than or equal to (same as £ in algebra)

The expressions on either side of the relational operator should be "compatible" - that is, you should only compare a numeric item to a numeric item or a string item to a string item.  (As with assignment statements, if Option Strict is off, VB will perform "implicit conversion" if you compare two data items of different types; if the conversion cannot be performed, an "invalid cast exception" error will occur. If Option Strict is on, VB will not attempt to compare items of different types and will instead generate a compiler error.)

Following are some examples of conditional expressions involving the numeric variables intI and intJ.  Assume intI contains the value 5 and intJ contains the value 10:

When the conditional expression involves a character string compare, you can think of the relational operators as performing a comparison based on "alphabetical order".  For example, the expression "A" < "D" is true, because "A" precedes "D" alphabetically.  Likewise, the expression "Z" > "Q" is true, because "Z" follows "Q" alphabetically.

Following are some examples of conditional expressions involving the string variables strA and strB.  Assume strA contains "MARY" and strB contains "JOE":

Technically, when character string data is compared, each character is compared one by one from left to right until the computer can determine whether the first string is less than, equal to, or greater than the second string.  The determination is based on the ASCII value of each character.

If you look at a chart of the ASCII characters, you should see that, generally speaking:

            special characters < digits < uppercase letters < lowercase letters

Bear in mind that when digits are used in character string comparisons, the comparison is based on the digits' ASCII value.  Consider these two examples:

You can have two or more individual conditions in a conditional expression if you join those conditions with the keywords And or Or.  The rules for multi-condition conditional expressions are as follows:

(1)        ALL conditions joined by the keyword And must be TRUE in order for the entire conditional expression to be considered TRUE - otherwise, the expression will be evaluated as FALSE.

(2)        If ANY of the conditions joined by the keyword Or are TRUE, the entire conditional expression will be considered TRUE - only if ALL the conditions joined by ORs are FALSE will the entire conditional expression be considered FALSE.

(3)        If you mix Ands and Ors in the same conditional expression, And has precedence over Or.

(4)        The And/Or precedence can be overridden with parentheses.

Examples follow.  Assume the following variables contain the indicated values:

            A = 4    B = 6    C = 10 D = 3     E = 2    F = 5    G = 4

The truth-value of any condition can be negated by placing the keyword Not in front of the conditional expression.  For example, if the condition A > B is true, then the condition Not A > B is false.

The keywords And, Or, and Not are called logical operators.

With And and Or, the system will evaluate all of the conditions within the conditional expression, even if the result is clear before all of the conditions are evaluated. For example (still using the variable values above), in the conditional expression

C > B And D > C And A >= G

it is clear that when “D > C” is evaluated, the result of the entire expression will be deemed to be False – but the system will still continue to evaluate “A >= G”.

Similarly, in the conditional expression

A = G Or F = G Or B = G

it is clear that as soon as “A = G” is evaluated, the result of the entire expression will be deemed to be True – but the system will still continue to evaluate “F = G” and “B = G”.

VB.NET introduces two new logical operators which address this inefficiency – AndAlso and OrElse. These operators work similar to And and Or, however, they apply a technique called short-circuiting - they stop evaluation of conditions as soon as the result is clear. Obviously, short-circuiting increases the performance of the application.

We know that for And to return true, all conditions must be true. AndAlso stops evaluating further the moment it encounters a false condition and returns False. So a more efficient alternative to the "And" example above would be:

C > B AndAlso D > C AndAlso A >= G

We also know that for Or to return true, any one condition must be true. OrElse stops evaluating further the moment it encounters a true condition and returns True. So a more efficient alternative to the "Or" example above would be:

A = G OrElse F = G OrElse B = G

(Note: In most other computer languages, short-circuiting of the "and" and "or" operators is standard behavior. The main exception was pre-.NET (classic) Visual Basic. However, rather than change the behavior of the "And" and "Or'" oeprators when .NET came along, MS decided to leave those as is and introduce "AndAlso" and "OrElse".)

Extra Topic:

When regular relational operators (like >, <, =) won't do, you can use the Like operator to compare a string against a specified pattern. The Like operator is similar to the LIKE operator found in the SQL of most DBMS products (although the syntax differs somewhat).

An expression using Like has this format:

string Like pattern

where string is any string expression and pattern is any string expression conforming to the pattern-matching conventions described below.

A Like expression can be used anywhere a conditional expression can be used, such as in an If statement or Do While statement:

If  string Like pattern Then . . .

Do While string Like pattern

A Like expression (or any conditional expression) can also be assigned to a Boolean variable to yield a True or False value:

BooleanVariable = stringLikepattern

If string matches pattern, the result is True; if there is no match, the result is False.

Built-in pattern matching provides a versatile tool for string comparisons. The pattern-matching features allow you to use wildcard characters, character lists, or character ranges, in any combination, to match strings. The following table shows the characters allowed in pattern and what they match:

Any single character in charlist.

Any single character not in charlist.

A group of one or more characters (charlist) enclosed in brackets ([ ]) can be used to match any single character in string and can include almost any character code, including digits.

Note: To match the special characters left bracket ([), question mark (?), number sign (#), and asterisk (*), enclose them in brackets. The right bracket (]) can't be used within a group to match itself, but it can be used outside a group as an individual character.

By using a hyphen (–) to separate the upper and lower bounds of the range, charlist can specify a range of characters. For example, [A-Z] results in a match if the corresponding character position in string contains any uppercase letters in the range A–Z. Multiple ranges are included within the brackets without delimiters.

Other important rules for pattern matching include the following:

· An exclamation point (!) at the beginning of charlist means that a match is made if any character except the characters in charlist is found in string. When used outside brackets, the exclamation point matches itself.

· A hyphen (–) can appear either at the beginning (after an exclamation point if one is used) or at the end of charlist to match itself. In any other location, the hyphen is used to identify a range of characters.

· When a range of characters is specified, they must appear in ascending sort order (from lowest to highest). [A-Z] is a valid pattern, but [Z-A] is not.

· The character sequence [] is considered a zero-length string ("").

Examples follow:

True (because "aBBBa" fits the pattern "letter a" – any characters – letter a")

True (because "F" is within the range "A to Z")

False (because "F" is "not not" within the range "A to Z")

True (because "a2a" fits the pattern "letter a – any single digit – letter a")

True (because "aM5b" fits the pattern "letter a – a letter between L and P – a single digit – a letter not between c and e)

True (because "BAT123khg" fits the pattern "letter B – any single character – letter T – any characters")

False (because "CAT123khg" does not fit the pattern "letter B – any single character – letter T – any characters")

To demonstrate the Like operator using the examples described above, set up another "Try It" Console project, and place the following code in the Main method:

Sub Main()Dim strTestString AsString strTestString = "aBBBa"If strTestString Like"a*a"ThenConsole.WriteLine("'{0}' matches the pattern 'a*a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a*a'.", strTestString)EndIf strTestString = "F"If strTestString Like"[A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[A-Z]'.", strTestString)EndIf If strTestString Like"[!A-Z]"ThenConsole.WriteLine("'{0}' matches the pattern '[!A-Z]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern '[!A-Z]'.", strTestString)EndIf strTestString = "a2a"If strTestString Like"a#a"ThenConsole.WriteLine("'{0}' matches the pattern 'a#a'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a#a'.", strTestString)EndIf strTestString = "aM5b"If strTestString Like"a[L-P]#[!c-e]"ThenConsole.WriteLine("'{0}' matches the pattern 'a[L-P]#[!c-e]'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'a[L-P]#[!c-e]'.", strTestString)EndIf strTestString = "BAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf strTestString = "CAT123khg"If strTestString Like"B?T*"ThenConsole.WriteLine("'{0}' matches the pattern 'B?T*'.", strTestString)ElseConsole.WriteLine("'{0}' does not match the pattern 'B?T*'.", strTestString)EndIf Console.WriteLine("")Console.WriteLine("(Press Enter to close this window.)")Console.ReadLine()EndSub

When you run the project, it will show the following output:

image

Download the VB.NET project code for this example: Comparisions in VB.NET Source Code

Note: While most types of applications will not require the pattern matching power offered by the Like operator, it’s nice to know it's available if it is needed. If you need pattern matching capabilities beyond what is offered by the Like operator, you are encouraged to look into Regular Expressions, which can be used by VB.NET as well as earlier versions of VB. (Regular Expressions are not covered here.)

Now that you are an expert on conditional expressions,feel free to look at the selection and the repetition control structures.

This article was original written by The VB Programmer.


View the original article here