© Charles Bell 2021
C. BellWindows 10 for the Internet of Thingshttps://doi.org/10.1007/978-1-4842-6609-0_7

7. Windows 10 IoT Development with Visual Basic

Charles Bell1  
(1)
Warsaw, VA, USA
 

Now that you have a basic understanding of how to use Visual Studio 2019, you can learn more about some of the languages you may encounter when developing your IoT solutions. One of those languages is Visual Basic (sometimes notated as VB)—another robust and powerful object-oriented language that you can use to write managed Windows .NET and UWP applications. Mastering Visual Basic is not as difficult as C++ or C# due to its simplified syntax. However, if you have never seen or worked with any form of Basic programming languages, the code may appear quite different. Fortunately, you need only learn the syntax since Visual Basic can be used to write the same applications as C++ and C#.

This chapter presents a crash course on the basics of Visual Basic programming in Visual Studio including an explanation about some of the most commonly used language features. As such, this chapter provides you with the skills you need to understand the growing number of IoT project examples available on the Internet. The chapter concludes with a walk-through of a Visual Basic example project that shows you how to interact with hardware. Specifically, you will implement the LED project you saw in Chapter 3. Only this time, you’ll be writing it as a Visual Basic Windows 10 IoT Core application. So, let’s get started!

Tip

If you are not interested in using Visual Basic in your IoT solutions, or you already know the basics of Visual Basic programming, feel free to skim through this chapter. I recommend working through the example project at the end of the chapter, especially if you’ve not written IoT applications.

Getting Started

The Visual Basic .Net language has been around since the first introduction of the .NET Framework (pronounced “dot net”) introduced in 2002. Visual Basic .Net is derived from an earlier product of the same name that originated in 1991 that combined the Basic programming language with a visual form designer, hence the “visual” in the name. The latest version of Visual Basic is version 8.0 and is sometimes called simply Visual Basic or VB.Net or simply VB.

Tip

I use “Visual Basic” to refer to Visual Basic .Net in this chapter because the previous product it replaced is no longer supported.

You may be thinking that Visual Basic and .NET may restrict the types of applications you can write, but that also is not true. You can use Visual Basic to write a host of applications from Windows 10 IoT Core to desktop to web applications and beyond. As you will see, you can also write Visual Basic console applications like you did in Chapter 5 with C++ and Chapter 6 with C#.

If you have ever worked with the Basic programming language or the Visual Basic for Applications (VBA) that is part of the macro language in Microsoft Office, Visual Basic will seem familiar to you. You may think Visual Basic is a “toy” language or too, well, basic for anything of significant complexity, but that is not the case. Visual Basic supports object-oriented and all of the resources and classes needed to write complex Windows applications. What sets Visual Basic apart is its simplified syntax.

Should you require more in-depth knowledge of Visual Basic, there are a number of excellent books on the topic. Here is a list of a few of my favorites. While some are a little dated (they cover Visual Studio 2015 or 2017), they provide excellent resources for the language:
  • Beginning Visual Basic 2015 by Bryan Newsome (Wrox, 2015)

  • Microsoft Visual Basic 2017 for Windows, Web, and Database Applications: Comprehensive by Shelly Cashman (Microsoft Press, 2017)

  • Visual Basic 2015 in 24 Hours by James Foxall (Sams Teach Yourself, 2015)

Another excellent resource is Microsoft’s documentation on MSDN. The following are some excellent resources for learning Visual Basic .Net:

Now that you know some of the origins and references for Visual Basic, let’s learn about the syntax and basic language features for creating applications.

Visual Basic Crash Course

Now let’s learn some of the basic concepts of Visual Basic programming. Let’s begin with the building blocks of the language, such as classes, methods, variables, and basic control structures, and then move into the more complex concepts of data structures and libraries.

While the material may seem to come at you in a rush (hence the crash part), this crash course on Visual Basic covers only the most fundamental knowledge of the language and how to use it in Visual Studio. It is intended to get you started writing Visual Basic Windows 10 IoT Core applications. If you find you want to write more complex applications than the examples in this book, I encourage you to acquire one or more of the resources listed earlier to learn more about the intriguing power of Visual Basic programming.

Visual Basic Fundamentals

There are a number of basic concepts about the Visual Basic programming language that you need to know in order to get started. In this section, I describe some of the fundamental concepts used in Visual Basic, including how the code is organized, how libraries are used, namespaces, and how to document your code.

Visual Basic is a case-sensitive language, so you must take care when typing the names of methods or classes in libraries. Fortunately, Visual Studio’s IntelliSense feature recognizes mistyped case letters and autocorrects the names. For example, if you type BLINKTimer for a variable that is declared as blinkTimer, Visual Studio corrects it for you. Once you get used to this feature, it is very hard to live without it.

Classes

The first thing you may notice is that Visual Basic is an object-oriented language and that every program you write is written as a class. However, simple console applications do not have to use a class and instead use a module definition, which resembles a class (it’s very similar). Just think object-oriented when you see the Class keyword and code module when you see the Module keyword. We will see an example of both in this chapter.

UWP applications are implemented using a class definition. A class is more than a simple data structure. You use classes to model concepts that include data and operations on the data. A class can contain private and public definitions (called members) and any number of operations (called methods) that operate on the data and give the class meaning.

Tip

Source files in Visual Basic have a file extension of .vb.

You can use classes to break your programs down into more manageable chunks. That is, you can place a class you’ve implemented in its own .vb file and refer to it in any of the code provided there aren’t namespace issues, and even then you simply use the namespace you want.

Let’s look at a simple class named Vector implemented in Visual Basic. This class manages a list of double variables hiding the data from the caller while providing rudimentary operations for using the class. Listing 7-1 shows how such a class could be constructed.
Public Class Vector
    Private elem() As Double
    Private sz As Integer
    Public Sub New(s As Integer)
        ReDim elem(s)
        sz = s
    End Sub
    Public Function size() As Integer
        Return sz
    End Function
    Public Function getValue(i As Integer) As Double
        Return elem(i)
    End Function
    Public Sub setValue(i As Integer, value As Double)
        elem(i) = value
    End Sub
End Class
Listing 7-1

Vector Class in Visual Basic

This is a basic class that is declared with the keyword Class followed by a name. The name can be any identifier you want to use, but the convention is to use an initial capital letter for the name. All classes are defined using a common indentation that defines the body or structure of the class.

By convention, you list the member variables (also called attributes) indented from the class definition. In this example, you see two member variables that are declared as private. You make them private to hide information from the caller. That is, only member methods inside the class itself can access and modify private member variables. Note that derivatives (classes built from other classes—sometimes called a child class) can also access protected member variables.

Notice we don’t have curly braces. Instead, we use the End <keyword> syntax to define a code block. For example, we use End Class to end the class, End Sub, and End Function to define code blocks for methods (Sub) and functions.

Next, you see a special method named New. This is called the constructor. The constructor is a method that is called when the class is instantiated (used). You call the code that defines the attributes and methods a class, and when executed, you call the resulting object an instance of the class.

In this case, the constructor takes a single integer parameter that is used to define the size of the private member variable that stores the array of double values. Notice how this code is used to dynamically define that array. More specifically, you use the ReDim command to reallocate memory for the array.

Next are three public methods, which users (or callers of the instance) can call. The first method, size(), looks as you would expect and in this case simply returns the value of the private member variable sz. The next methods are the get and set operations for storing a double in the array (setValue) and retrieving a specific double from the array using an index (getValue).

Let’s see the class in action. The following shows a main method for a typical Visual Basic console application that declares the vector, initializes it with values, then prints out the values. I placed the class in its own file (vector.vb).
Imports System
Module Program
    Sub Main(args As String())
        Dim v As New Vector(10)
        For i As Integer = 1 To 10
            v.setValue(i, i * 3)
        Next
        Console.Write("Values of v: ")
        For i As Integer = 1 To 10
            Console.Write(v.getValue(i))
            Console.Write(" ")
        Next
        Console.WriteLine()
    End Sub
End Module

Notice that it is easy to read what the code is doing. Neat, eh?

To add a new source file to a Visual Studio Visual Basic solution, simply right-click the project name in Solution Explorer, and then choose AddNew item… and click the Code section on the tree and then choose Class in the List. At the bottom of the dialog, you can name the file. When ready, click the Add button. You can then create any classes you want (or move classes) in the file. You can also use the same namespace to keep all of your classes in the same namespace. However, if you create a new namespace, you must use the using command to use the new namespace. Figure 7-1 shows an example of adding a new class to an existing Visual Basic solution.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig1_HTML.jpg
Figure 7-1

Visual Basic solution with a new class

As you may have surmised, classes are the building blocks for object-oriented programming, and as you learn more about using classes, you can build complex libraries of your own.

Tip

Visual Studio provides a tool called the Class View window that you can use to explore the libraries and classes used in your application.

Comments

One of the most fundamental concepts in any programming language is the ability to annotate your source code with text that not only allows you to make notes among the lines of code but also forms a way to document your source code.1

To add comments to your source code, use a single quote ('). Place them at the start of the line to create a comment for that line, repeating the quote for each subsequent line. This creates what is known as a block comment, as shown. Notice that I used a comment without any text to create whitespace. This helps with readability and is a common practice for block comments.
'
' Windows 10 for the IoT Second Edition
'
' Example Visual Basic console application rewrite.
'
' Created by Dr. Charles Bell
'
You can also use the quote to add a comment at the end of a line of code. That is, the compiler ignores whatever is written after the quote to the end of the line. You see an example of this next. Notice that I used the comment symbol (single quote) to comment out a section of code. This can be really handy when testing and debugging, but generally discouraged for final code. That is, don’t leave any commented out code in your deliverable (completed) source code. If it’s commented out, it’s not needed!
Function testComments(i As Integer) As Integer
    If i < 10 Then
        i = i + 1   ' Increment the value
    'Else
    '    Return -1
    End If
End Function

Writing good comments and indeed documenting your code well is a bit of an art form, one that I encourage you to practice regularly. Since it is an art rather than a science, keep in mind that your comments should be written to teach others what your code does or is intended to do. As such, you should use comments to describe any preconditions (or constraints) of using the code, limitations of use, errors handled, and a description of how the parameters are used and what data is altered or returned from the code (should it be a method or class member).

How Visual Basic Programs Are Structured

Now let’s look at how Visual Basic programs are structured by examining a slightly different version of the temperature application you saw in Chapter 4. Listing 7-2 shows the code rewritten for Visual Basic.
'
' Windows 10 for the IoT Second Edition
'
' Example Visual Basic console application rewrite
'
' Created by Dr. Charles Bell
'
Imports System
Module Program
    Public Function convertTemp(scale As Char, baseTemp As Double) As Double
        If scale = "c" Or scale = "C" Then
            Return ((9.0 / 5.0) * baseTemp) + 32.0
        Else
            Return (5.0 / 9.0) * (baseTemp - 32.0)
        End If
    End Function
    Sub Main(args As String())
        Dim tempRead As Double = 0.0
        Dim scale As Char = "c"
        Console.WriteLine("Welcome to the temperature conversion application.")
        Console.Write("Please choose a starting scale (F) or (C): ")
        scale = Console.ReadKey().KeyChar
        Console.WriteLine()
        Console.Write("Please enter a temperature: ")
        tempRead = Convert.ToDouble(Console.ReadLine())
        If scale = "c" Or scale = "C" Then
            Console.WriteLine("Converting value from Celsius to Fahrenheit.")
            Console.Write(tempRead)
            Console.Write(" degrees Celsius = ")
            Console.Write(convertTemp(scale, tempRead))
            Console.WriteLine(" degrees Fahrenheit.")
        ElseIf scale = "f" Or scale = "F" Then
            Console.WriteLine("Converting value from Fahrenheit to Celsius.")
            Console.Write(tempRead)
            Console.Write(" degrees Fahrenheit = ")
            Console.Write(convertTemp(scale, tempRead))
            Console.WriteLine(" degrees Celsius.")
        Else
            Console.Write("ERROR: I'm sorry, I don't understand '")
            Console.Write(scale)
            Console.WriteLine("'.")
        End If
    End Sub
End Module
Listing 7-2

Temperature Code Example Rewrite

In the example, the only methods created are convertTemp() and Main(), but this is because you are implementing a very simple solution. Here, you see the sample application named temperatureVB was implemented with a module with the name Program.

Wow, that’s quite a change from the code in the last chapter! While the functionality is exactly the same, the code looks very different from the C++ and C# versions. The following describe the Visual Basic concepts I have implemented in this example.

The Imports Keyword

First, you notice a number of lines that begin with Imports. These are preprocessor directives that tell the compiler you want to “use” a class or a class hierarchy that exists in a particular namespace. The Imports directive tells the compiler that you are using the namespace System.
Imports System
In the other lines, I have included additional namespaces with multiple names separated by a period. This is how you tell the compiler to use a specific namespace located in libraries of classes often form hierarchies that you can chain together. For example, if you wanted to use the namespace inside the Windows Foundations device library named Gpio, you would refer to it as follows:
Imports Windows.Devices.Gpio

This is a very common occurrence in Windows Visual Basic applications. In fact, you will use several namespaces in our example project.

The Main() Method

The Main() method is the starting or initial execution for the Visual Basic console project. Here, you see the name is preceded by the keyword Sub as follows:
Sub Main(args As String())

Next, you see the name, main, followed by a list of parameters enclosed in parentheses. For the Main() method, the parameters are fixed and are used to store any command-line arguments provided by the user. In this case, you have the arguments stored in args, which is a string.

A method in Visual Basic is used as an organizational mechanism to group functionality and make your programs easier to maintain (methods with hundreds of lines of code are very difficult to maintain), improve comprehensibility, and localize specialized operations in a single location, thereby reducing duplication.

Methods and functions therefore are used in your code to express the concepts of the functionality they provide. Notice how I used the convertTemp() method. Here, I declared it as a method that returned a double and takes a character and a double as input. As you can see, the body of the method (defined inside the FunctionEnd Function) uses the character as the scale in the same way as you do in main and uses the double parameter as the target (or base) temperature to convert. Since I made the parameters generic, I can use only one variable.

Tip

Method parameters and values passed must match on type and order when called.

Notice also that I placed it in the line of code that prints the value to the screen. This is a very common practice in Visual Basic (and other programming languages). That is, you use the method to perform some operation, and rather than store the result in a variable, you use it directly in the statements (code).

Variables and Types

No program would be very interesting if you did not use variables to store values for calculations. As you saw earlier, variables are declared with a type (the s <type> syntax) and once defined with a specific type cannot be changed. Since Visual Basic is strongly typed, the compiler ensures that anywhere you use the variable, it obeys its type, for example, that the operation on the variable is valid for the type. Thus, every variable must have a type assigned.

There are a number of simple types that the Visual Basic language supports. They are the basic building blocks for more complex types. Each type consumes a small segment of memory which defines not only how much space you have to store a value but also the range of values possible.2

For example, an integer consumes 4 bytes, and you can store values in the range –2,147,483,648 to 2,147,483,647. In this case, the integer variable is signed (the highest bit is used to indicate positive or negative values). An unsigned integer can store values in the range 0 to 4,294,967,295.

You can declare a variable by specifying the keyword Dim, followed by an identifier (name), then its type using the as keyword, and optionally assign it a value with the = operator. The following shows a number of variables using a variety of types:
Dim numFish as Integer = 0        ' number of fish caught
Dim maxLength as Double = 0.0;    ' length of the longest fish in feet
Dim fisherman(25) as char         ' name of the fisherman
Notice also that I have demonstrated how to assign a value to the variable in the declaration. The assignment operator is the equal sign. All assignments must obey the type rules. That is, I cannot assign a floating-point number (e.g., 17.55) to an integer value. Table 7-1 shows a list of the commonly used built-in types you will use in your applications.
Table 7-1

Commonly Used Types in Visual Basic

Symbol

Size in Bytes

Range

Boolean

1

False or true

Char

1

–128 to 127

String

User-defined

–128 to 127 per character

SByte

1

–128 to 127

Byte

1

0–255

Short

2

–32,768 to 32,767

UShort

2

0 to 65,535

Integer

4

–2,147,483,648 to 2,147,483,647

UInteger

4

0 to 4,294,967,295

Long

4

–2,147,483,648 to 2,147,483,647

ULong

4

0 to 4,294,967,295

Single

4

3.4E +/– 38 (7 digits)

Decimal

8

(–7.9 x 1028 to 7.9 x 1028) / (100 to 28)

Double

8

1.7E +/– 308 (15 digits)

It is always a good practice to initialize your variables when you declare them. It can save you from some nasty surprises if you use the variable before it is given a value (although the compiler will complain about this).

Arithmetic

You can perform a number of mathematical operations in Visual Basic, including the usual primitives, but also logical operations and operations used to compare values. Rather than discuss these in detail, I provide a quick reference in Table 7-2 that shows the operation and example of how to use the operation.
Table 7-2

Arithmetic, Logical, and Comparison Operators in Visual Basic

Type

Operator

Description

Example

Arithmetic

+

Addition

intVar + 1

-

Subtraction

intVar - 1

*

Multiplication

intVar * 2

/

Division

intVar / 3

Mod

Modulus

intVar % 4

^

Exponent

intVar ^ 2

Integer division

floatVar 3

+=

Unary addition

intVar += 1

-=

Unary subtraction

intVar -= 1

Logical

And

Bitwise and

var1&var2

Or

Bitwise or

var1|var2

Xor

Bitwise exclusive

var1^var2

And

Logical and

var1&&var2

Or

Logical or

var1||var2

Comparison

=

Equal

expr1==expr2

<>

Not equal

expr1!=expr2

<

Less than

expr1<expr2

>

Greater than

expr1>expr2

<=

Less than or equal

expr1<=expr2

>=

Greater than or equal

expr1>=expr2

Bitwise operations produce a result on the values performed on each bit. Logical operators (and, or) produce a value that is either true or false and are often used with expressions or conditions.

Now that you understand variables and types, the operations permitted on them, and expressions, let’s look at how you can use them in flow control statements.

Flow Control Statements

Flow control statements change the execution of the program. They can be conditionals that cause one section of code to execute vs. another (also called gates). These conditionals use expressions that, when evaluated, restrict execution to only those cases where the expression is true. There are special constructs that allow you to repeat a block of code (loops) as well as functions to switch context to perform some special operations. You’ve already seen how functions work, so let’s look at conditional and loop statements.

Conditionals

Conditional statements allow you to direct execution of your programs to sections (blocks) of code based on the evaluation of one or more expressions. There are two types of conditional statements in Visual Basic—the If...Then statement and the Select...Case statement.

You have seen the If statement in action in our example code. In the example, you can have one or more (optional) Else phrases that you execute once the expression for the If conditions evaluates to false. You can chain If/Else statements to encompass multiple conditions where the code executed depends on the evaluation of several conditions. The following shows the general structure of the If statement:
If expr1 Then
  ' execute only if expr1 is true
ElseIf expr2 Or Then
  ' execute only if expr1 is false *and* either expr2 or expr3 is true
Else
  ' execute if both sets of if conditions evaluate to false
End If

While you can chain the statement as much as you want, use some care here because the more ElseIf sections you have, the harder it becomes to understand, maintain, and avoid logic errors in your expressions.

If you have a situation where you want to execute code based on one of several values for a variable or expression that returns a value (such as a method or a calculation), you can use the Select...Case statement. The following shows the structure of the Select...Case statement as an example from the temperature project earlier with the If...Then statement rewritten as a Select...Case statement:
Select Case scale
    Case "c"
    Case "C"
        Console.WriteLine("Converting value from Celsius to Fahrenheit.")
        Console.Write(tempRead)
        Console.Write(" degrees Celsius = ")
        Console.Write(convertTemp(scale, tempRead))
        Console.WriteLine(" degrees Fahrenheit.")
    Case "f"
    Case "F"
        Console.WriteLine("Converting value from Fahrenheit to Celsius.")
        Console.Write(tempRead)
        Console.Write(" degrees Fahrenheit = ")
        Console.Write(convertTemp(scale, tempRead))
        Console.WriteLine(" degrees Celsius.")
    Case Else
        Console.Write("ERROR: I'm sorry, I don't understand '")
        Console.Write(scale)
        Console.WriteLine("'.")
End Select

The case values must match the type of the thing you are evaluating. That is, case values must be the same type as scale. Notice I placed Case statements “stacked” so that multiple cases can be directed to the same code block. That is a simple way of achieving that goal. Finally, there is a Case Else section for code you want to execute should scale fail to match any of the values.

Loops

Loops are used to control the repetitive execution of a block of code. There are three forms of loops that have slightly different behavior. All loops use conditional statements to determine whether to repeat execution or not. That is, they repeat as long as the condition is true. The three types of loops are While, Do, and For. I explain each with an example.

The While loop has its condition at the “top” or start of the block of code. Thus, While loops only execute the body (between the While and End While statements) if and only if the condition evaluates to true on the first pass. This form of loop is best used when you need to execute code only if some expression(s) evaluates to true, for example, iterating through a collection of things whose number of elements is unknown (loop until you run out of things in the collection).

The While loop in Visual Basic permits two additional directives. While developers try to structure their code to avoid such constructs, you can control the flow of the While loop using the Exit While and Continue While clauses.

The Exit While does what you expect—it will immediately stop executing any more statements and return control to the next statement after the End While, which is analogous with the break statement from other languages. The Continue While is interesting because it also stops executing any more statements in the loop but instead returns to the While condition (the top of the loop). As you view more Visual Basic examples, you may encounter these clauses.

The following illustrates the syntax for a While loop:
Console.WriteLine("While Loop:")
count = 10
While count > 0
    Console.Write(count)
    If count = 1 Then
        Exit While
    End If
    Console.Write(", ")
    count -= 1
End While
Console.WriteLine()

The Do loop normally places the condition at the “bottom” of the statement which permits the body of the loop to execute at least once. However, the Do loop in Visual Basic has a second form that permits you to add the condition at the “top” of the loop which performs the same as the While loop.

The Do loop in Visual Basic permits two additional directives. While developers try to structure their code to avoid such constructs, you can control the flow of the Do loop using the Exit Do and Continue Do clauses.

The Exit Do does what you expect—it will immediately stop executing any more statements and return control to the next statement after the End Do, which is analogous with the break statement from other languages. The Continue Do is interesting because it also stops executing any more statements in the loop but instead returns to the While condition (the top or bottom of the loop). As you view more Visual Basic examples, you may encounter these clauses.

This form of loop is handy for cases where you want to execute code that, depending on the results of that execution, may require repetition, for example, repeatedly asking the user for input that matches one or more known values, repeating the question if the answer doesn’t match.

The following illustrates the Do loop:
Console.WriteLine("Do Loop 'bottom' Condition:")
count = 10
Do
    Console.Write(count)
    If count = 1 Then
        Exit Do
    End If
    Console.Write(", ")
    count -= 1
Loop While count > 0
Console.WriteLine("Do Loop 'top' Condition:")
count = 10
Do While count > 0
    Console.Write(count)
    If count = 1 Then
        Exit Do
    End If
    Console.Write(", ")
    count -= 1
Loop

The For loop has two forms and is sometimes called a counting loop because of its unique way of executing a loop for a specific number of iterations or through the members of a container.

The first form of the For loop allows you to define a counting variable, a condition to evaluate, and an operation on the counting variable. Instead of an “End” clause, the For loop is defined by Next at the end of the body of the loop. More specifically, the For loop allows you to define stepping code for a precise number of operations, a <start> TO <stop> clause and optional Step <increment> clause that you can use to count by a constant such as counting by 2s, 3s, and so on. This form of loop is best used for a number of iterations for a known number (either at runtime or as a constant) and commonly used to step through memory, count, and so forth.

The For counting loop in Visual Basic permits two additional directives. While developers try to structure their code to avoid such constructs, you can control the flow of the For loop using the Exit For and Continue For clauses.

The Exit For does what you expect—it will immediately stop executing any more statements and return control to the next statement after the Next, which is analogous with the break statement from other languages. The Continue For is interesting because it also stops executing any more statements in the loop but instead returns to the count evaluation. As you view more Visual Basic examples, you may encounter these clauses.

The following illustrates the structure of the For counting loop:
Dim v As New Vector(10)
For i As Integer = 1 To 10
    v.setValue(i, i * 3)
Next

The second form is the For Each loop that iterates through a collection or container and has a slightly different syntax. Instead of a counting variable and optional step clause, we use a variable that contains the type of the things in the collection. For example, if we have a structure (more on those in the next section), we can use the For Each loop to iterate through a list (array) of books.

The following shows an example of using the For Each loop:
Public Structure bookInfo
    Public title As String
    Public cost As Double
End Structure
...
Dim books(10) As bookInfo
For Each book As bookInfo In books
    If book.title.StartsWith("S") Then
        Exit For
    End If
    Console.WriteLine(book.title)
Next

Now let’s look at some commonly used data structures.

Basic Data Structures

What you have learned so far about Visual Basic will allow you to create applications that do simple to moderately complex operations. However, when you start needing to operate on data—either from the user or from sensors and similar sources—you need a way to organize and store data and operations on the data in memory. The following introduces three data structures in order of complexity: arrays, structures, and classes.

Arrays allocate a contiguous area of memory for multiple storage of a type. That is, you can store several integers, characters, and so forth, set aside in memory. Arrays also provide an integer index that you can use to quickly access a specific element. The following illustrates how to create an array of integers and iterate through them with a for loop. Array indexes start at 0.
Dim numArray = New Integer() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}  ' an array Of 10 integers
Console.Write("Values of v: ")
For i As Integer = 0 To 9
    Console.Write(numArray(i))
    Console.Write(" ")
Next
Console.WriteLine()

You can also define multiple dimensional arrays (arrays of arrays). Arrays can be used with any type or data structure.

If you have a number of data items that you want to group together, you can use a special data structure called, amazingly, Structure. A Structure is formed as follows:
Private Structure <name>
  ' one or more declarations go here
End Structure
You can add whatever declarations you want inside the Structure body (before the End Structure statement). The following shows a crude example. Notice that you can use the structure in an array:
Private Structure address
    Public streetNum As Integer
    Public streetName As String
    Public city As String
    Public state As String
    Public zip As String
End Structure
...
Dim addressBook(100) As address

Arrays and structures can increase the power of your programs by allowing you to work with more complex data types.

Wow! That was a wild ride, wasn’t it? I hope that this short crash course in Visual Basic has explained enough about the sample programs shown so far that you now know how they work. This crash course also forms the basis for understanding the other Visual Basic examples in this book.

OK, now it’s time to see some of these fundamental elements of Visual Basic in action. Let’s look at the blink an LED application you saw in Chapter 3, only this time you’re going to write it for Windows 10 IoT Core!

Tip

For a complete, online reference guide to Visual Basic, see the Official Microsoft documentation at https://docs.microsoft.com/en-us/dotnet/visual-basic.

Blink an LED, Visual Basic Style

OK, let’s write some Visual Basic code! This project is the same concept as the project from Chapter 3 where you used Python to blink an LED on your Raspberry Pi. Rather than simply duplicate that project, you’ll mix it up a bit and make this example a headed application (recall a headed application has a user interface). The user interface presents the user with a greeting, a symbol that changes color in time with the LED, and a button to start and stop the blink timer.

Rather than build the entire application at once by presenting you a bunch of code, we walk through this example in two phases. The first phase builds the basic user interface. The code for the GPIO is added in the second phase. By using this approach, you can test the user interface on your PC, which is really convenient.

Recall that the PC does not support the GPIO libraries (there is no GPIO!), so if you built the entire application, you would have to test it on the device, which can be problematic if there are serious logic errors in your code. This way, you can ensure that the user interface is working correctly and therefore eliminate any possible issues in that code before you deploy it.

Before you get into the code for the user interface, let’s look at the components that you will use, and then set up the hardware.

Required Components

The following lists the components that you need. All of these are available in the Microsoft Internet of Things Pack for the Raspberry Pi from Adafruit. If you do not have that kit, you can find these components separately on the Adafruit website (www.adafruit.com), from SparkFun (www.sparkfun.com), or any electronics store that carries electronic components.
  • 560 ohm 5% 1/4W resistor (green, blue, brown stripes3)

  • Diffused 10mm red LED (or similar)

  • Breadboard (mini, half, or full sized)

  • (2) male-to-female jumper wires

You may notice that this is the same set of components you used in Chapter 3.

Set Up the Hardware

Begin by placing the breadboard next to your Raspberry Pi and power the Raspberry Pi off, orienting the Raspberry Pi with the label facing you (GPIO pins in the upper left). Next, take one of the jumper wires and connect the female connector to pin 6 on the GPIO. The pins are numbered left to right starting with the lower-left pin. Thus, the left two pins are 1 and 2 with pin 1 below pin 2. Connect the other wire to pin 7 on the GPIO. Figure 7-2 shows how all of the components are wired together. Be sure to study this drawing and double-check your connections prior to powering on your Raspberry Pi.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig2_HTML.jpg
Figure 7-2

Wiring the LED to a Raspberry Pi

Tip

The only component that is polarized is the LED. This longer side is the positive side.

Next, plug the resistor into the breadboard with each pin on one side of the center groove. You can choose whichever area you want on the breadboard. Next, connect the LED so that the long leg is plugged into the same row as the resistor and the other pin on another row. Finally, connect the wire from pin 6 to the same row as the negative side of the LED and the wire from pin 7 to the row with the resistor. Once you’re satisfied everything is connected correctly, you’re ready to power on the Raspberry Pi and write the code.

Since you are building a headed application, you’ll also need a keyboard, mouse, and monitor connected to the Raspberry Pi.

OK, now that the hardware is set up, it’s time to start writing the code.

Write the Code: User Interface

Begin by opening a new project template. Choose the Visual Basic Blank App (Universal Windows) template in the list. This template creates a new solution with all of the source files and resources you need for a UWP headed application. Figure 7-3 shows the project template you need. Use the project name BlinkVBStyle.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig3_HTML.jpg
Figure 7-3

New project dialog: blank Visual Basic application

You will be asked to choose the Windows 10 IoT Core version you want to use, and then Visual Studio will open with the project configured. Notice that there are a number of files created and the layout of the project is similar to what you’ve seen in previous examples.

Let’s begin our example by adding the XAML code in the MainPage.xaml file. Recall, we need only click the file in the project list to display the GUI and code. You may need to resize the code portion to see it all. Listing 7-3 shows the bare XAML code placed in the file by default. I’ve added a note that shows where to add new code.
<Page
    x:Class="BlinkVBStyle.MainPage"
    xmlns:="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BlinkVBStyle"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid>
-----> OUR CODE GOES HERE <----
    </Grid>
</Page>
Listing 7-3

Bare XAML Code (MainPage.xaml)

Recall that the XAML file is used to define a user interface in a platform-independent way using an XML-like language. In this project, I demonstrate the more basic controls: a text box, a button, and an ellipse (circle) placed inside a special control called a stacked panel. The stacked panel allows you to arrange the controls in a vertical “stack,” making it easier to position them. As you can see in the listing, you want to place your XAML user interface items in the <Grid></Grid> section.

In this example, you want a text box at the top and a circle (ellipse) to represent the LED that you will use to turn on (change to green) and off (change to gray) to correspond with the hardware on/off code that you will add later. You also need a button to toggle the blink operation on and off. Finally, you’ll add another text box to allow you to communicate with the user about the state of the GPIO code (that you’ll add later).

Now let’s add the code. Since the stacked panel is a container, all of the controls are placed inside it. Listing 7-4 shows the code you want to add (shown in bold).
<Page
    x:Class="BlinkVBStyle.MainPage"
    xmlns:="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:BlinkVBStyle"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    mc:Ignorable="d"
    Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
        <StackPanel Width="400" Height="400">
            <TextBlock x:Name="title" Height="60" TextWrapping="NoWrap"
                     Text="Hello, Blinky Visual Basic Style!" FontSize="28" Foreground="Blue"
                     Margin="10" HorizontalAlignment="Center"/>
            <Ellipse x:Name="led_indicator" Fill="LightGray" Stroke="Gray"  Width="75"
                     Height="75" Margin="10" HorizontalAlignment="Center"/>
            <Button x:Name="start_stop_button" Content="Start" Width="75" ClickMode="Press"
                     Click="start_stop_button_Click" Height="50" FontSize="24"
                     Margin="10" HorizontalAlignment="Center"/>
            <TextBlock x:Name="status" Height="60" TextWrapping="NoWrap"
                     Text="Status" FontSize="28" Foreground="Blue"
                     Margin="10" HorizontalAlignment="Center"/>
        </StackPanel>
    </Grid>
</Page>
Listing 7-4

Adding XAML Code for the User Interface: MainPage.xaml

Notice the button control. Here, you have an event that you want to associate with the button named start_stop_button_Click, which you assigned via the Click attribute. That is, when the user clicks it, a method named start_stop_button_Click() will be called.

XAML provides a great way to define a simple, easy user interface with the XML-like syntax. However, it also provides a mechanism to associate code with the controls. The code is placed in another file called a source-behind file named MainPage.xaml.vb. You will place all of the source code for the application in this file.

If you were typing this code in by hand, you will notice a nifty feature of Visual Studio—a context-sensitive help called IntelliSense that automatically completes the code you’re typing and provides drop-down lists of choices. For example, when you type in the button control and type Click=, a drop-down box will appear, allowing you to create the event handler (a part of the code that connects to the XML). In fact, it creates the code in the MainPage.xaml.vb file for you. If you copy and pasted the code, you will not get this option and would have to type in the code manually.

Let’s look at the code for the button control implemented in the class that you created in the source code file (MainPage.xaml.vb). Listing 7-5 shows the code you need to add in bold. You place everything in the class named BlinkVBStyle (the application).
'
' Windows 10 for the IoT Second Edition
'
' Blink Visual Basic Style Example
'
' Created by Dr. Charles Bell
'
Imports Windows.Devices.Gpio
Public NotInheritable Class MainPage
    Inherits Page
    ' Create brushes for painting contols
    Private greenBrush As SolidColorBrush = New SolidColorBrush(Windows.UI.Colors.Green)
    Private grayBrush As SolidColorBrush = New SolidColorBrush(Windows.UI.Colors.Gray)
    ' Add a variable to control button
    Private blinking As Boolean = False
    Public Sub New()
        Me.InitializeComponent()
        ' Add code to initialize the controls
        led_indicator.Fill = grayBrush
    End Sub
    Private Sub start_stop_button_Click(sender As Object, e As RoutedEventArgs)
        blinking = Not blinking
        If (blinking) Then
            start_stop_button.Content = "Stop"
            led_indicator.Fill = greenBrush
        Else
            start_stop_button.Content = "Start"
            led_indicator.Fill = grayBrush
        End If
    End Sub
End Class
Listing 7-5

Adding the Base Code: MainPage.xaml.vb

Note

Notice the New() method. This is the constructor for a Visual Basic class. In other languages, this method would have the same name as the class.

OK, there are a few extra bits here that may not be very obvious why they’re here. You want to paint the LED control green and gray for on and off. To do that, you need a reference to the green and gray brush resources. Thus, I create a new object from the Windows user interface colors namespace.

You also add the code for the button click event, start_stop_button_Click(), as well as a boolean member variable that you use to trigger the LED timer. You add code that inverts the blinking variable (toggles between false and true), and depending on the value, you turn the LED indicator control green (meaning the LED is on) or gray (meaning the LED is off). You also change the label of the button to correspond with the operation. That is, if the button is labeled Start, the LED indicator is off, and when clicked, the label changes to Stop and the LED indicator is turned on.

That’s it! You’ve finished the user interface. Go ahead and build the solution correcting any errors that may appear. Once compiled, you’re ready to test it.

Test and Execute: User Interface Only

That was easy, wasn’t it? Better still, since this is a universal app, you can run this code on your PC. To do so, choose debug and x86 (or x64) from the platform box and press Ctrl+F5. Figure 7-4 shows an excerpt of the output (just the control itself). Note that you may see the application run with a black background depending on your Windows settings. The figures are shown with a white background for clarity.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig4_HTML.jpg
Figure 7-4

The user interface: timer off

Figure 7-5 shows what happens when you click the button. Cool, eh?
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig5_HTML.jpg
Figure 7-5

The user interface: timer on

You may be wondering where the blink part is. Well, you haven’t implemented it yet. You will do that in the next phase.

Add the GPIO Code

Now, let’s add the code to work with the GPIO header. For this phase, you cannot run the code on your PC because the GPIO header doesn’t exist, but you can add code to check the GPIO header status—hence the extra text box in the interface.

Note

The following is a bit more complicated and requires additional objects. Thus, I walk through the code changes one part at a time. Henceforth, for brevity, I present excerpts of the files that we will be editing.

Now, let’s add the variables you need for the timer in the source file (MainPage.xaml.vb). Listing 7-6 shows the code you need to add. Here, you add an instance of the DispatchTimer as well as several private variables for working with the pin in the GPIO library. I show the changes in context with the new lines in bold.
...
    ' Create brushes for painting contols
    Private greenBrush As SolidColorBrush = New SolidColorBrush(Windows.UI.Colors.Green)
    Private grayBrush As SolidColorBrush = New SolidColorBrush(Windows.UI.Colors.Gray)
    ' Add a Dispatch Timer
    Private blinkTimer As DispatcherTimer
    ' Add variables for the GPIO
    Private Const LED_PIN As Integer = 4
    Private pin As GpioPin
    Private pinValue As GpioPinValue
    ' Add a variable to control button
    Private blinking As Boolean = False
...
Listing 7-6

Adding the Timer and GPIO Variables: MainPage.xaml.vb

The private variables store the pin value, a constant set to GPIO 4 (hardware pin #7), and a variable to store the pin variable result.

Next, you need a new method to initialize the GPIO—InitGPIO(). You add a new private method to the class and complete it with code to control the GPIO as shown in Listing 7-7. It is placed in the class declaration after the start_stop_button_Click() method. As you can see, there is a lot going on here. Ellipses shown indicate portions of the code omitted for brevity.
Public NotInheritable Class MainPage
    Inherits Page
...
    Private Sub InitGPIO()
        Dim gpio_ctrl = GpioController.GetDefault()
        ' Check GPIO state
        If (gpio_ctrl Is Nothing) Then
            pin = Nothing
            status.Text = "ERROR: No GPIO controller found!"
            Return
        End If
        ' Setup the GPIO pin
        pin = gpio_ctrl.OpenPin(LED_PIN)
        ' Check to see that pin Is Ok
        If (pin Is Nothing) Then
            status.Text = "ERROR: Can't get pin!"
            Return
        End If
        pin.SetDriveMode(GpioPinDriveMode.Output)
        pinValue = GpioPinValue.Low   ' turn off
        pin.Write(pinValue)
        status.Text = "Good to go!"
    End Sub
End Class
Listing 7-7

Adding the InitGPIO() Code: MainPage.xaml.vb

The code first creates an instance of the default GPIO controller class. Next, you check to see if that instance is null, which indicates the GPIO header cannot be initiated, and if so you change the label of the status text and return. Otherwise, you open the GPIO pin defined earlier. If that value is null, you print the message that you cannot get the pin. Otherwise, you set up the pin for output mode, and then turn off the bin and state all is well in the status label text.

Next, you add a new method to handle the event fired from the DispatchTimer named BlinkTimer_Tick(). The timer fires (or call) this method on the interval you specify (see Listing 7-8 for the changes to the New() method). You can place this code immediately after the InitGPIO() method in the class.
...
    Private Sub BlinkTimer_Tick(sender As Object, e As Object)
        ' If pin Is on, turn it off
        If (pinValue = GpioPinValue.High) Then
            led_indicator.Fill = grayBrush
            pinValue = GpioPinValue.Low
        Else
            ' else turn it on
            led_indicator.Fill = greenBrush
            pinValue = GpioPinValue.High
        End If
        pin.Write(pinValue)
    End Sub
End Class
Listing 7-8

Adding the BlinkTimer_Tick() Code: MainPage.xaml.vb

In this method, you check the value of the pin. Here is where the real operation of the code happens. In this code, if the pin is set to high (on), you set it to low (off) and paint the LED control gray. Otherwise, you set the pin to high (on) and paint the LED control green. Cool, eh?

Note

You could change this color to match the color of your LED if you wanted. Just remember to change the brush accordingly in the source file.

Next, you need to add code to the start_stop_button_Click() method to start and stop the timer. Listing 7-9 shows the changes in bold.
Private Sub start_stop_button_Click(sender As Object, e As RoutedEventArgs)
    blinking = Not blinking
    If (blinking) Then
        start_stop_button.Content = "Stop"
        led_indicator.Fill = greenBrush
        blinkTimer.Start()
    Else
        start_stop_button.Content = "Start"
        led_indicator.Fill = grayBrush
        blinkTimer.Stop()
        pinValue = GpioPinValue.Low
        pin.Write(pinValue)
    End If
End Sub
Listing 7-9

Adding the Timer Control Code: MainPage.xaml.vb

You see here a few things going on. First, notice that you invert the blinking variable to toggle blinking on and off. You then add a call to the blinkTimer instance of the DispatchTimer to start the timer if the user presses the button when it is labeled Start. Notice you also set the label of the button to Stop so that, when clicked again, the code turns off the timer and sets the pin value to low (off). This is an extra measure to ensure that if the button is clicked when the timer is between tick events, the LED is turned off. Try removing it and you’ll see.

Finally, you must add a few lines of code to the New() method to get everything started when you launch the application. Listing 7-10 shows the code modifications with changes in bold.
Public Sub New()
    Me.InitializeComponent()
    ' Add code to initialize the controls
    led_indicator.Fill = grayBrush
    ' Add code to setup timer
    blinkTimer = New DispatcherTimer()
    blinkTimer.Interval = TimeSpan.FromMilliseconds(1000)
    AddHandler blinkTimer.Tick, AddressOf BlinkTimer_Tick
    blinkTimer.Stop()
    ' Initialize GPIO
    InitGPIO()
End Sub
Listing 7-10

Adding the Timer and GPIO Initialization Code: MainPage.xaml.vb

Notice you add code to create a new instance of the DispatchTimer class, set the interval for the tick event to 1 second (1000 milliseconds), and add the BlinkTimer_Tick() method to the new instance (this is how you assign a method reference to an existing event handle). Next, you stop the timer and finally call the method that you wrote to initialize the GPIO.

That’s it! Now, let’s build the solution and check for errors. You should see something like the following in the output window:
1>------ Build started: Project: BlinkVBStyle, Configuration: Debug ARM ------
1>  BlinkVBStyle -> C:Usersoliassource eposBlinkVBStyleBlinkVBStyleinARMDebugBlinkVBStyle.exe
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

OK, now you’re ready to deploy the application to your device. Go ahead and set up everything, make the connections on the breadboard, and power on your device.

Deploy and Execute: Completed Application

Once your code compiles, you’re ready to deploy the application to your Raspberry Pi (or another device). Recall from Chapter 4, we have a different deployment method for Visual Basic applications. If you want to install your application, you can do so from Visual Studio with only a few steps. However, if you want to debug your application, you must use a slightly different process. Let’s look at each of these options starting with a normal deployment.

Before you attempt to deploy your application, make sure the remote debugger is stopped. We do not need the remote debugger running to deploy Visual Basic applications. This is because we will be using a different authentication mode.

Note

Make sure the remote debugger is stopped on your device before attempting to deploy a Visual Basic application.

Deploying Your Application (No Debugging)

Deploying your application with a Visual Basic project template is easy. Simply select the build mode, platform, and then device in Visual Studio. In this case, we want to select the Release or Debug build, the ARM platform, and select the Remote Machine entry in the device drop-down as shown in Figure 7-6. For this form of deployment, it doesn’t matter which build mode you choose.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig6_HTML.jpg
Figure 7-6

Select the build, platform, and device (Visual Studio)

When you select the Remote Machine entry, a Remote Connections dialog will appear that permits you to select the device from a list as shown in Figure 7-7. Simply select the device and click Select to select it.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig7_HTML.jpg
Figure 7-7

Remote Connections dialog

OK, we’re almost ready to deploy. There is just one more thing to change. I find it helpful to rename the package name using the package manifest. This is the name that will be displayed in the Device Portal. By default, it uses a generated name, but I find renaming it to the same as the project name helpful for easier tracking. Thus, this is an optional step.

If you look at the left side of Visual Studio, you will see one file in the tree view named Package.appxmanifest. Double-click that file to open it. As you will see, it is a set of options you can set for your package. The one we want is on the last tab named Packaging. Click that and change the Package name, as shown in Figure 7-8.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig8_HTML.jpg
Figure 7-8

Set the package name (package manifest)

Now all that is left is to deploy the application. Simply click Build ➤ Deploy Solution, and the deploy will begin. If this is the first time you’re deploying the application (or any application) to your device, the deployment could take a while.

Once complete, Visual Studio will indicate the build and deploy was successful similar to the output shown as follows:
Creating a new clean layout...
Copying files: Total 7 mb to layout...
Checking whether required frameworks are installed...
Registering the application to run from layout...
Deployment complete (0:00:22.489). Full package name: "BlinkVBStyle_1.0.0.0_arm__vmq2bagagk5h4"
========== Build: 0 succeeded, 0 failed, 1 up-to-date, 0 skipped ==========
========== Deploy: 1 succeeded, 0 failed, 0 skipped ==========
Now, you can go to the Device Portal and observe your application in the Apps manager as shown in Figure 7-9. Recall, you can start it by selecting Start from the Actions drop-down box. Go ahead and do that now. You should see your application start, and you can experiment with it.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig9_HTML.jpg
Figure 7-9

Controlling the application in the Apps manager (Device Portal)

After a few moments, you will see the application start on your device. If you have all of the wiring complete, you can click the button and observe the LED blinking until you stop it. Cool, eh?

If the LED is not blinking, double-check your wiring and ensure that you chose pin 4 in the code and pin 7 on the pin header (recall that the pin is named GPIO 4, but it is pin #7 on the header for the Raspberry Pi).

When you’re done, you can stop it from the Apps manager in the Device Portal by using the Actions drop-down box and selecting Stop. It may take a few seconds for the status to change from Running to Stopped.

If you want to start the application again, you do not need to redeploy it. The application is installed on the device. To start it, go back to the Device Portal, click Apps, then Apps manager, and then click the Actions drop-down box for the application and click Start.

Should you want to uninstall the application, go back to the Device Portal, click Apps, then Apps manager, and then click the Actions drop-down box for the application and click Uninstall.

And that’s it! Congratulations, you’ve just written your first Visual Basic application that uses the GPIO header to power some electronics!

Now, let’s see how to deploy and debug our application.

Deploy and Debug

If you want to debug your application, you can, but once again it is not the same process we saw with the C++ application. Specifically, we do not need to use the remote debugger. Instead, we can make the same selections from the debug toolbar, selecting the Debug build, the ARM platform, and the Remote Machine from the device drop-down. If you have previously completed the Remote Connections dialog, you will not see that again. If you do see the dialog, make sure to select your device as described earlier and click the Select button.

Before you start the debugger, let’s check a few settings. Most of these should be set correctly, but I’ve seen a couple of situations where the debug settings have changed. If they are not set correctly, you could have difficulty starting the debug session or may receive a series of strange, cryptic messages explaining either the application is already running or the debug symbols cannot be loaded.4

To open the debug settings, right-click the project (not the solution) and choose Properties. Then, select the Debug page. The principal settings we need to check include the following. Figure 7-10 shows the correct settings and their values. Be sure your project has the correct settings (the device name should be the name of your device).
  • Target device: Remote Machine

  • Remote Machine: The name of your device

  • (Optional) Uninstall and then re-install: Checked

  • (Optional) Deploy optional packages: Checked

  • Application process: Managed Only

  • Background task process: Managed Only

../images/416714_2_En_7_Chapter/416714_2_En_7_Fig10_HTML.jpg
Figure 7-10

Project debug settings

Notice there are two optional settings. Checking these will ensure your application will always be deployed (thus overwriting previous installations) and all optional packages are included, which may avoid certain dependency issues if you have installed and uninstalled other applications on the device.

Tip

If you want to reset the Remote Connection, remove the IP or device name in the Remote Machine text box.

Once you make any changes in this dialog, be sure to save your solution. Building or deploying does not automatically save these settings.

OK, now we are ready to debug our application. I find it helpful to place a breakpoint in the code so that when the application starts, I can step through it. Later, you may want to set a breakpoint somewhere in your code to observe certain variables or check for logic errors.

Recall, we set a breakpoint by clicking the left side of the code window in Visual Studio. A breakpoint is indicated with a red dot on the left side of the code window as demonstrated with an arrow in Figure 7-11.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig11_HTML.jpg
Figure 7-11

Setting a breakpoint (Visual Studio)

Now we can start the debugging session. Simply click DebugStart Debugging or click F5. You should see a lengthy set of messages in the output window under the deployment option, but when done, you will see the application running on your device, and it will also be displayed in the Device Portal under the Apps manager. You should also see the interactive debugger start in Visual Studio as shown in Figure 7-12.
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig12_HTML.jpg
Figure 7-12

Interactive debugger (Visual Studio)

Now, you can step through your application using the debug menu. For example, you can step over method calls by clicking F10 or step into methods with F11. Should you want to continue execution, you can click Continue in the debug toolbar. Or, you can stop the debugger using the Stop button or the Debug menu. Figure 7-13 shows what stepping through your code may look like. Yes, this means we can run the application on the device and debug it on our PC. Excellent!
../images/416714_2_En_7_Chapter/416714_2_En_7_Fig13_HTML.jpg
Figure 7-13

Stepping through code with interactive debugger (Visual Studio)

Go ahead and experiment with the application until you are satisfied it is working correctly. When you want to stop it, go to the Device Portal, and click AppsApps manager and use the Actions drop-down to stop the application.

If you get errors during the deployment, go back and check all of your settings to ensure you have everything correct. See the Visual Basic Application Deployment Troubleshooting section for more details.

Note

If the app deployed successfully but doesn’t show in the drop-down list, try disconnecting and reconnecting. If that doesn’t work, try rebooting your device.

Visual Basic Application Deployment Troubleshooting

If you’re like me, things sometimes go wonky and just don’t work, or they present you with an interesting but nearly indecipherable error message. I present a couple of these incidents you may encounter along with actions you can take to prevent or correct them.

Application Already/Not Running

If you get an error dialog saying the application is already or not running, you should double-check your debug settings for the project as described earlier. This can happen if you’ve deployed the application numerous times or have previous versions installed. Clearing the debug properties selections usually fixes the problem, but if that does not, change the package name or increment the version number, uninstall the application from the device, and restart your deployment.

Failure to Unregister Application

If you have installed the application many times and attempted to uninstall it, or it crashed and became corrupt, or you accidentally (maybe intentionally) removed the application files, you can see an error message during deployment like the following:
DEP0900: Failed to unregister application
"BlinkVBStyle_1.0.0.0_arm__vmq2bagagk5h4". [0x80073CFA] AppX Deployment operation failed with error 0x80070002 from API IsCurrentProfileSpecial
What this means is either the application is still registered on the device or some of its files are present, but it is not registered. To fix this, open an SSH terminal to the device and remove the application directory and all of its files like shown as follows. In this example, I had a derelict package on my device left over from a previous session,5 and it caused my deployment of a newer application with the same package name to fail. In this case, the package was named BlinkVBStyle_ vmq2bagagk5h4.
[192.168.42.13]: PS C:DataUsersAdministratorAppDataLocalPackages> rmdir /s BlinkVBStyle_1.0.0.0_arm__vmq2bagagk5h4
BlinkVBStyle_1.0.0.0_arm__vmq2bagagk5h4, Are you sure (Y/N)? Y.

Once you’ve removed the folder, you can deploy your application.

Deploy Succeeds, but Nothing Happens

It is possible you can deploy your application, but it either doesn’t start or doesn’t show up in your Apps manager on the Device Portal.

If Visual Studio reports the deployment succeeded, but the application doesn’t start, that’s OK and normal if you are doing a straight deployment. If you are deploying and debugging expecting the application to start, check the project properties as described earlier and correct any settings that may have changed. You can also attempt to uninstall the application using the App manager before retrying the deployment. If that still doesn’t work, try removing all applications you’ve built previously.

If the application doesn’t show up in the Apps manager, be sure to double-check all of the project settings in Visual Studio as described earlier, and the device is connected and reachable from the Device Portal. Try using the clean and build solution menu options again before attempting to deploy the application.

Tip

As a challenge, you can modify this project to add a Close or an Exit button to stop the application.

Summary

If you are learning how to work with Windows 10 IoT Core and don’t know how to program with Visual Basic, learning Visual Basic can be fun given its easy-to-understand syntax. While there are many examples on the Internet that you can use, most are not UWP projects and thus can be a challenge to understand how they translate to UWP applications. As you have seen, the UWP application template for Visual Basic follows the same pattern and uses the same libraries as the C# example from the last chapter. Only, the syntax is less complex.

This chapter has provided a crash course in Visual Basic that covers the basics of the things you encounter when examining most of the smaller example projects. You discovered the basic syntax and constructs of a Visual Basic application, including a walk-through of building a real Visual Basic application that blinks an LED. Through that example, you learned how to work with headless applications, including how to manage a startup background application.

The next chapter takes a short detour in your exploration of Windows 10 IoT Core projects. You are introduced to the basics of working with electronics. Like the programming crash course, the chapter provides a short introduction to working with electronics. A mastery of electronics in general is not required for the projects you explore, but if you’ve never worked with electronic components before, the next chapter will prepare you for the more advanced projects in Chapters 1014.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.128.94.171