/Library/EXTENSIONS/StringExtensions.vb
Visual Basic | 1446 lines | 805 code | 211 blank | 430 comment | 0 complexity | 4087620bb50c7ca76bcc7baf5c351968 MD5 | raw file
Large files files are truncated, but you can click here to view the full file
- Imports System
- Imports System.Globalization
- Imports System.ComponentModel
- Imports System.Runtime.CompilerServices
- Namespace StringExtensions
- ''' <summary>
- ''' Includes extensions for strings.
- ''' </summary>
- ''' <remarks></remarks>
- ''' <license>
- ''' (c) 2010 Integrated Scientific Resources, Inc.
- ''' Licensed under the Apache License Version 2.0.
- ''' Unless required by applicable law or agreed to in writing, this software is provided
- ''' "AS IS", WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ''' </license>
- ''' <history date="04/09/2009" by="David Hary" revision="1.1.3386.x">
- ''' Created
- ''' </history>
- Public Module [Extensions]
- #Region " STRING MANIPULATION "
- ''' <summary>
- ''' Returns the right most <paramref name="count"></paramref> characters
- ''' from the string.
- ''' </summary>
- ''' <param name="value">The string being chopped</param>
- ''' <param name="count">The number of
- ''' characters to return.</param>
- ''' <returns>A string containing the right most characters
- ''' in this string.</returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Right(ByVal value As String, ByVal count As Integer) As String
- If String.IsNullOrEmpty(value) OrElse value.Length <= count Then Return value
- Return value.Substring(value.Length - count)
- End Function
- ''' <summary>
- ''' Returns the left most <paramref name="count"></paramref> characters
- ''' from the string.
- ''' </summary>
- ''' <param name="value">The string being chopped</param>
- ''' <param name="count">The number of
- ''' characters to return.</param>
- ''' <returns>A string containing the left most characters
- ''' in this string.</returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Left(ByVal value As String, ByVal count As Integer) As String
- If String.IsNullOrEmpty(value) OrElse value.Length <= count Then Return value
- Return value.Substring(0, count)
- End Function
- ''' <summary>
- ''' Removes the left characters.
- ''' </summary>
- ''' <param name="value">The string.</param>
- ''' <param name="count">The count.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function RemoveLeft(ByVal value As String, ByVal count As Integer) As String
- If String.IsNullOrEmpty(value) OrElse value.Length <= count Then Return ""
- Return value.Substring(count)
- End Function
- ''' <summary>
- ''' Removes the right characters.
- ''' </summary>
- ''' <param name="value">The string.</param>
- ''' <param name="count">The count.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function RemoveRight(ByVal value As String, ByVal count As Integer) As String
- If String.IsNullOrEmpty(value) OrElse value.Length <= count Then Return ""
- Return value.Substring(0, value.Length - count)
- End Function
- #End Region
- #Region " STRING NUMERIC METHODS "
- ''' <summary>Returns true if the string represents a floating number.</summary>
- ''' <param name="value">Specifies the floating number candidate.</param>
- <Extension()> _
- Public Function IsFloat(ByVal value As String) As Boolean
- Dim a As Double
- Return System.Double.TryParse(value, Globalization.NumberStyles.Float, System.Globalization.CultureInfo.CurrentCulture, a)
- End Function
- ''' <summary>Returns true if the string represents a whole number.</summary>
- ''' <param name="value">Specifies the integer candidate.</param>
- <Extension()> _
- Public Function IsInteger(ByVal value As String) As Boolean
- Dim a As Double
- Return System.Double.TryParse(value, Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.CurrentCulture, a)
- End Function
- ''' <summary>Returns true if the string represents any number.</summary>
- ''' <param name="value">Specifies the number candidate.</param>
- <Extension()> _
- Public Function IsNumber(ByVal value As String) As Boolean
- Dim a As Double
- Return System.Double.TryParse(value, Globalization.NumberStyles.Number _
- Or Globalization.NumberStyles.AllowExponent, _
- System.Globalization.CultureInfo.CurrentCulture, a)
- End Function
- ''' <summary>Returns true if the string represents any number.</summary>
- ''' <param name="value">Specifies the number candidate.</param>
- <Extension()> _
- Public Function IsNumeric(ByVal value As String) As Boolean
- Return value.IsNumber()
- End Function
- #End Region
- #Region " STRING CONTENTS METHODS "
- ''' <summary>
- ''' Replaces the given <paramref name="characters">characters</paramref> with the
- ''' <paramref name="replacing">new characters.</paramref>
- ''' </summary>
- ''' <param name="source">The original string</param>
- ''' <param name="characters">The characters to be replaced</param>
- ''' <param name="replacing">The new characters.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Replace(ByVal source As String, ByVal characters As String, ByVal replacing As Char) As String
- If String.IsNullOrEmpty(source) Then
- Throw New ArgumentNullException("source")
- End If
- If String.IsNullOrEmpty(characters) Then
- Throw New ArgumentNullException("characters")
- End If
- If String.IsNullOrEmpty(replacing) Then
- Throw New ArgumentNullException("replacing")
- End If
- For Each c As Char In characters.ToCharArray
- source = source.Replace(c, replacing)
- Next
- Return source
- End Function
- Public Const IllegalFileCharacters As String = "/\\:*?""<>|"
- ''' <summary>Returns True if the validated string contains only alpha characters.</summary>
- ''' <param name="source">The string to validate.</param>
- <Extension()> _
- Public Function IncludesIllegalFileCharacters(ByVal source As String) As Boolean
- Return source.IncludesCharacters(IllegalFileCharacters)
- End Function
- ''' <summary>Returns true if the string includes the specified characters.</summary>
- ''' <param name="source">The string that is being searched.</param>
- ''' <param name="characters">The characters to search for.</param>
- <Extension()> _
- Public Function IncludesCharacters(ByVal source As String, ByVal characters As String) As Boolean
- If source Is Nothing Then
- Throw New ArgumentNullException("source")
- End If
- If characters Is Nothing Then
- Throw New ArgumentNullException("characters")
- End If
- Dim expression As String = String.Format(System.Globalization.CultureInfo.CurrentCulture, "[{0}]", characters)
- Dim r As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex( _
- expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
- Return r.IsMatch(source)
- End Function
- ''' <summary>Returns true if the string includes any of the specified characters.</summary>
- ''' <param name="source">The string that is being searched.</param>
- ''' <param name="characters">The characters to search for.</param>
- <Extension()> _
- Public Function IncludesAny(ByVal source As String, ByVal characters As String) As Boolean
- If source Is Nothing Then
- Throw New ArgumentNullException("source")
- End If
- If characters Is Nothing Then
- Throw New ArgumentNullException("characters")
- End If
- ' 2954: was ^[{0}]+$
- Dim expression As String = String.Format(System.Globalization.CultureInfo.CurrentCulture, "[{0}]", characters)
- Dim r As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex( _
- expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
- Return r.IsMatch(source)
- End Function
- ''' <summary>Returns True if the validated string contains only alpha characters.</summary>
- ''' <param name="value">The string to validate.</param>
- <Extension()> _
- Public Function ConsistsOfAlphaCharacters(ByVal value As String) As Boolean
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- ElseIf String.IsNullOrEmpty(value) Then
- Return False
- End If
- Dim r As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex("^[a-z]+$", _
- Text.RegularExpressions.RegexOptions.IgnoreCase)
- Return r.IsMatch(value)
- End Function
- ''' <summary>Returns True if the validated string contains only alpha characters.</summary>
- ''' <param name="value">The string to validate.</param>
- <Extension()> _
- Public Function ConsistsOfNumbers(ByVal value As String) As Boolean
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- ElseIf String.IsNullOrEmpty(value) Then
- Return False
- End If
- Dim r As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex("^[0-9]+$", _
- Text.RegularExpressions.RegexOptions.IgnoreCase)
- Return r.IsMatch(value)
- End Function
- ''' <summary>
- ''' Reverse the string from http://en.wikipedia.org/wiki/Extension_method
- ''' </summary>
- ''' <param name="value"></param>
- ''' <returns></returns>
- <Extension()> _
- Public Function Reverse(ByVal value As String) As String
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- ElseIf String.IsNullOrEmpty(value) Then
- Return value
- End If
- Dim chars As Char() = value.ToCharArray()
- Array.Reverse(chars)
- Return New String(chars)
- End Function
- #End Region
- #Region " COMPACT "
- ''' <summary>
- ''' Compacts the string to permit display within the given width.
- ''' For example, using <see cref="Windows.Forms.TextFormatFlags.PathEllipsis">Path Ellipsis</see>
- ''' as the <paramref name="formatInstruction">format instruction</paramref>
- ''' the string 'c:\program files\test app\runme.exe' might turn
- ''' into 'c:\program files\...\runme.exe' depending on the font and width.
- ''' </summary>
- ''' <param name="value">Specified the string to compact.</param>
- ''' <param name="width">Specifes the width</param>
- ''' <param name="font">Specifies the <see cref="Drawing.Font">font</see></param>
- ''' <param name="formatInstruction">Specifies the designed
- ''' <see cref="Windows.Forms.TextFormatFlags">formatting</see></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Compact(ByVal value As String, ByVal width As Integer, _
- ByVal font As Drawing.Font, ByVal formatInstruction As Windows.Forms.TextFormatFlags) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- End If
- If font Is Nothing Then
- Throw New ArgumentNullException("font")
- End If
- If width <= 0 Then
- Throw New ArgumentOutOfRangeException("width", width, "Must be non-zero")
- End If
- Dim result As String = String.Copy(value)
- System.Windows.Forms.TextRenderer.MeasureText(result, font, New Drawing.Size(width, font.Height), formatInstruction Or formatInstruction Or Windows.Forms.TextFormatFlags.ModifyString)
- Return result
- End Function
- ''' <summary>
- ''' Compacts the string to permit display within the given width.
- ''' For example, the string 'c:\program files\test app\runme.exe' might turn
- ''' into 'c:\program files\...\runme.exe' depending on the font and width.
- ''' </summary>
- ''' <param name="value">Specified the string to compact.</param>
- ''' <param name="width">Specifes the width</param>
- ''' <param name="font">Specifies the <see cref="Drawing.Font">font</see></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Compact(ByVal value As String, ByVal width As Integer, _
- ByVal font As Drawing.Font) As String
- Return value.Compact(width, font, Windows.Forms.TextFormatFlags.PathEllipsis)
- End Function
- ''' <summary>
- ''' Compacts the string to permit display within the given control.
- ''' For example, using <see cref="Windows.Forms.TextFormatFlags.PathEllipsis">Path Ellipsis</see>
- ''' as the <paramref name="formatInstruction">format instruction</paramref>
- ''' the string 'c:\program files\test app\runme.exe' might turn
- ''' into 'c:\program files\...\runme.exe' depending on the font and width.
- ''' </summary>
- ''' <param name="value">Specifies the text</param>
- ''' <param name="control">Specifies the control control within which to format the text.</param>
- ''' <param name="formatInstruction">Specifies the designed
- ''' <see cref="Windows.Forms.TextFormatFlags">formatting</see></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Compact(ByVal value As String, _
- ByVal control As System.Windows.Forms.Control, _
- ByVal formatInstruction As Windows.Forms.TextFormatFlags) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- End If
- If control Is Nothing Then
- Throw New ArgumentNullException("control")
- End If
- Return value.Compact(control.Width, control.Font, formatInstruction)
- End Function
- ''' <summary>
- ''' Compacts the string to permit display within the given control.
- ''' For example, the string 'c:\program files\test app\runme.exe' might turn
- ''' into 'c:\program files\...\runme.exe' depending on the font and width.
- ''' </summary>
- ''' <param name="value">Specified the string to compact.</param>
- ''' <param name="ctrl">Specifes the control receiving the string</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function Compact(ByVal value As String, ByVal ctrl As Windows.Forms.Control) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- End If
- If ctrl Is Nothing Then
- Throw New ArgumentNullException("ctrl")
- End If
- Return value.Compact(ctrl, Windows.Forms.TextFormatFlags.PathEllipsis)
- End Function
- #End Region
- #Region " CONTAINS "
- ''' <summary>
- ''' Returns true if the find string is in the search string.
- ''' </summary>
- ''' <param name="search">The item to search.</param>
- ''' <param name="find">The the item to find.</param>
- ''' <param name="comparisonType">Type of the comparison.</param><returns></returns>
- <Extension()> _
- Public Function Contains(ByVal search As String, ByVal find As String, ByVal comparisonType As StringComparison) As Boolean
- Return Location(search, find, comparisonType) >= 0
- End Function
- ''' <summary>
- ''' Returns the location of the find string in the search string.
- ''' </summary>
- ''' <param name="search">The item to search.</param>
- ''' <param name="find">The the item to find.</param>
- ''' <param name="comparisonType">Type of the comparison.</param><returns></returns>
- <Extension()> _
- Public Function Location(ByVal search As String, ByVal find As String, ByVal comparisonType As StringComparison) As Integer
- If String.IsNullOrEmpty(search) Then Return 0
- Return search.IndexOf(find, comparisonType)
- End Function
- #End Region
- #Region " SUBSTRING "
- ''' <summary>Returns a substring of the input string taking not of start index and length
- ''' exceptions.</summary>
- ''' <param name="value">The input string to sub string.</param>
- ''' <param name="startIndex">The zero bbased starting index.</param>
- ''' <param name="length">The total length.</param>
- <Extension()> _
- Public Function SafeSubstring(ByVal value As String, ByVal startIndex As Integer, ByVal length As Integer) As String
- If String.IsNullOrEmpty(value) OrElse length <= 0 Then
- Return ""
- End If
- Dim inputLength As Integer = value.Length
- If startIndex > inputLength Then
- Return ""
- Else
- If startIndex + length > inputLength Then
- length = inputLength - startIndex
- End If
- Return value.Substring(startIndex, length)
- End If
- End Function
- ''' <summary>Returns the substring after the last occurrence of the specified string</summary>
- ''' <param name="source">The string to substring.</param>
- ''' <param name="search">The string to search for.</param>
- <Extension()> _
- Public Function SubstringAfter(ByVal source As String, ByVal search As String) As String
- If String.IsNullOrEmpty(source) Then
- Return ""
- End If
- If String.IsNullOrEmpty(search) Then
- Return ""
- End If
- Dim location As Integer = source.LastIndexOf(search, StringComparison.OrdinalIgnoreCase)
- If location >= 0 Then
- If location + search.Length < source.Length Then
- Return source.Substring(location + search.Length)
- Else
- Return ""
- End If
- Else
- Return ""
- End If
- End Function
- ''' <summary>Returns the substring before the last occurrence of the specified string</summary>
- ''' <param name="source">The string to substring.</param>
- ''' <param name="search">The string to search for.</param>
- <Extension()> _
- Public Function SubstringBefore(ByVal source As String, ByVal search As String) As String
- If String.IsNullOrEmpty(source) Then
- Return ""
- End If
- If String.IsNullOrEmpty(search) Then
- Return ""
- End If
- Dim location As Integer = source.LastIndexOf(search, StringComparison.OrdinalIgnoreCase)
- If location >= 0 Then
- Return source.Substring(0, location)
- Else
- Return ""
- End If
- End Function
- ''' <summary>Returns the substring after the last occurrence of the specified string</summary>
- ''' <param name="source">The string to substring.</param>
- ''' <param name="startDelimiter">The start delimiter to search for.</param>
- ''' <param name="endDelimiter">The end delimiter to search for.</param>
- <Extension()> _
- Public Function SubstringBetween(ByVal source As String, ByVal startDelimiter As String, ByVal endDelimiter As String) As String
- If String.IsNullOrEmpty(source) Then
- Return ""
- End If
- If String.IsNullOrEmpty(startDelimiter) Then
- Return ""
- End If
- Dim startLocation As Integer = source.LastIndexOf(startDelimiter, StringComparison.OrdinalIgnoreCase) + startDelimiter.Length
- Dim endLocation As Integer = source.LastIndexOf(endDelimiter, StringComparison.OrdinalIgnoreCase)
- If startLocation >= 0 AndAlso startLocation < endLocation Then
- Return source.Substring(startLocation, endLocation - startLocation)
- Else
- Return ""
- End If
- End Function
- #End Region
- #Region " COMMON ESCAPE SEQUENCES "
- ''' <summary>
- ''' Replaces common escape strings such as <code>'\n'</code> or <code>'\r'</code>with control
- ''' characters such as <code>10</code> and <code>13</code>, respectively.
- ''' </summary>
- ''' <param name="value">Text including escape sequences.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function ReplaceCommonEscapeSequences(ByVal value As String) As String
- If (value <> Nothing) Then
- Return value.Replace("\n", Convert.ToChar(10)).Replace("\r", Convert.ToChar(13))
- Else
- Return Nothing
- End If
- End Function
- ''' <summary>
- ''' Replaces control characters such as <code>10</code> and <code>13</code> with
- ''' common escape strings such as <code>'\n'</code> or <code>'\r'</code>, respectively.
- ''' </summary>
- ''' <param name="value">Text including control characters.</param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- <Extension()> _
- Public Function InsertCommonEscapeSequences(ByVal value As String) As String
- If (value <> Nothing) Then
- Return value.Replace(Convert.ToChar(10), "\n").Replace(Convert.ToChar(13), "\r")
- Else
- Return Nothing
- End If
- End Function
- #End Region
- #Region " FORMATTING "
- ''' <summary>Returns a centered string.
- ''' </summary>
- ''' <returns>The input string centered with appropriate number of spaces
- ''' on each side.
- ''' </returns>
- ''' <param name="value">Specifies the original string.</param>
- ''' <param name="length">Specifies the total length of the new string</param>
- ''' <history>
- ''' </history>
- <Extension()> _
- Public Function Center(ByVal value As String, ByVal length As Integer) As String
- Dim leftSpacesCount As Double
- Dim rightSpacesCount As Double
- If length <= 0 Then
- Return ""
- ElseIf String.IsNullOrEmpty(value) Then
- Return "".PadLeft(length, " "c)
- ElseIf value.Length > length Then
- Return value.Substring(0, length)
- ElseIf value.Length = length Then
- Return value
- Else
- leftSpacesCount = (length - value.Length) \ 2S
- rightSpacesCount = length - value.Length - leftSpacesCount
- Return "".PadLeft(CInt(leftSpacesCount), " "c) & value _
- & "".PadLeft(CInt(rightSpacesCount), " "c)
- End If
- End Function
- ''' <summary>Returns a left aligned string. If the string is too large, the
- ''' only 'length' values are returned with the last character
- ''' set to '~' to signify the lost character.
- ''' </summary>
- <Extension()> _
- Public Function LeftAlign(ByVal caption As String, ByVal captionWidth As Integer) As String
- Const spaceCharacter As Char = " "c
- Const lostCharacter As Char = "~"c
- ' make sure we have one left space.
- If captionWidth <= 0 Then
- Return ""
- ElseIf String.IsNullOrEmpty(caption) Then
- Return ""
- ElseIf caption.Length > captionWidth Then
- Return caption.Substring(0, captionWidth - 1) & lostCharacter
- ElseIf caption.Length = captionWidth Then
- Return caption
- Else
- Return caption.PadRight(captionWidth, spaceCharacter)
- End If
- End Function
- ''' <summary>Returns a right aligned string. If the string is too large, the
- ''' only 'length' values are returned with the first character
- ''' set to '~' to signify the lost character.
- ''' </summary>
- <Extension()> _
- Public Function RightAlign(ByVal caption As String, ByVal captionWidth As Integer) As String
- Const spaceCharacter As Char = " "c
- Const lostCharacter As Char = "~"c
- ' make sure we have one left space.
- If captionWidth <= 0 Then
- Return ""
- ElseIf String.IsNullOrEmpty(caption) Then
- Return ""
- ElseIf caption.Length > captionWidth Then
- Return lostCharacter & caption.Substring(0, captionWidth - 1)
- ElseIf caption.Length = captionWidth Then
- Return caption
- Else
- Return caption.PadLeft(captionWidth, spaceCharacter)
- End If
- End Function
- #End Region
- #Region " COMPRESSION "
- ''' <summary>
- ''' Returns a compressed value.
- ''' </summary>
- ''' <param name="value"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history>
- ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
- ''' </history>
- <Extension()> _
- Public Function Compress(ByVal value As String) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- Exit Function
- End If
- Dim result As String = ""
- ' Compress the byte array
- Using memoryStream As New System.IO.MemoryStream()
- Using compressedStream As New System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Compress)
- ' Convert the uncompressed string into a byte array
- Dim values As Byte() = System.Text.Encoding.UTF8.GetBytes(value)
- compressedStream.Write(values, 0, values.Length)
- ' Don't FLUSH here - it possibly leads to data loss!
- compressedStream.Close()
- Dim compressedValues As Byte() = memoryStream.ToArray()
- ' Convert the compressed byte array back to a string
- result = System.Convert.ToBase64String(compressedValues)
- memoryStream.Close()
- End Using
- End Using
- Return result
- End Function
- ''' <summary>
- ''' Returns the decompressed string of the value.
- ''' </summary>
- ''' <param name="value"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history>
- ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
- ''' </history>
- ''' <history date="04/09/2009" by="David Hary" revision="1.1.3516.x">
- ''' Bug fix in getting the size. Changed memoryStream.Length - 5 to memoryStream.Length - 4
- ''' </history>
- <Extension()> _
- Public Function Decompress(ByVal value As String) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- Exit Function
- End If
- Dim result As String = ""
- ' Convert the compressed string into a byte array
- Dim compressedValues As Byte() = System.Convert.FromBase64String(value)
- ' Decompress the byte array
- Using memoryStream As New IO.MemoryStream(compressedValues)
- Using compressedStream As New System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Decompress)
- ' it looks like we are getting a bogus size.
- Dim sizeBytes(3) As Byte
- memoryStream.Position = memoryStream.Length - 4
- memoryStream.Read(sizeBytes, 0, 4)
- Dim outputSize As Int32 = BitConverter.ToInt32(sizeBytes, 0)
- memoryStream.Position = 0
- Dim values(outputSize - 1) As Byte
- compressedStream.Read(values, 0, outputSize)
- ' Convert the decompressed byte array back to a string
- result = System.Text.Encoding.UTF8.GetString(values)
- End Using
- End Using
- Return result
- End Function
- #End Region
- #Region " ENCRYPTION "
- <Extension()> _
- Public Function Encrypt(ByVal value As String, ByVal passphrase As String) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- ElseIf String.IsNullOrEmpty(passphrase) Then
- Throw New ArgumentNullException("passphrase")
- End If
- Return System.Convert.ToBase64String(Encrypt(System.Text.Encoding.UTF8.GetBytes(value), passphrase))
- End Function
- ''' <summary>
- ''' Encrypts the byte array using the
- ''' <see cref="System.Security.Cryptography.RijndaelManaged">Rijndael symmetrinc encryption algorithm</see>
- ''' </summary>
- ''' <param name="values"></param>
- ''' <param name="passPhrase"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history>
- ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
- ''' </history>
- Private Function encrypt(ByVal values As Byte(), ByVal passphrase As String) As Byte()
- If values Is Nothing Then
- Return values
- ElseIf String.IsNullOrEmpty(passphrase) Then
- Throw New ArgumentNullException("passphrase")
- End If
- Dim result As Byte() = {}
- Using encryptionAlgorithm As New System.Security.Cryptography.RijndaelManaged
- encryptionAlgorithm.KeySize = 256
- encryptionAlgorithm.Key = encryptionKey(passphrase)
- encryptionAlgorithm.IV = encryptionInitializationVector(passphrase)
- Using memoryStream As New IO.MemoryStream
- Using cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
- encryptionAlgorithm.CreateEncryptor, _
- Security.Cryptography.CryptoStreamMode.Write)
- cryptoStream.Write(values, 0, values.Length)
- cryptoStream.FlushFinalBlock()
- result = memoryStream.ToArray()
- cryptoStream.Close()
- memoryStream.Close()
- End Using
- End Using
- End Using
- Return result
- End Function
- <Extension()> _
- Public Function Decrypt(ByVal value As String, ByVal passphrase As String) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- ElseIf String.IsNullOrEmpty(passphrase) Then
- Throw New ArgumentNullException("passphrase")
- End If
- Return System.Text.Encoding.UTF8.GetString(Decrypt(System.Convert.FromBase64String(value), passphrase))
- End Function
- ''' <summary>
- ''' Decrypts the byte array using the
- ''' <see cref="System.Security.Cryptography.RijndaelManaged">Rijndael symmetrinc encryption algorithm</see>
- ''' </summary>
- ''' <param name="values"></param>
- ''' <param name="passPhrase"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history>
- ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
- ''' </history>
- Private Function decrypt(ByVal values As Byte(), ByVal passphrase As String) As Byte()
- If values Is Nothing Then
- Return values
- ElseIf String.IsNullOrEmpty(passphrase) Then
- Throw New ArgumentNullException("passphrase")
- End If
- Dim result As Byte() = {}
- Using encryptionAlgorithm As New System.Security.Cryptography.RijndaelManaged
- encryptionAlgorithm.KeySize = 256
- encryptionAlgorithm.Key = encryptionKey(passphrase)
- encryptionAlgorithm.IV = encryptionInitializationVector(passphrase)
- Using memoryStream As New IO.MemoryStream(values)
- Using cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
- encryptionAlgorithm.CreateDecryptor, _
- Security.Cryptography.CryptoStreamMode.Read)
- Dim workspace As Byte()
- ReDim workspace(values.Length)
- Dim decryptedByteCount As Integer
- decryptedByteCount = cryptoStream.Read(workspace, 0, values.Length)
- cryptoStream.Close()
- memoryStream.Close()
- ReDim result(decryptedByteCount)
- Array.Copy(workspace, result, decryptedByteCount)
- End Using
- End Using
- End Using
- Return result
- End Function
- ''' <summary>
- ''' Generates a byte array of required length as the encryption key.
- ''' </summary>
- ''' <param name="passPhrase"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history>
- ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
- ''' </history>
- Private Function encryptionKey(ByVal passphrase As String) As Byte()
- If String.IsNullOrEmpty(passphrase) Then
- Throw New ArgumentNullException("passphrase")
- End If
- 'A SHA256 hash of the passphrase has just the required length. It is used twice in a manner of self-salting.
- Using SHA256 As New System.Security.Cryptography.SHA256Managed
- Dim L1 As String = System.Convert.ToBase64String(SHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(passphrase)))
- Dim L2 As String = passphrase & L1
- Return SHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(L2))
- End Using
- End Function
- ''' <summary>
- ''' Generates a byte array of required length as the initialization vector.
- ''' </summary>
- ''' <param name="passPhrase"></param>
- ''' <returns></returns>
- ''' <remarks></remarks>
- ''' <history>
- ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
- ''' </history>
- Private Function encryptionInitializationVector(ByVal passphrase As String) As Byte()
- If String.IsNullOrEmpty(passphrase) Then
- Throw New ArgumentNullException("passphrase")
- End If
- ' A MD5 hash of the passphrase has just the required length. It is used twice in a manner of self-salting.
- Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
- Dim L1 As String = System.Convert.ToBase64String(MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(passphrase)))
- Dim L2 As String = passphrase & L1
- Return MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(L2))
- End Using
- End Function
- #End Region
- #Region " SPLIT TO WORDS "
- ''' <summary>
- ''' Splits the string to words by adding spaces between lower and upper case characters.
- ''' </summary>
- ''' <param name="value">The <c>String</c> value to split.</param>
- ''' <returns>A <c>String</c> of words separated by spaces.</returns>
- <Extension()> _
- Public Function SplitWords(ByVal value As String) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- Else
- Dim isSpace As Boolean = False
- Dim isLowerCase As Boolean = False
- Dim newValue As New System.Text.StringBuilder
- For Each c As Char In value
- If Not isSpace AndAlso isLowerCase AndAlso Char.IsUpper(c) Then
- newValue.Append(" ")
- End If
- isSpace = c.Equals(" "c)
- isLowerCase = Not Char.IsUpper(c)
- newValue.Append(c)
- Next
- Return newValue.ToString()
- End If
- End Function
- #End Region
- #Region " HASH "
- ''' <summary>
- ''' Converts the value to a Base 64 Hash.
- ''' </summary>
- ''' <param name="value">Specifies the value to convert</param>
- ''' <returns></returns>
- ''' <remarks>Uses SHA Crypto service provider.</remarks>
- <Extension()> _
- Public Function ToBase64Hash(ByVal value As String) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- End If
- Using algorithm As New System.Security.Cryptography.SHA1CryptoServiceProvider
- Return ToBase64Hash(value, algorithm)
- End Using
- End Function
- ''' <summary>
- ''' Converts the value to a Base 64 Hash.
- ''' </summary>
- ''' <param name="value">Specifies the value to convert</param>
- ''' <param name="algorithm">Specifies the algorithm for computing the hash.</param>
- ''' <returns></returns>
- ''' <remarks>Uses SHA Crypto service provider.</remarks>
- <Extension()> _
- Public Function ToBase64Hash(ByVal value As String, ByVal algorithm As System.Security.Cryptography.HashAlgorithm) As String
- If String.IsNullOrEmpty(value) Then
- Return ""
- ElseIf algorithm Is Nothing Then
- Return value
- End If
- Dim encoding As New System.Text.UnicodeEncoding
- ' Store the source string in a byte array
- Dim values() As Byte = encoding.GetBytes(value)
- ' get a SHA provider.
- ' Dim provider As New System.Security.Cryptography.SHA1CryptoServiceProvider
- ' Create the hash
- values = algorithm.ComputeHash(values)
- ' return as a base64 encoded string
- Return Convert.ToBase64String(values)
- End Function
- #End Region
- #Region " VALIDATION "
- ''' <summary>
- ''' true, if is valid email address
- ''' from http://www.davidhayden.com/blog/dave/
- ''' archive/2006/11/30/ExtensionMethodsCSharp.aspx
- ''' </summary>
- ''' <param name="value">email address to test</param>
- ''' <returns>true, if is valid email address</returns>
- <Extension()> _
- Public Function IsValidEmailAddress(ByVal value As String) As Boolean
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- ElseIf String.IsNullOrEmpty(value) Then
- Return False
- End If
- Return New Text.RegularExpressions.Regex("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$").IsMatch(value)
- End Function
- ''' <summary>
- ''' from http://www.osix.net/modules/article/?id=586
- '''
- ''' complete (not only http) url regex can be found
- ''' at http://internet.ls-la.net/folklore/url-regexpr.html
- ''' </summary>
- ''' <param name="value"></param>
- ''' <returns></returns>
- <Extension()> _
- Public Function IsValidUrl(ByVal value As String) As Boolean
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- ElseIf String.IsNullOrEmpty(value) Then
- Return False
- End If
- Return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)
- #If False Then
- Dim regularExpression As String = "^(https?://)" _
- & "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" _
- & "(([0-9]{1,3}\.){3}[0-9]{1,3}" _
- & "|" & "([0-9a-z_!~*'()-]+\.)*" _
- & "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." _
- & "[a-z]{2,6})" & "(:[0-9]{1,4})?" & "((/?)|" _
- & "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
- Return New Regex(regularExpression).IsMatch(value)
- #End If
- End Function
- ''' <summary>
- ''' Check if url (http) is available.
- ''' </summary>
- ''' <param name="value">url to check</param>
- ''' <example>
- ''' string url = "www.codeproject.com;
- ''' if( !url.UrlAvailable())
- ''' ...codeproject is not available
- ''' </example>
- ''' <returns>true if available</returns>
- <Extension()> _
- Public Function IsUrlAvailable(ByVal value As String) As Boolean
- ' use URI instead.
- If value Is Nothing Then
- Throw New ArgumentNullException("value")
- ElseIf String.IsNullOrEmpty(value) Then
- Return False
- Else
- Return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)
- End If
- #If False Then
- If (Not value.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) OrElse (Not value.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) Then
- value = "http://" & value
- End If
- Try
- Dim myRequest As Net.HttpWebRequest = CType(Net.WebRequest.Create(value), Net.HttpWebRequest)
- myRequest.Method = "GET"
- myRequest.ContentType = "application/x-www-form-urlencoded"
- Dim myHttpWebResponse As Net.HttpWebResponse = CType(myRequest.GetResponse(), Net.HttpWebResponse)
- Return myHttpWebResponse IsNot Nothing
- Catch
- Return False
- End Try
- #End If
- End Function
- #End Region
- End Module
- ''' <summary>
- ''' Includes extensions for strings.
- ''' </summary>
- ''' <remarks></remarks>
- ''' <license>
- ''' (c) 2009 Elmarg.
- ''' Licensed under The Code Project Open License.
- ''' Unless required by applicable law or agreed to in writing, this software is provided
- ''' "AS IS", WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- ''' </license>
- ''' <history date="04/09/2009" by="David Hary" revision="1.2.3981.x">
- ''' From http://www.codeproject.com/KB/string/stringconversion.aspx
- ''' </history>
- Public Module [ConvertTo]
- #Region " WITH DEFAULT CULTURE "
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails an exception will be raised. Supply a default value to suppress the exception.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")> _
- Public Function ConvertTo(Of T)(ByVal value As String) As T
- Return ConvertTo(Of T)(value, CultureInfo.InvariantCulture)
- End Function
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- Public Function ConvertTo(Of T)(ByVal value As String, ByVal defaultValue As T) As T
- Return ConvertTo(Of T)(value, CultureInfo.InvariantCulture, defaultValue)
- End Function
- #End Region
- #Region " WITH CULTURE AS STRING VALUE "
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails an exception will be raised. Supply a default value to suppress the exception.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")> _
- Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As String) As T
- Return ConvertTo(Of T)(value, CultureInfo.GetCultureInfo(culture))
- End Function
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As String, ByVal defaultValue As T) As T
- Return ConvertTo(Of T)(value, CultureInfo.GetCultureInfo(culture), defaultValue)
- End Function
- #End Region
- #Region " WITH STRONG TYPED CULTURE "
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails an exception will be raised. Supply a default value to suppress the exception.
- ''' </summary>
- ''' <typeparam name="T">The type to return</typeparam>
- ''' <param name="value">The value.</param>
- ''' <param name="culture">The culture.</param>
- ''' <returns></returns>
- <System.Runtime.CompilerServices.Extension()> _
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")> _
- Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As CultureInfo) As T
- Return ConvertTo(Of T)(value, culture, Nothing, True)
- End Function
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As CultureInfo, ByVal defaultValue As T) As T
- Return ConvertTo(Of T)(value, culture, defaultValue, False)
- End Function
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- Public Function ConvertTo(Of T)(ByVal value As String, ByVal styles As NumberStyles, ByVal culture As CultureInfo, ByVal defaultValue As T) As T
- Return ConvertTo(Of T)(value, styles, culture, defaultValue, False)
- End Function
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- Public Function TryParse(Of T)(ByVal value As String, ByVal styles As NumberStyles, ByVal culture As CultureInfo, ByVal defaultValue As T, ByVal result As T) As Boolean
- Return _TryParse(Of T)(value, styles, culture, defaultValue, result)
- End Function
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart.
- ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
- ''' </summary>
- <System.Runtime.CompilerServices.Extension()> _
- Public Function TryParse(Of T)(ByVal value As String, ByVal result As T) As Boolean
- Return _TryParse(Of T)(value, Globalization.CultureInfo.CurrentCulture, result)
- End Function
- #End Region
- #Region " WORKERS "
- ''' <summary>
- ''' Converts the specified string value to its strong-typed counterpart. If the conversion fails
- ''' either an exception is raised or the default value will be returned.
- ''' </summary>
- ''' <typeparam name="T"></typeparam>
- ''' <param name="value">The value.</param>
- ''' <param name="culture">The culture.</param>
- ''' <param name="result">The result.</param>
- ''' <returns></returns>
- <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
- Private Function _TryParse(Of T)(ByVal value As String, ByVal culture As CultureInfo, ByRef result As T) As Boolean
- Dim converter As TypeConverter = TypeDescriptor.GetConverter(GetType(T))
- Try
- 'nasty but ne…
Large files files are truncated, but you can click here to view the full file