PageRenderTime 56ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 0ms

/Library/EXTENSIONS/StringExtensions.vb

https://bitbucket.org/davidhary/my.vs10.core.vb.1.x
Visual Basic | 2251 lines | 1213 code | 317 blank | 721 comment | 0 complexity | c0abe5e4ae50b5c4c08bc8e576e68a14 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. Imports System
  2. Imports System.Globalization
  3. Imports System.ComponentModel
  4. Imports System.Runtime.CompilerServices
  5. Namespace StringExtensions
  6. ''' <summary>
  7. ''' Includes extensions for strings.
  8. ''' </summary>
  9. ''' <remarks></remarks>
  10. ''' <license>
  11. ''' (c) 2010 Integrated Scientific Resources, Inc.
  12. ''' Licensed under the Apache License Version 2.0.
  13. ''' Unless required by applicable law or agreed to in writing, this software is provided
  14. ''' "AS IS", WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. ''' </license>
  16. ''' <history date="04/09/2009" by="David Hary" revision="1.1.3386.x">
  17. ''' Created
  18. ''' </history>
  19. Public Module [Extensions]
  20. #Region " STRING MANIPULATION "
  21. ''' <summary>
  22. ''' Returns the right most <paramref name="count"></paramref> characters
  23. ''' from the string.
  24. ''' </summary>
  25. ''' <param name="value">The string being chopped</param>
  26. ''' <param name="count">The number of
  27. ''' characters to return.</param>
  28. ''' <returns>A string containing the right most characters
  29. ''' in this string.</returns>
  30. ''' <remarks></remarks>
  31. <Extension()> _
  32. Public Function Right(ByVal value As String, ByVal count As Integer) As String
  33. If value.Length <= count Then Return value
  34. Return value.Substring(value.Length - count)
  35. End Function
  36. ''' <summary>
  37. ''' Returns the left most <paramref name="count"></paramref> characters
  38. ''' from the string.
  39. ''' </summary>
  40. ''' <param name="value">The string being chopped</param>
  41. ''' <param name="count">The number of
  42. ''' characters to return.</param>
  43. ''' <returns>A string containing the left most characters
  44. ''' in this string.</returns>
  45. ''' <remarks></remarks>
  46. <Extension()> _
  47. Public Function Left(ByVal value As String, ByVal count As Integer) As String
  48. If value.Length <= count Then Return value
  49. Return value.Substring(0, count)
  50. End Function
  51. ''' <summary>
  52. ''' Removes the left characters.
  53. ''' </summary>
  54. ''' <param name="value">The string.</param>
  55. ''' <param name="count">The count.</param>
  56. ''' <returns></returns>
  57. ''' <remarks></remarks>
  58. <Extension()> _
  59. Public Function RemoveLeft(ByVal value As String, ByVal count As Integer) As String
  60. If value.Length <= count Then Return ""
  61. Return value.Substring(count)
  62. End Function
  63. ''' <summary>
  64. ''' Removes the right characters.
  65. ''' </summary>
  66. ''' <param name="value">The string.</param>
  67. ''' <param name="count">The count.</param>
  68. ''' <returns></returns>
  69. ''' <remarks></remarks>
  70. <Extension()> _
  71. Public Function RemoveRight(ByVal value As String, ByVal count As Integer) As String
  72. If value.Length <= count Then Return ""
  73. Return value.Substring(0, value.Length - count)
  74. End Function
  75. #End Region
  76. #Region " STRING NUMERIC METHODS "
  77. ''' <summary>Returns true if the string represents a floating number.</summary>
  78. ''' <param name="value">Specifies the floating number candidate.</param>
  79. <Extension()> _
  80. Public Function IsFloat(ByVal value As String) As Boolean
  81. Dim a As Double
  82. Return System.Double.TryParse(value, Globalization.NumberStyles.Float, System.Globalization.CultureInfo.CurrentCulture, a)
  83. End Function
  84. ''' <summary>Returns true if the string represents a whole number.</summary>
  85. ''' <param name="value">Specifies the integer candidate.</param>
  86. <Extension()> _
  87. Public Function IsInteger(ByVal value As String) As Boolean
  88. Dim a As Double
  89. Return System.Double.TryParse(value, Globalization.NumberStyles.Integer, System.Globalization.CultureInfo.CurrentCulture, a)
  90. End Function
  91. ''' <summary>Returns true if the string represents any number.</summary>
  92. ''' <param name="value">Specifies the number candidate.</param>
  93. <Extension()> _
  94. Public Function IsNumber(ByVal value As String) As Boolean
  95. Dim a As Double
  96. Return System.Double.TryParse(value, Globalization.NumberStyles.Number _
  97. Or Globalization.NumberStyles.AllowExponent, _
  98. System.Globalization.CultureInfo.CurrentCulture, a)
  99. End Function
  100. ''' <summary>Returns true if the string represents any number.</summary>
  101. ''' <param name="value">Specifies the number candidate.</param>
  102. <Extension()> _
  103. Public Function IsNumeric(ByVal value As String) As Boolean
  104. Return value.IsNumber()
  105. End Function
  106. #End Region
  107. #Region " STRING CONTENTS METHODS "
  108. ''' <summary>
  109. ''' Replaces the given <paramref name="characters">characters</paramref> with the
  110. ''' <paramref name="replacing">new characters.</paramref>
  111. ''' </summary>
  112. ''' <param name="source">The original string</param>
  113. ''' <param name="characters">The characters to be replaced</param>
  114. ''' <param name="replacing">The new characters.</param>
  115. ''' <returns></returns>
  116. ''' <remarks></remarks>
  117. <Extension()> _
  118. Public Function Replace(ByVal source As String, ByVal characters As String, ByVal replacing As Char) As String
  119. If String.IsNullOrEmpty(source) Then
  120. Throw New ArgumentNullException("source")
  121. End If
  122. If String.IsNullOrEmpty(characters) Then
  123. Throw New ArgumentNullException("characters")
  124. End If
  125. If String.IsNullOrEmpty(replacing) Then
  126. Throw New ArgumentNullException("replacing")
  127. End If
  128. For Each c As Char In characters.ToCharArray
  129. source = source.Replace(c, replacing)
  130. Next
  131. Return source
  132. End Function
  133. Public Const IllegalFileCharacters As String = "/\\:*?""<>|"
  134. ''' <summary>Returns True if the validated string contains only alpha characters.</summary>
  135. ''' <param name="source">The string to validate.</param>
  136. <Extension()> _
  137. Public Function IncludesIllegalFileCharacters(ByVal source As String) As Boolean
  138. Return source.IncludesCharacters(IllegalFileCharacters)
  139. End Function
  140. ''' <summary>Returns true if the string includes the specified characters.</summary>
  141. ''' <param name="source">The string that is being searched.</param>
  142. ''' <param name="characters">The characters to search for.</param>
  143. <Extension()> _
  144. Public Function IncludesCharacters(ByVal source As String, ByVal characters As String) As Boolean
  145. If source Is Nothing Then
  146. Throw New ArgumentNullException("source")
  147. End If
  148. If characters Is Nothing Then
  149. Throw New ArgumentNullException("characters")
  150. End If
  151. Dim expression As String = String.Format(System.Globalization.CultureInfo.CurrentCulture, "[{0}]", characters)
  152. Dim r As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex( _
  153. expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
  154. Return r.IsMatch(source)
  155. End Function
  156. ''' <summary>Returns true if the string includes any of the specified characters.</summary>
  157. ''' <param name="source">The string that is being searched.</param>
  158. ''' <param name="characters">The characters to search for.</param>
  159. <Extension()> _
  160. Public Function IncludesAny(ByVal source As String, ByVal characters As String) As Boolean
  161. If source Is Nothing Then
  162. Throw New ArgumentNullException("source")
  163. End If
  164. If characters Is Nothing Then
  165. Throw New ArgumentNullException("characters")
  166. End If
  167. ' 2954: was ^[{0}]+$
  168. Dim expression As String = String.Format(System.Globalization.CultureInfo.CurrentCulture, "[{0}]", characters)
  169. Dim r As System.Text.RegularExpressions.Regex = New System.Text.RegularExpressions.Regex( _
  170. expression, System.Text.RegularExpressions.RegexOptions.IgnoreCase)
  171. Return r.IsMatch(source)
  172. End Function
  173. ''' <summary>Returns True if the validated string contains only alpha characters.</summary>
  174. ''' <param name="value">The string to validate.</param>
  175. <Extension()> _
  176. Public Function ConsistsOfAlphaCharacters(ByVal value As String) As Boolean
  177. If value Is Nothing Then
  178. Throw New ArgumentNullException("value")
  179. ElseIf String.IsNullOrEmpty(value) Then
  180. Return False
  181. End If
  182. Dim r As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex("^[a-z]+$", _
  183. Text.RegularExpressions.RegexOptions.IgnoreCase)
  184. Return r.IsMatch(value)
  185. End Function
  186. ''' <summary>Returns True if the validated string contains only alpha characters.</summary>
  187. ''' <param name="value">The string to validate.</param>
  188. <Extension()> _
  189. Public Function ConsistsOfNumbers(ByVal value As String) As Boolean
  190. If value Is Nothing Then
  191. Throw New ArgumentNullException("value")
  192. ElseIf String.IsNullOrEmpty(value) Then
  193. Return False
  194. End If
  195. Dim r As Text.RegularExpressions.Regex = New Text.RegularExpressions.Regex("^[0-9]+$", _
  196. Text.RegularExpressions.RegexOptions.IgnoreCase)
  197. Return r.IsMatch(value)
  198. End Function
  199. ''' <summary>
  200. ''' Reverse the string from http://en.wikipedia.org/wiki/Extension_method
  201. ''' </summary>
  202. ''' <param name="value"></param>
  203. ''' <returns></returns>
  204. <Extension()> _
  205. Public Function Reverse(ByVal value As String) As String
  206. If value Is Nothing Then
  207. Throw New ArgumentNullException("value")
  208. ElseIf String.IsNullOrEmpty(value) Then
  209. Return value
  210. End If
  211. Dim chars As Char() = value.ToCharArray()
  212. Array.Reverse(chars)
  213. Return New String(chars)
  214. End Function
  215. #End Region
  216. #Region " COMPACT "
  217. ''' <summary>
  218. ''' Compacts the string to permit display within the given width.
  219. ''' For example, using <see cref="Windows.Forms.TextFormatFlags.PathEllipsis">Path Ellipsis</see>
  220. ''' as the <paramref name="formatInstruction">format instruction</paramref>
  221. ''' the string 'c:\program files\test app\runme.exe' might turn
  222. ''' into 'c:\program files\...\runme.exe' depending on the font and width.
  223. ''' </summary>
  224. ''' <param name="value">Specified the string to compact.</param>
  225. ''' <param name="width">Specifes the width</param>
  226. ''' <param name="font">Specifies the <see cref="Drawing.Font">font</see></param>
  227. ''' <param name="formatInstruction">Specifies the designed
  228. ''' <see cref="Windows.Forms.TextFormatFlags">formatting</see></param>
  229. ''' <returns></returns>
  230. ''' <remarks></remarks>
  231. <Extension()> _
  232. Public Function Compact(ByVal value As String, ByVal width As Integer, _
  233. ByVal font As Drawing.Font, ByVal formatInstruction As Windows.Forms.TextFormatFlags) As String
  234. If String.IsNullOrEmpty(value) Then
  235. Return String.Empty
  236. End If
  237. If font Is Nothing Then
  238. Throw New ArgumentNullException("font")
  239. End If
  240. If width <= 0 Then
  241. Throw New ArgumentOutOfRangeException("width", width, "Must be non-zero")
  242. End If
  243. Dim result As String = String.Copy(value)
  244. System.Windows.Forms.TextRenderer.MeasureText(result, font, New Drawing.Size(width, font.Height), formatInstruction Or formatInstruction Or Windows.Forms.TextFormatFlags.ModifyString)
  245. Return result
  246. End Function
  247. ''' <summary>
  248. ''' Compacts the string to permit display within the given width.
  249. ''' For example, the string 'c:\program files\test app\runme.exe' might turn
  250. ''' into 'c:\program files\...\runme.exe' depending on the font and width.
  251. ''' </summary>
  252. ''' <param name="value">Specified the string to compact.</param>
  253. ''' <param name="width">Specifes the width</param>
  254. ''' <param name="font">Specifies the <see cref="Drawing.Font">font</see></param>
  255. ''' <returns></returns>
  256. ''' <remarks></remarks>
  257. <Extension()> _
  258. Public Function Compact(ByVal value As String, ByVal width As Integer, _
  259. ByVal font As Drawing.Font) As String
  260. Return value.Compact(width, font, Windows.Forms.TextFormatFlags.PathEllipsis)
  261. End Function
  262. ''' <summary>
  263. ''' Compacts the string to permit display within the given control.
  264. ''' For example, using <see cref="Windows.Forms.TextFormatFlags.PathEllipsis">Path Ellipsis</see>
  265. ''' as the <paramref name="formatInstruction">format instruction</paramref>
  266. ''' the string 'c:\program files\test app\runme.exe' might turn
  267. ''' into 'c:\program files\...\runme.exe' depending on the font and width.
  268. ''' </summary>
  269. ''' <param name="value">Specifies the text</param>
  270. ''' <param name="control">Specifies the control control within which to format the text.</param>
  271. ''' <param name="formatInstruction">Specifies the designed
  272. ''' <see cref="Windows.Forms.TextFormatFlags">formatting</see></param>
  273. ''' <returns></returns>
  274. ''' <remarks></remarks>
  275. <Extension()> _
  276. Public Function Compact(ByVal value As String, _
  277. ByVal control As System.Windows.Forms.Control, _
  278. ByVal formatInstruction As Windows.Forms.TextFormatFlags) As String
  279. If String.IsNullOrEmpty(value) Then
  280. Return String.Empty
  281. End If
  282. If control Is Nothing Then
  283. Throw New ArgumentNullException("control")
  284. End If
  285. Return value.Compact(control.Width, control.Font, formatInstruction)
  286. End Function
  287. ''' <summary>
  288. ''' Compacts the string to permit display within the given control.
  289. ''' For example, the string 'c:\program files\test app\runme.exe' might turn
  290. ''' into 'c:\program files\...\runme.exe' depending on the font and width.
  291. ''' </summary>
  292. ''' <param name="value">Specified the string to compact.</param>
  293. ''' <param name="ctrl">Specifes the control receiving the string</param>
  294. ''' <returns></returns>
  295. ''' <remarks></remarks>
  296. <Extension()> _
  297. Public Function Compact(ByVal value As String, ByVal ctrl As Windows.Forms.Control) As String
  298. If String.IsNullOrEmpty(value) Then
  299. Return String.Empty
  300. End If
  301. If ctrl Is Nothing Then
  302. Throw New ArgumentNullException("ctrl")
  303. End If
  304. Return value.Compact(ctrl, Windows.Forms.TextFormatFlags.PathEllipsis)
  305. End Function
  306. #End Region
  307. #Region " CONTAINS "
  308. ''' <summary>
  309. ''' Returns true if the find string is in the search string.
  310. ''' </summary>
  311. ''' <param name="search">The item to search.</param>
  312. ''' <param name="find">The the item to find.</param>
  313. ''' <param name="comparisonType">Type of the comparison.</param><returns></returns>
  314. <Extension()> _
  315. Public Function Contains(ByVal search As String, ByVal find As String, ByVal comparisonType As StringComparison) As Boolean
  316. Return Location(search, find, comparisonType) >= 0
  317. End Function
  318. ''' <summary>
  319. ''' Returns the location of the find string in the search string.
  320. ''' </summary>
  321. ''' <param name="search">The item to search.</param>
  322. ''' <param name="find">The the item to find.</param>
  323. ''' <param name="comparisonType">Type of the comparison.</param><returns></returns>
  324. <Extension()> _
  325. Public Function Location(ByVal search As String, ByVal find As String, ByVal comparisonType As StringComparison) As Integer
  326. Return search.IndexOf(find, comparisonType)
  327. End Function
  328. #End Region
  329. #Region " SUBSTRING "
  330. ''' <summary>Returns a substring of the input string taking not of start index and length
  331. ''' exceptions.</summary>
  332. ''' <param name="value">The input string to sub string.</param>
  333. ''' <param name="startIndex">The zero bbased starting index.</param>
  334. ''' <param name="length">The total length.</param>
  335. <Extension()> _
  336. Public Function SafeSubstring(ByVal value As String, ByVal startIndex As Integer, ByVal length As Integer) As String
  337. If String.IsNullOrEmpty(value) OrElse length <= 0 Then
  338. Return String.Empty
  339. End If
  340. Dim inputLength As Integer = value.Length
  341. If startIndex > inputLength Then
  342. Return String.Empty
  343. Else
  344. If startIndex + length > inputLength Then
  345. length = inputLength - startIndex
  346. End If
  347. Return value.Substring(startIndex, length)
  348. End If
  349. End Function
  350. ''' <summary>Returns the substring after the last occurrence of the specified string</summary>
  351. ''' <param name="source">The string to substring.</param>
  352. ''' <param name="search">The string to search for.</param>
  353. <Extension()> _
  354. Public Function SubstringAfter(ByVal source As String, ByVal search As String) As String
  355. If String.IsNullOrEmpty(source) Then
  356. Return String.Empty
  357. End If
  358. If String.IsNullOrEmpty(search) Then
  359. Return String.Empty
  360. End If
  361. Dim location As Integer = source.LastIndexOf(search)
  362. If location >= 0 Then
  363. If location + search.Length < source.Length Then
  364. Return source.Substring(location + search.Length)
  365. Else
  366. Return String.Empty
  367. End If
  368. Else
  369. Return String.Empty
  370. End If
  371. End Function
  372. ''' <summary>Returns the substring before the last occurrence of the specified string</summary>
  373. ''' <param name="source">The string to substring.</param>
  374. ''' <param name="search">The string to search for.</param>
  375. <Extension()> _
  376. Public Function SubstringBefore(ByVal source As String, ByVal search As String) As String
  377. If String.IsNullOrEmpty(source) Then
  378. Return String.Empty
  379. End If
  380. If String.IsNullOrEmpty(search) Then
  381. Return String.Empty
  382. End If
  383. Dim location As Integer = source.LastIndexOf(search)
  384. If location >= 0 Then
  385. Return source.Substring(0, location)
  386. Else
  387. Return String.Empty
  388. End If
  389. End Function
  390. ''' <summary>Returns the substring after the last occurrence of the specified string</summary>
  391. ''' <param name="source">The string to substring.</param>
  392. ''' <param name="startDelimiter">The start delimiter to search for.</param>
  393. ''' <param name="endDelimiter">The end delimiter to search for.</param>
  394. <Extension()> _
  395. Public Function SubstringBetween(ByVal source As String, ByVal startDelimiter As String, ByVal endDelimiter As String) As String
  396. If String.IsNullOrEmpty(source) Then
  397. Return String.Empty
  398. End If
  399. If String.IsNullOrEmpty(startDelimiter) Then
  400. Return String.Empty
  401. End If
  402. Dim startLocation As Integer = source.LastIndexOf(startDelimiter) + startDelimiter.Length
  403. Dim endLocation As Integer = source.LastIndexOf(endDelimiter)
  404. If startLocation >= 0 AndAlso startLocation < endLocation Then
  405. Return source.Substring(startLocation, endLocation - startLocation)
  406. Else
  407. Return String.Empty
  408. End If
  409. End Function
  410. #End Region
  411. #Region " COMMON ESCAPE SEQUENCES "
  412. ''' <summary>
  413. ''' Replaces common escape strings such as <code>'\n'</code> or <code>'\r'</code>with control
  414. ''' characters such as <code>10</code> and <code>13</code>, respectively.
  415. ''' </summary>
  416. ''' <param name="value">Text including escape sequences.</param>
  417. ''' <returns></returns>
  418. ''' <remarks></remarks>
  419. <Extension()> _
  420. Public Function ReplaceCommonEscapeSequences(ByVal value As String) As String
  421. If (value <> Nothing) Then
  422. Return value.Replace("\n", Convert.ToChar(10)).Replace("\r", Convert.ToChar(13))
  423. Else
  424. Return Nothing
  425. End If
  426. End Function
  427. ''' <summary>
  428. ''' Replaces control characters such as <code>10</code> and <code>13</code> with
  429. ''' common escape strings such as <code>'\n'</code> or <code>'\r'</code>, respectively.
  430. ''' </summary>
  431. ''' <param name="value">Text including control characters.</param>
  432. ''' <returns></returns>
  433. ''' <remarks></remarks>
  434. <Extension()> _
  435. Public Function InsertCommonEscapeSequences(ByVal value As String) As String
  436. If (value <> Nothing) Then
  437. Return value.Replace(Convert.ToChar(10), "\n").Replace(Convert.ToChar(13), "\r")
  438. Else
  439. Return Nothing
  440. End If
  441. End Function
  442. #End Region
  443. #Region " FORMATTING "
  444. ''' <summary>Returns a centered string.
  445. ''' </summary>
  446. ''' <returns>The input string centered with appropriate number of spaces
  447. ''' on each side.
  448. ''' </returns>
  449. ''' <param name="value">Specifies the original string.</param>
  450. ''' <param name="length">Specifies the total length of the new string</param>
  451. ''' <history>
  452. ''' </history>
  453. <Extension()> _
  454. Public Function Center(ByVal value As String, ByVal length As Integer) As String
  455. Dim leftSpacesCount As Double
  456. Dim rightSpacesCount As Double
  457. If length <= 0 Then
  458. Return String.Empty
  459. ElseIf String.IsNullOrEmpty(value) Then
  460. Return String.Empty.PadLeft(length, " "c)
  461. ElseIf value.Length > length Then
  462. Return value.Substring(0, length)
  463. ElseIf value.Length = length Then
  464. Return value
  465. Else
  466. leftSpacesCount = (length - value.Length) \ 2S
  467. rightSpacesCount = length - value.Length - leftSpacesCount
  468. Return String.Empty.PadLeft(CInt(leftSpacesCount), " "c) & value _
  469. & String.Empty.PadLeft(CInt(rightSpacesCount), " "c)
  470. End If
  471. End Function
  472. ''' <summary>Returns a left aligned string. If the string is too large, the
  473. ''' only 'length' values are returned with the last character
  474. ''' set to '~' to signify the lost character.
  475. ''' </summary>
  476. <Extension()> _
  477. Public Function LeftAlign(ByVal caption As String, ByVal captionWidth As Integer) As String
  478. Const spaceCharacter As Char = " "c
  479. Const lostCharacter As Char = "~"c
  480. ' make sure we have one left space.
  481. If captionWidth <= 0 Then
  482. Return String.Empty
  483. ElseIf caption.Length > captionWidth Then
  484. Return caption.Substring(0, captionWidth - 1) & lostCharacter
  485. ElseIf caption.Length = captionWidth Then
  486. Return caption
  487. Else
  488. Return caption.PadRight(captionWidth, spaceCharacter)
  489. End If
  490. End Function
  491. ''' <summary>Returns a right aligned string. If the string is too large, the
  492. ''' only 'length' values are returned with the first character
  493. ''' set to '~' to signify the lost character.
  494. ''' </summary>
  495. <Extension()> _
  496. Public Function RightAlign(ByVal caption As String, ByVal captionWidth As Integer) As String
  497. Const spaceCharacter As Char = " "c
  498. Const lostCharacter As Char = "~"c
  499. ' make sure we have one left space.
  500. If captionWidth <= 0 Then
  501. Return String.Empty
  502. ElseIf caption.Length > captionWidth Then
  503. Return lostCharacter & caption.Substring(0, captionWidth - 1)
  504. ElseIf caption.Length = captionWidth Then
  505. Return caption
  506. Else
  507. Return caption.PadLeft(captionWidth, spaceCharacter)
  508. End If
  509. End Function
  510. #End Region
  511. #Region " COMPRESSION "
  512. ''' <summary>
  513. ''' Returns a compressed value.
  514. ''' </summary>
  515. ''' <param name="value"></param>
  516. ''' <returns></returns>
  517. ''' <remarks></remarks>
  518. ''' <history>
  519. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  520. ''' </history>
  521. <Extension()> _
  522. Public Function Compress(ByVal value As String) As String
  523. If String.IsNullOrEmpty(value) Then
  524. Return ""
  525. Exit Function
  526. End If
  527. Dim result As String = ""
  528. ' Compress the byte array
  529. Using memoryStream As New System.IO.MemoryStream()
  530. Using compressedStream As New System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Compress)
  531. ' Convert the uncompressed string into a byte array
  532. Dim values As Byte() = System.Text.Encoding.UTF8.GetBytes(value)
  533. compressedStream.Write(values, 0, values.Length)
  534. ' Don't FLUSH here - it possibly leads to data loss!
  535. compressedStream.Close()
  536. Dim compressedValues As Byte() = memoryStream.ToArray()
  537. ' Convert the compressed byte array back to a string
  538. result = System.Convert.ToBase64String(compressedValues)
  539. memoryStream.Close()
  540. End Using
  541. End Using
  542. Return result
  543. End Function
  544. ''' <summary>
  545. ''' Returns the decompressed string of the value.
  546. ''' </summary>
  547. ''' <param name="value"></param>
  548. ''' <returns></returns>
  549. ''' <remarks></remarks>
  550. ''' <history>
  551. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  552. ''' </history>
  553. ''' <history date="04/09/2009" by="David Hary" revision="1.1.3516.x">
  554. ''' Bug fix in getting the size. Changed memoryStream.Length - 5 to memoryStream.Length - 4
  555. ''' </history>
  556. <Extension()> _
  557. Public Function Decompress(ByVal value As String) As String
  558. If String.IsNullOrEmpty(value) Then
  559. Return ""
  560. Exit Function
  561. End If
  562. Dim result As String = ""
  563. ' Convert the compressed string into a byte array
  564. Dim compressedValues As Byte() = System.Convert.FromBase64String(value)
  565. ' Decompress the byte array
  566. Using memoryStream As New IO.MemoryStream(compressedValues)
  567. Using compressedStream As New System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Decompress)
  568. ' it looks like we are getting a bogus size.
  569. Dim sizeBytes(3) As Byte
  570. memoryStream.Position = memoryStream.Length - 4
  571. memoryStream.Read(sizeBytes, 0, 4)
  572. Dim outputSize As Int32 = BitConverter.ToInt32(sizeBytes, 0)
  573. memoryStream.Position = 0
  574. Dim values(outputSize - 1) As Byte
  575. compressedStream.Read(values, 0, outputSize)
  576. ' Convert the decompressed byte array back to a string
  577. result = System.Text.Encoding.UTF8.GetString(values)
  578. End Using
  579. End Using
  580. Return result
  581. End Function
  582. #End Region
  583. #Region " ENCRYPTION "
  584. <Extension()> _
  585. Public Function Encrypt(ByVal value As String, ByVal passPhrase As String) As String
  586. If String.IsNullOrEmpty(value) Then
  587. Return ""
  588. ElseIf String.IsNullOrEmpty(passPhrase) Then
  589. Throw New ArgumentNullException("passPhrase")
  590. End If
  591. Return System.Convert.ToBase64String(Encrypt(System.Text.Encoding.UTF8.GetBytes(value), passPhrase))
  592. End Function
  593. ''' <summary>
  594. ''' Encrypts the byte array using the
  595. ''' <see cref="System.Security.Cryptography.RijndaelManaged">Rijndael symmetrinc encryption algorithm</see>
  596. ''' </summary>
  597. ''' <param name="values"></param>
  598. ''' <param name="passPhrase"></param>
  599. ''' <returns></returns>
  600. ''' <remarks></remarks>
  601. ''' <history>
  602. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  603. ''' </history>
  604. Private Function encrypt(ByVal values As Byte(), ByVal passPhrase As String) As Byte()
  605. Dim result As Byte()
  606. Dim encryptionAlgorithm As New System.Security.Cryptography.RijndaelManaged
  607. encryptionAlgorithm.KeySize = 256
  608. encryptionAlgorithm.Key = encryptionKey(passPhrase)
  609. encryptionAlgorithm.IV = encryptionInitializationVector(passPhrase)
  610. Using memoryStream As New IO.MemoryStream
  611. Using cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
  612. encryptionAlgorithm.CreateEncryptor, _
  613. Security.Cryptography.CryptoStreamMode.Write)
  614. cryptoStream.Write(values, 0, values.Length)
  615. cryptoStream.FlushFinalBlock()
  616. result = memoryStream.ToArray()
  617. cryptoStream.Close()
  618. memoryStream.Close()
  619. End Using
  620. End Using
  621. Return result
  622. End Function
  623. <Extension()> _
  624. Public Function Decrypt(ByVal value As String, ByVal passPhrase As String) As String
  625. If String.IsNullOrEmpty(value) Then
  626. Return ""
  627. ElseIf String.IsNullOrEmpty(passPhrase) Then
  628. Throw New ArgumentNullException("passPhrase")
  629. End If
  630. Return System.Text.Encoding.UTF8.GetString(Decrypt(System.Convert.FromBase64String(value), passPhrase))
  631. End Function
  632. ''' <summary>
  633. ''' Decrypts the byte array using the
  634. ''' <see cref="System.Security.Cryptography.RijndaelManaged">Rijndael symmetrinc encryption algorithm</see>
  635. ''' </summary>
  636. ''' <param name="values"></param>
  637. ''' <param name="passPhrase"></param>
  638. ''' <returns></returns>
  639. ''' <remarks></remarks>
  640. ''' <history>
  641. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  642. ''' </history>
  643. Private Function decrypt(ByVal values As Byte(), ByVal passPhrase As String) As Byte()
  644. Dim result As Byte()
  645. Using encryptionAlgorithm As New System.Security.Cryptography.RijndaelManaged
  646. encryptionAlgorithm.KeySize = 256
  647. encryptionAlgorithm.Key = encryptionKey(passPhrase)
  648. encryptionAlgorithm.IV = encryptionInitializationVector(passPhrase)
  649. Using memoryStream As New IO.MemoryStream(values)
  650. Using cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
  651. encryptionAlgorithm.CreateDecryptor, _
  652. Security.Cryptography.CryptoStreamMode.Read)
  653. Dim workspace As Byte()
  654. ReDim workspace(values.Length)
  655. Dim decryptedByteCount As Integer
  656. decryptedByteCount = cryptoStream.Read(workspace, 0, values.Length)
  657. cryptoStream.Close()
  658. memoryStream.Close()
  659. ReDim result(decryptedByteCount)
  660. Array.Copy(workspace, result, decryptedByteCount)
  661. End Using
  662. End Using
  663. End Using
  664. Return result
  665. End Function
  666. ''' <summary>
  667. ''' Generates a byte array of required length as the encryption key.
  668. ''' </summary>
  669. ''' <param name="passPhrase"></param>
  670. ''' <returns></returns>
  671. ''' <remarks></remarks>
  672. ''' <history>
  673. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  674. ''' </history>
  675. Private Function encryptionKey(ByVal passPhrase As String) As Byte()
  676. 'A SHA256 hash of the passphrase has just the required length. It is used twice in a manner of self-salting.
  677. Dim SHA256 As New System.Security.Cryptography.SHA256Managed
  678. Dim L1 As String = System.Convert.ToBase64String(SHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(passPhrase)))
  679. Dim L2 As String = passPhrase & L1
  680. Return SHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(L2))
  681. End Function
  682. ''' <summary>
  683. ''' Generates a byte array of required length as the initialization vector.
  684. ''' </summary>
  685. ''' <param name="passPhrase"></param>
  686. ''' <returns></returns>
  687. ''' <remarks></remarks>
  688. ''' <history>
  689. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  690. ''' </history>
  691. Private Function encryptionInitializationVector(ByVal passPhrase As String) As Byte()
  692. ' A MD5 hash of the passphrase has just the required length. It is used twice in a manner of self-salting.
  693. Dim MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
  694. Dim L1 As String = System.Convert.ToBase64String(MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(passPhrase)))
  695. Dim L2 As String = passPhrase & L1
  696. Return MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(L2))
  697. End Function
  698. #End Region
  699. #Region " SPLIT TO WORDS "
  700. ''' <summary>
  701. ''' Splits the string to words by adding spaces between lower and upper case characters.
  702. ''' </summary>
  703. ''' <param name="value">The <c>String</c> value to split.</param>
  704. ''' <returns>A <c>String</c> of words separated by spaces.</returns>
  705. <Extension()> _
  706. Public Function SplitWords(ByVal value As String) As String
  707. If String.IsNullOrEmpty(value) Then
  708. Return ""
  709. Else
  710. Dim isLowerCase As Boolean = False
  711. Dim newValue As New System.Text.StringBuilder
  712. For Each c As Char In value
  713. If isLowerCase AndAlso Char.IsUpper(c) Then
  714. newValue.Append(" ")
  715. End If
  716. isLowerCase = Not Char.IsUpper(c)
  717. newValue.Append(c)
  718. Next
  719. Return newValue.ToString()
  720. End If
  721. End Function
  722. #End Region
  723. #Region " HASH "
  724. ''' <summary>
  725. ''' Converts the value to a Base 64 Hash.
  726. ''' </summary>
  727. ''' <param name="value">Specifies the value to convert</param>
  728. ''' <returns></returns>
  729. ''' <remarks>Uses SHA Crypto service provider.</remarks>
  730. <Extension()> _
  731. Public Function ToBase64Hash(ByVal value As String) As String
  732. Return ToBase64Hash(value, New System.Security.Cryptography.SHA1CryptoServiceProvider)
  733. End Function
  734. ''' <summary>
  735. ''' Converts the value to a Base 64 Hash.
  736. ''' </summary>
  737. ''' <param name="value">Specifies the value to convert</param>
  738. ''' <param name="algorithm">Specifies the algorithm for computing the hash.</param>
  739. ''' <returns></returns>
  740. ''' <remarks>Uses SHA Crypto service provider.</remarks>
  741. <Extension()> _
  742. Public Function ToBase64Hash(ByVal value As String, ByVal algorithm As System.Security.Cryptography.HashAlgorithm) As String
  743. Dim encoding As New System.Text.UnicodeEncoding
  744. ' Store the source string in a byte array
  745. Dim values() As Byte = encoding.GetBytes(value)
  746. ' get a SHA provider.
  747. ' Dim provider As New System.Security.Cryptography.SHA1CryptoServiceProvider
  748. ' Create the hash
  749. values = algorithm.ComputeHash(values)
  750. ' return as a base64 encoded string
  751. Return Convert.ToBase64String(values)
  752. End Function
  753. #End Region
  754. #Region " VALIDATION "
  755. ''' <summary>
  756. ''' true, if is valid email address
  757. ''' from http://www.davidhayden.com/blog/dave/
  758. ''' archive/2006/11/30/ExtensionMethodsCSharp.aspx
  759. ''' </summary>
  760. ''' <param name="value">email address to test</param>
  761. ''' <returns>true, if is valid email address</returns>
  762. <Extension()> _
  763. Public Function IsValidEmailAddress(ByVal value As String) As Boolean
  764. If value Is Nothing Then
  765. Throw New ArgumentNullException("value")
  766. ElseIf String.IsNullOrEmpty(value) Then
  767. Return False
  768. End If
  769. Return New Text.RegularExpressions.Regex("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$").IsMatch(value)
  770. End Function
  771. ''' <summary>
  772. ''' from http://www.osix.net/modules/article/?id=586
  773. '''
  774. ''' complete (not only http) url regex can be found
  775. ''' at http://internet.ls-la.net/folklore/url-regexpr.html
  776. ''' </summary>
  777. ''' <param name="value"></param>
  778. ''' <returns></returns>
  779. <Extension()> _
  780. Public Function IsValidUrl(ByVal value As String) As Boolean
  781. If value Is Nothing Then
  782. Throw New ArgumentNullException("value")
  783. ElseIf String.IsNullOrEmpty(value) Then
  784. Return False
  785. End If
  786. Return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)
  787. #If False Then
  788. Dim regularExpression As String = "^(https?://)" _
  789. & "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" _
  790. & "(([0-9]{1,3}\.){3}[0-9]{1,3}" _
  791. & "|" & "([0-9a-z_!~*'()-]+\.)*" _
  792. & "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." _
  793. & "[a-z]{2,6})" & "(:[0-9]{1,4})?" & "((/?)|" _
  794. & "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
  795. Return New Regex(regularExpression).IsMatch(value)
  796. #End If
  797. End Function
  798. ''' <summary>
  799. ''' Check if url (http) is available.
  800. ''' </summary>
  801. ''' <param name="value">url to check</param>
  802. ''' <example>
  803. ''' string url = "www.codeproject.com;
  804. ''' if( !url.UrlAvailable())
  805. ''' ...codeproject is not available
  806. ''' </example>
  807. ''' <returns>true if available</returns>
  808. <Extension()> _
  809. Public Function IsUrlAvailable(ByVal value As String) As Boolean
  810. ' use URI instead.
  811. If value Is Nothing Then
  812. Throw New ArgumentNullException("value")
  813. ElseIf String.IsNullOrEmpty(value) Then
  814. Return False
  815. Else
  816. Return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)
  817. End If
  818. #If False Then
  819. If (Not value.StartsWith("http://")) OrElse (Not value.StartsWith("https://")) Then
  820. value = "http://" & value
  821. End If
  822. Try
  823. Dim myRequest As Net.HttpWebRequest = CType(Net.WebRequest.Create(value), Net.HttpWebRequest)
  824. myRequest.Method = "GET"
  825. myRequest.ContentType = "application/x-www-form-urlencoded"
  826. Dim myHttpWebResponse As Net.HttpWebResponse = CType(myRequest.GetResponse(), Net.HttpWebResponse)
  827. Return myHttpWebResponse IsNot Nothing
  828. Catch
  829. Return False
  830. End Try
  831. #End If
  832. End Function
  833. #End Region
  834. #Region " REPLACED WITH CONVERT TO "
  835. #If False Then
  836. #Region " BYTE "
  837. ''' <summary>
  838. ''' Parses and returns the parsed <paramref name="default">default</paramref> if failed to parse.
  839. ''' </summary>
  840. ''' <param name="value">The string containing the value</param>
  841. ''' <param name="default">The default value</param>
  842. ''' <param name="style">Indicates the permitted format or <see cref="Globalization.NumberStyles">number style.</see>
  843. ''' If <see cref="Globalization.NumberStyles.AllowHexSpecifier">allows hex</see>, checks and strips for hex prefixes
  844. ''' such as '&amp;H' or '0x'.
  845. ''' </param>
  846. ''' <returns></returns>
  847. ''' <remarks></remarks>
  848. <Extension()> _
  849. Public Function Parse(ByVal value As String, ByVal [default] As Byte, ByVal style As Globalization.NumberStyles) As Byte
  850. Dim numericValue As Byte
  851. If String.IsNullOrEmpty(value) Then
  852. Return [default]
  853. ElseIf (style And Globalization.NumberStyles.AllowHexSpecifier) <> 0 AndAlso value.StartsWith("&") Then
  854. value = value.TrimStart("&Hh".ToCharArray)
  855. If Byte.TryParse(value, style, _
  856. Globalization.CultureInfo.CurrentCulture, numericValue) Then
  857. Return numericValue
  858. Else
  859. Return [default]
  860. End If
  861. ElseIf (style And Globalization.NumberStyles.AllowHexSpecifier) <> 0 AndAlso value.StartsWith("0x") Then
  862. value = value.Substring(2)
  863. If Byte.TryParse(value, style, _
  864. Globalization.CultureInfo.CurrentCulture, numericValue) Then
  865. Return numericValue
  866. Else
  867. Return [default]
  868. End If
  869. ElseIf Byte.TryParse(value, style, _
  870. System.Globalization.CultureInfo.CurrentCulture, numericValue) Then
  871. Return numericValue
  872. Else
  873. Return [default]
  874. End If
  875. End Function
  876. ''' <summary>
  877. ''' Parses and returns the parsed <paramref name="default">default</paramref> if failed to parse.
  878. ''' </summary>
  879. ''' <param name="value">The string containing the value</param>
  880. ''' <param name="style">Specifies the <see cref="Globalization.NumberStyles">number style.</see>
  881. ''' If <see cref="Globalization.NumberStyles.AllowHexSpecifier">allows hex</see>, checks and strips for hex prefixes
  882. ''' such as '&amp;H' or '0x'.
  883. ''' </param>
  884. ''' <returns></returns>
  885. ''' <remarks></remarks>
  886. <Extension()> _
  887. <CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId:="dummy")> _
  888. Public Function Parse(ByVal value As String, ByVal style As Globalization.NumberStyles, ByVal dummy As Byte) As Byte
  889. If String.IsNullOrEmpty(value) Then
  890. Throw New ArgumentNullException("value")
  891. ElseIf (style And Globalization.NumberStyles.AllowHexSpecifier) <> 0 AndAlso value.StartsWith("&") Then
  892. value = value.TrimStart("&Hh".ToCharArray)
  893. ElseIf (style And Globalization.NumberStyles.AllowHexSpecifier) <> 0 AndAlso value.StartsWith("0x") Then
  894. value = value.Substring(2)
  895. End If
  896. Return Byte.Parse(value, style, Globalization.CultureInfo.CurrentCulture)
  897. End Function
  898. ''' <summary>
  899. ''' Parses and sets the <paramref name="numericValue">numeric value</paramref> and return True.
  900. ''' or set to <paramref name="default">default</paramref> and return false.
  901. ''' </summary>
  902. ''' <param name="value">The string containing the value</param>
  903. ''' <param name="style">Specifies the <see cref="Globalization.NumberStyles">number style.</see>
  904. ''' If <see cref="Globalization.NumberStyles.AllowHexSpecifier">allows hex</see>, checks and strips for hex prefixes
  905. ''' such as '&amp;H' or '0x'.
  906. ''' </param>
  907. ''' <param name="numericValue">The parsed numeric value.</param>
  908. ''' <returns></returns>
  909. ''' <remarks></remarks>
  910. <Extension()> _
  911. <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId:="2#")> _
  912. Public Function TryParse(ByVal value As String, ByVal style As Globalization.NumberStyles, ByRef numericValue As Byte) As Boolean
  913. If String.IsNullOrEmpty(value) Then
  914. Return False
  915. ElseIf (style And Globalization.NumberStyles.AllowHexSpecifier) <> 0 AndAlso value.StartsWith("&") Then
  916. value = value.TrimStart("&Hh".ToCharArray)
  917. ElseIf (style And Globalization.NumberStyles.AllowHexSpecifier) <> 0 AndAlso value.StartsWith("0x") Then
  918. value = value.Substring(2)
  919. End If
  920. Return Byte.TryParse(value, style, Globalization.CultureInfo.CurrentCulture, numericValue)
  921. End Function
  922. ''' <summary>
  923. ''' Parses and sets the <paramref name="numericValue">numeric value</paramref> and return True.
  924. ''' or set to <paramref name="default">default</paramref> and return false.
  925. ''' </summary>
  926. ''' <param name="value">The string containing the value</param>
  927. ''' <param name="default">The default value</param>
  928. ''' <param name="style">Specifies the <see cref="Globalization.NumberStyles">number style.</see>
  929. ''' If <see cref="Globalization.NumberStyles.AllowHexSpecifier">allows hex</see>, checks and strips for hex prefixes
  930. ''' such as '&amp;H' or '0x'.
  931. ''' </param>
  932. ''' <param name="numericValue">The parsed numeric value.</param>
  933. ''' <returns></returns>
  934. ''' <remarks></remarks>
  935. <Extension()> _
  936. <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1045:DoNotPassTypesByReference", MessageId:="3#")> _
  937. Public Function TryParse(ByVal value As String, ByVal [default] As Byte, ByVal style As Globalization.NumberStyles, ByRef numericValue As Byte) As Boolean
  938. If String.IsNullOrEmpty(value) Then
  939. numericValue = [default]
  940. Return False
  941. ElseIf TryParse(value, style, numericValue) Then
  942. Return True
  943. Else
  944. numericValue = [default]
  945. Return False
  946. End If
  947. End Function
  948. #End Region
  949. #Region " DOUBLE "
  950. ''' <summary>
  951. ''' Parses and returns the parsed <paramref name="default">default</paramref> if failed to parse.
  952. ''' </summary>
  953. ''' <param name="value">The string containing the value</param>
  954. ''' <param name="default">The default value</param>
  955. ''' <param name="style">Indicates the permitted format.</param>
  956. ''' <returns></returns>
  957. ''' <remarks></remarks>
  958. <Extension()> _
  959. Public Function Parse(ByVal value As String, ByVal [default] As Double, ByVal style As Globalization.NumberStyles) As Double
  960. Dim numericValue As Double
  961. If String.IsNullOrEmpty(value) Then
  962. Return [default]
  963. ElseIf Double.TryParse(value, style, System.Globalization.CultureInfo.CurrentCulture, numericValue) Then
  964. Return numericValue
  965. Else
  966. Return [default]
  967. End If
  968. End Function
  969. ''' <summary>
  970. ''' Parses and returns the parsed <paramref name="default">default</paramref> if failed to parse.
  971. ''' </summary>
  972. ''' <param name="value">The string containing the value</param>
  973. ''' <param name="default">The default value</param>
  974. ''' <returns></returns>
  975. ''' <remarks></remarks>
  976. <Extension()> _
  977. Public Function Parse(ByVal value As String, ByVal [default] As Double) As Double
  978. Return Parse(value, [default], Globalization.NumberStyles.Number Or Globalization.NumberStyles.AllowExponent)
  979. End Function
  980. ''' <summary>
  981. ''' Parses and returns the parsed <paramref name="default">default</paramref> if failed to parse.
  982. ''' </summary>
  983. ''' <param name="value">The string containing the value</param>
  984. ''' <param name="default">The default value</param>
  985. ''' <returns></returns>
  986. ''' <remarks></remarks>
  987. <Extension()> _
  988. Public Function Parse(ByVal value As String, ByVal [default] As Double?, ByVal style As Globalization.NumberStyles) As Double?
  989. Dim numericValue As Double
  990. If String.IsNullOrEmpty(value) Then
  991. Return [default]
  992. ElseIf Double.TryParse(value, style, System.Globalization.CultureInfo.CurrentCulture, numericValue) Then
  993. Return numericValue
  994. Else
  995. Return [default]
  996. End If
  997. End Function
  998. ''' <summary>
  999. ''' Parses and returns the parsed <paramref name="default">default</paramref> if failed to parse.
  1000. ''' </summary>
  1001. ''' <param name="value">The string containing the value</param>
  1002. ''' <param …

Large files files are truncated, but you can click here to view the full file