Advertisement
sylviapsh

DocumentationExample StringExtensions

May 18th, 2013
59
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 21.30 KB | None | 0 0
  1. //-----------------------------------------------------------------------
  2. // <copyright file="StringExtensions.cs" company="Telerik Academy">
  3. //     All rights reserved © Telerik Academy 2012-2013
  4. // </copyright>
  5. //-----------------------------------------------------------------------
  6. namespace Telerik.ILS.Common
  7. {
  8.     using System;
  9.     using System.Collections.Generic;
  10.     using System.Globalization;
  11.     using System.Linq;
  12.     using System.Security.Cryptography;
  13.     using System.Text;
  14.     using System.Text.RegularExpressions;
  15.  
  16.     /// <summary>
  17.     /// Extension methods for the <see cref="System.String"/> class.
  18.     /// </summary>
  19.     public static class StringExtensions
  20.     {
  21.         /// <summary>
  22.         /// Computes the hash of the input string using the MD5 Message-Digest Algorithm. It converts the input string to a byte array and formats it as a hexadecimal string.
  23.         /// </summary>
  24.         /// <param name="input">The input gets the string whose MD5 hash the method computes.</param>
  25.         /// <returns>Hexadecimal string of the computed hash of the input string</returns>
  26.         /// <example>
  27.         /// How to use the <see cref="ToMD5Hash"/> method
  28.         /// <code>
  29.         /// class TestClass
  30.         /// {
  31.         ///     static void Main()
  32.         ///     {
  33.         ///         string value = "test";
  34.         ///         Console.WriteLine(value.ToMD5Hash());
  35.         ///     }
  36.         /// }
  37.         /// </code>
  38.         /// </example>
  39.         /// <seealso cref="http://en.wikipedia.org/wiki/Md5"/>
  40.         public static string ToMd5Hash(this string input)
  41.         {
  42.             var md5Hash = MD5.Create();
  43.  
  44.             var hashArray = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
  45.  
  46.             var hexadecimalStringBuilder = new StringBuilder();
  47.  
  48.             for (int i = 0; i < hashArray.Length; i++)
  49.             {
  50.                 hexadecimalStringBuilder.Append(hashArray[i].ToString("x2"));
  51.             }
  52.  
  53.             return hexadecimalStringBuilder.ToString();
  54.         }
  55.  
  56.         /// <summary>
  57.         /// Checks if the input string is among the specified values that qualify as <see cref="System.Boolean"/> 'true'
  58.         /// </summary>
  59.         /// <param name="input"> Gets the string that should be checked</param>
  60.         /// <returns><see cref="System.Boolean"/> true or false depending on the presence of the input string in the array of 'true' values</returns>
  61.         /// <example>
  62.         /// How to use the <see cref="ToBoolean"/> method.
  63.         /// <code>
  64.         /// class TestClass
  65.         /// {
  66.         ///     static void Main()
  67.         ///     {
  68.         ///         string value = "ok";
  69.         ///         Console.WriteLine(value.ToBoolean());
  70.         ///     }
  71.         /// }
  72.         /// </code>
  73.         /// </example>
  74.         public static bool ToBoolean(this string input)
  75.         {
  76.             var trueValuesArray = new[] { "true", "ok", "yes", "1", "да" };
  77.             bool isTrueInput = trueValuesArray.Contains(input.ToLower());
  78.             return isTrueInput;
  79.         }
  80.  
  81.         /// <summary>
  82.         /// Converts the input string to <see cref="System.Int16"/>.
  83.         /// </summary>
  84.         /// <param name="input">Gets the string to be converted</param>
  85.         /// <returns>The converted to <see cref="System.Int16"/> string</returns>
  86.         /// <example>
  87.         /// How to use the <see cref="ToShort"/> method.
  88.         /// <code>
  89.         /// class TestClass
  90.         /// {
  91.         ///     static void Main()
  92.         ///     {
  93.         ///         string value = "3435";
  94.         ///         Console.WriteLine(value.ToShort());
  95.         ///     }
  96.         /// }
  97.         /// </code>
  98.         /// </example>
  99.         public static short ToShort(this string input)
  100.         {
  101.             short shortValue;
  102.             short.TryParse(input, out shortValue);
  103.             return shortValue;
  104.         }
  105.  
  106.         /// <summary>
  107.         /// Converts the input string to <see cref="System.Int32"/>.
  108.         /// </summary>
  109.         /// <param name="input">Gets the string to be converted</param>
  110.         /// <returns>The converted to <see cref="System.Int32"/> string</returns>
  111.         /// <example>
  112.         /// How to use the <see cref="ToInteger"/> method.
  113.         /// <code>
  114.         /// class TestClass
  115.         /// {
  116.         ///     static void Main()
  117.         ///     {
  118.         ///         string value = "1234";
  119.         ///         Console.WriteLine(value.ToInteger());
  120.         ///     }
  121.         /// }
  122.         /// </code>
  123.         /// </example>
  124.         public static int ToInteger(this string input)
  125.         {
  126.             int integerValue;
  127.             int.TryParse(input, out integerValue);
  128.             return integerValue;
  129.         }
  130.  
  131.         /// <summary>
  132.         /// Converts the input string to <see cref="System.Int64"/>.
  133.         /// </summary>
  134.         /// <param name="input">Gets the string to be converted</param>
  135.         /// <returns>The converted to <see cref="System.Int64"/> string</returns>
  136.         /// <example>
  137.         /// How to use the <see cref="ToLong"/> method.
  138.         /// <code>
  139.         /// class TestClass
  140.         /// {
  141.         ///     static void Main()
  142.         ///     {
  143.         ///         string value = "1234567";
  144.         ///         Console.WriteLine(value.ToLong());
  145.         ///     }
  146.         /// }
  147.         /// </code>
  148.         /// </example>
  149.         public static long ToLong(this string input)
  150.         {
  151.             long longValue;
  152.             long.TryParse(input, out longValue);
  153.             return longValue;
  154.         }
  155.  
  156.         /// <summary>
  157.         /// Converts the input string to <see cref="System.DateTime"/>.
  158.         /// </summary>
  159.         /// <param name="input">Gets the string to be converted</param>
  160.         /// <returns>The converted to <see cref="System.DateTime"/> date</returns>
  161.         /// <example>
  162.         /// How to use the <see cref="ToDateTime"/> method.
  163.         /// <code>
  164.         /// class TestClass
  165.         /// {
  166.         ///     static void Main()
  167.         ///     {
  168.         ///         string value = "2013/3/31 10:30:00";
  169.         ///         Console.WriteLine(value.ToDateTime());
  170.         ///     }
  171.         /// }
  172.         /// </code>
  173.         /// </example>
  174.         public static DateTime ToDateTime(this string input)
  175.         {
  176.             DateTime dateTimeValue;
  177.             DateTime.TryParse(input, out dateTimeValue);
  178.             return dateTimeValue;
  179.         }
  180.  
  181.         /// <summary>
  182.         /// Capitalizes the first letter of non-empty string
  183.         /// </summary>
  184.         /// <param name="input">String whose first letter should be capitalized</param>
  185.         /// <returns>The input string with the first letter in upper case or empty string if the string ahs been empty.</returns>
  186.         /// <example>
  187.         /// How to use the <see cref="CapitalizeFirstLetter"/> method.
  188.         /// <code>
  189.         /// class TestClass
  190.         /// {
  191.         ///     static void Main()
  192.         ///     {
  193.         ///         string value = "something to test with.";
  194.         ///         Console.WriteLine(value.CapitalizeFirstLetter()); //Output: Something to test with.
  195.         ///     }
  196.         /// }
  197.         /// </code>
  198.         /// </example>
  199.         public static string CapitalizeFirstLetter(this string input)
  200.         {
  201.             if (string.IsNullOrEmpty(input))
  202.             {
  203.                 return input;
  204.             }
  205.             else
  206.             {
  207.                 var capitalizedInput = input.Substring(0, 1).ToUpper(CultureInfo.CurrentCulture) + input.Substring(1, input.Length - 1);
  208.                 return capitalizedInput;
  209.             }
  210.         }
  211.  
  212.         /// <summary>
  213.         /// Returns a substring between <paramref name="startString"/> and <paramref name="endString"/>.
  214.         /// The search starts from <paramref name="startFrom"/> index.
  215.         /// </summary>
  216.         /// <param name="input">The initial string</param>
  217.         /// <param name="startString">The starting point of the result string.</param>
  218.         /// <param name="endString">The ending point of the result string.</param>
  219.         /// <param name="startFromIndex">The start index of the search.</param>
  220.         /// <returns>A substring of the initial string that is between the <paramref name="startString"/>
  221.         /// and the <paramref name="endString"/> searching from the <paramref name="startFromIndex"/> index or System.String.Empty
  222.         /// if <paramref name="startString"/> or <paramref name="endString"/> are not found in the initial string.</returns>
  223.         /// <example>
  224.         /// How to use the <see cref="GetStringBetween"/> method.
  225.         /// <code>
  226.         /// class TestClass
  227.         /// {
  228.         ///     static void Main()
  229.         ///     {
  230.         ///         string value = "If I want to start here and see all these things until I end here.";
  231.         ///         Console.WriteLine(value.GetStringBetween("start here", "end here", 10));
  232.         ///     }
  233.         /// }
  234.         /// </code>
  235.         /// </example>
  236.         public static string GetStringBetween(this string input, string startString, string endString, int startFromIndex)
  237.         {
  238.             input = input.Substring(startFromIndex);
  239.             startFromIndex = 0;
  240.             if (!input.Contains(startString) || !input.Contains(endString))
  241.             {
  242.                 return string.Empty;
  243.             }
  244.  
  245.             var startPosition = input.IndexOf(startString, startFromIndex, StringComparison.Ordinal) + startString.Length;
  246.             if (startPosition == -1)
  247.             {
  248.                 return string.Empty;
  249.             }
  250.  
  251.             var endPosition = input.IndexOf(endString, startPosition, StringComparison.Ordinal);
  252.             if (endPosition == -1)
  253.             {
  254.                 return string.Empty;
  255.             }
  256.  
  257.             return input.Substring(startPosition, endPosition - startPosition);
  258.         }
  259.  
  260.         /// <summary>
  261.         /// Replaces all Cyrillic letters in the input string with their Latin counterparts.
  262.         /// </summary>
  263.         /// <param name="input">The string to be converted.</param>
  264.         /// <returns>A string with latin letters.</returns>
  265.         /// <example>
  266.         /// How to use the <see cref="ConvertCyrillicToLatinLetters"/> method.
  267.         /// <code>
  268.         /// class TestClass
  269.         /// {
  270.         ///     static void Main()
  271.         ///     {
  272.         ///         string value = "Букви за преминаване към латиница";
  273.         ///         Console.WriteLine(value.ConvertCyrillicToLatinLetters());
  274.         ///     }
  275.         /// }
  276.         /// </code>
  277.         /// </example>
  278.         public static string ConvertCyrillicToLatinLetters(this string input)
  279.         {
  280.             var bulgarianLetters = new[]
  281.                                        {
  282.                                            "а", "б", "в", "г", "д", "е", "ж", "з", "и", "й", "к", "л", "м", "н", "о", "п",
  283.                                            "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ь", "ю", "я"
  284.                                        };
  285.             var latinRepresentationsOfBulgarianLetters = new[]
  286.                                                              {
  287.                                                                  "a", "b", "v", "g", "d", "e", "j", "z", "i", "y", "k",
  288.                                                                  "l", "m", "n", "o", "p", "r", "s", "t", "u", "f", "h",
  289.                                                                  "c", "ch", "sh", "sht", "u", "i", "yu", "ya"
  290.                                                              };
  291.             for (var i = 0; i < bulgarianLetters.Length; i++)
  292.             {
  293.                 input = input.ToLowerInvariant();
  294.                 input = input.Replace(bulgarianLetters[i], latinRepresentationsOfBulgarianLetters[i]);
  295.                 input = input.Replace(bulgarianLetters[i].ToUpper(), latinRepresentationsOfBulgarianLetters[i].CapitalizeFirstLetter());
  296.             }
  297.  
  298.             return input;
  299.         }
  300.  
  301.         /// <summary>
  302.         /// Replaces all Latin letters in the input string with their Cyrillic counterparts.
  303.         /// </summary>
  304.         /// <param name="input">The string to be converted.</param>
  305.         /// <returns>A string with cyrillic letters.</returns>
  306.         /// <example>
  307.         /// How to use the <see cref="ConvertCyrillicToLatinLetters"/> method.
  308.         /// <code>
  309.         /// class TestClass
  310.         /// {
  311.         ///     static void Main()
  312.         ///     {
  313.         ///         string value = "Bukvi za preminavane kym kirilica";
  314.         ///         Console.WriteLine(value.ConvertCyrillicToLatinLetters());
  315.         ///     }
  316.         /// }
  317.         /// </code>
  318.         /// </example>
  319.         public static string ConvertLatinToCyrillicLetters(this string input)
  320.         {
  321.             var latinLetters = new[]
  322.                                    {
  323.                                        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p",
  324.                                        "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
  325.                                    };
  326.  
  327.             var bulgarianRepresentationOfLatinLetters = new[]
  328.                                                              {
  329.                                                                  "а", "б", "ц", "д", "е", "ф", "г", "х", "и", "й", "к",
  330.                                                                  "л", "м", "н", "о", "п", "я", "р", "с", "т", "у", "ж",
  331.                                                                  "в", "ь", "ъ", "з"
  332.                                                              };
  333.  
  334.             for (int i = 0; i < latinLetters.Length; i++)
  335.             {
  336.                 input = input.ToLowerInvariant();
  337.                 input = input.Replace(latinLetters[i], bulgarianRepresentationOfLatinLetters[i]);
  338.                 input = input.Replace(latinLetters[i].ToUpper(), bulgarianRepresentationOfLatinLetters[i].ToUpper());
  339.             }
  340.  
  341.             return input;
  342.         }
  343.  
  344.         /// <summary>
  345.         /// Makes a user name valid by replacing all Cyrillic letters with their Latin equivalents and removing all non-alphanumeric characters except for the period (".") in the typed user name.
  346.         /// </summary>
  347.         /// <param name="input">User name</param>
  348.         /// <returns>A valid user name (allowed symbols: latin letters and a period)</returns>
  349.         /// <example>
  350.         /// How to use the <see cref="ToValidUsername"/> method.
  351.         /// <code>
  352.         /// class TestClass
  353.         /// {
  354.         ///     static void Main()
  355.         ///     {
  356.         ///         string value = "#$иван.иванов!@#";
  357.         ///         Console.WriteLine(value.ToValidUsername());// Output: иван.иванов
  358.         ///     }
  359.         /// }
  360.         /// </code>
  361.         /// </example>
  362.         public static string ToValidUsername(this string input)
  363.         {
  364.             input = input.ConvertCyrillicToLatinLetters();
  365.             return Regex.Replace(input, @"[^a-zA-z0-9_\.]+", string.Empty);
  366.         }
  367.  
  368.         /// <summary>
  369.         /// Makes a file name valid by replacing all Cyrillic letters with their Latin equivalents, all spaces are with hyphens and by removing all non-alphanumeric characters excluding hyphens and periods.
  370.         /// </summary>
  371.         /// <param name="input">File name.</param>
  372.         /// <returns>Valid file name (allowed symbols: latin letters, hyphens and periods)</returns>
  373.         /// <example>
  374.         /// How to use the <see cref="ToValidLatinFileName"/> method.
  375.         /// <code>
  376.         /// class TestClass
  377.         /// {
  378.         ///     static void Main()
  379.         ///     {
  380.         ///         string value = "Файл 30 раздел едно №$ 9А.docx";
  381.         ///         Console.WriteLine(value.ToValidLatinFileName()); // Output: Fail-razdel-edno-a.docx
  382.         ///     }
  383.         /// }
  384.         /// </code>
  385.         /// </example>
  386.         public static string ToValidLatinFileName(this string input)
  387.         {
  388.             input = input.Replace(" ", "-").ConvertCyrillicToLatinLetters();
  389.             return Regex.Replace(input, @"[^a-zA-z0-9_\.\-]+", string.Empty);
  390.         }
  391.  
  392.         /// <summary>
  393.         /// Extracts a substring of the input string from the start to a given number of characters <paramref name="charsCount"/> or the end of the string if the total characters are bigger than the input string length.
  394.         /// </summary>
  395.         /// <param name="input">Input string.</param>
  396.         /// <param name="charsCount">The number of characters in the desired substring.</param>
  397.         /// <returns>A substring containing the characters from the start of the input string to the number of characters specified with the  <paramref name="charsCount"/> or to the end of the input string.</returns>
  398.         /// <example>
  399.         /// How to use the <see cref="GetFirstCharacters"/> method.
  400.         /// <code>
  401.         /// class TestClass
  402.         /// {
  403.         ///     static void Main()
  404.         ///     {
  405.         ///         string value = "Playing around with the string values";
  406.         ///         Console.WriteLine(value.GetFirstCharacters(14)); // Output: Playing around
  407.         ///     }
  408.         /// }
  409.         /// </code>
  410.         /// </example>
  411.         public static string GetFirstCharacters(this string input, int charsCount)
  412.         {
  413.             return input.Substring(0, Math.Min(input.Length, charsCount));
  414.         }
  415.  
  416.         /// <summary>
  417.         /// Gets the file extension of the inputted as a string file name by splitting the input using the period as a delimiter
  418.         /// </summary>
  419.         /// <param name="fileName">The file name</param>
  420.         /// <returns>Returns the characters after the last found period</returns>
  421.         /// <example>
  422.         /// How to use the <see cref="GetFileExtension"/> method.
  423.         /// <code>
  424.         /// class TestClass
  425.         /// {
  426.         ///     static void Main()
  427.         ///     {
  428.         ///         string value = "Test.cs";
  429.         ///         Console.WriteLine(value.GetFileExtension()); //Output: cs
  430.         ///     }
  431.         /// }
  432.         /// </code>
  433.         /// </example>
  434.         public static string GetFileExtension(this string fileName)
  435.         {
  436.             if (string.IsNullOrWhiteSpace(fileName))
  437.             {
  438.                 return string.Empty;
  439.             }
  440.  
  441.             string[] fileParts = fileName.Split(new[] { "." }, StringSplitOptions.None);
  442.             if (fileParts.Count() == 1 || string.IsNullOrEmpty(fileParts.Last()))
  443.             {
  444.                 return string.Empty;
  445.             }
  446.  
  447.             return fileParts.Last().Trim().ToLower();
  448.         }
  449.  
  450.         /// <summary>
  451.         /// Returns the corresponding content type (a.k.a. Internet media type) for the specified file extension.
  452.         /// </summary>
  453.         /// <param name="fileExtension">File extension</param>
  454.         /// <returns>The content type</returns>
  455.         /// <example>
  456.         /// How to use the <see cref="ToContentType"/> method.
  457.         /// <code>
  458.         /// class TestClass
  459.         /// {
  460.         ///     static void Main()
  461.         ///     {
  462.         ///         string value = "png";
  463.         ///         Console.WriteLine(value.ToContentType());
  464.         ///     }
  465.         /// }
  466.         /// </code>
  467.         /// </example>
  468.         /// <seealso cref="http://en.wikipedia.org/wiki/Content_type"/>
  469.         public static string ToContentType(this string fileExtension)
  470.         {
  471.             var fileExtensionToContentType = new Dictionary<string, string>
  472.                                                  {
  473.                                                      { "jpg", "image/jpeg" },
  474.                                                      { "jpeg", "image/jpeg" },
  475.                                                      { "png", "image/x-png" },
  476.                                                      {
  477.                                                          "docx",
  478.                                                          "application/vnd.openxmlformats-officedocument.wordprocessingml.document"
  479.                                                      },
  480.                                                      { "doc", "application/msword" },
  481.                                                      { "pdf", "application/pdf" },
  482.                                                      { "txt", "text/plain" },
  483.                                                      { "rtf", "application/rtf" }
  484.                                                  };
  485.             if (fileExtensionToContentType.ContainsKey(fileExtension.Trim()))
  486.             {
  487.                 return fileExtensionToContentType[fileExtension.Trim()];
  488.             }
  489.  
  490.             return "application/octet-stream";
  491.         }
  492.  
  493.         /// <summary>
  494.         /// Converts the input string to a char array and block-copies the specified number of bytes to a byte array without offset.
  495.         /// </summary>
  496.         /// <param name="input">Input string</param>
  497.         /// <returns>A byte array</returns>
  498.         public static byte[] ToByteArray(this string input)
  499.         {
  500.             var bytesArray = new byte[input.Length * sizeof(char)];
  501.             Buffer.BlockCopy(input.ToCharArray(), 0, bytesArray, 0, bytesArray.Length);
  502.             return bytesArray;
  503.         }
  504.     }
  505. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement