PageRenderTime 67ms CodeModel.GetById 29ms RepoModel.GetById 0ms app.codeStats 1ms

/Library/EXTENSIONS/StringExtensions.vb

https://bitbucket.org/dhary/isr.core.vb.1.x
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

  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 String.IsNullOrEmpty(value) OrElse 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 String.IsNullOrEmpty(value) OrElse 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 String.IsNullOrEmpty(value) OrElse 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 String.IsNullOrEmpty(value) OrElse 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 ""
  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 ""
  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 ""
  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. If String.IsNullOrEmpty(search) Then Return 0
  327. Return search.IndexOf(find, comparisonType)
  328. End Function
  329. #End Region
  330. #Region " SUBSTRING "
  331. ''' <summary>Returns a substring of the input string taking not of start index and length
  332. ''' exceptions.</summary>
  333. ''' <param name="value">The input string to sub string.</param>
  334. ''' <param name="startIndex">The zero bbased starting index.</param>
  335. ''' <param name="length">The total length.</param>
  336. <Extension()> _
  337. Public Function SafeSubstring(ByVal value As String, ByVal startIndex As Integer, ByVal length As Integer) As String
  338. If String.IsNullOrEmpty(value) OrElse length <= 0 Then
  339. Return ""
  340. End If
  341. Dim inputLength As Integer = value.Length
  342. If startIndex > inputLength Then
  343. Return ""
  344. Else
  345. If startIndex + length > inputLength Then
  346. length = inputLength - startIndex
  347. End If
  348. Return value.Substring(startIndex, length)
  349. End If
  350. End Function
  351. ''' <summary>Returns the substring after the last occurrence of the specified string</summary>
  352. ''' <param name="source">The string to substring.</param>
  353. ''' <param name="search">The string to search for.</param>
  354. <Extension()> _
  355. Public Function SubstringAfter(ByVal source As String, ByVal search As String) As String
  356. If String.IsNullOrEmpty(source) Then
  357. Return ""
  358. End If
  359. If String.IsNullOrEmpty(search) Then
  360. Return ""
  361. End If
  362. Dim location As Integer = source.LastIndexOf(search, StringComparison.OrdinalIgnoreCase)
  363. If location >= 0 Then
  364. If location + search.Length < source.Length Then
  365. Return source.Substring(location + search.Length)
  366. Else
  367. Return ""
  368. End If
  369. Else
  370. Return ""
  371. End If
  372. End Function
  373. ''' <summary>Returns the substring before the last occurrence of the specified string</summary>
  374. ''' <param name="source">The string to substring.</param>
  375. ''' <param name="search">The string to search for.</param>
  376. <Extension()> _
  377. Public Function SubstringBefore(ByVal source As String, ByVal search As String) As String
  378. If String.IsNullOrEmpty(source) Then
  379. Return ""
  380. End If
  381. If String.IsNullOrEmpty(search) Then
  382. Return ""
  383. End If
  384. Dim location As Integer = source.LastIndexOf(search, StringComparison.OrdinalIgnoreCase)
  385. If location >= 0 Then
  386. Return source.Substring(0, location)
  387. Else
  388. Return ""
  389. End If
  390. End Function
  391. ''' <summary>Returns the substring after the last occurrence of the specified string</summary>
  392. ''' <param name="source">The string to substring.</param>
  393. ''' <param name="startDelimiter">The start delimiter to search for.</param>
  394. ''' <param name="endDelimiter">The end delimiter to search for.</param>
  395. <Extension()> _
  396. Public Function SubstringBetween(ByVal source As String, ByVal startDelimiter As String, ByVal endDelimiter As String) As String
  397. If String.IsNullOrEmpty(source) Then
  398. Return ""
  399. End If
  400. If String.IsNullOrEmpty(startDelimiter) Then
  401. Return ""
  402. End If
  403. Dim startLocation As Integer = source.LastIndexOf(startDelimiter, StringComparison.OrdinalIgnoreCase) + startDelimiter.Length
  404. Dim endLocation As Integer = source.LastIndexOf(endDelimiter, StringComparison.OrdinalIgnoreCase)
  405. If startLocation >= 0 AndAlso startLocation < endLocation Then
  406. Return source.Substring(startLocation, endLocation - startLocation)
  407. Else
  408. Return ""
  409. End If
  410. End Function
  411. #End Region
  412. #Region " COMMON ESCAPE SEQUENCES "
  413. ''' <summary>
  414. ''' Replaces common escape strings such as <code>'\n'</code> or <code>'\r'</code>with control
  415. ''' characters such as <code>10</code> and <code>13</code>, respectively.
  416. ''' </summary>
  417. ''' <param name="value">Text including escape sequences.</param>
  418. ''' <returns></returns>
  419. ''' <remarks></remarks>
  420. <Extension()> _
  421. Public Function ReplaceCommonEscapeSequences(ByVal value As String) As String
  422. If (value <> Nothing) Then
  423. Return value.Replace("\n", Convert.ToChar(10)).Replace("\r", Convert.ToChar(13))
  424. Else
  425. Return Nothing
  426. End If
  427. End Function
  428. ''' <summary>
  429. ''' Replaces control characters such as <code>10</code> and <code>13</code> with
  430. ''' common escape strings such as <code>'\n'</code> or <code>'\r'</code>, respectively.
  431. ''' </summary>
  432. ''' <param name="value">Text including control characters.</param>
  433. ''' <returns></returns>
  434. ''' <remarks></remarks>
  435. <Extension()> _
  436. Public Function InsertCommonEscapeSequences(ByVal value As String) As String
  437. If (value <> Nothing) Then
  438. Return value.Replace(Convert.ToChar(10), "\n").Replace(Convert.ToChar(13), "\r")
  439. Else
  440. Return Nothing
  441. End If
  442. End Function
  443. #End Region
  444. #Region " FORMATTING "
  445. ''' <summary>Returns a centered string.
  446. ''' </summary>
  447. ''' <returns>The input string centered with appropriate number of spaces
  448. ''' on each side.
  449. ''' </returns>
  450. ''' <param name="value">Specifies the original string.</param>
  451. ''' <param name="length">Specifies the total length of the new string</param>
  452. ''' <history>
  453. ''' </history>
  454. <Extension()> _
  455. Public Function Center(ByVal value As String, ByVal length As Integer) As String
  456. Dim leftSpacesCount As Double
  457. Dim rightSpacesCount As Double
  458. If length <= 0 Then
  459. Return ""
  460. ElseIf String.IsNullOrEmpty(value) Then
  461. Return "".PadLeft(length, " "c)
  462. ElseIf value.Length > length Then
  463. Return value.Substring(0, length)
  464. ElseIf value.Length = length Then
  465. Return value
  466. Else
  467. leftSpacesCount = (length - value.Length) \ 2S
  468. rightSpacesCount = length - value.Length - leftSpacesCount
  469. Return "".PadLeft(CInt(leftSpacesCount), " "c) & value _
  470. & "".PadLeft(CInt(rightSpacesCount), " "c)
  471. End If
  472. End Function
  473. ''' <summary>Returns a left aligned string. If the string is too large, the
  474. ''' only 'length' values are returned with the last character
  475. ''' set to '~' to signify the lost character.
  476. ''' </summary>
  477. <Extension()> _
  478. Public Function LeftAlign(ByVal caption As String, ByVal captionWidth As Integer) As String
  479. Const spaceCharacter As Char = " "c
  480. Const lostCharacter As Char = "~"c
  481. ' make sure we have one left space.
  482. If captionWidth <= 0 Then
  483. Return ""
  484. ElseIf String.IsNullOrEmpty(caption) Then
  485. Return ""
  486. ElseIf caption.Length > captionWidth Then
  487. Return caption.Substring(0, captionWidth - 1) & lostCharacter
  488. ElseIf caption.Length = captionWidth Then
  489. Return caption
  490. Else
  491. Return caption.PadRight(captionWidth, spaceCharacter)
  492. End If
  493. End Function
  494. ''' <summary>Returns a right aligned string. If the string is too large, the
  495. ''' only 'length' values are returned with the first character
  496. ''' set to '~' to signify the lost character.
  497. ''' </summary>
  498. <Extension()> _
  499. Public Function RightAlign(ByVal caption As String, ByVal captionWidth As Integer) As String
  500. Const spaceCharacter As Char = " "c
  501. Const lostCharacter As Char = "~"c
  502. ' make sure we have one left space.
  503. If captionWidth <= 0 Then
  504. Return ""
  505. ElseIf String.IsNullOrEmpty(caption) Then
  506. Return ""
  507. ElseIf caption.Length > captionWidth Then
  508. Return lostCharacter & caption.Substring(0, captionWidth - 1)
  509. ElseIf caption.Length = captionWidth Then
  510. Return caption
  511. Else
  512. Return caption.PadLeft(captionWidth, spaceCharacter)
  513. End If
  514. End Function
  515. #End Region
  516. #Region " COMPRESSION "
  517. ''' <summary>
  518. ''' Returns a compressed value.
  519. ''' </summary>
  520. ''' <param name="value"></param>
  521. ''' <returns></returns>
  522. ''' <remarks></remarks>
  523. ''' <history>
  524. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  525. ''' </history>
  526. <Extension()> _
  527. Public Function Compress(ByVal value As String) As String
  528. If String.IsNullOrEmpty(value) Then
  529. Return ""
  530. Exit Function
  531. End If
  532. Dim result As String = ""
  533. ' Compress the byte array
  534. Using memoryStream As New System.IO.MemoryStream()
  535. Using compressedStream As New System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Compress)
  536. ' Convert the uncompressed string into a byte array
  537. Dim values As Byte() = System.Text.Encoding.UTF8.GetBytes(value)
  538. compressedStream.Write(values, 0, values.Length)
  539. ' Don't FLUSH here - it possibly leads to data loss!
  540. compressedStream.Close()
  541. Dim compressedValues As Byte() = memoryStream.ToArray()
  542. ' Convert the compressed byte array back to a string
  543. result = System.Convert.ToBase64String(compressedValues)
  544. memoryStream.Close()
  545. End Using
  546. End Using
  547. Return result
  548. End Function
  549. ''' <summary>
  550. ''' Returns the decompressed string of the value.
  551. ''' </summary>
  552. ''' <param name="value"></param>
  553. ''' <returns></returns>
  554. ''' <remarks></remarks>
  555. ''' <history>
  556. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  557. ''' </history>
  558. ''' <history date="04/09/2009" by="David Hary" revision="1.1.3516.x">
  559. ''' Bug fix in getting the size. Changed memoryStream.Length - 5 to memoryStream.Length - 4
  560. ''' </history>
  561. <Extension()> _
  562. Public Function Decompress(ByVal value As String) As String
  563. If String.IsNullOrEmpty(value) Then
  564. Return ""
  565. Exit Function
  566. End If
  567. Dim result As String = ""
  568. ' Convert the compressed string into a byte array
  569. Dim compressedValues As Byte() = System.Convert.FromBase64String(value)
  570. ' Decompress the byte array
  571. Using memoryStream As New IO.MemoryStream(compressedValues)
  572. Using compressedStream As New System.IO.Compression.GZipStream(memoryStream, System.IO.Compression.CompressionMode.Decompress)
  573. ' it looks like we are getting a bogus size.
  574. Dim sizeBytes(3) As Byte
  575. memoryStream.Position = memoryStream.Length - 4
  576. memoryStream.Read(sizeBytes, 0, 4)
  577. Dim outputSize As Int32 = BitConverter.ToInt32(sizeBytes, 0)
  578. memoryStream.Position = 0
  579. Dim values(outputSize - 1) As Byte
  580. compressedStream.Read(values, 0, outputSize)
  581. ' Convert the decompressed byte array back to a string
  582. result = System.Text.Encoding.UTF8.GetString(values)
  583. End Using
  584. End Using
  585. Return result
  586. End Function
  587. #End Region
  588. #Region " ENCRYPTION "
  589. <Extension()> _
  590. Public Function Encrypt(ByVal value As String, ByVal passphrase As String) As String
  591. If String.IsNullOrEmpty(value) Then
  592. Return ""
  593. ElseIf String.IsNullOrEmpty(passphrase) Then
  594. Throw New ArgumentNullException("passphrase")
  595. End If
  596. Return System.Convert.ToBase64String(Encrypt(System.Text.Encoding.UTF8.GetBytes(value), passphrase))
  597. End Function
  598. ''' <summary>
  599. ''' Encrypts the byte array using the
  600. ''' <see cref="System.Security.Cryptography.RijndaelManaged">Rijndael symmetrinc encryption algorithm</see>
  601. ''' </summary>
  602. ''' <param name="values"></param>
  603. ''' <param name="passPhrase"></param>
  604. ''' <returns></returns>
  605. ''' <remarks></remarks>
  606. ''' <history>
  607. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  608. ''' </history>
  609. Private Function encrypt(ByVal values As Byte(), ByVal passphrase As String) As Byte()
  610. If values Is Nothing Then
  611. Return values
  612. ElseIf String.IsNullOrEmpty(passphrase) Then
  613. Throw New ArgumentNullException("passphrase")
  614. End If
  615. Dim result As Byte() = {}
  616. Using encryptionAlgorithm As New System.Security.Cryptography.RijndaelManaged
  617. encryptionAlgorithm.KeySize = 256
  618. encryptionAlgorithm.Key = encryptionKey(passphrase)
  619. encryptionAlgorithm.IV = encryptionInitializationVector(passphrase)
  620. Using memoryStream As New IO.MemoryStream
  621. Using cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
  622. encryptionAlgorithm.CreateEncryptor, _
  623. Security.Cryptography.CryptoStreamMode.Write)
  624. cryptoStream.Write(values, 0, values.Length)
  625. cryptoStream.FlushFinalBlock()
  626. result = memoryStream.ToArray()
  627. cryptoStream.Close()
  628. memoryStream.Close()
  629. End Using
  630. End Using
  631. End Using
  632. Return result
  633. End Function
  634. <Extension()> _
  635. Public Function Decrypt(ByVal value As String, ByVal passphrase As String) As String
  636. If String.IsNullOrEmpty(value) Then
  637. Return ""
  638. ElseIf String.IsNullOrEmpty(passphrase) Then
  639. Throw New ArgumentNullException("passphrase")
  640. End If
  641. Return System.Text.Encoding.UTF8.GetString(Decrypt(System.Convert.FromBase64String(value), passphrase))
  642. End Function
  643. ''' <summary>
  644. ''' Decrypts the byte array using the
  645. ''' <see cref="System.Security.Cryptography.RijndaelManaged">Rijndael symmetrinc encryption algorithm</see>
  646. ''' </summary>
  647. ''' <param name="values"></param>
  648. ''' <param name="passPhrase"></param>
  649. ''' <returns></returns>
  650. ''' <remarks></remarks>
  651. ''' <history>
  652. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  653. ''' </history>
  654. Private Function decrypt(ByVal values As Byte(), ByVal passphrase As String) As Byte()
  655. If values Is Nothing Then
  656. Return values
  657. ElseIf String.IsNullOrEmpty(passphrase) Then
  658. Throw New ArgumentNullException("passphrase")
  659. End If
  660. Dim result As Byte() = {}
  661. Using encryptionAlgorithm As New System.Security.Cryptography.RijndaelManaged
  662. encryptionAlgorithm.KeySize = 256
  663. encryptionAlgorithm.Key = encryptionKey(passphrase)
  664. encryptionAlgorithm.IV = encryptionInitializationVector(passphrase)
  665. Using memoryStream As New IO.MemoryStream(values)
  666. Using cryptoStream As New Security.Cryptography.CryptoStream(memoryStream, _
  667. encryptionAlgorithm.CreateDecryptor, _
  668. Security.Cryptography.CryptoStreamMode.Read)
  669. Dim workspace As Byte()
  670. ReDim workspace(values.Length)
  671. Dim decryptedByteCount As Integer
  672. decryptedByteCount = cryptoStream.Read(workspace, 0, values.Length)
  673. cryptoStream.Close()
  674. memoryStream.Close()
  675. ReDim result(decryptedByteCount)
  676. Array.Copy(workspace, result, decryptedByteCount)
  677. End Using
  678. End Using
  679. End Using
  680. Return result
  681. End Function
  682. ''' <summary>
  683. ''' Generates a byte array of required length as the encryption key.
  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 encryptionKey(ByVal passphrase As String) As Byte()
  692. If String.IsNullOrEmpty(passphrase) Then
  693. Throw New ArgumentNullException("passphrase")
  694. End If
  695. 'A SHA256 hash of the passphrase has just the required length. It is used twice in a manner of self-salting.
  696. Using SHA256 As New System.Security.Cryptography.SHA256Managed
  697. Dim L1 As String = System.Convert.ToBase64String(SHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(passphrase)))
  698. Dim L2 As String = passphrase & L1
  699. Return SHA256.ComputeHash(System.Text.Encoding.UTF8.GetBytes(L2))
  700. End Using
  701. End Function
  702. ''' <summary>
  703. ''' Generates a byte array of required length as the initialization vector.
  704. ''' </summary>
  705. ''' <param name="passPhrase"></param>
  706. ''' <returns></returns>
  707. ''' <remarks></remarks>
  708. ''' <history>
  709. ''' From "Easy String Compression and Encryption" http://www.codeproject.com/KB/string/string_compression.aspx
  710. ''' </history>
  711. Private Function encryptionInitializationVector(ByVal passphrase As String) As Byte()
  712. If String.IsNullOrEmpty(passphrase) Then
  713. Throw New ArgumentNullException("passphrase")
  714. End If
  715. ' A MD5 hash of the passphrase has just the required length. It is used twice in a manner of self-salting.
  716. Using MD5 As New System.Security.Cryptography.MD5CryptoServiceProvider
  717. Dim L1 As String = System.Convert.ToBase64String(MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(passphrase)))
  718. Dim L2 As String = passphrase & L1
  719. Return MD5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(L2))
  720. End Using
  721. End Function
  722. #End Region
  723. #Region " SPLIT TO WORDS "
  724. ''' <summary>
  725. ''' Splits the string to words by adding spaces between lower and upper case characters.
  726. ''' </summary>
  727. ''' <param name="value">The <c>String</c> value to split.</param>
  728. ''' <returns>A <c>String</c> of words separated by spaces.</returns>
  729. <Extension()> _
  730. Public Function SplitWords(ByVal value As String) As String
  731. If String.IsNullOrEmpty(value) Then
  732. Return ""
  733. Else
  734. Dim isSpace As Boolean = False
  735. Dim isLowerCase As Boolean = False
  736. Dim newValue As New System.Text.StringBuilder
  737. For Each c As Char In value
  738. If Not isSpace AndAlso isLowerCase AndAlso Char.IsUpper(c) Then
  739. newValue.Append(" ")
  740. End If
  741. isSpace = c.Equals(" "c)
  742. isLowerCase = Not Char.IsUpper(c)
  743. newValue.Append(c)
  744. Next
  745. Return newValue.ToString()
  746. End If
  747. End Function
  748. #End Region
  749. #Region " HASH "
  750. ''' <summary>
  751. ''' Converts the value to a Base 64 Hash.
  752. ''' </summary>
  753. ''' <param name="value">Specifies the value to convert</param>
  754. ''' <returns></returns>
  755. ''' <remarks>Uses SHA Crypto service provider.</remarks>
  756. <Extension()> _
  757. Public Function ToBase64Hash(ByVal value As String) As String
  758. If String.IsNullOrEmpty(value) Then
  759. Return ""
  760. End If
  761. Using algorithm As New System.Security.Cryptography.SHA1CryptoServiceProvider
  762. Return ToBase64Hash(value, algorithm)
  763. End Using
  764. End Function
  765. ''' <summary>
  766. ''' Converts the value to a Base 64 Hash.
  767. ''' </summary>
  768. ''' <param name="value">Specifies the value to convert</param>
  769. ''' <param name="algorithm">Specifies the algorithm for computing the hash.</param>
  770. ''' <returns></returns>
  771. ''' <remarks>Uses SHA Crypto service provider.</remarks>
  772. <Extension()> _
  773. Public Function ToBase64Hash(ByVal value As String, ByVal algorithm As System.Security.Cryptography.HashAlgorithm) As String
  774. If String.IsNullOrEmpty(value) Then
  775. Return ""
  776. ElseIf algorithm Is Nothing Then
  777. Return value
  778. End If
  779. Dim encoding As New System.Text.UnicodeEncoding
  780. ' Store the source string in a byte array
  781. Dim values() As Byte = encoding.GetBytes(value)
  782. ' get a SHA provider.
  783. ' Dim provider As New System.Security.Cryptography.SHA1CryptoServiceProvider
  784. ' Create the hash
  785. values = algorithm.ComputeHash(values)
  786. ' return as a base64 encoded string
  787. Return Convert.ToBase64String(values)
  788. End Function
  789. #End Region
  790. #Region " VALIDATION "
  791. ''' <summary>
  792. ''' true, if is valid email address
  793. ''' from http://www.davidhayden.com/blog/dave/
  794. ''' archive/2006/11/30/ExtensionMethodsCSharp.aspx
  795. ''' </summary>
  796. ''' <param name="value">email address to test</param>
  797. ''' <returns>true, if is valid email address</returns>
  798. <Extension()> _
  799. Public Function IsValidEmailAddress(ByVal value As String) As Boolean
  800. If value Is Nothing Then
  801. Throw New ArgumentNullException("value")
  802. ElseIf String.IsNullOrEmpty(value) Then
  803. Return False
  804. End If
  805. Return New Text.RegularExpressions.Regex("^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$").IsMatch(value)
  806. End Function
  807. ''' <summary>
  808. ''' from http://www.osix.net/modules/article/?id=586
  809. '''
  810. ''' complete (not only http) url regex can be found
  811. ''' at http://internet.ls-la.net/folklore/url-regexpr.html
  812. ''' </summary>
  813. ''' <param name="value"></param>
  814. ''' <returns></returns>
  815. <Extension()> _
  816. Public Function IsValidUrl(ByVal value As String) As Boolean
  817. If value Is Nothing Then
  818. Throw New ArgumentNullException("value")
  819. ElseIf String.IsNullOrEmpty(value) Then
  820. Return False
  821. End If
  822. Return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)
  823. #If False Then
  824. Dim regularExpression As String = "^(https?://)" _
  825. & "?(([0-9a-z_!~*'().&=+$%-]+: )?[0-9a-z_!~*'().&=+$%-]+@)?" _
  826. & "(([0-9]{1,3}\.){3}[0-9]{1,3}" _
  827. & "|" & "([0-9a-z_!~*'()-]+\.)*" _
  828. & "([0-9a-z][0-9a-z-]{0,61})?[0-9a-z]\." _
  829. & "[a-z]{2,6})" & "(:[0-9]{1,4})?" & "((/?)|" _
  830. & "(/[0-9a-z_!~*'().;?:@&=+$,%#-]+)+/?)$"
  831. Return New Regex(regularExpression).IsMatch(value)
  832. #End If
  833. End Function
  834. ''' <summary>
  835. ''' Check if url (http) is available.
  836. ''' </summary>
  837. ''' <param name="value">url to check</param>
  838. ''' <example>
  839. ''' string url = "www.codeproject.com;
  840. ''' if( !url.UrlAvailable())
  841. ''' ...codeproject is not available
  842. ''' </example>
  843. ''' <returns>true if available</returns>
  844. <Extension()> _
  845. Public Function IsUrlAvailable(ByVal value As String) As Boolean
  846. ' use URI instead.
  847. If value Is Nothing Then
  848. Throw New ArgumentNullException("value")
  849. ElseIf String.IsNullOrEmpty(value) Then
  850. Return False
  851. Else
  852. Return Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)
  853. End If
  854. #If False Then
  855. If (Not value.StartsWith("http://", StringComparison.OrdinalIgnoreCase)) OrElse (Not value.StartsWith("https://", StringComparison.OrdinalIgnoreCase)) Then
  856. value = "http://" & value
  857. End If
  858. Try
  859. Dim myRequest As Net.HttpWebRequest = CType(Net.WebRequest.Create(value), Net.HttpWebRequest)
  860. myRequest.Method = "GET"
  861. myRequest.ContentType = "application/x-www-form-urlencoded"
  862. Dim myHttpWebResponse As Net.HttpWebResponse = CType(myRequest.GetResponse(), Net.HttpWebResponse)
  863. Return myHttpWebResponse IsNot Nothing
  864. Catch
  865. Return False
  866. End Try
  867. #End If
  868. End Function
  869. #End Region
  870. End Module
  871. ''' <summary>
  872. ''' Includes extensions for strings.
  873. ''' </summary>
  874. ''' <remarks></remarks>
  875. ''' <license>
  876. ''' (c) 2009 Elmarg.
  877. ''' Licensed under The Code Project Open License.
  878. ''' Unless required by applicable law or agreed to in writing, this software is provided
  879. ''' "AS IS", WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  880. ''' </license>
  881. ''' <history date="04/09/2009" by="David Hary" revision="1.2.3981.x">
  882. ''' From http://www.codeproject.com/KB/string/stringconversion.aspx
  883. ''' </history>
  884. Public Module [ConvertTo]
  885. #Region " WITH DEFAULT CULTURE "
  886. ''' <summary>
  887. ''' Converts the specified string value to its strong-typed counterpart.
  888. ''' If the conversion fails an exception will be raised. Supply a default value to suppress the exception.
  889. ''' </summary>
  890. <System.Runtime.CompilerServices.Extension()> _
  891. <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")> _
  892. Public Function ConvertTo(Of T)(ByVal value As String) As T
  893. Return ConvertTo(Of T)(value, CultureInfo.InvariantCulture)
  894. End Function
  895. ''' <summary>
  896. ''' Converts the specified string value to its strong-typed counterpart.
  897. ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
  898. ''' </summary>
  899. <System.Runtime.CompilerServices.Extension()> _
  900. Public Function ConvertTo(Of T)(ByVal value As String, ByVal defaultValue As T) As T
  901. Return ConvertTo(Of T)(value, CultureInfo.InvariantCulture, defaultValue)
  902. End Function
  903. #End Region
  904. #Region " WITH CULTURE AS STRING VALUE "
  905. ''' <summary>
  906. ''' Converts the specified string value to its strong-typed counterpart.
  907. ''' If the conversion fails an exception will be raised. Supply a default value to suppress the exception.
  908. ''' </summary>
  909. <System.Runtime.CompilerServices.Extension()> _
  910. <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")> _
  911. Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As String) As T
  912. Return ConvertTo(Of T)(value, CultureInfo.GetCultureInfo(culture))
  913. End Function
  914. ''' <summary>
  915. ''' Converts the specified string value to its strong-typed counterpart.
  916. ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
  917. ''' </summary>
  918. <System.Runtime.CompilerServices.Extension()> _
  919. Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As String, ByVal defaultValue As T) As T
  920. Return ConvertTo(Of T)(value, CultureInfo.GetCultureInfo(culture), defaultValue)
  921. End Function
  922. #End Region
  923. #Region " WITH STRONG TYPED CULTURE "
  924. ''' <summary>
  925. ''' Converts the specified string value to its strong-typed counterpart.
  926. ''' If the conversion fails an exception will be raised. Supply a default value to suppress the exception.
  927. ''' </summary>
  928. ''' <typeparam name="T">The type to return</typeparam>
  929. ''' <param name="value">The value.</param>
  930. ''' <param name="culture">The culture.</param>
  931. ''' <returns></returns>
  932. <System.Runtime.CompilerServices.Extension()> _
  933. <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1004:GenericMethodsShouldProvideTypeParameter")> _
  934. Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As CultureInfo) As T
  935. Return ConvertTo(Of T)(value, culture, Nothing, True)
  936. End Function
  937. ''' <summary>
  938. ''' Converts the specified string value to its strong-typed counterpart.
  939. ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
  940. ''' </summary>
  941. <System.Runtime.CompilerServices.Extension()> _
  942. Public Function ConvertTo(Of T)(ByVal value As String, ByVal culture As CultureInfo, ByVal defaultValue As T) As T
  943. Return ConvertTo(Of T)(value, culture, defaultValue, False)
  944. End Function
  945. ''' <summary>
  946. ''' Converts the specified string value to its strong-typed counterpart.
  947. ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
  948. ''' </summary>
  949. <System.Runtime.CompilerServices.Extension()> _
  950. Public Function ConvertTo(Of T)(ByVal value As String, ByVal styles As NumberStyles, ByVal culture As CultureInfo, ByVal defaultValue As T) As T
  951. Return ConvertTo(Of T)(value, styles, culture, defaultValue, False)
  952. End Function
  953. ''' <summary>
  954. ''' Converts the specified string value to its strong-typed counterpart.
  955. ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
  956. ''' </summary>
  957. <System.Runtime.CompilerServices.Extension()> _
  958. 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
  959. Return _TryParse(Of T)(value, styles, culture, defaultValue, result)
  960. End Function
  961. ''' <summary>
  962. ''' Converts the specified string value to its strong-typed counterpart.
  963. ''' If the conversion fails the <param name="defaultValue">default value</param> will be returned.
  964. ''' </summary>
  965. <System.Runtime.CompilerServices.Extension()> _
  966. Public Function TryParse(Of T)(ByVal value As String, ByVal result As T) As Boolean
  967. Return _TryParse(Of T)(value, Globalization.CultureInfo.CurrentCulture, result)
  968. End Function
  969. #End Region
  970. #Region " WORKERS "
  971. ''' <summary>
  972. ''' Converts the specified string value to its strong-typed counterpart. If the conversion fails
  973. ''' either an exception is raised or the default value will be returned.
  974. ''' </summary>
  975. ''' <typeparam name="T"></typeparam>
  976. ''' <param name="value">The value.</param>
  977. ''' <param name="culture">The culture.</param>
  978. ''' <param name="result">The result.</param>
  979. ''' <returns></returns>
  980. <CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes")> _
  981. Private Function _TryParse(Of T)(ByVal value As String, ByVal culture As CultureInfo, ByRef result As T) As Boolean
  982. Dim converter As TypeConverter = TypeDescriptor.GetConverter(GetType(T))
  983. Try
  984. 'nasty but ne…

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