├── .gitattributes ├── .gitignore ├── README.md ├── StringExtensionLibrary ├── Properties │ └── AssemblyInfo.cs ├── StringExtensionLibrary.csproj ├── StringExtensionLibrary.licenseheader ├── StringExtensions.cs └── packages.config ├── StringExtensions.sln └── StringExtensions ├── Properties └── AssemblyInfo.cs ├── StringExtensionTest.cs └── StringExtensions.csproj /.gitattributes: -------------------------------------------------------------------------------- 1 | ############################################################################### 2 | # Set default behavior to automatically normalize line endings. 3 | ############################################################################### 4 | * text=auto 5 | 6 | ############################################################################### 7 | # Set default behavior for command prompt diff. 8 | # 9 | # This is need for earlier builds of msysgit that does not have it on by 10 | # default for csharp files. 11 | # Note: This is only used by command line 12 | ############################################################################### 13 | #*.cs diff=csharp 14 | 15 | ############################################################################### 16 | # Set the merge driver for project and solution files 17 | # 18 | # Merging from the command prompt will add diff markers to the files if there 19 | # are conflicts (Merging from VS is not affected by the settings below, in VS 20 | # the diff markers are never inserted). Diff markers may cause the following 21 | # file extensions to fail to load in VS. An alternative would be to treat 22 | # these files as binary and thus will always conflict and require user 23 | # intervention with every merge. To do so, just uncomment the entries below 24 | ############################################################################### 25 | #*.sln merge=binary 26 | #*.csproj merge=binary 27 | #*.vbproj merge=binary 28 | #*.vcxproj merge=binary 29 | #*.vcproj merge=binary 30 | #*.dbproj merge=binary 31 | #*.fsproj merge=binary 32 | #*.lsproj merge=binary 33 | #*.wixproj merge=binary 34 | #*.modelproj merge=binary 35 | #*.sqlproj merge=binary 36 | #*.wwaproj merge=binary 37 | 38 | ############################################################################### 39 | # behavior for image files 40 | # 41 | # image files are treated as binary by default. 42 | ############################################################################### 43 | #*.jpg binary 44 | #*.png binary 45 | #*.gif binary 46 | 47 | ############################################################################### 48 | # diff behavior for common document formats 49 | # 50 | # Convert binary document formats to text before diffing them. This feature 51 | # is only available from the command line. Turn it on by uncommenting the 52 | # entries below. 53 | ############################################################################### 54 | #*.doc diff=astextplain 55 | #*.DOC diff=astextplain 56 | #*.docx diff=astextplain 57 | #*.DOCX diff=astextplain 58 | #*.dot diff=astextplain 59 | #*.DOT diff=astextplain 60 | #*.pdf diff=astextplain 61 | #*.PDF diff=astextplain 62 | #*.rtf diff=astextplain 63 | #*.RTF diff=astextplain 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | 4 | # User-specific files 5 | *.suo 6 | *.user 7 | *.sln.docstates 8 | 9 | # Build results 10 | 11 | [Dd]ebug/ 12 | [Rr]elease/ 13 | x64/ 14 | build/ 15 | [Bb]in/ 16 | [Oo]bj/ 17 | 18 | # Enable "build/" folder in the NuGet Packages folder since NuGet packages use it for MSBuild targets 19 | !packages/*/build/ 20 | 21 | # MSTest test Results 22 | [Tt]est[Rr]esult*/ 23 | [Bb]uild[Ll]og.* 24 | 25 | *_i.c 26 | *_p.c 27 | *.ilk 28 | *.meta 29 | *.obj 30 | *.pch 31 | *.pdb 32 | *.pgc 33 | *.pgd 34 | *.rsp 35 | *.sbr 36 | *.tlb 37 | *.tli 38 | *.tlh 39 | *.tmp 40 | *.tmp_proj 41 | *.log 42 | *.vspscc 43 | *.vssscc 44 | .builds 45 | *.pidb 46 | *.log 47 | *.scc 48 | 49 | # Visual C++ cache files 50 | ipch/ 51 | *.aps 52 | *.ncb 53 | *.opensdf 54 | *.sdf 55 | *.cachefile 56 | 57 | # Visual Studio profiler 58 | *.psess 59 | *.vsp 60 | *.vspx 61 | 62 | # Guidance Automation Toolkit 63 | *.gpState 64 | 65 | # ReSharper is a .NET coding add-in 66 | _ReSharper*/ 67 | *.[Rr]e[Ss]harper 68 | 69 | # TeamCity is a build add-in 70 | _TeamCity* 71 | 72 | # DotCover is a Code Coverage Tool 73 | *.dotCover 74 | 75 | # NCrunch 76 | *.ncrunch* 77 | .*crunch*.local.xml 78 | 79 | # Installshield output folder 80 | [Ee]xpress/ 81 | 82 | # DocProject is a documentation generator add-in 83 | DocProject/buildhelp/ 84 | DocProject/Help/*.HxT 85 | DocProject/Help/*.HxC 86 | DocProject/Help/*.hhc 87 | DocProject/Help/*.hhk 88 | DocProject/Help/*.hhp 89 | DocProject/Help/Html2 90 | DocProject/Help/html 91 | 92 | # Click-Once directory 93 | publish/ 94 | 95 | # Publish Web Output 96 | *.Publish.xml 97 | 98 | # NuGet Packages Directory 99 | ## TODO: If you have NuGet Package Restore enabled, uncomment the next line 100 | #packages/ 101 | 102 | # Windows Azure Build Output 103 | csx 104 | *.build.csdef 105 | 106 | # Windows Store app package directory 107 | AppPackages/ 108 | 109 | # Others 110 | sql/ 111 | *.Cache 112 | ClientBin/ 113 | [Ss]tyle[Cc]op.* 114 | ~$* 115 | *~ 116 | *.dbmdl 117 | *.[Pp]ublish.xml 118 | *.pfx 119 | *.publishsettings 120 | 121 | # RIA/Silverlight projects 122 | Generated_Code/ 123 | 124 | # Backup & report files from converting an old project file to a newer 125 | # Visual Studio version. Backup files are not needed, because we have git ;-) 126 | _UpgradeReport_Files/ 127 | Backup*/ 128 | UpgradeLog*.XML 129 | UpgradeLog*.htm 130 | 131 | # SQL Server files 132 | App_Data/*.mdf 133 | App_Data/*.ldf 134 | 135 | 136 | #LightSwitch generated files 137 | GeneratedArtifacts/ 138 | _Pvt_Extensions/ 139 | ModelManifest.xml 140 | 141 | # ========================= 142 | # Windows detritus 143 | # ========================= 144 | 145 | # Windows image file caches 146 | Thumbs.db 147 | ehthumbs.db 148 | 149 | # Folder config file 150 | Desktop.ini 151 | 152 | # Recycle Bin used on file shares 153 | $RECYCLE.BIN/ 154 | 155 | # Mac desktop service store files 156 | .DS_Store 157 | packages/ 158 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # StringExtensions 2 | 3 | c# StringExtensions Library provides comprehensive string extension methods that go behold just the common string validation methods extending the .Net System.string class. The idea to create such a library was motivated by the lack of such a StringUtil library such as org.apache.commons.lang3.StringUtils in the the .Net realm. The aim of this library is to serve as a goto library for those wishing to have such a library readily available to incorporate in to new or existing projects. 4 | 5 | 6 | ## Installation 7 | 8 | ```PM> 9 | Install-Package StringExtensionsLibrary 10 | ``` 11 | 12 | ## Usage 13 | 14 | Once you have installed the String extension library within your project. String extensions functions will be available on all string types 15 | 16 | 17 | if("64.233.161.1470".IsValidIPv4()){ 18 | \\do something 19 | } 20 | 21 | 22 | ## String Extension functions 23 | 24 | 25 | 26 | | Function Name | Description | 27 | |-------------------------|---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| 28 | | IsDateTime | Checks if date with dateFormat is parse-able to System.DateTime format returns boolean | 29 | | ToInt32 | Converts the string representation of a number to its 32-bit signed integer equivalent | 30 | | ToInt64 | Converts the string representation of a number to its 64-bit signed integer equivalent | 31 | | ToInt16 | Converts the string representation of a number to its 16-bit signed integer equivalent | 32 | | ToDecimal | Converts the string representation of a number to its System.Decimal equivalent | 33 | | ToBoolean | Converts string to its boolean equivalent | 34 | | ToBytes | Convert a string to its equivalent byte array | 35 | | SplitTo | Returns an enumerable collection of the specified type containing the substrings in this instance that are delimited by elements of a specified Char array | 36 | | ToEnum | Converts string to its Enum type,,Checks if string is a member of type T enum before converting. if fails returns default enum | 37 | | Format | Replaces one or more format items in a specified string with the string representation of a specified object | 38 | | GetEmptyStringIfNull | Gets empty String if passed value is of type Null | 39 | | GetDefaultIfEmpty | Returns a default String value if given value is null or empty | 40 | | IsInteger | IsInteger Function checks if a string is a valid int32 value | 41 | | IsNumeric | Checks if a string is a valid floating value | 42 | | IsAlpha | Checks if String contains only Unicode letters | 43 | | IsAlphaNumeric | Checks if the String contains only Unicode letters & digits. | 44 | | IsValidIPv4 | Checks if a string is valid IPv4 | 45 | | IsEmailAddress | checks if string is a valid email address | 46 | | Truncate | Truncate String and appends trailing ... | 47 | | Capitalize | Reads in a sequence of words from standard input and capitalize each,one (make first letter uppercase; make rest lowercase | 48 | | FristCharacter | Gets the first character in string | 49 | | LastCharacter | Gets last character in string | 50 | | Replace | Replace specified characters with an empty string | 51 | | RemoveChars | Remove Characters from string | 52 | | Reverse | Reverse string | 53 | | ParseStringToCsv | Escapes string by appending quotes for csv output | 54 | | Encrypt | Encrypt a string using the supplied key. Encoding is done using RSA encryption | 55 | | Decrypt | Decrypt a string using the supplied key. Decoding is done using RSA encryption | 56 | | CountOccurrences | Count number of occurrences in string based on the string to match | 57 | | JsonToDictionary | Converts a Json string to dictionary object. function is only applicable for single hierarchy objects i.e no parent child relationships, for parent child relationships JsonToExpanderObject | 58 | | JsonToExpanderObject | Converts a Json string to ExpandoObject method applicable for multi hierarchy objects i.e,having zero or many parent child relationships | 59 | | JsonToObject | Converts a Json string to object of type T. function applicable for multi hierarchy objects i.e,having zero or many parent child relationships, Ignore loop references and do not serialize if cycles are detected. | 60 | | RemovePrefix | Removes the first part of the string, if no match found return original string | 61 | | RemoveSuffix | Removes the end part of the string, if no match found return original string | 62 | | EndsWithIgnoreCase | Check a String ends with another string ignoring the case. | 63 | | StartsWithIgnoreCase | Check a String starts with another string ignoring the case. | 64 | | DoesNotStartWith | Check if a string does not start with prefix | 65 | | DoesNotEndWith | Check if a string does not end with prefix | 66 | | AppendSuffixIfMissing | Appends the suffix to the end of the string if the string does not already end in the suffix | 67 | | AppendPrefixIfMissing | Appends the prefix to the start of the string if the string does not already start with prefix | 68 | | CreateHashSha512 | Convert string to Hash using Sha512 | 69 | | CreateHashSha256 | Convert string to Hash using Sha256 | 70 | | QueryStringToDictionary | Convert url query string to IDictionary value key pair | 71 | | ReverseSlash | Reverse back or forward slashes | 72 | | ReplaceLineFeeds | Replace Line Feeds | 73 | | GetByteSize | Calculates the amount of bytes occupied by the input string based on the specified encoding argument | 74 | | Left | Extracts the left part of the input string limited by the length argument | 75 | | Right | Extracts the right part of the input string limited by the length argument | 76 | | ToTextElements | Converts a string to an Enumerable collection type of string elements | 77 | | IsNull | Checks if a string is null | 78 | | IsMinLength | Checks if string length is a certain minimum number of characters, does not ignore leading and trailing,white-space.,null strings will always evaluate to false. | 79 | | IsMaxLength | Checks if string length consists of the specified allowable maximum char length | 80 | | IsLength | Checks if string length satisfies minimum and maximum allowable char length. does not ignore leading and,trailing white-space | 81 | | GetLength | Gets the number of characters in string checks if string is null | 82 | | CreateParameters | Create basic dynamic SQL where parameters from a JSON key value pair string | 83 | -------------------------------------------------------------------------------- /StringExtensionLibrary/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | /*StringExtensions Library provides comprehensive string extension methods that go behold just the common string validation methods extending the .Net System.string class. The idea to create such a library was motivated by the lack of such a StringUtil library such as org.apache.commons.lang3.StringUtils in the the .Net realm. The aim of this library is to serve as a goto library for those wishing to have such a library readily available to incorporate in to new or existing projects. 2 | 3 | Copyright (C) 2015 Timothy Mugayi 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU General Public License as published by 6 | the Free Software Foundation, either version 3 of the License, or 7 | (at your option) any later version. 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU General Public License for more details. 12 | You should have received a copy of the GNU General Public License 13 | along with this program. If not, see .*/ 14 | using System.Reflection; 15 | using System.Runtime.InteropServices; 16 | 17 | // General Information about an assembly is controlled through the following 18 | // set of attributes. Change these attribute values to modify the information 19 | // associated with an assembly. 20 | [assembly: AssemblyTitle("StringExtensionLibrary")] 21 | [assembly: AssemblyDescription("String Extension Library")] 22 | [assembly: AssemblyConfiguration("")] 23 | [assembly: AssemblyCompany("Timothy Mugayi")] 24 | [assembly: AssemblyProduct("StringExtensionLibrary")] 25 | [assembly: AssemblyCopyright("Copyright © 2015")] 26 | [assembly: AssemblyTrademark("")] 27 | [assembly: AssemblyCulture("")] 28 | 29 | // Setting ComVisible to false makes the types in this assembly not visible 30 | // to COM components. If you need to access a type in this assembly from 31 | // COM, set the ComVisible attribute to true on that type. 32 | [assembly: ComVisible(false)] 33 | 34 | // The following GUID is for the ID of the typelib if this project is exposed to COM 35 | [assembly: Guid("741db6b4-1f05-4a4e-ad6f-c631d7de511c")] 36 | 37 | // Version information for an assembly consists of the following four values: 38 | // 39 | // Major Version 40 | // Minor Version 41 | // Build Number 42 | // Revision 43 | // 44 | // You can specify all the values or you can default the Build and Revision Numbers 45 | // by using the '*' as shown below: 46 | // [assembly: AssemblyVersion("1.0.*")] 47 | [assembly: AssemblyVersion("1.0.0.0")] 48 | [assembly: AssemblyFileVersion("1.0.0.0")] 49 | -------------------------------------------------------------------------------- /StringExtensionLibrary/StringExtensionLibrary.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {91DC5C7A-7DD0-4E71-B6D9-5D3DD76D2C77} 8 | Library 9 | Properties 10 | StringExtensionLibrary 11 | StringExtensionLibrary 12 | v4.5.1 13 | 512 14 | 15 | 16 | true 17 | full 18 | false 19 | bin\Debug\ 20 | DEBUG;TRACE 21 | prompt 22 | 4 23 | bin\Debug\StringExtensionLibrary.XML 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | False 36 | ..\packages\Newtonsoft.Json.6.0.8\lib\net45\Newtonsoft.Json.dll 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 62 | -------------------------------------------------------------------------------- /StringExtensionLibrary/StringExtensionLibrary.licenseheader: -------------------------------------------------------------------------------- 1 | extensions: designer.cs generated.cs 2 | extensions: .cs .cpp .h 3 | /* StringExtensions Library provides comprehensive string extension methods that go behold 4 | * just the common string validation methods extending the .Net System.string class. 5 | * The idea to create such a library was motivated by the lack of such a StringUtil library such as 6 | * org.apache.commons.lang3.StringUtils in the the .Net realm. The aim of this library is to serve as a goto library 7 | * for those wishing to have such a library readily available to incorporate in to new or existing projects. 8 | * 9 | * Copyright (C) 2015 Timothy Mugayi 10 | * 11 | * This program is free software: you can redistribute it and/or modify 12 | * it under the terms of the GNU General Public License as published by the Free Software Foundation, 13 | * either version 3 of the License, or (at your option) any later version. 14 | * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; 15 | * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 16 | * GNU General Public License for more details.You should have received a copy of the GNU General Public License along with this program. 17 | * If not, see . 18 | */ 19 | extensions: .aspx .ascx 20 | <%-- 21 | Sample license text. 22 | --%> 23 | extensions: .vb 24 | 'Sample license text. 25 | extensions: .xml .config .xsd 26 | -------------------------------------------------------------------------------- /StringExtensionLibrary/StringExtensions.cs: -------------------------------------------------------------------------------- 1 | /* StringExtensions Library provides comprehensive string extension methods that go behold 2 | * just the common string validation methods extending the .Net System.string class. 3 | * The idea to create such a library was motivated by the lack of such a StringUtil library such as 4 | * org.apache.commons.lang3.StringUtils in the .Net realm. The aim of this library is to serve as a goto library 5 | * for those wishing to have such a library readily available to incorporate in to new or existing projects. 6 | * 7 | * Copyright (C) 2015 Timothy Mugayi 8 | * 9 | * This program is free software: you can redistribute it and/or modify 10 | * it under the terms of the GNU General Public License as published by the Free Software Foundation, 11 | * either version 3 of the License, or (at your option) any later version. 12 | * This program is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; 13 | * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 | * GNU General Public License for more details.You should have received a copy of the GNU General Public License along with this program. 15 | * If not, see . 16 | */ 17 | 18 | using System; 19 | using System.Collections.Generic; 20 | using System.Dynamic; 21 | using System.Globalization; 22 | using System.Linq; 23 | using System.Security.Cryptography; 24 | using System.Text; 25 | using System.Text.RegularExpressions; 26 | using Newtonsoft.Json; 27 | using Newtonsoft.Json.Converters; 28 | 29 | namespace StringExtensionLibrary 30 | { 31 | /// 32 | /// Provides extension methods to the System.string object. 33 | /// 34 | public static class StringExtensions 35 | { 36 | /// 37 | /// Checks if date with dateFormat is parse-able to System.DateTime format returns boolean value if true else false 38 | /// 39 | /// String date 40 | /// date format example dd/MM/yyyy HH:mm:ss 41 | /// boolean True False if is valid System.DateTime 42 | public static bool IsDateTime(this string data, string dateFormat) 43 | { 44 | // ReSharper disable once RedundantAssignment 45 | DateTime dateVal = default(DateTime); 46 | return DateTime.TryParseExact(data, dateFormat, CultureInfo.InvariantCulture, DateTimeStyles.None, 47 | out dateVal); 48 | } 49 | 50 | /// 51 | /// Converts the string representation of a number to its 32-bit signed integer equivalent 52 | /// 53 | /// string containing a number to convert 54 | /// System.Int32 55 | /// 56 | /// The conversion fails if the string parameter is null, is not of the correct format, or represents a number 57 | /// less than System.Int32.MinValue or greater than System.Int32.MaxValue 58 | /// 59 | public static int ToInt32(this string value) 60 | { 61 | int number; 62 | Int32.TryParse(value, out number); 63 | return number; 64 | } 65 | 66 | /// 67 | /// Converts the string representation of a number to its 64-bit signed integer equivalent 68 | /// 69 | /// string containing a number to convert 70 | /// System.Int64 71 | /// 72 | /// The conversion fails if the string parameter is null, is not of the correct format, or represents a number 73 | /// less than System.Int64.MinValue or greater than System.Int64.MaxValue 74 | /// 75 | public static long ToInt64(this string value) 76 | { 77 | long number; 78 | Int64.TryParse(value, out number); 79 | return number; 80 | } 81 | 82 | /// 83 | /// Converts the string representation of a number to its 16-bit signed integer equivalent 84 | /// 85 | /// string containing a number to convert 86 | /// System.Int16 87 | /// 88 | /// The conversion fails if the string parameter is null, is not of the correct format, or represents a number 89 | /// less than System.Int16.MinValue or greater than System.Int16.MaxValue 90 | /// 91 | public static short ToInt16(this string value) 92 | { 93 | short number; 94 | Int16.TryParse(value, out number); 95 | return number; 96 | } 97 | 98 | /// 99 | /// Converts the string representation of a number to its System.Decimal equivalent 100 | /// 101 | /// string containing a number to convert 102 | /// System.Decimal 103 | /// 104 | /// The conversion fails if the s parameter is null, is not a number in a valid format, or represents a number 105 | /// less than System.Decimal.MinValue or greater than System.Decimal.MaxValue 106 | /// 107 | public static Decimal ToDecimal(this string value) 108 | { 109 | Decimal number; 110 | Decimal.TryParse(value, out number); 111 | return number; 112 | } 113 | 114 | /// 115 | /// Converts string to its boolean equivalent 116 | /// 117 | /// string to convert 118 | /// boolean equivalent 119 | /// 120 | /// 121 | /// thrown in the event no boolean equivalent found or an empty or whitespace 122 | /// string is passed 123 | /// 124 | /// 125 | public static bool ToBoolean(this string value) 126 | { 127 | if (string.IsNullOrEmpty(value) || string.IsNullOrWhiteSpace(value)) 128 | { 129 | throw new ArgumentException("value"); 130 | } 131 | string val = value.ToLower().Trim(); 132 | switch (val) 133 | { 134 | case "false": 135 | return false; 136 | case "f": 137 | return false; 138 | case "true": 139 | return true; 140 | case "t": 141 | return true; 142 | case "yes": 143 | return true; 144 | case "no": 145 | return false; 146 | case "y": 147 | return true; 148 | case "n": 149 | return false; 150 | default: 151 | throw new ArgumentException("Invalid boolean"); 152 | } 153 | } 154 | 155 | /// 156 | /// Returns an enumerable collection of the specified type containing the substrings in this instance that are 157 | /// delimited by elements of a specified Char array 158 | /// 159 | /// The string. 160 | /// 161 | /// An array of Unicode characters that delimit the substrings in this instance, an empty array containing no 162 | /// delimiters, or null. 163 | /// 164 | /// 165 | /// The type of the element to return in the collection, this type must implement IConvertible. 166 | /// 167 | /// 168 | /// An enumerable collection whose elements contain the substrings in this instance that are delimited by one or more 169 | /// characters in separator. 170 | /// 171 | public static IEnumerable SplitTo(this string str, params char[] separator) where T : IConvertible 172 | { 173 | return str.Split(separator, StringSplitOptions.None).Select(s => (T) Convert.ChangeType(s, typeof (T))); 174 | } 175 | 176 | /// 177 | /// Returns an enumerable collection of the specified type containing the substrings in this instance that are 178 | /// delimited by elements of a specified Char array 179 | /// 180 | /// The string. 181 | /// StringSplitOptions 182 | /// 183 | /// An array of Unicode characters that delimit the substrings in this instance, an empty array containing no 184 | /// delimiters, or null. 185 | /// 186 | /// 187 | /// The type of the element to return in the collection, this type must implement IConvertible. 188 | /// 189 | /// 190 | /// An enumerable collection whose elements contain the substrings in this instance that are delimited by one or more 191 | /// characters in separator. 192 | /// 193 | public static IEnumerable SplitTo(this string str, StringSplitOptions options, params char[] separator) 194 | where T : IConvertible 195 | { 196 | return str.Split(separator, options).Select(s => (T) Convert.ChangeType(s, typeof (T))); 197 | } 198 | 199 | /// 200 | /// Converts string to its Enum type 201 | /// Checks of string is a member of type T enum before converting 202 | /// if fails returns default enum 203 | /// 204 | /// generic type 205 | /// The string representation of the enumeration name or underlying value to convert 206 | /// 207 | /// Enum object 208 | /// 209 | /// 210 | /// enumType is not an System.Enum.-or- value is either an empty string ("") or 211 | /// only contains white space.-or- value is a name, but not one of the named constants defined for the enumeration 212 | /// 213 | /// 214 | public static T ToEnum(this string value, T defaultValue = default(T)) where T : struct 215 | { 216 | if (!typeof (T).IsEnum) 217 | { 218 | throw new ArgumentException("Type T Must of type System.Enum"); 219 | } 220 | 221 | T result; 222 | bool isParsed = Enum.TryParse(value, true, out result); 223 | return isParsed ? result : defaultValue; 224 | } 225 | 226 | /// 227 | /// Replaces one or more format items in a specified string with the string representation of a specified object. 228 | /// 229 | /// A composite format string 230 | /// An System.Object to format 231 | /// A copy of format in which any format items are replaced by the string representation of arg0 232 | /// format or args is null. 233 | /// 234 | /// format is invalid.-or- The index of a format item is less than zero, or 235 | /// greater than or equal to the length of the args array. 236 | /// 237 | public static string Format(this string value, object arg0) 238 | { 239 | return string.Format(value, arg0); 240 | } 241 | 242 | /// 243 | /// Replaces the format item in a specified string with the string representation of a corresponding object in a 244 | /// specified array. 245 | /// 246 | /// A composite format string 247 | /// An object array that contains zero or more objects to format 248 | /// 249 | /// A copy of format in which the format items have been replaced by the string representation of the 250 | /// corresponding objects in args 251 | /// 252 | /// format or args is null. 253 | /// 254 | /// format is invalid.-or- The index of a format item is less than zero, or 255 | /// greater than or equal to the length of the args array. 256 | /// 257 | public static string Format(this string value, params object[] args) 258 | { 259 | return string.Format(value, args); 260 | } 261 | 262 | /// 263 | /// Gets empty String if passed value is of type Null/Nothing 264 | /// 265 | /// val 266 | /// System.String 267 | /// 268 | public static string GetEmptyStringIfNull(this string val) 269 | { 270 | return (val != null ? val.Trim() : ""); 271 | } 272 | 273 | /// 274 | /// Checks if a string is null and returns String if not Empty else returns null/Nothing 275 | /// 276 | /// String value 277 | /// null/nothing if String IsEmpty 278 | /// 279 | public static string GetNullIfEmptyString(this string myValue) 280 | { 281 | if (myValue == null || myValue.Length <= 0) 282 | { 283 | return null; 284 | } 285 | myValue = myValue.Trim(); 286 | if (myValue.Length > 0) 287 | { 288 | return myValue; 289 | } 290 | return null; 291 | } 292 | 293 | /// 294 | /// IsInteger Function checks if a string is a valid int32 value 295 | /// 296 | /// val 297 | /// Boolean True if isInteger else False 298 | public static bool IsInteger(this string val) 299 | { 300 | // Variable to collect the Return value of the TryParse method. 301 | 302 | // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero. 303 | int retNum; 304 | 305 | // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent. 306 | // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned. 307 | bool isNum = Int32.TryParse(val, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out retNum); 308 | return isNum; 309 | } 310 | 311 | /// 312 | /// Read in a sequence of words from standard input and capitalize each 313 | /// one (make first letter uppercase; make rest lowercase). 314 | /// 315 | /// string 316 | /// Word with capitalization 317 | public static string Capitalize(this string s) 318 | { 319 | if (s.Length == 0) 320 | { 321 | return s; 322 | } 323 | return s.Substring(0, 1).ToUpper() + s.Substring(1).ToLower(); 324 | } 325 | 326 | /// 327 | /// Gets first character in string 328 | /// 329 | /// val 330 | /// System.string 331 | public static string FirstCharacter(this string val) 332 | { 333 | return (!string.IsNullOrEmpty(val)) 334 | ? (val.Length >= 1) 335 | ? val.Substring(0, 1) 336 | : val 337 | : null; 338 | } 339 | 340 | /// 341 | /// Gets last character in string 342 | /// 343 | /// val 344 | /// System.string 345 | public static string LastCharacter(this string val) 346 | { 347 | return (!string.IsNullOrEmpty(val)) 348 | ? (val.Length >= 1) 349 | ? val.Substring(val.Length - 1, 1) 350 | : val 351 | : null; 352 | } 353 | 354 | /// 355 | /// Check a String ends with another string ignoring the case. 356 | /// 357 | /// string 358 | /// suffix 359 | /// true or false 360 | public static bool EndsWithIgnoreCase(this string val, string suffix) 361 | { 362 | if (val == null) 363 | { 364 | throw new ArgumentNullException("val", "val parameter is null"); 365 | } 366 | if (suffix == null) 367 | { 368 | throw new ArgumentNullException("suffix", "suffix parameter is null"); 369 | } 370 | if (val.Length < suffix.Length) 371 | { 372 | return false; 373 | } 374 | return val.EndsWith(suffix, StringComparison.InvariantCultureIgnoreCase); 375 | } 376 | 377 | /// 378 | /// Check a String starts with another string ignoring the case. 379 | /// 380 | /// string 381 | /// prefix 382 | /// true or false 383 | public static bool StartsWithIgnoreCase(this string val, string prefix) 384 | { 385 | if (val == null) 386 | { 387 | throw new ArgumentNullException("val", "val parameter is null"); 388 | } 389 | if (prefix == null) 390 | { 391 | throw new ArgumentNullException("prefix", "prefix parameter is null"); 392 | } 393 | if (val.Length < prefix.Length) 394 | { 395 | return false; 396 | } 397 | return val.StartsWith(prefix, StringComparison.InvariantCultureIgnoreCase); 398 | } 399 | 400 | /// 401 | /// Replace specified characters with an empty string. 402 | /// 403 | /// the string 404 | /// list of characters to replace from the string 405 | /// 406 | /// string s = "Friends"; 407 | /// s = s.Replace('F', 'r','i','s'); //s becomes 'end; 408 | /// 409 | /// System.string 410 | public static string Replace(this string s, params char[] chars) 411 | { 412 | return chars.Aggregate(s, (current, c) => current.Replace(c.ToString(CultureInfo.InvariantCulture), "")); 413 | } 414 | 415 | /// 416 | /// Remove Characters from string 417 | /// 418 | /// string to remove characters 419 | /// array of chars 420 | /// System.string 421 | public static string RemoveChars(this string s, params char[] chars) 422 | { 423 | var sb = new StringBuilder(s.Length); 424 | foreach (char c in s.Where(c => !chars.Contains(c))) 425 | { 426 | sb.Append(c); 427 | } 428 | return sb.ToString(); 429 | } 430 | 431 | /// 432 | /// Validate email address 433 | /// 434 | /// string email address 435 | /// true or false if email if valid 436 | public static bool IsEmailAddress(this string email) 437 | { 438 | string pattern = 439 | "^[a-zA-Z][\\w\\.-]*[a-zA-Z0-9]@[a-zA-Z0-9][\\w\\.-]*[a-zA-Z0-9]\\.[a-zA-Z][a-zA-Z\\.]*[a-zA-Z]$"; 440 | return Regex.Match(email, pattern).Success; 441 | } 442 | 443 | /// 444 | /// IsNumeric checks if a string is a valid floating value 445 | /// 446 | /// 447 | /// Boolean True if isNumeric else False 448 | /// 449 | public static bool IsNumeric(this string val) 450 | { 451 | // Variable to collect the Return value of the TryParse method. 452 | 453 | // Define variable to collect out parameter of the TryParse method. If the conversion fails, the out parameter is zero. 454 | double retNum; 455 | 456 | // The TryParse method converts a string in a specified style and culture-specific format to its double-precision floating point number equivalent. 457 | // The TryParse method does not generate an exception if the conversion fails. If the conversion passes, True is returned. If it does not, False is returned. 458 | bool isNum = Double.TryParse(val, NumberStyles.Any, NumberFormatInfo.InvariantInfo, out retNum); 459 | return isNum; 460 | } 461 | 462 | /// 463 | /// Truncate String and append ... at end 464 | /// 465 | /// String to be truncated 466 | /// number of chars to truncate 467 | /// 468 | /// 469 | public static string Truncate(this string s, int maxLength) 470 | { 471 | if (String.IsNullOrEmpty(s) || maxLength <= 0) 472 | { 473 | return String.Empty; 474 | } 475 | if (s.Length > maxLength) 476 | { 477 | return s.Substring(0, maxLength) + "..."; 478 | } 479 | return s; 480 | } 481 | 482 | /// 483 | /// Function returns a default String value if given value is null or empty 484 | /// 485 | /// String value to check if isEmpty 486 | /// default value to return if String value isEmpty 487 | /// returns either String value or default value if IsEmpty 488 | /// 489 | public static string GetDefaultIfEmpty(this string myValue, string defaultValue) 490 | { 491 | if (!String.IsNullOrEmpty(myValue)) 492 | { 493 | myValue = myValue.Trim(); 494 | return myValue.Length > 0 ? myValue : defaultValue; 495 | } 496 | return defaultValue; 497 | } 498 | 499 | /// 500 | /// Convert a string to its equivalent byte array 501 | /// 502 | /// string to convert 503 | /// System.byte array 504 | public static byte[] ToBytes(this string val) 505 | { 506 | var bytes = new byte[val.Length*sizeof (char)]; 507 | Buffer.BlockCopy(val.ToCharArray(), 0, bytes, 0, bytes.Length); 508 | return bytes; 509 | } 510 | 511 | /// 512 | /// Reverse string 513 | /// 514 | /// string to reverse 515 | /// System.string 516 | public static string Reverse(this string val) 517 | { 518 | var chars = new char[val.Length]; 519 | for (int i = val.Length - 1, j = 0; i >= 0; --i, ++j) 520 | { 521 | chars[j] = val[i]; 522 | } 523 | val = new String(chars); 524 | return val; 525 | } 526 | 527 | /// 528 | /// Appends String quotes for type CSV data 529 | /// 530 | /// val 531 | /// 532 | /// 533 | public static string ParseStringToCsv(this string val) 534 | { 535 | return '"' + GetEmptyStringIfNull(val).Replace("\"", "\"\"") + '"'; 536 | } 537 | 538 | /// 539 | /// Encrypt a string using the supplied key. Encoding is done using RSA encryption. 540 | /// 541 | /// String that must be encrypted. 542 | /// Encryption key 543 | /// A string representing a byte array separated by a minus sign. 544 | /// Occurs when stringToEncrypt or key is null or empty. 545 | public static string Encrypt(this string stringToEncrypt, string key) 546 | { 547 | var cspParameter = new CspParameters {KeyContainerName = key}; 548 | var rsaServiceProvider = new RSACryptoServiceProvider(cspParameter) {PersistKeyInCsp = true}; 549 | byte[] bytes = rsaServiceProvider.Encrypt(Encoding.UTF8.GetBytes(stringToEncrypt), true); 550 | return BitConverter.ToString(bytes); 551 | } 552 | 553 | 554 | /// 555 | /// Decrypt a string using the supplied key. Decoding is done using RSA encryption. 556 | /// 557 | /// String that must be decrypted. 558 | /// Decryption key. 559 | /// The decrypted string or null if decryption failed. 560 | /// Occurs when stringToDecrypt or key is null or empty. 561 | public static string Decrypt(this string stringToDecrypt, string key) 562 | { 563 | var cspParamters = new CspParameters {KeyContainerName = key}; 564 | var rsaServiceProvider = new RSACryptoServiceProvider(cspParamters) {PersistKeyInCsp = true}; 565 | string[] decryptArray = stringToDecrypt.Split(new[] {"-"}, StringSplitOptions.None); 566 | byte[] decryptByteArray = Array.ConvertAll(decryptArray, 567 | (s => Convert.ToByte(byte.Parse(s, NumberStyles.HexNumber)))); 568 | byte[] bytes = rsaServiceProvider.Decrypt(decryptByteArray, true); 569 | string result = Encoding.UTF8.GetString(bytes); 570 | return result; 571 | } 572 | 573 | /// 574 | /// Count number of occurrences in string 575 | /// 576 | /// string containing text 577 | /// string or pattern find 578 | /// 579 | public static int CountOccurrences(this string val, string stringToMatch) 580 | { 581 | return Regex.Matches(val, stringToMatch, RegexOptions.IgnoreCase).Count; 582 | } 583 | 584 | /// 585 | /// Converts a Json string to dictionary object method applicable for single hierarchy objects i.e 586 | /// no parent child relationships, for parent child relationships 587 | /// 588 | /// string formated as Json 589 | /// IDictionary Json object 590 | /// 591 | /// if string parameter is null or empty 592 | /// 593 | public static IDictionary JsonToDictionary(this string val) 594 | { 595 | if (string.IsNullOrEmpty(val)) 596 | { 597 | throw new ArgumentNullException("val"); 598 | } 599 | return 600 | (Dictionary) JsonConvert.DeserializeObject(val, typeof (Dictionary)); 601 | } 602 | 603 | /// 604 | /// Converts a Json string to ExpandoObject method applicable for multi hierarchy objects i.e 605 | /// having zero or many parent child relationships 606 | /// 607 | /// string formated as Json 608 | /// System.Dynamic.ExpandoObject Json objectExpandoObject 609 | public static dynamic JsonToExpanderObject(this string json) 610 | { 611 | var converter = new ExpandoObjectConverter(); 612 | return JsonConvert.DeserializeObject(json, converter); 613 | } 614 | 615 | /// 616 | /// Converts a Json string to object of type T method applicable for multi hierarchy objects i.e 617 | /// having zero or many parent child relationships, Ignore loop references and do not serialize if cycles are detected. 618 | /// 619 | /// object to convert to 620 | /// json 621 | /// object 622 | public static T JsonToObject(this string json) 623 | { 624 | var settings = new JsonSerializerSettings {ReferenceLoopHandling = ReferenceLoopHandling.Ignore}; 625 | return JsonConvert.DeserializeObject(json, settings); 626 | } 627 | 628 | /// 629 | /// Removes the first part of the string, if no match found return original string 630 | /// 631 | /// string to remove prefix 632 | /// prefix 633 | /// Indicates whether the compare should ignore case 634 | /// trimmed string with no prefix or original string 635 | public static string RemovePrefix(this string val, string prefix, bool ignoreCase = true) 636 | { 637 | if (!string.IsNullOrEmpty(val) && (ignoreCase ? val.StartsWithIgnoreCase(prefix) : val.StartsWith(prefix))) 638 | { 639 | return val.Substring(prefix.Length, val.Length - prefix.Length); 640 | } 641 | return val; 642 | } 643 | 644 | /// 645 | /// Removes the end part of the string, if no match found return original string 646 | /// 647 | /// string to remove suffix 648 | /// suffix 649 | /// Indicates whether the compare should ignore case 650 | /// trimmed string with no suffix or original string 651 | public static string RemoveSuffix(this string val, string suffix, bool ignoreCase = true) 652 | { 653 | if (!string.IsNullOrEmpty(val) && (ignoreCase ? val.EndsWithIgnoreCase(suffix) : val.EndsWith(suffix))) 654 | { 655 | return val.Substring(0, val.Length - suffix.Length); 656 | } 657 | return null; 658 | } 659 | 660 | /// 661 | /// Appends the suffix to the end of the string if the string does not already end in the suffix. 662 | /// 663 | /// string to append suffix 664 | /// suffix 665 | /// Indicates whether the compare should ignore case 666 | /// 667 | public static string AppendSuffixIfMissing(this string val, string suffix, bool ignoreCase = true) 668 | { 669 | if (string.IsNullOrEmpty(val) || (ignoreCase ? val.EndsWithIgnoreCase(suffix) : val.EndsWith(suffix))) 670 | { 671 | return val; 672 | } 673 | return val + suffix; 674 | } 675 | 676 | /// 677 | /// Appends the prefix to the start of the string if the string does not already start with prefix. 678 | /// 679 | /// string to append prefix 680 | /// prefix 681 | /// Indicates whether the compare should ignore case 682 | /// 683 | public static string AppendPrefixIfMissing(this string val, string prefix, bool ignoreCase = true) 684 | { 685 | if (string.IsNullOrEmpty(val) || (ignoreCase ? val.StartsWithIgnoreCase(prefix) : val.StartsWith(prefix))) 686 | { 687 | return val; 688 | } 689 | return prefix + val; 690 | } 691 | 692 | /// 693 | /// Checks if the String contains only Unicode letters. 694 | /// null will return false. An empty String ("") will return false. 695 | /// 696 | /// string to check if is Alpha 697 | /// true if only contains letters, and is non-null 698 | public static bool IsAlpha(this string val) 699 | { 700 | if (string.IsNullOrEmpty(val)) 701 | { 702 | return false; 703 | } 704 | return val.Trim().Replace(" ", "").All(Char.IsLetter); 705 | } 706 | 707 | /// 708 | /// Checks if the String contains only Unicode letters, digits. 709 | /// null will return false. An empty String ("") will return false. 710 | /// 711 | /// string to check if is Alpha or Numeric 712 | /// 713 | public static bool IsAlphaNumeric(this string val) 714 | { 715 | if (string.IsNullOrEmpty(val)) 716 | { 717 | return false; 718 | } 719 | return val.Trim().Replace(" ", "").All(Char.IsLetterOrDigit); 720 | } 721 | 722 | /// 723 | /// Convert string to Hash using Sha512 724 | /// 725 | /// string to hash 726 | /// Hashed string 727 | /// 728 | public static string CreateHashSha512(string val) 729 | { 730 | if (string.IsNullOrEmpty(val)) 731 | { 732 | throw new ArgumentException("val"); 733 | } 734 | var sb = new StringBuilder(); 735 | using (SHA512 hash = SHA512.Create()) 736 | { 737 | byte[] data = hash.ComputeHash(val.ToBytes()); 738 | foreach (byte b in data) 739 | { 740 | sb.Append(b.ToString("x2")); 741 | } 742 | } 743 | return sb.ToString(); 744 | } 745 | 746 | /// 747 | /// Convert string to Hash using Sha256 748 | /// 749 | /// string to hash 750 | /// Hashed string 751 | public static string CreateHashSha256(string val) 752 | { 753 | if (string.IsNullOrEmpty(val)) 754 | { 755 | throw new ArgumentException("val"); 756 | } 757 | var sb = new StringBuilder(); 758 | using (SHA256 hash = SHA256.Create()) 759 | { 760 | byte[] data = hash.ComputeHash(val.ToBytes()); 761 | foreach (byte b in data) 762 | { 763 | sb.Append(b.ToString("x2")); 764 | } 765 | } 766 | return sb.ToString(); 767 | } 768 | 769 | /// 770 | /// Convert url query string to IDictionary value key pair 771 | /// 772 | /// query string value 773 | /// IDictionary value key pair 774 | public static IDictionary QueryStringToDictionary(this string queryString) 775 | { 776 | if (string.IsNullOrWhiteSpace(queryString)) 777 | { 778 | return null; 779 | } 780 | if (!queryString.Contains("?")) 781 | { 782 | return null; 783 | } 784 | string query = queryString.Replace("?", ""); 785 | if (!query.Contains("=")) 786 | { 787 | return null; 788 | } 789 | return query.Split('&').Select(p => p.Split('=')).ToDictionary( 790 | key => key[0].ToLower().Trim(), value => value[1]); 791 | } 792 | 793 | /// 794 | /// Reverse back or forward slashes 795 | /// 796 | /// string 797 | /// 798 | /// 0 - replace forward slash with back 799 | /// 1 - replace back with forward slash 800 | /// 801 | /// 802 | public static string ReverseSlash(this string val, int direction) 803 | { 804 | switch (direction) 805 | { 806 | case 0: 807 | return val.Replace(@"/", @"\"); 808 | case 1: 809 | return val.Replace(@"\", @"/"); 810 | default: 811 | return val; 812 | } 813 | } 814 | 815 | /// 816 | /// Replace Line Feeds 817 | /// 818 | /// string to remove line feeds 819 | /// System.string 820 | public static string ReplaceLineFeeds(this string val) 821 | { 822 | return Regex.Replace(val, @"^[\r\n]+|\.|[\r\n]+$", ""); 823 | } 824 | 825 | /// 826 | /// Validates if a string is valid IPv4 827 | /// Regular expression taken from Regex reference 828 | /// 829 | /// string IP address 830 | /// true if string matches valid IP address else false 831 | public static bool IsValidIPv4(this string val) 832 | { 833 | if (string.IsNullOrEmpty(val)) 834 | { 835 | return false; 836 | } 837 | return Regex.Match(val, 838 | @"(?:^|\s)([a-z]{3,6}(?=://))?(://)?((?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.(?:25[0-5]|2[0-4]\d|[01]?\d\d?))(?::(\d{2,5}))?(?:\s|$)") 839 | .Success; 840 | } 841 | 842 | /// 843 | /// Calculates the amount of bytes occupied by the input string encoded as the encoding specified 844 | /// 845 | /// The input string to check 846 | /// The encoding to use 847 | /// The total size of the input string in bytes 848 | /// input is null 849 | /// encoding is null 850 | public static int GetByteSize(this string val, Encoding encoding) 851 | { 852 | if (val == null) 853 | { 854 | throw new ArgumentNullException("val"); 855 | } 856 | if (encoding == null) 857 | { 858 | throw new ArgumentNullException("encoding"); 859 | } 860 | return encoding.GetByteCount(val); 861 | } 862 | 863 | /// 864 | /// Extracts the left part of the input string limited with the length parameter 865 | /// 866 | /// The input string to take the left part from 867 | /// The total number characters to take from the input string 868 | /// The substring starting at startIndex 0 until length 869 | /// input is null 870 | /// Length is smaller than zero or higher than the length of input 871 | public static string Left(this string val, int length) 872 | { 873 | if (string.IsNullOrEmpty(val)) 874 | { 875 | throw new ArgumentNullException("val"); 876 | } 877 | if (length < 0 || length > val.Length) 878 | { 879 | throw new ArgumentOutOfRangeException("length", 880 | "length cannot be higher than total string length or less than 0"); 881 | } 882 | return val.Substring(0, length); 883 | } 884 | 885 | /// 886 | /// Extracts the right part of the input string limited with the length parameter 887 | /// 888 | /// The input string to take the right part from 889 | /// The total number characters to take from the input string 890 | /// The substring taken from the input string 891 | /// input is null 892 | /// Length is smaller than zero or higher than the length of input 893 | public static string Right(this string val, int length) 894 | { 895 | if (string.IsNullOrEmpty(val)) 896 | { 897 | throw new ArgumentNullException("val"); 898 | } 899 | if (length < 0 || length > val.Length) 900 | { 901 | throw new ArgumentOutOfRangeException("length", 902 | "length cannot be higher than total string length or less than 0"); 903 | } 904 | return val.Substring(val.Length - length); 905 | } 906 | 907 | /// 908 | /// ToTextElements 909 | /// 910 | /// 911 | /// 912 | public static IEnumerable ToTextElements(this string val) 913 | { 914 | if (val == null) 915 | { 916 | throw new ArgumentNullException("val"); 917 | } 918 | TextElementEnumerator elementEnumerator = StringInfo.GetTextElementEnumerator(val); 919 | while (elementEnumerator.MoveNext()) 920 | { 921 | string textElement = elementEnumerator.GetTextElement(); 922 | yield return textElement; 923 | } 924 | } 925 | 926 | /// 927 | /// Check if a string does not start with prefix 928 | /// 929 | /// string to evaluate 930 | /// prefix 931 | /// true if string does not match prefix else false, null values will always evaluate to false 932 | public static bool DoesNotStartWith(this string val, string prefix) 933 | { 934 | return val == null || prefix == null || 935 | !val.StartsWith(prefix, StringComparison.InvariantCulture); 936 | } 937 | 938 | /// 939 | /// Check if a string does not end with prefix 940 | /// 941 | /// string to evaluate 942 | /// suffix 943 | /// true if string does not match prefix else false, null values will always evaluate to false 944 | public static bool DoesNotEndWith(this string val, string suffix) 945 | { 946 | return val == null || suffix == null || 947 | !val.EndsWith(suffix, StringComparison.InvariantCulture); 948 | } 949 | 950 | /// 951 | /// Checks if a string is null 952 | /// 953 | /// string to evaluate 954 | /// true if string is null else false 955 | public static bool IsNull(this string val) 956 | { 957 | return val == null; 958 | } 959 | 960 | /// 961 | /// Checks if a string is null or empty 962 | /// 963 | /// string to evaluate 964 | /// true if string is null or is empty else false 965 | public static bool IsNullOrEmpty(this string val) 966 | { 967 | return String.IsNullOrEmpty(val); 968 | } 969 | 970 | /// 971 | /// Checks if string length is a certain minimum number of characters, does not ignore leading and trailing 972 | /// white-space. 973 | /// null strings will always evaluate to false. 974 | /// 975 | /// string to evaluate minimum length 976 | /// minimum allowable string length 977 | /// true if string is of specified minimum length 978 | public static bool IsMinLength(this string val, int minCharLength) 979 | { 980 | return val != null && val.Length >= minCharLength; 981 | } 982 | 983 | /// 984 | /// Checks if string length is consists of specified allowable maximum char length. does not ignore leading and 985 | /// trailing white-space. 986 | /// null strings will always evaluate to false. 987 | /// 988 | /// string to evaluate maximum length 989 | /// maximum allowable string length 990 | /// true if string has specified maximum char length 991 | public static bool IsMaxLength(this string val, int maxCharLength) 992 | { 993 | return val != null && val.Length <= maxCharLength; 994 | } 995 | 996 | /// 997 | /// Checks if string length satisfies minimum and maximum allowable char length. does not ignore leading and 998 | /// trailing white-space 999 | /// 1000 | /// string to evaluate 1001 | /// minimum char length 1002 | /// maximum char length 1003 | /// true if string satisfies minimum and maximum allowable length 1004 | public static bool IsLength(this string val, int minCharLength, int maxCharLength) 1005 | { 1006 | return val != null && val.Length >= minCharLength && val.Length <= minCharLength; 1007 | } 1008 | 1009 | /// 1010 | /// Gets the number of characters in string checks if string is null 1011 | /// 1012 | /// string to evaluate length 1013 | /// total number of chars or null if string is null 1014 | public static int? GetLength(string val) 1015 | { 1016 | return val == null ? (int?) null : val.Length; 1017 | } 1018 | 1019 | /// 1020 | /// Create basic dynamic SQL where parameters from a JSON key value pair string 1021 | /// 1022 | /// json key value pair string 1023 | /// if true constructs parameters using or statement if false and 1024 | /// 1025 | public static string CreateParameters(this string value, bool useOr) 1026 | { 1027 | if (string.IsNullOrEmpty(value)) 1028 | { 1029 | return string.Empty; 1030 | } 1031 | IDictionary searchParamters = value.JsonToDictionary(); 1032 | var @params = new StringBuilder(""); 1033 | if (searchParamters == null) 1034 | { 1035 | return @params.ToString(); 1036 | } 1037 | for (int i = 0; i <= searchParamters.Count() - 1; i++) 1038 | { 1039 | string key = searchParamters.Keys.ElementAt(i); 1040 | var val = (string) searchParamters[key]; 1041 | if (!string.IsNullOrEmpty(key)) 1042 | { 1043 | @params.Append(key).Append(" like '").Append(val.Trim()).Append("%' "); 1044 | if (i < searchParamters.Count() - 1 && useOr) 1045 | { 1046 | @params.Append(" or "); 1047 | } 1048 | else if (i < searchParamters.Count() - 1) 1049 | { 1050 | @params.Append(" and "); 1051 | } 1052 | } 1053 | } 1054 | return @params.ToString(); 1055 | } 1056 | } 1057 | } 1058 | -------------------------------------------------------------------------------- /StringExtensionLibrary/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /StringExtensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 2013 4 | VisualStudioVersion = 12.0.30723.0 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringExtensions", "StringExtensions\StringExtensions.csproj", "{44BA3FC1-8BFF-413C-B272-01193769DE0F}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StringExtensionLibrary", "StringExtensionLibrary\StringExtensionLibrary.csproj", "{91DC5C7A-7DD0-4E71-B6D9-5D3DD76D2C77}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 16 | {44BA3FC1-8BFF-413C-B272-01193769DE0F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 17 | {44BA3FC1-8BFF-413C-B272-01193769DE0F}.Debug|Any CPU.Build.0 = Debug|Any CPU 18 | {44BA3FC1-8BFF-413C-B272-01193769DE0F}.Release|Any CPU.ActiveCfg = Release|Any CPU 19 | {44BA3FC1-8BFF-413C-B272-01193769DE0F}.Release|Any CPU.Build.0 = Release|Any CPU 20 | {91DC5C7A-7DD0-4E71-B6D9-5D3DD76D2C77}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {91DC5C7A-7DD0-4E71-B6D9-5D3DD76D2C77}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {91DC5C7A-7DD0-4E71-B6D9-5D3DD76D2C77}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {91DC5C7A-7DD0-4E71-B6D9-5D3DD76D2C77}.Release|Any CPU.Build.0 = Release|Any CPU 24 | EndGlobalSection 25 | GlobalSection(SolutionProperties) = preSolution 26 | HideSolutionNode = FALSE 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /StringExtensions/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("StringExtensions")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("StringExtensions")] 13 | [assembly: AssemblyCopyright("Copyright © 2015")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("f247ca55-e78f-42b9-8d9f-3b538c5d670e")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /StringExtensions/StringExtensionTest.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Dynamic; 4 | using System.Security.Cryptography; 5 | using Microsoft.VisualStudio.TestTools.UnitTesting; 6 | using StringExtensionLibrary; 7 | 8 | namespace StringExtensions 9 | { 10 | [TestClass] 11 | public class StringExtensionTest 12 | { 13 | [TestMethod] 14 | public void TestJsonToExpandoObject() 15 | { 16 | const string productString = "{'name':'Widget','expiryDate':'2010-12-20T18:01Z'," + 17 | "'price':9.99,'sizes':['Small','Medium','Large']}"; 18 | 19 | dynamic product = productString.JsonToExpanderObject(); 20 | Assert.IsInstanceOfType(product, typeof (ExpandoObject)); 21 | 22 | Assert.IsNotNull(product.name); 23 | Assert.IsNotNull(product.expiryDate); 24 | Assert.IsNotNull(product.price); 25 | Assert.IsNotNull(product.sizes); 26 | 27 | var sizes = (List) product.sizes; 28 | foreach (string item in sizes) 29 | { 30 | Assert.IsNotNull(item); 31 | } 32 | } 33 | 34 | [TestMethod] 35 | public void TestLength() 36 | { 37 | string sample = "There is currently no easy way to update all packages within a solution"; 38 | Assert.IsTrue(sample.IsMinLength(2)); 39 | sample = "The running"; 40 | Assert.IsFalse(sample.IsMinLength(50)); 41 | sample = null; 42 | Assert.IsFalse(sample.IsMinLength(1)); 43 | sample = "One"; 44 | Assert.IsTrue(sample.IsMaxLength(3)); 45 | sample = "three"; 46 | Assert.IsFalse(sample.IsMaxLength(3)); 47 | } 48 | 49 | [TestMethod] 50 | public void TestDoesNotStartWith() 51 | { 52 | Assert.IsTrue("test".DoesNotStartWith("a")); 53 | Assert.IsFalse("test".DoesNotStartWith("t")); 54 | Assert.IsTrue("".DoesNotStartWith("t")); 55 | string NULL = null; 56 | Assert.IsTrue(NULL.DoesNotStartWith("t")); 57 | } 58 | 59 | [TestMethod] 60 | public void ToTextElements() 61 | { 62 | string testing = "asdfasdf aasdflk asdfasdf"; 63 | IEnumerable a = testing.ToTextElements(); 64 | foreach (string k in a) 65 | { 66 | Console.WriteLine(k); 67 | } 68 | } 69 | 70 | [TestMethod] 71 | public void TestIPv4Address() 72 | { 73 | Assert.IsFalse("64.233.161.1470".IsValidIPv4()); 74 | Assert.IsTrue("64.233.161.147".IsValidIPv4()); 75 | } 76 | 77 | [TestMethod] 78 | public void TestQueryStringToDictionary() 79 | { 80 | const string url = "?name=ferret&field1=value1&field2=value2&field3=value3"; 81 | IDictionary queryValues = url.QueryStringToDictionary(); 82 | Assert.IsNotNull(queryValues); 83 | foreach (var obj in queryValues) 84 | { 85 | Console.WriteLine("key={0},value={1}", obj.Key, obj.Value); 86 | } 87 | } 88 | 89 | [TestMethod] 90 | public void TestIsAlphaOrNumeric() 91 | { 92 | Assert.IsTrue("Burning bridges as we go".IsAlpha()); 93 | Assert.IsFalse("Burning bridges as we go!".IsAlpha()); 94 | Assert.IsTrue("10 minutes left to code".IsAlphaNumeric()); 95 | Assert.IsTrue("123456".IsAlphaNumeric()); 96 | } 97 | 98 | [TestMethod] 99 | public void TestRemovePrefixSufix() 100 | { 101 | Assert.AreEqual("berbahaya".RemovePrefix("ber", false), "bahaya"); 102 | Assert.AreEqual("masakan".RemoveSuffix("an"), "masak"); 103 | } 104 | 105 | [TestMethod] 106 | public void TestJsonStringToObject() 107 | { 108 | const string productString = "{'name':'Widget','expiryDate':'2010-12-20T18:01Z'," + 109 | "'price':9.99,'sizes':['Small','Medium','Large']}"; 110 | var product = productString.JsonToObject(); 111 | Assert.IsNotNull(product); 112 | Console.WriteLine(product); 113 | 114 | const string productListString = 115 | "[{'name':'Widget','expiryDate':'2010-12-20T18:01Z','price':9.99,'sizes':['Small','Medium','Large']}," + 116 | "{'name':'Image','expiryDate':'2015-12-20T18:01Z','price':20.50,'sizes':['Small','Medium','Large','Extra Large']}]"; 117 | var products = productListString.JsonToObject>(); 118 | Assert.IsNotNull(products); 119 | foreach (Product obj in products) 120 | { 121 | Console.WriteLine(obj); 122 | } 123 | } 124 | 125 | [TestMethod] 126 | [ExpectedException(typeof (ArgumentException))] 127 | public void TestToEnum() 128 | { 129 | Temperature guage = "VeryHigh".ToEnum(Temperature.High); 130 | Assert.IsTrue(guage.Equals(Temperature.High)); 131 | guage = "low".ToEnum(Temperature.Unknown); 132 | Assert.IsTrue(guage.Equals(Temperature.Low)); 133 | guage = "veryHigh".ToEnum(); 134 | Assert.IsTrue(guage.Equals(Temperature.Unknown)); 135 | guage = "Medium".ToEnum(); 136 | Assert.IsTrue(guage.Equals(Temperature.Medium)); 137 | Assert.IsInstanceOfType("high".ToEnum(), typeof (Temperature)); 138 | } 139 | 140 | [TestMethod] 141 | public void TestCountOccurrences() 142 | { 143 | const string sentence = "hey man! i went to the apple store, hey man! are you listening to me"; 144 | Assert.IsTrue(sentence.CountOccurrences("HEY MAN!") == 2); 145 | } 146 | 147 | [TestMethod] 148 | [ExpectedException(typeof (CryptographicException))] 149 | public void TestEncryptDecrypt() 150 | { 151 | const string key = "1234567890!@#$%^&*()_+"; 152 | const string stringToEncrypt = "In my opinion best movie released 2014 is prometheus"; 153 | string encryptedString = stringToEncrypt.Encrypt(key); 154 | string decryptedString = encryptedString.Decrypt(key); 155 | Assert.AreEqual(stringToEncrypt, decryptedString); 156 | encryptedString.Decrypt("wrongkey"); 157 | } 158 | } 159 | 160 | /// 161 | /// Temperature enum default values in c# are always 0 or first enum element 162 | /// 163 | internal enum Temperature 164 | { 165 | Unknown, 166 | Low, 167 | Medium, 168 | High, 169 | }; 170 | 171 | internal class Product 172 | { 173 | public string Name { set; get; } 174 | public DateTime ExpiryDate { set; get; } 175 | public decimal Price { set; get; } 176 | public string[] Sizes { set; get; } 177 | 178 | public override string ToString() 179 | { 180 | return string.Format("Name: {0}, ExpiryDate: {1}, Price: {2}, Sizes: [{3}]", Name, ExpiryDate, Price, 181 | string.Join(",", Sizes)); 182 | } 183 | } 184 | 185 | 186 | internal class Address 187 | { 188 | public Address() 189 | { 190 | CreatedOn = DateTime.UtcNow; 191 | Active = true; 192 | } 193 | 194 | public string Street1 { set; get; } 195 | public string Street2 { set; get; } 196 | public string Street3 { set; get; } 197 | public string City { set; get; } 198 | public string Country { set; get; } 199 | public DateTime CreatedOn { set; get; } 200 | public bool Active { set; get; } 201 | 202 | public override string ToString() 203 | { 204 | return 205 | string.Format( 206 | "Active: {0}, City: {1}, Country: {2}, CreatedOn: {3}, Street1: {4}, Street2: {5}, Street3: {6}", 207 | Active, City, Country, CreatedOn, Street1, Street2, Street3); 208 | } 209 | } 210 | 211 | internal class Person 212 | { 213 | public Person() 214 | { 215 | CreatedOn = DateTime.UtcNow; 216 | Addresses = new HashSet
(); 217 | } 218 | 219 | public string Name { set; get; } 220 | public int Age { set; get; } 221 | public DateTime Dob { set; get; } 222 | public string Email { set; get; } 223 | public string SocialSecurityNo { set; get; } 224 | public string MobileNo { set; get; } 225 | public string OfficeNo { set; get; } 226 | public string PassportNo { set; get; } 227 | public ICollection
Addresses { set; get; } 228 | public string BirthPlace { set; get; } 229 | public string Nationality { set; get; } 230 | public DateTime CreatedOn { set; get; } 231 | 232 | public override string ToString() 233 | { 234 | return 235 | string.Format( 236 | "Name: {0}, Age: {1}, Dob: {2}, Email: {3}, SocialSecurityNo: {4}, MobileNo: {5}, OfficeNo: {6}, Address: {7}, PassportNo: {8}, BirthPlace: {9}, Nationality: {10}", 237 | Name, Age, Dob, Email, SocialSecurityNo, MobileNo, OfficeNo, Addresses, PassportNo, BirthPlace, 238 | Nationality); 239 | } 240 | } 241 | } -------------------------------------------------------------------------------- /StringExtensions/StringExtensions.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | Debug 5 | AnyCPU 6 | {44BA3FC1-8BFF-413C-B272-01193769DE0F} 7 | Library 8 | Properties 9 | StringExtensions 10 | StringExtensions 11 | v4.5.1 12 | 512 13 | {3AC096D0-A1C2-E12C-1390-A8335801FDAB};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC} 14 | 10.0 15 | $(MSBuildExtensionsPath32)\Microsoft\VisualStudio\v$(VisualStudioVersion) 16 | $(ProgramFiles)\Common Files\microsoft shared\VSTT\$(VisualStudioVersion)\UITestExtensionPackages 17 | False 18 | UnitTest 19 | 20 | 21 | true 22 | full 23 | false 24 | bin\Debug\ 25 | DEBUG;TRACE 26 | prompt 27 | 4 28 | 29 | 30 | pdbonly 31 | true 32 | bin\Release\ 33 | TRACE 34 | prompt 35 | 4 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | {91dc5c7a-7dd0-4e71-b6d9-5d3dd76d2c77} 60 | StringExtensionLibrary 61 | 62 | 63 | 64 | 65 | 66 | 67 | False 68 | 69 | 70 | False 71 | 72 | 73 | False 74 | 75 | 76 | False 77 | 78 | 79 | 80 | 81 | 82 | 83 | 90 | --------------------------------------------------------------------------------