Monthly Archives: November 2020
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 ' Date: Nov 30, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ' Date: Nov 30, 2020 ' Taken From: http://programmingnotes.org/ ' 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 Debug.Print($"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 ' Date: Nov 30, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ''' </summary> ''' <param name="length">The length of the random string</param> ''' <param name="type">The type of string to generate</param> ''' <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 ' Date: Nov 30, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ' Date: Nov 30, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ''' </summary> ''' <param name="directory">The relative or absolute path to the directory to search</param> ''' <param name="searchOption">The file search option</param> ''' <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 ' Date: Nov 30, 2020 ' Taken From: http://programmingnotes.org/ ' 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 Get The Computer & User Client IP Address Using VB.NET
The following is a module with functions which demonstrates how to get the computers and user client request IPv4 IP address using VB.NET.
The function demonstrated on this page returns the IPv4 address of the calling user. When under a web environment, it returns the clients System.Web.HttpContext.Current.Request IP address, otherwise it returns the IP address of the local machine (i.e: server) if there is no request.
The following function uses System.Web to determine the IP address of the client.
Note: To use the function in this module, make sure you have a reference to ‘System.Web‘ 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 ‘Add Reference‘, then type ‘System.Web‘ in the search box, and add the reference titled System.Web in the results Tab.
1. Get IP Address
The example below demonstrates the use of ‘Utils.GetIPv4Address‘ to get the IPv4 address of the calling user.
1 2 3 4 5 6 7 8 9 |
' Get IP Address ' Get IP address of the current user Dim ipAddress = Utils.GetIPv4Address Debug.Print($"IP Address: {ipAddress}") ' example output: ' IP Address: 192.168.0.5 |
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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 29, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Returns the IPv4 address of the calling user. When under a web ''' environment, returns the <see cref="System.Web.HttpRequest"/> ''' IP address, otherwise returns the IP address of the local machine ''' </summary> ''' <returns>The IPv4 address of the calling user</returns> Public Function GetIPv4Address() As String Dim ipAddress = String.Empty ' Get client ip address If System.Web.HttpContext.Current IsNot Nothing _ AndAlso System.Web.HttpContext.Current.Request IsNot Nothing Then ' Get client ip address using ServerVariables Dim request = System.Web.HttpContext.Current.Request ipAddress = request.ServerVariables("HTTP_X_FORWARDED_FOR") If Not String.IsNullOrEmpty(ipAddress) Then Dim addresses = ipAddress.Split(",".ToCharArray, StringSplitOptions.RemoveEmptyEntries) If addresses.Length > 0 Then ipAddress = addresses(0) End If End If If String.IsNullOrEmpty(ipAddress) Then ipAddress = request.ServerVariables("REMOTE_ADDR") End If ' Get client ip address using UserHostAddress If String.IsNullOrEmpty(ipAddress) Then Dim clientIPA = GetNetworkAddress(request.UserHostAddress) If clientIPA IsNot Nothing Then ipAddress = clientIPA.ToString End If End If End If ' Get local machine ip address If String.IsNullOrEmpty(ipAddress) Then Dim loacalIPA = GetNetworkAddress(System.Net.Dns.GetHostName) If loacalIPA IsNot Nothing Then ipAddress = loacalIPA.ToString End If End If Return ipAddress End Function Private Function GetNetworkAddress(addresses As String) As System.Net.IPAddress Return System.Net.Dns.GetHostAddresses(addresses) _ .FirstOrDefault(Function(x) x.AddressFamily = System.Net.Sockets.AddressFamily.InterNetwork) 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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 29, 2020 ' Taken From: http://programmingnotes.org/ ' 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 IP address of the current user Dim ipAddress = Utils.GetIPv4Address Display($"IP Address: {ipAddress}") 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 ' Date: Nov 29, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ' Date: Nov 29, 2020 ' Taken From: http://programmingnotes.org/ ' 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.QRCode.Create‘ 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 = "https://www.programmingnotes.org/" ' Encode data to a QR code byte array Dim bytes = Utils.QRCode.Create(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.QRCode.Read‘ 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 data = Utils.QRCode.Read(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 59 60 61 62 63 64 65 66 67 68 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 28, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Namespace QRCode Public Module modQRCode ''' <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 Create(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 Read(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 With { .AutoRotate = True, .TryInverted = True, .Options = New ZXing.Common.DecodingOptions With { .TryHarder = True, .PossibleFormats = New ZXing.BarcodeFormat() { ZXing.BarcodeFormat.QR_CODE } } } 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 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 ' Date: Nov 28, 2020 ' Taken From: http://programmingnotes.org/ ' 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 = "https://www.programmingnotes.org/" ' Encode data to a QR code byte array Dim bytes = Utils.QRCode.Create(data) Display($"Length: {bytes.Length}") ' Decode QR code to a string Dim result = Utils.QRCode.Read(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.SetTime‘ 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.SetTime(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 ' Date: Nov 27, 2020 ' Taken From: http://programmingnotes.org/ ' 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 SetTime([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 ' Date: Nov 27, 2020 ' Taken From: http://programmingnotes.org/ ' 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.SetTime(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.DateRange.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.DateRange.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.DateRange.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.DateRange.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.DateRange.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.DateRange.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.DateRange.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.DateRange.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 ' Date: Nov 26, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils Public Class DateRange 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 time value list from 'Starting Hour' to 'Ending Hour'</returns> Public Shared Function GetTimeRange(startingHour As Integer, endingHour As Integer _ , minuteStep As Double, Optional includeFullHour As Boolean = False) As List(Of DateRange) Dim result = New List(Of DateRange) 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.SetTime(TimeValue($"{Format(startingHour, "00")}:{Format(startingMinute, "00")}")) Dim endTime = today.SetTime(TimeValue($"{Format(endingHour, "00")}:{Format(endingMinute, "00")}")) Dim currentTime = startTime While If(startingHour < endingHour, currentTime <= endTime, currentTime >= endTime) result.Add(New DateRange 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 SetTime([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 ' Date: Nov 26, 2020 ' Taken From: http://programmingnotes.org/ ' 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.DateRange.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.DateRange.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.DateRange.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.DateRange.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 ' Date: Nov 25, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ' Date: Nov 25, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' 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 ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' 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 14 15 16 |
' 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 ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' 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 Dim pattern = "\s" Dim result = System.Text.RegularExpressions.Regex.Replace(source, pattern, String.Empty) 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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Module Program Sub Main(args As String()) Try Dim word = "This document uses 3 other documents " ' Remove whitespace from the string Dim result = word.RemoveWhitespace 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 Non Alphanumeric Characters From A String Using VB.NET
The following is a module with functions which demonstrates how to remove and replace non alphanumeric characters from a string using VB.NET.
1. Alphanumeric Characters
The example below demonstrates the use of ‘Utils.ToAlphaNumeric‘ to create an alphanumeric string.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
' Alphanumeric Characters Imports Utils Dim word = "This-document_uses-3#other@documents!!!" ' Create alpha numeric string Dim result = word.ToAlphaNumeric 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 26 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Returns the string as alphanumeric ''' </summary> ''' <param name="source">The source string</param> ''' <param name="replacement">The string replacement for invalid characters</param> ''' <returns>The modified source string</returns> <Runtime.CompilerServices.Extension()> Public Function ToAlphaNumeric(source As String, Optional replacement As String = " ") As String Dim pattern = "[^a-zA-Z0-9]+" Dim result = System.Text.RegularExpressions.Regex.Replace(source, pattern, replacement).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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Module Program Sub Main(args As String()) Try Dim word = "This-document_uses-3#other@documents!!!" ' Create alpha numeric string Dim result = word.ToAlphaNumeric 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 Replace Entire Words In A String Using VB.NET
The following is a module with functions which demonstrates how to replace entire words in a string using VB.NET.
This function is different from String.Replace in that instead of replacing all substring instances in a word, it replaces all instances of matching entire words in a string.
1. Replace Entire Word
The example below demonstrates the use of ‘Utils.ReplaceWord‘ to replace an entire word.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
' Replace Entire Word Imports Utils Dim word = "This docment uses 3 other docments to docment the docmentation" ' Replace the entire word in the string Dim result = word.ReplaceWord("docment", "document") Debug.Print(result) ' expected output: ' This document uses 3 other docments to document the docmentation |
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 ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Replaces the entire word in the string ''' </summary> ''' <param name="source">The source string</param> ''' <param name="wordToReplace">The word to replace</param> ''' <param name="replacementWord">The replacement word</param> ''' <param name="regexOptions">The search options</param> ''' <returns>The modified source string</returns> <Runtime.CompilerServices.Extension()> Public Function ReplaceWord(source As String, wordToReplace As String, replacementWord As String _ , Optional regexOptions As System.Text.RegularExpressions.RegexOptions = System.Text.RegularExpressions.RegexOptions.None) As String Dim pattern = $"\b{System.Text.RegularExpressions.Regex.Escape(wordToReplace)}\b" Dim result = System.Text.RegularExpressions.Regex.Replace(source, pattern, replacementWord, regexOptions) 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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Imports Utils Module Program Sub Main(args As String()) Try Dim word = "This docment uses 3 other docments to docment the docmentation" ' Replace the entire word in the string Dim result = word.ReplaceWord("docment", "document") 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 Manually Copy Two Streams From One To Another Using VB.NET
The following is a module with functions which demonstrates how to manually copy two steams from one to another using VB.NET.
1. Manually Copy Stream
The example below demonstrates the use of ‘Utils.CopyStream‘ to copy two streams.
1 2 3 4 5 6 7 |
' Manually Copy Stream Dim stream1 As System.IO.Stream Dim stream2 As System.IO.Stream ' Copy stream1 to stream2 Utils.CopyStream(stream1, stream2) |
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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Utils.vb ' Description: Handles general utility functions ' ============================================================================ Option Strict On Option Explicit On Namespace Global.Utils Public Module modUtils ''' <summary> ''' Reads bytes from the 'streamFrom' and writes them to 'streamTo' ''' </summary> ''' <param name="streamFrom">The source stream</param> ''' <param name="streamTo">The destination stram</param> ''' <returns>The total bytes written</returns> <Runtime.CompilerServices.Extension()> Public Function CopyStream(streamFrom As System.IO.Stream, streamTo As System.IO.Stream, Optional bufferSize As Integer = 4096) As Integer Dim bytesWritten As Integer = 0 Dim bytBuffer(bufferSize - 1) As Byte Dim bytesRead As Integer = 0 Dim tempPos = If(streamFrom.CanSeek, CType(streamFrom.Position, Integer?), Nothing) If streamFrom.CanSeek Then streamFrom.Position = 0 Do bytesRead = streamFrom.Read(bytBuffer, 0, bytBuffer.Length) If bytesRead > 0 Then streamTo.Write(bytBuffer, 0, bytesRead) bytesWritten += bytesRead End If Loop While bytesRead > 0 If tempPos.HasValue Then streamFrom.Position = tempPos.Value Return bytesWritten 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 |
' ============================================================================ ' Author: Kenneth Perkins ' Date: Nov 24, 2020 ' Taken From: http://programmingnotes.org/ ' File: Program.vb ' Description: The following demonstrates the use of the Utils Namespace ' ============================================================================ Option Strict On Option Explicit On Imports System Module Program Sub Main(args As String()) Try Dim stream1 As System.IO.Stream Dim stream2 As System.IO.Stream ' Copy stream1 to stream2 Utils.CopyStream(stream1, stream2) 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.