### VB: Complete Example for Async Task Processing
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/async/start-multiple-async-tasks-and-process-them-as-they-complete
This is the complete MainWindow.xaml.vb file for the example. It includes setup for asynchronous downloads, cancellation handling, and processing results as they complete. Ensure you add a reference to System.Net.Http.
```vb
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &= vbCrLf & "Downloads complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' You can still include a Cancel button if you want to.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' ***Create a query that, when executed, returns a collection of tasks.
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url, client, ct)
' ***Use ToList to execute the query and start the download tasks.
Dim downloadTasks As List(Of Task(Of Integer)) = downloadTasksQuery.ToList()
' ***Add a loop to process the tasks one at a time until none remain.
While downloadTasks.Count > 0
' ***Identify the first task that completes.
Dim finishedTask As Task(Of Integer) = Await Task.WhenAny(downloadTasks)
' ***Remove the selected task from the list so that you don't
' process it more than once.
downloadTasks.Remove(finishedTask)
' ***Await the first completed task and display the results.
Dim length = Await finishedTask
resultsTextBox.Text &= String.Format(vbCrLf & "Length of the downloaded website: {0}" & vbCrLf, length)
End While
End Function
' Bundle the processing steps for a website into one async method.
Async Function ProcessURLAsync(url As String, client As HttpClient, ct As CancellationToken) As Task(Of Integer)
' GetAsync returns a Task(Of HttpResponseMessage).
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
Return urlContents.Length
End Function
' Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/hh290138.aspx",
"https://msdn.microsoft.com/library/hh290140.aspx",
"https://msdn.microsoft.com/library/dd4070362.aspx",
"https://msdn.microsoft.com/library/aa578028.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Sample output:
' Length of the download: 226093
' Length of the download: 412588
' Length of the download: 175490
' Length of the download: 204890
' Length of the download: 158855
' Length of the download: 145790
' Length of the download: 44908
' Downloads complete.
```
--------------------------------
### Complete app.config Example for Logging
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/log-info/walkthrough-changing-where-my-application-log-writes-information
This is a comprehensive example of an app.config file configured for application logging. It includes the system.diagnostics section with sources, switches, and shared listeners, demonstrating a full setup for directing log output.
```XML
```
--------------------------------
### LINQ Data Setup: Customers and Orders
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/linq/introduction-to-linq
Provides the necessary data structures and methods to retrieve lists of customers and orders for LINQ examples. Ensure these classes and functions are included to run LINQ queries.
```VB.NET
' Return a list of customers.
Private Function GetCustomers() As List(Of Customer)
Return New List(Of Customer) From
{
New Customer With {.CustomerID = 1, .CompanyName = "Contoso, Ltd", .City = "Halifax", .Country = "Canada"},
New Customer With {.CustomerID = 2, .CompanyName = "Margie's Travel", .City = "Redmond", .Country = "United States"},
New Customer With {.CustomerID = 3, .CompanyName = "Fabrikam, Inc.", .City = "Vancouver", .Country = "Canada"}
}
End Function
' Return a list of orders.
Private Function GetOrders() As List(Of Order)
Return New List(Of Order) From
{
New Order With {.CustomerID = 1, .Amount = "200.00"},
New Order With {.CustomerID = 3, .Amount = "600.00"},
New Order With {.CustomerID = 1, .Amount = "300.00"},
New Order With {.CustomerID = 2, .Amount = "100.00"},
New Order With {.CustomerID = 3, .Amount = "800.00"}
}
End Function
' Customer Class.
Private Class Customer
Public Property CustomerID As Integer
Public Property CompanyName As String
Public Property City As String
Public Property Country As String
End Class
' Order Class.
Private Class Order
Public Property CustomerID As Integer
Public Property Amount As Decimal
End Class
```
--------------------------------
### Basic Try-Catch Block
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/try-catch-finally-statement
A simple example demonstrating how to use a Try-Catch block to handle potential exceptions when starting a process. This is useful for gracefully managing errors like network access issues.
```vb
Try
Process.Start("http://www.microsoft.com")
Catch ex As Exception
Console.WriteLine("Can't load Web page" & vbCrLf & ex.Message)
End Try
```
--------------------------------
### Calling AppActivate with a String and a Shell Return Value
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-call-a-procedure-that-does-not-return-a-value
This example demonstrates calling the AppActivate function twice. First, it activates a Notepad window using its title. Second, it starts a new instance of Notepad using the Shell function and then activates that new instance using the returned process ID.
```vb
Dim notepadID As Integer
' Activate a running Notepad process.
AppActivate("Untitled - Notepad")
' AppActivate can also use the return value of the Shell function.
' Shell runs a new instance of Notepad.
notepadID = Shell("C:\WINNT\NOTEPAD.EXE", AppWinStyle.NormalFocus)
' Activate the new instance of Notepad.
AppActivate(notepadID)
```
--------------------------------
### Output of Regular Initializer Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/type-members
Shows the console output produced by the regular initializer example.
```Console
x = 10, y = 20
```
--------------------------------
### Execute Query and Start Download Tasks
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/async/cancel-remaining-async-tasks-after-one-is-complete
Explicitly executes the query to start all asynchronous download tasks and stores them in an array. This ensures that all tasks are initiated before proceeding.
```vb
' ***Use ToArray to execute the query and start the download tasks.
Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
```
--------------------------------
### XML Syntax for Example Tag
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/xmldoc/example
This shows the basic XML structure for the tag, which encloses a description of the code sample.
```xml
description
```
--------------------------------
### Example of Compiling with -bugreport
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/bugreport
This example demonstrates how to compile the T2.vb file and direct all bug-reporting information to a file named Problem.txt.
```console
vbc -bugreport:problem.txt t2.vb
```
--------------------------------
### Example: Compiling with Debugging Information
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/debug
This example demonstrates how to compile a Visual Basic file named 'test.vb' and include debugging information in the output executable 'App.exe'.
```console
vbc -debug -out:app.exe test.vb
```
--------------------------------
### Full Example Using My.Computer.FileSystem
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/drives-directories-files/walkthrough-manipulating-files-and-directories
This comprehensive example demonstrates various file and directory operations including setting the default directory, listing text files, examining file content, and logging information. It utilizes the My.Computer.FileSystem object.
```vb
' This example uses members of the My.Computer.FileSystem
' object, which are available in Visual Basic.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath = My.Computer.FileSystem.CurrentDirectory
SetEnabled()
End Sub
Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
End If
SetEnabled()
End Sub
Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames = My.Computer.FileSystem.GetFiles(
folderPath, FileIO.SearchOption.SearchTopLevelOnly, "*.txt")
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If My.Computer.FileSystem.FileExists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String = My.Computer.FileSystem.GetFileInfo(filePath).DirectoryName
Dim logFilePath = My.Computer.FileSystem.CombinePath(logFolder, "log.txt")
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
' Append text to the log file.
My.Computer.FileSystem.WriteAllText(logFilePath, logText, append:=True)
End If
End Sub
Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If My.Computer.FileSystem.FileExists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
My.Computer.FileSystem.OpenTextFileReader(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
SetEnabled()
End Sub
Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
```
--------------------------------
### Distinct Query Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/expressions
Example of a Distinct query operator in Visual Basic to get unique pairings.
```vb
Dim distinctCustomerPrice = _
From cust In Customers, ord In cust.Orders _
Select cust.Name, ord.Price _
Distinct
```
--------------------------------
### Create Sample Data Lists
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/linq/how-to-combine-data-with-linq-by-using-joins
Initializes and populates `List(Of Person)` and `List(Of Pet)` collections with sample data. This setup is necessary for demonstrating LINQ join operations.
```VB
Private _people As List(Of Person)
Private _pets As List(Of Pet)
Function GetPeople() As List(Of Person)
If _people Is Nothing Then CreateLists()
Return _people
End Function
Function GetPets(ByVal people As List(Of Person)) As List(Of Pet)
If _pets Is Nothing Then CreateLists()
Return _pets
End Function
Private Sub CreateLists()
Dim pers As Person
_people = New List(Of Person)
_pets = New List(Of Pet)
pers = New Person With {.FirstName = "Magnus", .LastName = "Hedlund"}
_people.Add(pers)
_pets.Add(New Pet With {.Name = "Daisy", .Owner = pers})
pers = New Person With {.FirstName = "Terry", .LastName = "Adams"}
_people.Add(pers)
_pets.Add(New Pet With {.Name = "Barley", .Owner = pers})
_pets.Add(New Pet With {.Name = "Boots", .Owner = pers})
_pets.Add(New Pet With {.Name = "Blue Moon", .Owner = pers})
pers = New Person With {.FirstName = "Charlotte", .LastName = "Weiss"}
_people.Add(pers)
_pets.Add(New Pet With {.Name = "Whiskers", .Owner = pers})
' Add a person with no pets for the sake of Join examples.
_people.Add(New Person With {.FirstName = "Arlene", .LastName = "Huff"})
pers = New Person With {.FirstName = "Don", .LastName = "Hall"}
' Do not add person to people list for the sake of Join examples.
_pets.Add(New Pet With {.Name = "Spot", .Owner = pers})
' Add a pet with no owner for the sake of Join examples.
_pets.Add(New Pet With {.Name = "Unknown",
.Owner = New Person With {.FirstName = String.Empty,
.LastName = String.Empty}})
End Sub
```
--------------------------------
### Declare a Property with Get and Set Procedures
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/property-statement
This example demonstrates how to declare a property in a class with both Get and Set procedures. The Get procedure returns the property's value, and the Set procedure assigns a new value to it.
```VB
Class Class1
' Define a local variable to store the property value.
Private propertyValue As String
' Define the property.
Public Property Prop1() As String
Get
' The Get property procedure is called when the value
' of a property is retrieved.
Return propertyValue
End Get
Set(ByVal value As String)
' The Set property procedure is called when the value
' of a property is modified. The value to be assigned
' is passed in the argument to Set.
propertyValue = value
End Set
End Property
End Class
```
--------------------------------
### Visual Basic Get Statement Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/get-statement
This snippet demonstrates how to use the Get statement within a read-only property to retrieve and return the current date and time as a string. The Get procedure is automatically executed when the property's value is accessed.
```visualbasic
Class propClass
' Define a private local variable to store the property value.
Private currentTime As String
' Define the read-only property.
Public ReadOnly Property DateAndTime() As String
Get
' The Get procedure is called automatically when the
' value of the property is retrieved.
currentTime = CStr(Now)
' Return the date and time As a string.
Return currentTime
End Get
End Property
End Class
```
--------------------------------
### Full Example: System.IO File and Directory Operations
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/drives-directories-files/walkthrough-manipulating-files-and-directories
This comprehensive example demonstrates file and directory manipulation using System.IO classes. It includes listing text files, examining file details, and appending to a log file. Ensure the System.IO namespace is imported.
```Visual Basic
' This example uses classes from the System.IO namespace.
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
' Set the default directory of the folder browser to the current directory.
FolderBrowserDialog1.SelectedPath =
System.IO.Directory.GetCurrentDirectory()
SetEnabled()
End Sub
Private Sub browseButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles browseButton.Click
If FolderBrowserDialog1.ShowDialog() = DialogResult.OK Then
' List files in the folder.
ListFiles(FolderBrowserDialog1.SelectedPath)
SetEnabled()
End If
End Sub
Private Sub ListFiles(ByVal folderPath As String)
filesListBox.Items.Clear()
Dim fileNames As String() =
System.IO.Directory.GetFiles(folderPath,
"*.txt", System.IO.SearchOption.TopDirectoryOnly)
For Each fileName As String In fileNames
filesListBox.Items.Add(fileName)
Next
End Sub
Private Sub examineButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles examineButton.Click
If filesListBox.SelectedItem Is Nothing Then
MessageBox.Show("Please select a file.")
Exit Sub
End If
' Obtain the file path from the list box selection.
Dim filePath = filesListBox.SelectedItem.ToString
' Verify that the file was not removed since the
' Browse button was clicked.
If System.IO.File.Exists(filePath) = False Then
MessageBox.Show("File Not Found: " & filePath)
Exit Sub
End If
' Obtain file information in a string.
Dim fileInfoText As String = GetTextForOutput(filePath)
' Show the file information.
MessageBox.Show(fileInfoText)
If saveCheckBox.Checked = True Then
' Place the log file in the same folder as the examined file.
Dim logFolder As String =
System.IO.Path.GetDirectoryName(filePath)
Dim logFilePath = System.IO.Path.Combine(logFolder, "log.txt")
' Append text to the log file.
Dim logText As String = "Logged: " & Date.Now.ToString &
vbCrLf & fileInfoText & vbCrLf & vbCrLf
System.IO.File.AppendAllText(logFilePath, logText)
End If
End Sub
Private Function GetTextForOutput(ByVal filePath As String) As String
' Verify that the file exists.
If System.IO.File.Exists(filePath) = False Then
Throw New Exception("File Not Found: " & filePath)
End If
' Create a new StringBuilder, which is used
' to efficiently build strings.
Dim sb As New System.Text.StringBuilder()
' Obtain file information.
Dim thisFile As New System.IO.FileInfo(filePath)
' Add file attributes.
sb.Append("File: " & thisFile.FullName)
sb.Append(vbCrLf)
sb.Append("Modified: " & thisFile.LastWriteTime.ToString)
sb.Append(vbCrLf)
sb.Append("Size: " & thisFile.Length.ToString & " bytes")
sb.Append(vbCrLf)
' Open the text file.
Dim sr As System.IO.StreamReader =
System.IO.File.OpenText(filePath)
' Add the first line from the file.
If sr.Peek() >= 0 Then
sb.Append("First Line: " & sr.ReadLine())
End If
sr.Close()
Return sb.ToString
End Function
Private Sub filesListBox_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles filesListBox.SelectedIndexChanged
SetEnabled()
End Sub
Private Sub SetEnabled()
Dim anySelected As Boolean =
(filesListBox.SelectedItem IsNot Nothing)
examineButton.Enabled = anySelected
saveCheckBox.Enabled = anySelected
End Sub
```
--------------------------------
### Iterator Get Accessor Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/modifiers/iterator
Shows a Get accessor for a property that acts as an iterator, yielding Galaxy objects. This allows iterating over a collection of galaxies directly through the property.
```Visual Basic
Sub Main()
Dim theGalaxies As New Galaxies
For Each theGalaxy In theGalaxies.NextGalaxy
With theGalaxy
Console.WriteLine(.Name & " " & .MegaLightYears)
End With
Next
Console.ReadKey()
End Sub
Public Class Galaxies
Public ReadOnly Iterator Property NextGalaxy _
As System.Collections.Generic.IEnumerable(Of Galaxy)
Get
Yield New Galaxy With {.Name = "Tadpole", .MegaLightYears = 400}
Yield New Galaxy With {.Name = "Pinwheel", .MegaLightYears = 25}
Yield New Galaxy With {.Name = "Milky Way", .MegaLightYears = 0}
Yield New Galaxy With {.Name = "Andromeda", .MegaLightYears = 3}
End Get
End Property
End Class
Public Class Galaxy
Public Property Name As String
Public Property MegaLightYears As Integer
End Class
```
--------------------------------
### Compile with a Key File
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/keyfile
This example shows how to compile the source file 'input.vb' using a specified key file named 'myfile.sn'.
```text
vbc -keyfile:myfile.sn input.vb
```
--------------------------------
### External Checksum Directive Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/preprocessing-directives
Demonstrates the usage of the #ExternalChecksum directive along with #ExternalSource in Visual Basic. This example shows how to specify an external file, its GUID, and checksum, and then use it within a module.
```vb
#ExternalChecksum("c:\wwwroot\inetpub\test.aspx", _
"{12345678-1234-1234-1234-123456789abc}", _
"1a2b3c4e5f617239a49b9a9c0391849d34950f923fab9484")
Module Test
Sub Main()
#ExternalSource("c:\wwwroot\inetpub\test.aspx", 30)
Console.WriteLine("In test.aspx")
#End ExternalSource
End Sub
End Module
```
--------------------------------
### Instantiate and Use a Class with a Partial Method (Visual Basic)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/partial-methods
This example demonstrates how to create an instance of the Product class and set its Quantity property, which in turn triggers the partial method implementation.
```vb
Module Module1
Sub Main()
Dim product1 As New Product With {.Quantity = 100}
End Sub
End Module
```
--------------------------------
### Late Binding Example with Excel
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/early-late-binding
Illustrates late binding by assigning objects to variables of type Object. This example requires Microsoft Excel to be installed and Option Strict Off to be enabled. It demonstrates interacting with Excel application objects.
```vb
' To use this example, you must have Microsoft Excel installed on your computer.
' Compile with Option Strict Off to allow late binding.
Sub TestLateBinding()
Dim xlApp As Object
Dim xlBook As Object
Dim xlSheet As Object
xlApp = CreateObject("Excel.Application")
' Late bind an instance of an Excel workbook.
xlBook = xlApp.Workbooks.Add
' Late bind an instance of an Excel worksheet.
xlSheet = xlBook.Worksheets(1)
xlSheet.Activate()
' Show the application.
xlSheet.Application.Visible = True
' Place some text in the second row of the sheet.
xlSheet.Cells(2, 2) = "This is column B row 2"
End Sub
```
--------------------------------
### Example: Displaying Help from Command Line
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/help
This example demonstrates how to invoke the Visual Basic compiler with the -help option from the command line to view compiler options. The vbc command is used for this purpose.
```console
vbc -help
```
--------------------------------
### Take Clause in LINQ
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/linq/introduction-to-linq
Use the Take clause to select a specified number of contiguous elements from the start of a collection. This example returns the first 10 customers.
```vb
' Returns the first 10 customers.
Dim customerList = From cust In customers
Take 10
```
--------------------------------
### Creating New Object Instances with Constructors
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/operators/new-operator
Demonstrates creating instances of a class using constructors with and without parameters. Also shows declaring an instance first and then instantiating it, and using `Option Infer` for concise instantiation.
```Visual Basic
' For customer1, call the constructor that takes no arguments.
Dim customer1 As New Customer()
' For customer2, call the constructor that takes the name of the
' customer as an argument.
Dim customer2 As New Customer("Blue Yonder Airlines")
' For customer3, declare an instance of Customer in the first line
' and instantiate it in the second.
Dim customer3 As Customer
customer3 = New Customer()
' With Option Infer set to On, the following declaration declares
' and instantiates a new instance of Customer.
Dim customer4 = New Customer("Coho Winery")
```
--------------------------------
### Accessing an Object's Property
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/variables/how-to-access-members-of-an-object
Use the member-access operator (.) to get the value of a property from an object variable. This example shows how to retrieve the Text property of a Form object.
```Visual Basic
currentText = newForm.Text
```
--------------------------------
### Declare a Default Property on a Class
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-declare-and-call-a-default-property
This example shows how to declare a default property named 'myProperty' on a class. The 'Get' and 'Set' procedures handle property retrieval and assignment.
```Visual Basic
Public Class class1
Private myStrings() As String
Sub New(ByVal size As Integer)
ReDim myStrings(size)
End Sub
Default Property myProperty(ByVal index As Integer) As String
Get
' The Get property procedure is called when the value
' of the property is retrieved.
Return myStrings(index)
End Get
Set(ByVal Value As String)
' The Set property procedure is called when the value
' of the property is modified.
' The value to be assigned is passed in the argument
' to Set.
myStrings(index) = Value
End Set
End Property
End Class
```
--------------------------------
### Display Compiler Options (Help)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/command-line-compiler/help
Use the -help option to display all available compiler options when compiling from the command line. No output file is created and no compilation occurs.
```console
-help
```
--------------------------------
### Get Files Matching a Pattern
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/drives-directories-files/how-to-copy-files-with-a-specific-pattern-to-a-directory
Use `GetFiles` to retrieve a collection of file paths that match a specified pattern. This example retrieves all .rtf files in the top-level directory.
```Visual Basic
For Each foundFile As String In My.Computer.FileSystem.GetFiles(
My.Computer.FileSystem.SpecialDirectories.MyDocuments,
Microsoft.VisualBasic.FileIO.SearchOption.SearchTopLevelOnly, "*.rtf")
```
--------------------------------
### Object Creation with Member Initializers (Equivalent)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/expressions
Shows the equivalent code for the previous snippet, illustrating how the 'With' clause is expanded.
```vb
Module Test
Sub Main()
Dim x, _t1 As Customer
_t1 = New Customer()
With _t1
.Name = "Bob Smith"
.Address = "123 Main St."
End With
x = _t1
End Sub
End Module
```
--------------------------------
### Get Type Information of a Variable
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/reflection
Use the GetType method, inherited from the Object base class, to obtain the type of a variable. This is a fundamental way to start using reflection.
```Visual Basic
' Using GetType to obtain type information:
Dim i As Integer = 42
Dim type As System.Type = i.GetType()
System.Console.WriteLine(type)
```
--------------------------------
### Start Notepad and Send Keystrokes (Visual Basic)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/computer-resources/how-to-start-an-application-and-send-it-keystrokes
Starts the Notepad application, activates it, and then sends a predefined sentence as keystrokes. Ensure Notepad is accessible and the process ID is correctly captured.
```Visual Basic
Dim ProcID As Integer
' Start the Notepad application, and store the process id.
ProcID = Shell("NOTEPAD.EXE", AppWinStyle.NormalFocus)
' Activate the Notepad application.
AppActivate(ProcID)
' Send the keystrokes to the Notepad application.
My.Computer.Keyboard.SendKeys("I ", True)
My.Computer.Keyboard.SendKeys("♥", True)
My.Computer.Keyboard.SendKeys(" Visual Basic!", True)
' The sentence I ♥ Visual Basic! is printed on Notepad.
```
--------------------------------
### Run LINQ Join Examples
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/linq/how-to-combine-data-with-linq-by-using-joins
This code snippet serves as the entry point to execute the various LINQ join examples provided in the topic, including inner join, left outer join, and composite key join.
```Visual Basic
Sub Main()
InnerJoinExample()
LeftOuterJoinExample()
CompositeKeyJoinExample()
Console.ReadLine()
End Sub
```
--------------------------------
### Visual Basic Call Statement Examples
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/call-statement
Demonstrates scenarios where the 'Call' keyword is necessary because the called expression does not start with an identifier. Includes calls to a lambda expression and a class method.
```vb
Sub TestCall()
Call (Sub() Console.Write("Hello"))()
Call New TheClass().ShowText()
End Sub
Class TheClass
Public Sub ShowText()
Console.Write(" World")
End Sub
End Class
```
--------------------------------
### Application Startup and Shutdown Event Handlers
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/developing-apps/programming/log-info/how-to-log-messages-when-the-application-starts-or-shuts-down
This code demonstrates how to implement the MyApplication_Startup and MyApplication_Shutdown event handlers to log messages at the start and end of the application's lifecycle.
```vb
Private Sub MyApplication_Startup(
ByVal sender As Object,
ByVal e As ApplicationServices.StartupEventArgs
) Handles Me.Startup
My.Application.Log.WriteEntry("Application started at " &
My.Computer.Clock.GmtTime.ToString)
End Sub
Private Sub MyApplication_Shutdown(
ByVal sender As Object,
ByVal e As System.EventArgs
) Handles Me.Shutdown
My.Application.Log.WriteEntry("Application shut down at " &
My.Computer.Clock.GmtTime.ToString)
End Sub
```
--------------------------------
### Complete Async Task Cancellation Example in VB.NET
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/async/cancel-remaining-async-tasks-after-one-is-complete
This VB.NET code demonstrates how to cancel all remaining asynchronous downloads once the first one completes. It requires adding references to `System.Net.Http` and `System.Threading`. The example includes UI event handlers for starting and canceling the operations, along with methods to fetch and process web content.
```vb
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
Await AccessTheWebAsync(cts.Token)
resultsTextBox.Text &= vbCrLf & "Download complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Download canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Download failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' You can still include a Cancel button if you want to.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
'' Comment out or delete the loop.
''For Each url In urlList
'' ' GetAsync returns a Task(Of HttpResponseMessage).
'' ' Argument ct carries the message if the Cancel button is chosen.
'' ' Note that the Cancel button can cancel all remaining downloads.
'' Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
'' ' Retrieve the website contents from the HttpResponseMessage.
'' Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
'' resultsTextBox.Text &=
'' vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf
''Next
' ***Create a query that, when executed, returns a collection of tasks.
Dim downloadTasksQuery As IEnumerable(Of Task(Of Integer)) =
From url In urlList Select ProcessURLAsync(url, client, ct)
' ***Use ToArray to execute the query and start the download tasks.
Dim downloadTasks As Task(Of Integer)() = downloadTasksQuery.ToArray()
' ***Call WhenAny and then await the result. The task that finishes
' first is assigned to finishedTask.
Dim finishedTask As Task(Of Integer) = Await Task.WhenAny(downloadTasks)
' ***Cancel the rest of the downloads. You just want the first one.
cts.Cancel()
' ***Await the first completed task and display the results
' Run the program several times to demonstrate that different
' websites can finish first.
Dim length = Await finishedTask
resultsTextBox.Text &= vbCrLf & $"Length of the downloaded website: {length}" & vbCrLf
End Function
' ***Bundle the processing steps for a website into one async method.
Async Function ProcessURLAsync(url As String, client As HttpClient, ct As CancellationToken) As Task(Of Integer)
' GetAsync returns a Task(Of HttpResponseMessage).
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
Return urlContents.Length
End Function
' Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/hh290138.aspx",
"https://msdn.microsoft.com/library/hh290140.aspx",
"https://msdn.microsoft.com/library/dd470362.aspx",
"https://msdn.microsoft.com/library/aa578028.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Sample output:
' Length of the downloaded website: 158856
' Download complete.
```
--------------------------------
### Object Creation with Member Initializers
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/expressions
Demonstrates creating a new Customer instance and initializing its Name and Address properties using a 'With' clause.
```vb
Module Test
Sub Main()
Dim x As New Customer() With { .Name = "Bob Smith", _
.Address = "123 Main St." }
End Sub
End Module
```
--------------------------------
### Calling a Property's Get Procedure (Visual Basic)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-call-a-property-procedure
Use this snippet to retrieve the value of a property. The property's Get procedure is implicitly called when the property is used in an expression or on the right side of an assignment statement. No specific setup is required beyond declaring a variable to hold the retrieved value.
```vb
Dim ThisMoment As Date
' The following statement calls the Get procedure of the Visual Basic Now property.
ThisMoment = Now
```
--------------------------------
### Exit Property Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/statements/exit-statement
Immediately exits the Property procedure in which it appears. Execution continues with the statement that called the Property procedure. Can only be used inside a property's Get or Set procedure.
```VB
Exit Property
```
--------------------------------
### Using Distinct with Joins and Select
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/language-reference/queries/distinct-clause
This example demonstrates how to use the Distinct clause after joining customer and order data and selecting specific fields to get unique customer names and order dates.
```vb
Dim customerOrders = From cust In customers, ord In orders
Where cust.CustomerID = ord.CustomerID
Select cust.CompanyName, ord.OrderDate
Distinct
```
--------------------------------
### Call SetUpURLList in AccessTheWebAsync
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks
Integrates the URL list generation into the main asynchronous method by calling the SetUpURLList function.
```VB
' ***Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
```
--------------------------------
### Cancel a List of Tasks Example (VB)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/concepts/async/cancel-an-async-task-or-a-list-of-tasks
This code demonstrates how to cancel a list of asynchronous download tasks. It includes event handlers for starting and canceling downloads, and a method to fetch web content.
```vb
' Add an Imports directive and a reference for System.Net.Http.
Imports System.Net.Http
' Add the following Imports directive for System.Threading.
Imports System.Threading
Class MainWindow
' Declare a System.Threading.CancellationTokenSource.
Dim cts As CancellationTokenSource
Private Async Sub startButton_Click(sender As Object, e As RoutedEventArgs)
' Instantiate the CancellationTokenSource.
cts = New CancellationTokenSource()
resultsTextBox.Clear()
Try
' ***AccessTheWebAsync returns a Task, not a Task(Of Integer).
Await AccessTheWebAsync(cts.Token)
' ***Small change in the display lines.
resultsTextBox.Text &= vbCrLf & "Downloads complete."
Catch ex As OperationCanceledException
resultsTextBox.Text &= vbCrLf & "Downloads canceled." & vbCrLf
Catch ex As Exception
resultsTextBox.Text &= vbCrLf & "Downloads failed." & vbCrLf
End Try
' Set the CancellationTokenSource to Nothing when the download is complete.
cts = Nothing
End Sub
' Add an event handler for the Cancel button.
Private Sub cancelButton_Click(sender As Object, e As RoutedEventArgs)
If cts IsNot Nothing Then
cts.Cancel()
End If
End Sub
' Provide a parameter for the CancellationToken.
' ***Change the return type to Task because the method has no return statement.
Async Function AccessTheWebAsync(ct As CancellationToken) As Task
Dim client As HttpClient = New HttpClient()
' ***Call SetUpURLList to make a list of web addresses.
Dim urlList As List(Of String) = SetUpURLList()
' ***Add a loop to process the list of web addresses.
For Each url In urlList
' GetAsync returns a Task(Of HttpResponseMessage).
' Argument ct carries the message if the Cancel button is chosen.
' ***Note that the Cancel button can cancel all remaining downloads.
Dim response As HttpResponseMessage = Await client.GetAsync(url, ct)
' Retrieve the website contents from the HttpResponseMessage.
Dim urlContents As Byte() = Await response.Content.ReadAsByteArrayAsync()
resultsTextBox.Text &=
vbCrLf & $"Length of the downloaded string: {urlContents.Length}." & vbCrLf
Next
End Function
' ***Add a method that creates a list of web addresses.
Private Function SetUpURLList() As List(Of String)
Dim urls = New List(Of String) From
{
"https://msdn.microsoft.com",
"https://msdn.microsoft.com/library/hh290138.aspx",
"https://msdn.microsoft.com/library/hh290140.aspx",
"https://msdn.microsoft.com/library/dd470362.aspx",
"https://msdn.microsoft.com/library/aa578028.aspx",
"https://msdn.microsoft.com/library/ms404677.aspx",
"https://msdn.microsoft.com/library/ff730837.aspx"
}
Return urls
End Function
End Class
' Output if you do not choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Length of the downloaded string: 158124.
' Length of the downloaded string: 204890.
' Length of the downloaded string: 175488.
' Length of the downloaded string: 145790.
' Downloads complete.
' Sample output if you choose to cancel:
' Length of the downloaded string: 35939.
' Length of the downloaded string: 237682.
' Length of the downloaded string: 128607.
' Downloads canceled.
```
--------------------------------
### Instance Constructor Example
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/type-members
Demonstrates instance constructors, variable initializers, and their execution order when creating an object. The output shows that variable initializers are executed after the base class constructor.
```vb
Class A
Protected x As Integer = 1
End Class
Class B
Inherits A
Private y As Integer = x
Public Sub New()
Console.WriteLine("x = " & x & ", y = " & y)
End Sub
End Class
```
```console
x = 1, y = 1
```
--------------------------------
### Complete Example: Create and Use Extension Method
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-call-an-extension-method
A full Visual Basic program demonstrating the declaration of the `PrintAndPunctuate` extension method and its usage with different string instances and punctuation.
```vb
Imports System.Runtime.CompilerServices
Imports ConsoleApplication1.StringExtensions
Module Module1
Sub Main()
Dim example = "Hello"
example.PrintAndPunctuate(".")
example.PrintAndPunctuate("!!!!")
Dim example2 = "Goodbye"
example2.PrintAndPunctuate("?")
End Sub
Public Sub PrintAndPunctuate(ByVal aString As String,
ByVal punc As String)
Console.WriteLine(aString & punc)
End Sub
End Module
' Output:
' Hello.
' Hello!!!!
' Goodbye?'
```
--------------------------------
### Valid and Equivalent Class Initialization
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/misc/bc30053
Demonstrates the shortcut syntax for initializing objects from a class, which is not applicable to arrays.
```Visual Basic
Dim formA as Form = New Form
Dim formA as New Form
```
--------------------------------
### Declare Property with Mixed Access Levels
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/how-to-declare-a-property-with-mixed-access-levels
This example demonstrates declaring a property with a Protected Get procedure and a Private Set procedure. This allows derived classes to read the property but only the current class to set it.
```vb
Public Class employee
Private salaryValue As Double
Protected Property salary() As Double
Get
Return salaryValue
End Get
Private Set(ByVal value As Double)
salaryValue = value
End Set
End Property
End Class
```
--------------------------------
### Implementing a Simple Interface
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/interfaces
Provides an example of a class implementing a basic interface, including the required method.
```vb
Public Class ImplementationClass1
Implements Interface1
Sub Sub1(ByVal i As Integer) Implements Interface1.sub1
' Insert code here to implement this method.
End Sub
End Class
```
--------------------------------
### Call Extension and Instance Methods
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/procedures/extension-methods
Demonstrates calling both an extension method and an instance method when parameter types influence method resolution.
```VB
Sub Main()
Dim example As New ExampleClass
Dim arg1 As Long = 10
Dim arg2 As Integer = 5
' The following statement calls the extension method.
example.exampleMethod(arg1)
' The following statement calls the instance method.
example.exampleMethod(arg2)
End Sub
```
--------------------------------
### Invalid Visual Basic Element Names
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/declared-element-names
Examples of element names that violate Visual Basic's naming rules. These include names that start with a digit, contain invalid characters, or consist only of an underscore.
```Visual Basic
' Three INVALID element names
_
12ABC
xyz$wv
```
--------------------------------
### Interface Implementation Example (Visual Basic)
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/reference/language-specification/types
Demonstrates a simple interface 'I1' and a class 'C1' that implements it. Shows calling an Object member on an interface instance.
```vb
Interface I1
End Interface
Class C1
Implements I1
End Class
Module Test
Sub Main()
Dim i As I1 = New C1()
Dim h As Integer = i.GetHashCode()
End Sub
End Module
```
--------------------------------
### Valid Visual Basic Element Names
Source: https://learn.microsoft.com/en-us/dotnet/visual-basic/programming-guide/language-features/declared-elements/declared-element-names
Examples of element names that adhere to Visual Basic's naming rules. These names start with an alphabetic character or underscore and contain only alphanumeric characters and underscores.
```Visual Basic
aB123__45
_567
```