BaseExtensions.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. using System;
  2. using System.Security.Cryptography;
  3. using System.Text;
  4. using System.Text.RegularExpressions;
  5. namespace MediaBrowser.Common.Extensions
  6. {
  7. /// <summary>
  8. /// Class BaseExtensions
  9. /// </summary>
  10. public static class BaseExtensions
  11. {
  12. /// <summary>
  13. /// Strips the HTML.
  14. /// </summary>
  15. /// <param name="htmlString">The HTML string.</param>
  16. /// <returns>System.String.</returns>
  17. public static string StripHtml(this string htmlString)
  18. {
  19. // http://stackoverflow.com/questions/1349023/how-can-i-strip-html-from-text-in-net
  20. const string pattern = @"<(.|\n)*?>";
  21. return Regex.Replace(htmlString, pattern, string.Empty).Trim();
  22. }
  23. /// <summary>
  24. /// Replaces the specified STR.
  25. /// </summary>
  26. /// <param name="str">The STR.</param>
  27. /// <param name="oldValue">The old value.</param>
  28. /// <param name="newValue">The new value.</param>
  29. /// <param name="comparison">The comparison.</param>
  30. /// <returns>System.String.</returns>
  31. public static string Replace(this string str, string oldValue, string newValue, StringComparison comparison)
  32. {
  33. var sb = new StringBuilder();
  34. var previousIndex = 0;
  35. var index = str.IndexOf(oldValue, comparison);
  36. while (index != -1)
  37. {
  38. sb.Append(str.Substring(previousIndex, index - previousIndex));
  39. sb.Append(newValue);
  40. index += oldValue.Length;
  41. previousIndex = index;
  42. index = str.IndexOf(oldValue, index, comparison);
  43. }
  44. sb.Append(str.Substring(previousIndex));
  45. return sb.ToString();
  46. }
  47. /// <summary>
  48. /// Gets the M d5.
  49. /// </summary>
  50. /// <param name="str">The STR.</param>
  51. /// <returns>Guid.</returns>
  52. public static Guid GetMD5(this string str)
  53. {
  54. using (var provider = MD5.Create())
  55. {
  56. return new Guid(provider.ComputeHash(Encoding.Unicode.GetBytes(str)));
  57. }
  58. }
  59. /// <summary>
  60. /// Gets the MB id.
  61. /// </summary>
  62. /// <param name="str">The STR.</param>
  63. /// <param name="type">The type.</param>
  64. /// <returns>Guid.</returns>
  65. /// <exception cref="System.ArgumentNullException">type</exception>
  66. [Obsolete("Use LibraryManager.GetNewItemId")]
  67. public static Guid GetMBId(this string str, Type type)
  68. {
  69. if (type == null)
  70. {
  71. throw new ArgumentNullException("type");
  72. }
  73. var key = type.FullName + str.ToLower();
  74. return key.GetMD5();
  75. }
  76. }
  77. }