Tag Archives: vb.net
VB.NET || How To Create Multiple Tasks With Maximum Concurrency Using VB.NET

The following is a module with functions which demonstrates how to create multiple tasks with maximum concurrency using VB.NET.
The examples demonstrated on this page uses System.Threading.Tasks.Task to start and run tasks. They also use System.Threading.SemaphoreSlim to limit the number of tasks that can run concurrently.
The examples on this page demonstrates how to start and run multiple tasks with a maximum concurrency. It also demonstrated how to start and run multiple tasks with a return value.
1. Task – Maximum Concurrency
The example below demonstrates how to start and run multiple tasks with a maximum concurrency. For example purposes, the tasks do not return a value.
The functions shown in the example below are called asynchronously, but they can also be called synchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 |
' Task - Maximum Concurrency Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Debug.Print($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Debug.Print($" - Task #{taskNumber} completed!") Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Debug.Print($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Debug.Print($"All tasks completed!") ' example output: ' Task #1 starting... ' Task #2 starting... ' Task #3 starting... ' Task #4 starting... ' Task #5 starting... ' - Task #1 completed! ' - Task #2 completed! ' Task #6 starting... ' Task #7 starting... ' - Task #4 completed! ' - Task #3 completed! ' - Task #5 completed! ' Task #8 starting... ' Task #9 starting... ' Task #10 starting... ' - Task #7 completed! ' - Task #6 completed! ' Task #11 starting... ' Task #12 starting... ' - Task #9 completed! ' - Task #10 completed! ' Task #13 starting... ' Task #14 starting... ' - Task #8 completed! ' Task #15 starting... ' - Task #12 completed! ' - Task #11 completed! ' Task #16 starting... ' Task #17 starting... ' - Task #14 completed! ' - Task #13 completed! ' - Task #15 completed! ' Task #19 starting... ' Waiting for tasks to complete ' Task #18 starting... ' Task #20 starting... ' - Task #17 completed! ' - Task #16 completed! ' - Task #19 completed! ' - Task #20 completed! ' - Task #18 completed! ' All tasks completed! |
2. Task – Maximum Concurrency – Return Value
The example below demonstrates how to start and run multiple tasks with a maximum concurrency. In this example, a value is returned and retrieved from the tasks
The functions shown in the example below are called asynchronously, but they can also be called synchronously.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 |
' Task - Maximum Concurrency - Return Value Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task(Of Part)) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Debug.Print($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Debug.Print($" - Task #{taskNumber} completed!") ' Return result Return New Part With { .PartId = taskNumber, .PartName = $"Part #{taskNumber}" } Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Debug.Print($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Debug.Print($"All tasks completed!") Debug.Print("") ' Get the results For Each task In tasks Dim part = task.Result Debug.Print($"Id: {part.PartId}, Name: {part.PartName}") Next ' example output: ' Task #1 starting... ' Task #2 starting... ' Task #3 starting... ' Task #4 starting... ' Task #5 starting... ' - Task #3 completed! ' - Task #2 completed! ' - Task #5 completed! ' - Task #1 completed! ' Task #8 starting... ' Task #7 starting... ' Task #6 starting... ' - Task #4 completed! ' Task #9 starting... ' Task #10 starting... ' - Task #8 completed! ' Task #11 starting... ' - Task #7 completed! ' Task #12 starting... ' - Task #6 completed! ' Task #13 starting... ' - Task #10 completed! ' - Task #9 completed! ' Task #14 starting... ' Task #15 starting... ' - Task #11 completed! ' Task #16 starting... ' - Task #12 completed! ' Task #17 starting... ' - Task #13 completed! ' Task #18 starting... ' - Task #15 completed! ' - Task #14 completed! ' Task #19 starting... ' Waiting for tasks to complete ' Task #20 starting... ' - Task #16 completed! ' - Task #17 completed! ' - Task #18 completed! ' - Task #19 completed! ' - Task #20 completed! ' All tasks completed! ' ' Id: 1, Name: Part #1 ' Id: 2, Name: Part #2 ' Id: 3, Name: Part #3 ' Id: 4, Name: Part #4 ' Id: 5, Name: Part #5 ' Id: 6, Name: Part #6 ' Id: 7, Name: Part #7 ' Id: 8, Name: Part #8 ' Id: 9, Name: Part #9 ' Id: 10, Name: Part #10 ' Id: 11, Name: Part #11 ' Id: 12, Name: Part #12 ' Id: 13, Name: Part #13 ' Id: 14, Name: Part #14 ' Id: 15, Name: Part #15 ' Id: 16, Name: Part #16 ' Id: 17, Name: Part #17 ' Id: 18, Name: Part #18 ' Id: 19, Name: Part #19 ' Id: 20, Name: Part #20 |
3. More Examples
Below is a full example of the process demonstrated on this page!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 4, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Public Class Part Public Property PartName As String Public Property PartId As Integer End Class Sub Main(args As String()) Try 'TaskSub.Wait() TaskFunction.Wait() Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Async Function TaskFunction() As Task(Of List(Of Part)) Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task(Of Part)) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Display($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Display($" - Task #{taskNumber} completed!") Return New Part With { .PartId = taskNumber, .PartName = $"Part #{taskNumber}" } Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Display($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Display($"All tasks completed!") Display("") ' Get the results For Each task In tasks Dim part = task.Result Display($"Id: {part.PartId}, Name: {part.PartName}") Next Return tasks.Select(Function(task) task.Result).ToList End Function Public Async Function TaskSub() As Task Dim concurrentTasks = 5 Dim semaphore = New System.Threading.SemaphoreSlim(concurrentTasks, concurrentTasks) Dim tasks = New List(Of System.Threading.Tasks.Task) For count = 1 To 20 Dim taskNumber = count ' Blocks execution until another task can be started. ' This function also accepts a timeout in milliseconds Await semaphore.WaitAsync() ' Start a task Dim task = System.Threading.Tasks.Task.Run(Async Function() ' Execute long running code Try Display($"Task #{taskNumber} starting...") Await System.Threading.Tasks.Task.Delay(5000) Display($" - Task #{taskNumber} completed!") Catch ex As Exception Throw Finally ' Signal that the task is completed ' so another task can start semaphore.Release() End Try End Function) tasks.Add(task) Next Display($"Waiting for tasks to complete") ' Wait for all tasks to complete Await System.Threading.Tasks.Task.WhenAll(tasks.ToArray) Display($"All tasks completed!") End Function Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Convert Bytes To Kilobytes, Megabytes, Gigabytes, Terabytes Using VB.NET

The following is a module with functions which demonstrates how to convert bytes to decimal formats like kilobytes, megabytes, gigabytes, terabytes, petabytes, exabytes, zettabytes, and yottabytes, as well as binary formats like kibibytes, mebibytes, gibibytes, tebibytes, pebibytes, exbibytes, zebibytes, and yobibytes using VB.NET.
The function demonstrated on this page follows the IEC standard, which means:
• 1 kilobyte = 1000 bytes (Decimal)
• 1 kibibyte = 1024 bytes (Binary)
This function allows you to convert bytes to a measurement unit, a measurement unit to bytes, and allows to convert from one measurement unit to another measurement unit.
1. Convert Bytes To Measurement Unit
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert bytes to a measurement unit.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
' Convert Bytes To Measurement Unit ' Declare values to convert Dim values = {2287879, 536870912, 1073741824} ' Convert values For Each value In values ' Convert bytes to megabyte Dim mb = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Megabyte) ' Convert bytes to mebibyte Dim mib = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Mebibyte) ' Display the converted values Debug.Print($"Bytes: {value}, Megabyte: {mb}, Mebibyte: {mib}") Next ' expected output: ' Bytes: 2287879, Megabyte: 2.287879, Mebibyte: 2.18189144134521484375 ' Bytes: 536870912, Megabyte: 536.870912, Mebibyte: 512 ' Bytes: 1073741824, Megabyte: 1073.741824, Mebibyte: 1024 |
2. Convert Measurement Unit To Bytes
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert a measurement unit to bytes.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
' Convert Measurement Unit To Bytes ' Declare values to convert Dim values = {1, 0.5D, 10.75D} ' Convert values For Each value In values ' Convert gibibyte to byte Dim bytes = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gibibyte, value, Utils.Bytes.Unit.Byte) ' Display the converted values Debug.Print($"Gibibyte: {value}, Bytes: {bytes}") Next ' expected output: ' Gibibyte: 1, Bytes: 1073741824 ' Gibibyte: 0.5, Bytes: 536870912.0 ' Gibibyte: 10.75, Bytes: 11542724608.00 |
3. Convert Measurement Unit To Measurement Unit
The example below demonstrates the use of ‘Utils.Bytes.FromTo‘ to convert a measurement unit to another measurement unit.
The optional function parameter allows you to specify the decimal places.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
' Convert Measurement Unit To Measurement Unit ' Declare values to convert Dim values = {1991, 1987, 28.31D, 19.22D} ' Convert values For Each value In values ' Convert value from one unit to another Dim size = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gigabyte, value, Utils.Bytes.Unit.Terabyte) ' Display the converted values Debug.Print($"Gigabyte: {value}, Terabyte: {size}") Next ' expected output: ' Gigabyte: 1991, Terabyte: 1.991 ' Gigabyte: 1987, Terabyte: 1.987 ' Gigabyte: 28.31, Terabyte: 0.02831 ' Gigabyte: 19.22, Terabyte: 0.01922 |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 3, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Namespace Bytes Public Module modBytes Public Enum Unit [Byte] ' Decimal Kilobyte Megabyte Gigabyte Terabyte Petabyte Exabyte Zettabyte Yottabyte ' Binary Kibibyte Mebibyte Gibibyte Tebibyte Pebibyte Exbibyte Zebibyte Yobibyte End Enum ''' <summary> ''' Converts a measurement 'Unit' to another measurement 'Unit' ''' </summary> ''' <param name="unitFrom">The measurement unit converting from</param> ''' <param name="sizeFrom">The size of the 'from' measurement unit</param> ''' <param name="unitTo">The measurement unit to convert to</param> ''' <param name="decimalPlaces">The decimal places to round to</param> ''' <returns>The value converted to the specified measurement unit</returns> Public Function FromTo(unitFrom As Unit, sizeFrom As Decimal, unitTo As Unit _ , Optional decimalPlaces As Integer? = Nothing) As Decimal Dim result = sizeFrom If unitFrom <> unitTo Then If unitFrom = Unit.Byte Then result = ConvertTo(unitTo, sizeFrom, decimalPlaces) ElseIf unitTo = Unit.Byte Then result = ConvertFrom(unitFrom, sizeFrom, decimalPlaces) Else result = ConvertTo(unitTo, ConvertFrom(unitFrom, sizeFrom), decimalPlaces) End If End If Return result End Function Private Enum Conversion From [To] End Enum ' Converts bytes to a measurement unit Private Function ConvertTo(unit As Unit, bytes As Decimal _ , Optional decimalPlaces As Integer? = Nothing) As Decimal Return Convert(Conversion.To, bytes, unit, decimalPlaces) End Function ' Converts a measurement unit to bytes Private Function ConvertFrom(unit As Unit, bytes As Decimal _ , Optional decimalPlaces As Integer? = Nothing) As Decimal Return Convert(Conversion.From, bytes, unit, decimalPlaces) End Function Private Function Convert(operation As Conversion, bytes As Decimal, unit As Unit _ , decimalPlaces As Integer?) As Decimal ' Get the unit type definition Dim definition = GetDefinition(unit) If definition Is Nothing Then Throw New ArgumentException($"Unknown unit type: {unit}", NameOf(unit)) End If ' Get the unit value Dim value = definition.Value ' Calculate the result Dim result = If(operation = Conversion.To, bytes / value, bytes * value) If decimalPlaces.HasValue Then result = Math.Round(result, decimalPlaces.Value, MidpointRounding.AwayFromZero) End If Return result End Function Public Enum Prefix [Decimal] Binary End Enum Public Class Definition Public Property Prefix As Prefix Public Property OrderOfMagnitude As Integer Public ReadOnly Property Multiple As Decimal Get Return If(Prefix = Prefix.Decimal, 1000, 1024) End Get End Property Public ReadOnly Property Value As Decimal Get Return CDec(Math.Pow(Multiple, OrderOfMagnitude)) End Get End Property End Class Public Function GetDefinition(unit As Unit) As Definition Dim definitions = GetDefinitions() Return If(definitions.ContainsKey(unit), definitions(unit), Nothing) End Function Public Function GetDefinitions() As Dictionary(Of Unit, Definition) ' Create and add definitions Static definitions As Dictionary(Of Unit, Definition) If definitions Is Nothing Then definitions = New Dictionary(Of Unit, Definition) ' Place units in order of magnitude ' Decimal units Dim decimals = { Unit.Kilobyte, Unit.Megabyte, Unit.Gigabyte, Unit.Terabyte _ , Unit.Petabyte, Unit.Exabyte, Unit.Zettabyte, Unit.Yottabyte } ' Binary units Dim binary = { Unit.Kibibyte, Unit.Mebibyte, Unit.Gibibyte, Unit.Tebibyte _ , Unit.Pebibyte, Unit.Exbibyte, Unit.Zebibyte, Unit.Yobibyte } AddDefinitions(definitions, Prefix.Decimal, decimals) AddDefinitions(definitions, Prefix.Binary, binary) End If Return definitions End Function Private Sub AddDefinitions(definitions As Dictionary(Of Unit, Definition) _ , prefix As Prefix, units As IEnumerable(Of Unit)) For index = 0 To units.Count - 1 Dim unit = units(index) definitions.Add(unit, New Definition With { .Prefix = prefix, .OrderOfMagnitude = index + 1 }) Next End Sub End Module End Namespace End Namespace ' http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 3, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Declare values to convert Dim values = {2287879, 536870912, 1073741824} ' Convert values For Each value In values ' Convert bytes to megabyte Dim mb = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Megabyte) ' Convert bytes to mebibyte Dim mib = Utils.Bytes.FromTo(Utils.Bytes.Unit.Byte, value, Utils.Bytes.Unit.Mebibyte) ' Display the converted values Display($"Bytes: {value}, Megabyte: {mb}, Mebibyte: {mib}") Next Display("") ' Declare values to convert Dim values2 = {1, 0.5D, 10.75D} ' Convert values For Each value In values2 ' Convert gibibyte to byte Dim bytes = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gibibyte, value, Utils.Bytes.Unit.Byte) ' Display the converted values Display($"Gibibyte: {value}, Bytes: {bytes}") Next Display("") ' Declare values to convert Dim values3 = {1991, 1987, 28.31D, 19.22D} ' Convert values For Each value In values3 ' Convert value from one unit to another Dim size = Utils.Bytes.FromTo(Utils.Bytes.Unit.Gigabyte, value, Utils.Bytes.Unit.Terabyte) ' Display the converted values Display($"Gigabyte: {value}, Terabyte: {size}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Parse A Delimited CSV File Using VB.NET

The following is a module with functions which demonstrates how to parse a delimited CSV file using VB.NET.
The function demonstrated on this page uses FileIO.TextFieldParser to parse values in a CSV file.
This function parses a CSV file and returns its results as a List. Each List index represents a line in the CSV file, with each item in the list representing a record contained on that line.
1. Parse CSV File
The example below demonstrates the use of ‘Utils.ParseCsv‘ to parse a CSV file and return its results as a List.
The optional function parameter allows you to specify the delimiters. Default delimiter is a comma (,).
Sample CSV used in this example is the following:
1 2 3 4 5 6 |
Kenneth,Perkins,120 jefferson st.,Riverside, NJ, 08075 Jack,McGinnis,220 hobo Av.,Phila, PA,09119 "Jennifer ""Da Man""",Repici,120 Jefferson St.,Riverside, NJ,08075 Stephen,Tyler,"7452 Terrace ""At the Plaza"" road",SomeTown,SD, 91234 ,Blankman,,SomeTown, SD, 00298 "Joan ""the bone"", Anne",Jet,"9th, at Terrace plc",Desert City,CO,00123 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 |
' Parse CSV File ' Read file into byte array Dim fileBytes As Byte() ' Parse the contents of the file into a list Dim fileContents = Utils.ParseCsv(fileBytes) ' Display the contents of the file For lineIndex = 0 To fileContents.Count - 1 Dim line = fileContents(lineIndex) Debug.Print($"Line #{lineIndex + 1}") For Each item In line Debug.Print($" Item: {item}") Next Next ' expected output: ' Line #1 ' Item: Kenneth ' Item: Perkins ' Item: 120 jefferson st. ' Item: Riverside ' Item: NJ ' Item: 08075 ' Line #2 ' Item: Jack ' Item: McGinnis ' Item: 220 hobo Av. ' Item: Phila ' Item: PA ' Item: 09119 ' Line #3 ' Item: Jennifer "Da Man" ' Item: Repici ' Item: 120 Jefferson St. ' Item: Riverside ' Item: NJ ' Item: 08075 ' Line #4 ' Item: Stephen ' Item: Tyler ' Item: 7452 Terrace "At the Plaza" road ' Item: SomeTown ' Item: SD ' Item: 91234 ' Line #5 ' Item: ' Item: Blankman ' Item: ' Item: SomeTown ' Item: SD ' Item: 00298 ' Line #6 ' Item: Joan "the bone", Anne ' Item: Jet ' Item: 9th, at Terrace plc ' Item: Desert City ' Item: CO ' Item: 00123 |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 2, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Parses a Csv file and returns its results as a List. ''' Each List index represents a line in the Csv file, with each ''' item in the list representing a record contained on that line. ''' </summary> ''' <param name="fileBytes">The Csv file as a byte array</param> ''' <param name="delimiters">The Csv data delimiter</param> ''' <returns>The file contents as a List</returns> Public Function ParseCsv(fileBytes As Byte() _ , Optional delimiters As String = ",") As List(Of List(Of String)) Dim results = New List(Of List(Of String)) Using stream = New System.IO.MemoryStream(fileBytes) Using parser = New Microsoft.VisualBasic.FileIO.TextFieldParser(stream) parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited parser.Delimiters = delimiters.Select(Function(letter) letter.ToString).ToArray parser.HasFieldsEnclosedInQuotes = True ' Parse each line in the file While Not parser.EndOfData Dim currentLine = parser.ReadFields results.Add(currentLine.ToList) End While End Using End Using Return results End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 2, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Read file into byte array Dim fileBytes As Byte() ' Parse the contents of the file into a list Dim fileContents = Utils.ParseCsv(fileBytes) ' Display the contents of the file For lineIndex = 0 To fileContents.Count - 1 Dim line = fileContents(lineIndex) Display($"Line #{lineIndex + 1}") For Each item In line Display($" Item: {item}") Next Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Round A Number To The Nearest X Using VB.NET

The following is a module with functions which demonstrates how to round a number to the nearest X using VB.NET.
This function has the ability to either round a number to the nearest amount, always round up, or always round down. For example, when dealing with money, this is good for rounding a dollar amount to the nearest 5 cents.
1. Round – Nearest
The example below demonstrates the use of ‘Utils.RoundAmount‘ to round a number to the nearest 5 cents.
The optional function parameter determines they type of rounding to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
' Round - Nearest ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round to nearest amount For Each value In values Debug.Print($"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount)}") Next ' expected output: ' Value: 19.28, Rounded: 19.3 ' Value: 31.22, Rounded: 31.2 ' Value: 19.91, Rounded: 19.9 ' Value: 19.87, Rounded: 19.85 ' Value: 0.05, Rounded: 0.05 |
2. Round – Up
The example below demonstrates the use of ‘Utils.RoundAmount‘ to always round a number up to the nearest 5 cents.
The optional function parameter determines they type of rounding to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
' Round - Up ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round up to nearest amount For Each value In values Debug.Print($"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Up)}") Next ' expected output: ' Value: 19.28, Rounded: 19.3 ' Value: 31.22, Rounded: 31.25 ' Value: 19.91, Rounded: 19.95 ' Value: 19.87, Rounded: 19.9 ' Value: 0.05, Rounded: 0.05 |
3. Round – Down
The example below demonstrates the use of ‘Utils.RoundAmount‘ to always round a number down to the nearest 5 cents.
The optional function parameter determines they type of rounding to perform.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
' Round - Down ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round down to nearest amount For Each value In values Debug.Print($"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Down)}") Next ' expected output: ' Value: 19.28, Rounded: 19.25 ' Value: 31.22, Rounded: 31.2 ' Value: 19.91, Rounded: 19.9 ' Value: 19.87, Rounded: 19.85 ' Value: 0.05, Rounded: 0.05 |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 1, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Enum RoundType Nearest Up Down End Enum ''' <summary> ''' Rounds a number to the nearest X ''' </summary> ''' <param name="value">The value to round</param> ''' <param name="stepAmount">The amount to round the value by</param> ''' <param name="type">The type of rounding to perform</param> ''' <returns>The value rounded by the step amount and type</returns> Public Function RoundAmount(value As Decimal, stepAmount As Decimal _ , Optional type As RoundType = RoundType.Nearest) As Decimal Dim inverse = 1 / stepAmount Dim dividend = value * inverse Select Case type Case RoundType.Nearest dividend = Math.Round(dividend) Case RoundType.Up dividend = Math.Ceiling(dividend) Case RoundType.Down dividend = Math.Floor(dividend) Case Else Throw New ArgumentException($"Unknown type: {type}", NameOf(type)) End Select Dim result = dividend / inverse Return result End Function End Module End Namespace ' http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Dec 1, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Declare values to round Dim values = New Decimal() {19.28D, 31.22D, 19.91D, 19.87D, 0.05D} ' Declare step amount Dim stepAmount = 0.05D ' Round to nearest amount For Each value In values Display($"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount)}") Next Display("") ' Round up to nearest amount For Each value In values Display($"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Up)}") Next Display("") ' Round down to nearest amount For Each value In values Display($"Value: {value}, Rounded: {Utils.RoundAmount(value, stepAmount, Utils.RoundType.Down)}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Replace A Letter With Its Alphabet Position Using VB.NET

The following is a module with functions which demonstrates how to replace a letter with its alphabet position using VB.NET.
1. Replace With Alphabet Position
The example below demonstrates the use of ‘Utils.GetAlphabetPosition‘ to replace a letter with its alphabet position.
1 2 3 4 5 6 7 8 9 10 |
' Replace With Alphabet Position ' Get alphabet position Dim result = Utils.GetAlphabetPosition("The sunset sets at twelve o' clock.") ' Display the results Debug.Print(String.Join(" ", result)) ' expected output: ' 20 8 5 19 21 14 19 5 20 19 5 20 19 1 20 20 23 5 12 22 5 15 3 12 15 3 11 |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 30, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Gets the alphabet position of each character in a string ''' </summary> ''' <param name="text">The text to get the position</param> ''' <returns>The alphabet position of each character</returns> Public Function GetAlphabetPosition(text As String) As List(Of Integer) Dim alphabet = "abcdefghijklmnopqrstuvwxyz" Dim result = New List(Of Integer) For Each letter In text.ToLower Dim index = alphabet.IndexOf(letter) If index > -1 Then result.Add(index + 1) End If Next Return result End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 30, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try Dim result = Utils.GetAlphabetPosition("The sunset sets at twelve o' clock.") Display(String.Join(" ", result)) Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Generate A Random String Of A Specified Length Using VB.NET

The following is a module with functions which demonstrates how to generate a random code of a specified length using VB.NET.
The function demonstrated on this page has the ability to generate random strings that contains only letters, only numerical digits, or alphanumeric strings.
1. Random Code – Alphabetical
The example below demonstrates the use of ‘Utils.GetRandomCode‘ to generate a code of a specified length that contains only letters.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 |
' Random Code - Alphabetical ' Generate code containing only letters Dim letters = Utils.GetRandomCode(5) ' Display the code Debug.Print($"Code: {letters}") ' example output: ' Code: DWhxO |
2. Random Code – Numeric
The example below demonstrates the use of ‘Utils.GetRandomCode‘ to generate a code of a specified length that contains only digits.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 |
' Random Code - Numeric ' Generate code containing only digits Dim numeric = Utils.GetRandomCode(7, Utils.CodeType.Numeric) ' Display the code Debug.Print($"Code: {numeric}") ' example output: ' Code: 6407422 |
3. Random Code – Alphanumeric
The example below demonstrates the use of ‘Utils.GetRandomCode‘ to generate a code of a specified length that is alphanumeric.
The optional function parameter determines the type of code that is generated.
1 2 3 4 5 6 7 8 9 10 |
' Random Code - Alphanumeric ' Generate alphanumeric code Dim alphaNumeric = Utils.GetRandomCode(10, Utils.CodeType.AlphaNumeric) ' Display the code Display($"Code: {alphaNumeric}") ' example output: ' Code: C3G9mt9wf8 |
4. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 30, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Enum CodeType ''' <summary> ''' Code contains only letters ''' </summary> Alphabetical ''' <summary> ''' Code contains only digits ''' </summary> Numeric ''' <summary> ''' Code contains letters and digits ''' </summary> AlphaNumeric End Enum ''' <summary> ''' Generates a random string of a specified length according to the type ''' <param name="length">The length of the random string</param> ''' <param name="type">The type of string to generate</param> ''' </summary> ''' <returns>The random string according to the type</returns> Public Function GetRandomCode(length As Integer _ , Optional type As CodeType = CodeType.Alphabetical) As String Dim digits = "0123456789" Dim alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" Dim source = String.Empty Select Case type Case CodeType.Alphabetical source = alphabet Case CodeType.Numeric source = digits Case CodeType.AlphaNumeric source = alphabet + digits Case Else Throw New ArgumentException($"Unknown type: {type}", NameOf(type)) End Select Dim r = New Random Dim result = New System.Text.StringBuilder While result.Length < length result.Append(source(r.Next(0, source.Length))) End While Return result.ToString End Function End Module End Namespace ' http://programmingnotes.org/ |
5. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 30, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Generate code containing only letters Dim letters = Utils.GetRandomCode(5) ' Display the code Display($"Code: {letters}") Display("") ' Generate code containing only digits Dim numeric = Utils.GetRandomCode(7, Utils.CodeType.Numeric) ' Display the code Display($"Code: {numeric}") Display("") ' Generate alphanumeric code Dim alphaNumeric = Utils.GetRandomCode(10, Utils.CodeType.AlphaNumeric) ' Display the code Display($"Code: {alphaNumeric}") Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Get A List Of Files At A Given Path Directory Using VB.NET

The following is a module with functions which demonstrates how to get a list of files at a given directory path using VB.NET.
The function demonstrated on this page returns a list of System.IO.FileInfo, which contains information about the files in the given directory.
1. Get Files In Directory
The example below demonstrates the use of ‘Utils.GetFilesInDirectory‘ to get a list of files at a given path directory.
The optional function parameter lets you specify the search option. This lets you specify whether to limit the search to just the current directory, or expand the search to the current directory and all subdirectories when searching for files.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
' Get Files In Directory ' Declare directory path Dim directory = "C:\Users\Name\Desktop" ' Get files at the specified directory Dim files = Utils.GetFilesInDirectory(directory) ' Display info about the files For Each file In files Debug.Print($"File: {file.FullName} - Last Modified: {file.LastWriteTime}") Next ' example output: ' File: C:\Users\Name\Desktop\text.txt - Last Modified: 10/7/2020 12:47:56 PM ' File: C:\Users\Name\Desktop\image.png - Last Modified: 9/4/2020 8:36:25 PM ' File: C:\Users\Name\Desktop\document.docx - Last Modified: 3/7/2018 9:26:19 PM |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 30, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Returns a list of <see cref="System.IO.FileInfo"/> of the files ''' in the given directory ''' <param name="directory">The relative or absolute path to the directory to search</param> ''' <param name="searchOption">The file search option</param> ''' </summary> ''' <returns>A list of <see cref="System.IO.FileInfo"/> in the given directory</returns> Public Function GetFilesInDirectory(directory As String _ , Optional searchOption As System.IO.SearchOption = System.IO.SearchOption.TopDirectoryOnly) As List(Of System.IO.FileInfo) Return System.IO.Directory.GetFiles(directory, "*", searchOption) _ .Select(Function(fileName) New System.IO.FileInfo(fileName)).ToList End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 30, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Declare directory path Dim directory = "C:\path\to\directory" ' Get files at the specified directory Dim files = Utils.GetFilesInDirectory(directory) ' Display info about the files For Each file In files Display($"File: {file.FullName} - Last Modified: {file.LastWriteTime}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Copy DataTable DataRow From One DataRow To Another Using VB.NET

The following is a module with functions which demonstrates how to copy a DataTable DataRow from one DataRow to another using VB.NET.
The function demonstrated on this page is an extension method, which copies all matching columns from the source DataRow to the destination DataRow. If no matching column exists between the two rows, the data at that column is skipped. This allows to safely copy a single row from one DataTable to other.
1. Copy DataRow
The example below demonstrates the use of ‘Utils.Collections.CopyTo‘ to copy all matching columns from a source row to a destination row.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
' Copy DataRow Imports Utils.Collections ' Declare the source datatable Dim table1 = New DataTable table1.Columns.Add("Name", GetType(String)) table1.Rows.Add("Kenneth") table1.Rows.Add("Jennifer") table1.Rows.Add("Lynn") table1.Rows.Add("Sole") table1.Rows.Add(System.DBNull.Value) ' Declare the destination datatable Dim table2 = New DataTable table2.Columns.Add("Id", GetType(Integer)) table2.Columns.Add("Name", GetType(String)) For index = 0 To table1.Rows.Count - 1 ' Get the source row Dim rowSource = table1.Rows(index) ' Get the destination row Dim rowDestination = table2.NewRow ' Do something with the destination row rowDestination("Id") = index + 1 ' Copy contents from source to destination rowSource.CopyTo(rowDestination) table2.Rows.Add(rowDestination) Next ' Display information from destination table For Each row As DataRow In table2.Rows Debug.Print($"Id: {row("Id")}, Name: {row("Name")}") Next ' expected output: ' Id: 1, Name: Kenneth ' Id: 2, Name: Jennifer ' Id: 3, Name: Lynn ' Id: 4, Name: Sole ' Id: 5, Name: |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 29, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Namespace Collections Public Module modCollections ''' <summary> ''' Copies all matching columns from the source row to the destination row ''' </summary> ''' <param name="source">The DataRow source</param> ''' <param name="destination">The DataRow destination</param> <Runtime.CompilerServices.Extension()> Public Sub CopyTo(source As DataRow, destination As DataRow) For Each col As DataColumn In source.Table.Columns If destination.Table.Columns.Contains(col.ColumnName) Then destination(col.ColumnName) = source(col.ColumnName) End If Next End Sub End Module End Namespace End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 29, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils.Collections Public Module Program Sub Main(args As String()) Try ' Declare the source datatable Dim table1 = New DataTable table1.Columns.Add("Name", GetType(String)) table1.Rows.Add("Kenneth") table1.Rows.Add("Jennifer") table1.Rows.Add("Lynn") table1.Rows.Add("Sole") table1.Rows.Add(System.DBNull.Value) ' Declare the destination datatable Dim table2 = New DataTable table2.Columns.Add("Id", GetType(Integer)) table2.Columns.Add("Name", GetType(String)) For index = 0 To table1.Rows.Count - 1 ' Get the source row Dim rowSource = table1.Rows(index) ' Get the destination row Dim rowDestination = table2.NewRow ' Do something with the destination row rowDestination("Id") = index + 1 ' Copy contents from source to destination rowSource.CopyTo(rowDestination) table2.Rows.Add(rowDestination) Next ' Display information from destination table For Each row As DataRow In table2.Rows Display($"Id: {row("Id")}, Name: {row("Name")}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Generate, Create & Read A QR Code Using VB.NET

The following is a module with functions which demonstrates how to generate, create and read a QR code using VB.NET.
The functions demonstrated on this page has the ability to create and encode a string to a QR code byte array, and another function to read and decode a byte array QR code to a string.
The following functions use ZXing.Net to create and read QR codes.
Note: To use the functions in this module, make sure you have the ‘ZXing.Net‘ package installed in your project.
One way to do this is, in your Solution Explorer (where all the files are shown with your project), right click the ‘References‘ folder, click ‘Manage NuGet Packages….‘, then type ‘ZXing.Net‘ in the search box, and install the package titled ZXing.Net in the results Tab.
1. Create QR Code – Encode
The example below demonstrates the use of ‘Utils.CreateQRCode‘ to create a QR code byte array from string data.
The optional function parameters allows you to specify the QR code height, width and margin.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
' Create QR Code - Encode ' Data to encode Dim data = "http://programmingnotes.org/" ' Encode data to a QR code byte array Dim bytes = Utils.CreateQRCode(data) ' Display bytes length Debug.Print($"Length: {bytes.Length}") ' expected output: ' Length: 1959 |
2. Read QR Code – Decode
The example below demonstrates the use of ‘Utils.ReadQRCode‘ to read a QR code byte array and decode its contents to a string.
1 2 3 4 5 6 7 8 9 |
' Read QR Code - Decode ' Read QR as byte array Dim qrBytes As Byte() ' Decode QR code to a string Dim result = Utils.ReadQRCode(qrBytes) ' ... Do something with the result string |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 28, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Converts a string and encodes it to a QR code byte array ''' </summary> ''' <param name="data">The data to encode</param> ''' <param name="height">The height of the QR code</param> ''' <param name="width">The width of the QR code</param> ''' <param name="margin">The margin around the QR code</param> ''' <returns>The byte array of the data encoded into a QR code</returns> Public Function CreateQRCode(data As String, Optional height As Integer = 100 _ , Optional width As Integer = 100, Optional margin As Integer = 0) As Byte() Dim bytes As Byte() = Nothing Dim barcodeWriter = New ZXing.BarcodeWriter With { .Format = ZXing.BarcodeFormat.QR_CODE, .Options = New ZXing.QrCode.QrCodeEncodingOptions With { .Height = height, .Width = width, .Margin = margin } } Using image = barcodeWriter.Write(data) Using stream = New System.IO.MemoryStream image.Save(stream, System.Drawing.Imaging.ImageFormat.Png) bytes = stream.ToArray End Using End Using Return bytes End Function ''' <summary> ''' Converts a QR code and decodes it to its string data ''' </summary> ''' <param name="bytes">The QR code byte array</param> ''' <returns>The string data decoded from the QR code</returns> Public Function ReadQRCode(bytes As Byte()) As String Dim result = String.Empty Using stream = New System.IO.MemoryStream(bytes) Using image = System.Drawing.Image.FromStream(stream) Dim barcodeReader = New ZXing.BarcodeReader Dim decoded = barcodeReader.Decode(CType(image, System.Drawing.Bitmap)) If decoded IsNot Nothing Then result = decoded.Text End If End Using End Using Return result End Function End Module End Namespace ' http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 28, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Data to encode Dim data = "http://programmingnotes.org/" ' Encode data to a QR code byte array Dim bytes = Utils.CreateQRCode(data) Display($"Length: {bytes.Length}") ' Decode QR code to a string Dim result = Utils.ReadQRCode(bytes) Display($"Result: {result}") Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Append & Join A Date & Time Value Together Using VB.NET

The following is a module with functions which demonstrates how to append and join a date and time value together using VB.NET.
1. Append Date & Time
The example below demonstrates the use of ‘Utils.AppendTime‘ to append a date and time value together.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
' Append Date & Time Imports Utils Dim dteDate = DateValue("1/27/1991") Dim time = TimeValue("7:28:33 PM") Debug.Print($"dteDate: {dteDate}") ' Append time to the date Dim result = dteDate.AppendTime(time) Debug.Print($"Result: {result}") ' expected output: ' dteDate: 1/27/1991 12:00:00 AM ' Result: 1/27/1991 7:28:33 PM |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 27, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Appends a date and time value together ''' </summary> ''' <param name="[date]">The date portion</param> ''' <param name="time">The time portion</param> ''' <returns>The appended date and time value</returns> <Runtime.CompilerServices.Extension()> Public Function AppendTime([date] As Date, time As Date) As Date Return [date].Date.Add(time.TimeOfDay) End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 27, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Public Module Program Sub Main(args As String()) Try Dim dteDate = DateValue("1/27/1991") Dim time = TimeValue("7:28:33 PM") Display($"dteDate: {dteDate}") ' Append time to the date Dim result = dteDate.AppendTime(time) Display($"Result: {result}") Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Generate Hourly Time Range With Minute Interval Using VB.NET

The following is a module with functions which demonstrates how to generate an hourly time range with minute interval between a start and end time using VB.NET.
The function demonstrated in this page generates a time value list containing the time from a starting hour to an ending hour, separated by a minute step. The starting and ending hour is an integer from 0 through 23 representing the 24 hour period of the day, and the minute step can be any minute interval, including decimal values.
The starting and ending hours can also be flipped, indicating that the results should be returned in descending order.
An optional parameter also exists which allows to tune the results. When the range is in ascending order, the parameter indicates that the results should exclude/include the entire ending hour. When the range is in descending order, the parameter indicates that the results should exclude/include the entire starting hour.
1. Ascending Time Range – Minute Interval – Default
The example below demonstrates the use of ‘Utils.DateVal.GetTimeRange‘ to get the time range with a minute interval in ascending order.
In this example, the default options are used, which excludes the full ending hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
' Ascending Time Range - Minute Interval - Default ' Get time range from 12AM - 11PM, with a 15 and half minute interval Dim result = Utils.DateVal.GetTimeRange(0, 23, 15.5) For Each value In result Debug.Print($"Time: {value.Time}, String: {value.ToString}") Next ' expected output: ' Time: 1/1/0001 12:00:00 AM, String: 12:00:00 AM ' Time: 1/1/0001 12:15:30 AM, String: 12:15:30 AM ' Time: 1/1/0001 12:31:00 AM, String: 12:31:00 AM ' Time: 1/1/0001 12:46:30 AM, String: 12:46:30 AM ' Time: 1/1/0001 1:02:00 AM, String: 1:02:00 AM ' Time: 1/1/0001 1:17:30 AM, String: 1:17:30 AM ' Time: 1/1/0001 1:33:00 AM, String: 1:33:00 AM ' Time: 1/1/0001 1:48:30 AM, String: 1:48:30 AM ' .... ' .... ' .... ' .... ' Time: 1/1/0001 9:11:00 PM, String: 9:11:00 PM ' Time: 1/1/0001 9:26:30 PM, String: 9:26:30 PM ' Time: 1/1/0001 9:42:00 PM, String: 9:42:00 PM ' Time: 1/1/0001 9:57:30 PM, String: 9:57:30 PM ' Time: 1/1/0001 10:13:00 PM, String: 10:13:00 PM ' Time: 1/1/0001 10:28:30 PM, String: 10:28:30 PM ' Time: 1/1/0001 10:44:00 PM, String: 10:44:00 PM ' Time: 1/1/0001 10:59:30 PM, String: 10:59:30 PM |
2. Descending Time Range – Hourly Interval – Default
The example below demonstrates the use of ‘Utils.DateVal.GetTimeRange‘ to get the time range with a hourly interval in descending order.
In this example, the default options are used, which excludes the full starting hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
' Descending Time Range - Hourly Interval - Default ' Get an hour range from 10PM - 10AM, with a 2 hour interval Dim result = Utils.DateVal.GetTimeRange(22, 10, 120) For Each value In result Debug.Print($"Time: {value.Time}, String: {value.ToString(True)}") Next ' expected output: ' Time: 1/1/0001 10:00:00 PM, String: 10 PM ' Time: 1/1/0001 8:00:00 PM, String: 8 PM ' Time: 1/1/0001 6:00:00 PM, String: 6 PM ' Time: 1/1/0001 4:00:00 PM, String: 4 PM ' Time: 1/1/0001 2:00:00 PM, String: 2 PM ' Time: 1/1/0001 12:00:00 PM, String: 12 PM ' Time: 1/1/0001 10:00:00 AM, String: 10 AM |
3. Ascending Time Range – Minute Interval – Include Full Hour
The example below demonstrates the use of ‘Utils.DateVal.GetTimeRange‘ to get the time range with a minute interval in ascending order.
In this example, the optional parameter is used, which includes the full ending hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
' Ascending Time Range - Minute Interval - Include Full Hour ' Get time range from 12AM - 11PM, with a 15 and half minute interval Dim result = Utils.DateVal.GetTimeRange(0, 23, 15.5, True) For Each value In result Debug.Print($"Time: {value.Time}, String: {value.ToString}") Next ' expected output: ' Time: 1/1/0001 12:00:00 AM, String: 12:00:00 AM ' Time: 1/1/0001 12:15:30 AM, String: 12:15:30 AM ' Time: 1/1/0001 12:31:00 AM, String: 12:31:00 AM ' Time: 1/1/0001 12:46:30 AM, String: 12:46:30 AM ' Time: 1/1/0001 1:02:00 AM, String: 1:02:00 AM ' Time: 1/1/0001 1:17:30 AM, String: 1:17:30 AM ' Time: 1/1/0001 1:33:00 AM, String: 1:33:00 AM ' Time: 1/1/0001 1:48:30 AM, String: 1:48:30 AM ' .... ' .... ' .... ' .... ' Time: 1/1/0001 10:13:00 PM, String: 10:13:00 PM ' Time: 1/1/0001 10:28:30 PM, String: 10:28:30 PM ' Time: 1/1/0001 10:44:00 PM, String: 10:44:00 PM ' Time: 1/1/0001 10:59:30 PM, String: 10:59:30 PM ' Time: 1/1/0001 11:15:00 PM, String: 11:15:00 PM ' Time: 1/1/0001 11:30:30 PM, String: 11:30:30 PM ' Time: 1/1/0001 11:46:00 PM, String: 11:46:00 PM |
4. Descending Time Range – Hourly Interval – Include Full Hour
The example below demonstrates the use of ‘Utils.DateVal.GetTimeRange‘ to get the time range with a hourly interval in descending order.
In this example, the optional parameter is used, which includes the full starting hour from the results.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
' Descending Time Range - Hourly Interval - Include Full Hour ' Get an hour range from 10PM - 10AM, with a 2 hour interval Dim result = Utils.DateVal.GetTimeRange(22, 10, 120, True) For Each value In result Debug.Print($"Time: {value.Time}, String: {value.ToString(True)}") Next ' expected output: ' Time: 1/1/0001 10:59:00 PM, String: 10:59 PM ' Time: 1/1/0001 8:59:00 PM, String: 8:59 PM ' Time: 1/1/0001 6:59:00 PM, String: 6:59 PM ' Time: 1/1/0001 4:59:00 PM, String: 4:59 PM ' Time: 1/1/0001 2:59:00 PM, String: 2:59 PM ' Time: 1/1/0001 12:59:00 PM, String: 12:59 PM ' Time: 1/1/0001 10:59:00 AM, String: 10:59 AM |
5. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 26, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Class DateVal Public Property Time As Date Protected showSeconds As Boolean = False Public Shadows Function ToString(Optional condensed As Boolean = False) As String Dim str = Time.ToShortTimeString If condensed Then str = str.Replace(":00", String.Empty) ElseIf showSeconds Then str = Time.ToString("h:mm:ss tt") End If Return str End Function ''' <summary> ''' Generates a time value list containing the time from 'Starting Hour' ''' to 'Ending Hour' separated by 'Minute Step'. 'Starting Hour' and 'Ending Hour' ''' should be an integer from 0 through 23 representing the hour of the day. ''' </summary> ''' <param name="startingHour">The starting hour from 0 through 23</param> ''' <param name="endingHour">The ending hour from 0 through 23</param> ''' <param name="minuteStep">The minute step</param> ''' <param name="includeFullHour">If going in ascending direction, indicates ''' the results should include the entire 'Ending Hour'. If going in descending ''' direction, indicates the results should include the entire 'Starting Hour'</param> ''' <returns>The objects property data</returns> Public Shared Function GetTimeRange(startingHour As Integer, endingHour As Integer _ , minuteStep As Double, Optional includeFullHour As Boolean = False) As List(Of DateVal) Dim result = New List(Of DateVal) Dim maxHour = 23 Dim minHour = 0 Dim maxMinute = 59 Dim minMinute = 0 Dim startingMinute = minMinute Dim endingMinute = maxMinute Dim showSeconds = Int(minuteStep) <> minuteStep If minuteStep < 0 Then minuteStep = 1 ' Flip results if going in opposite direction If startingHour > endingHour Then minuteStep *= -1 startingMinute = maxMinute endingMinute = minMinute startingHour = Math.Min(startingHour, maxHour) endingHour = Math.Max(endingHour, minHour) Else startingHour = Math.Max(startingHour, minHour) endingHour = Math.Min(endingHour, maxHour) End If If Not includeFullHour Then startingMinute = 0 endingMinute = 0 End If Dim today = Date.Today Dim startTime = today.AppendTime(TimeValue($"{Format(startingHour, "00")}:{Format(startingMinute, "00")}")) Dim endTime = today.AppendTime(TimeValue($"{Format(endingHour, "00")}:{Format(endingMinute, "00")}")) Dim currentTime = startTime While If(startingHour < endingHour, currentTime <= endTime, currentTime >= endTime) result.Add(New DateVal With { .Time = TimeValue(currentTime.ToString), .showSeconds = showSeconds }) currentTime = currentTime.AddMinutes(minuteStep) End While Return result End Function End Class ' Appends a date and time value together <Runtime.CompilerServices.Extension()> Public Function AppendTime([date] As Date, time As Date) As Date Return [date].Date.Add(time.TimeOfDay) End Function End Module End Namespace ' http://programmingnotes.org/ |
6. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 26, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Public Module Program Sub Main(args As String()) Try ' Get an hour range from 12AM - 11PM, with a 15 and half minute interval Dim result = Utils.DateVal.GetTimeRange(0, 23, 15.5) For Each value In result Display($"Time: {value.Time}, String: {value.ToString}") Next Display("") ' Get an hour range from 10PM - 10AM, with a 2 hour interval Dim result2 = Utils.DateVal.GetTimeRange(22, 10, 120) For Each value In result2 Display($"Time: {value.Time}, String: {value.ToString(True)}") Next Display("") ' Get an hour range from 12AM - 11PM, with a 15 and half minute interval Dim result3 = Utils.DateVal.GetTimeRange(0, 23, 15.5, True) For Each value In result3 Display($"Time: {value.Time}, String: {value.ToString}") Next Display("") ' Get an hour range from 10PM - 10AM, with a 2 hour interval Dim result4 = Utils.DateVal.GetTimeRange(22, 10, 120, True) For Each value In result4 Display($"Time: {value.Time}, String: {value.ToString(True)}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Add & Use Custom Attributes To Class Properties Using VB.NET

The following is a module with functions which demonstrates how to add and use custom attributes for class properties using VB.NET.
The function demonstrated on this page is a generic extension method which uses reflection to get object property data transformed according to its custom attribute.
1. Custom Attribute
The example below demonstrates the use of ‘Utils.GetPropertyData‘ to get object property data transformed according to its custom attribute.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 |
' Custom Attribute Imports Utils ' Create custom attribute class Public Class DateFormatAttribute Inherits System.Attribute Public Property format As DateFormat End Class ' An enum to describe the custom attribute options Public Enum DateFormat [Default] ToLongDateString ToLongTimeString ToShortDateString ToShortTimeString End Enum ' Class that has a property that uses the custom attribute Public Class User <DateFormatAttribute(format:=DateFormat.ToShortDateString)> Public Property registered As Date Public Property name As String End Class ' Declare user Dim user = New User With { .name = "Kenneth", .registered = Date.Now } ' Get the properties with the processed attribute Dim result = user.GetPropertyData ' Display Info For Each prop In result Debug.Print($"Property: {prop.Key}, Value: {prop.Value}") Next ' expected output: ' Property: registered, Value: 11/25/2020 ' Property: name, Value: Kenneth |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 25, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Class DateFormatAttribute Inherits System.Attribute Public Property format As DateFormat End Class Public Enum DateFormat [Default] ToLongDateString ToLongTimeString ToShortDateString ToShortTimeString End Enum ''' <summary> ''' Returns an objects property data with the data transformed ''' according to its attributes ''' </summary> ''' <returns>The objects property data</returns> <Runtime.CompilerServices.Extension()> Public Function GetPropertyData(Of T As {Class})(source As T) As Dictionary(Of String, Object) Dim result = New Dictionary(Of String, Object) Dim flags = System.Reflection.BindingFlags.Instance Or System.Reflection.BindingFlags.Public Dim properties = source.GetType.GetProperties(flags) For Each prop In properties Dim key = prop.Name Dim value = If(prop.CanRead, prop.GetValue(source _ , If(prop.GetIndexParameters.Count = 1, New Object() {Nothing}, Nothing)), Nothing) ' Get custom attributes for the property Dim customAttributes = Attribute.GetCustomAttributes(prop) For Each attribute In customAttributes If attribute.GetType.Equals(GetType(DateFormatAttribute)) Then Dim dateValue = CType(value, Date) Select Case CType(attribute, DateFormatAttribute).format Case DateFormat.ToLongDateString value = dateValue.ToLongDateString Case DateFormat.ToLongTimeString value = dateValue.ToLongTimeString Case DateFormat.ToShortDateString value = dateValue.ToShortDateString Case DateFormat.ToShortTimeString value = dateValue.ToShortTimeString Case Else value = dateValue.ToString End Select End If Next result.Add(key, value) Next Return result End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 25, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Public Module Program Public Class User <DateFormatAttribute(format:=DateFormat.ToShortDateString)> Public Property registered As Date Public Property name As String End Class Sub Main(args As String()) Try Dim user = New User With { .name = "Kenneth", .registered = Date.Now } ' Get the properties with the processed attribute Dim result = user.GetPropertyData For Each prop In result Display($"Property: {prop.Key}, Value: {prop.Value}") Next Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Remove Excess Whitespace From A String Using VB.NET

The following is a module with functions which demonstrates how to remove excess whitespace from a string, replacing multiple spaces into just one using VB.NET.
1. Remove Excess Whitespace
The example below demonstrates the use of ‘Utils.ToSingleSpace‘ to remove excess whitespace from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
' Remove Excess Whitespace Imports Utils Dim word = " This document uses 3 other documents " ' Creates single space string Dim result = word.ToSingleSpace Debug.Print(result) ' expected output: ' This document uses 3 other documents |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 24, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Removes excess whitespace from a string ''' </summary> ''' <param name="source">The source string</param> ''' <returns>The modified source string</returns> <Runtime.CompilerServices.Extension()> Public Function ToSingleSpace(source As String) As String Dim pattern = "\s\s+" Dim result = System.Text.RegularExpressions.Regex.Replace(source, pattern, " ").Trim Return result End Function End Module End Namespace ' http://programmingnotes.org/ |
3. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 24, 2020 ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace. ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Public Module Program Sub Main(args As String()) Try Dim word = " This document uses 3 other documents " ' Creates single space string Dim result = word.ToSingleSpace Display(result) Catch ex As Exception Display(ex.ToString) Finally Console.ReadLine() End Try End Sub Public Sub Display(message As String) Console.WriteLine(message) Debug.Print(message) End Sub End Module ' http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
VB.NET || How To Remove All Whitespace From A String Using VB.NET

The following is a module with functions which demonstrates how to remove all whitespace from a string using VB.NET.
1. Remove All Whitespace
The example below demonstrates the use of ‘Utils.RemoveWhitespace‘ to remove all whitespace from a string.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
' Remove All Whitespace Imports Utils Dim word = "This document uses 3 other documents " ' Remove whitespace from the string Dim result = word.RemoveWhitespace Debug.Print(result) ' expected output: ' Thisdocumentuses3otherdocuments |
2. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
' ============================================================================ ' Author: Kenneth Perkins ' Taken From: http://programmingnotes.org/ ' Date: Nov 24, 2020 ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Removes all whitespace from a string ''' </summary> ''' <param name="source">The source string</param> ''' <returns>The modified source string</returns> <Runtime.CompilerServices.Extension()> Public Function RemoveWhitespace(source As String) As String & |