Some sample extension methods for the string class
Because String is a sealed class you cannot inherit from it and add to it. However, C# has a wonderful feature called extension methods.
Extension methods enable you to “add” methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type. Extension methods are a special kind of static method, but they are called as if they were instance methods on the extended type. For client code written in C# and Visual Basic, there is no apparent difference between calling an extension method and the methods that are actually defined in a type. [1]
Here is a list of extension methods I have used for the String class.
If you know of any more cool extension methods, please comment.
using System;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Security;
namespace LANDesk.Install.Common.Extenders
{
/// <summary>
/// This class adds methods to String that are useful
/// </summary>
public static class StringExtender
{
#region DLL Imports
[DllImport("ldmsinst.dll", CharSet = CharSet.Ansi, EntryPoint = "Decrypt", CallingConvention = CallingConvention.Cdecl)]
public static extern void Decrypt(int pwdLen, byte[] pwd);
[DllImport("ldmsinst.dll", CharSet = CharSet.Ansi, EntryPoint = "Encrypt", CallingConvention = CallingConvention.Cdecl)]
public static extern void Encrypt(int length, byte[] data);
#endregion
/// <summary>
/// This adds a function to a string object that will convert the string
/// to a SecureString.
/// </summary>
/// <param name="password">The string to convert to a secure string.</param>
/// <returns>SecureString</returns>
public static SecureString ConvertToSecureString(this string password)
{
SecureString ss = new SecureString();
if (password == null)
throw new ArgumentNullException("password");
foreach (Char c in password)
{
ss.AppendChar(c);
}
return ss;
}
/// <summary>
/// Checks if the string contains any of a list of characters
/// entered as a string.
/// </summary>
/// <param name="password">Any string.</param>
/// <param name="listofcharacters">Any string representing a list of characters.</param>
/// <returns>bool</returns>
public static bool ContainsAnyOf(this string password, char[] listofcharacters)
{
foreach (char c in listofcharacters)
{
if (password.Contains(c.ToString()))
return true;
}
return false;
}
/// <summary>
/// Checks if the string contains any of a list of characters
/// entered as a string.
/// </summary>
/// <param name="password">Any string.</param>
/// <param name="listofcharacters">Any string representing a list of characters.</param>
/// <returns>bool</returns>
public static bool ContainsAnyOf(this string password, string listofcharacters)
{
return password.ContainsAnyOf(listofcharacters.ToCharArray());
}
/// <summary>
/// Checks if the string has a space.
/// </summary>
/// <param name="txt">Any string.</param>
/// <returns>bool</returns>
public static bool HasSpaces(string txt)
{
if (txt.Contains(" "))
{
return true;
}
return false;
}
/// <summary>
/// To be a strong password, Must have 3 out of 4 of the following conditions:
/// Uppercase, lowercase, numberic, symbol
/// </summary>
/// </summary>
/// <param name="password"></param>
/// <returns></returns>
public static bool IsPasswordStrong(this string password)
{
int numTypes = 0;
if (HasUppercaseCharacter(password) == true)
{
numTypes = numTypes + 1;
}
if (HasLowercaseCharacter(password) == true)
{
numTypes = numTypes + 1;
}
if (HasNonAlphaNumeric(password) == true)
{
numTypes = numTypes + 1;
}
if (HasDigit(password) == true)
{
numTypes = numTypes + 1;
}
if (numTypes > 2)
{
return true;
}
else
{
return false;
}
}
public static bool HasUppercaseCharacter(string str)
{
if (str == str.ToLower())
return false;
return true;
}
public static bool HasLowercaseCharacter(string str)
{
if (str == str.ToUpper())
return false;
return true;
}
public static bool HasDigit(string str)
{
Regex regexNums = new Regex("[0-9]");
return regexNums.IsMatch(str);
}
public static bool HasNonAlphaNumeric(string str)
{
string newString = str;
Regex regexNums = new Regex("[0-9]");
Regex regexAlphas = new Regex("[a-z]", RegexOptions.IgnoreCase);
newString = regexNums.Replace(newString, "");
newString = regexAlphas.Replace(newString, "");
return (newString.Length > 0);
}
/// <summary>
/// This adds a function to a string object that RC4 Encrypts a password.
/// </summary>
/// <param name="password">A password as a string.</param>
/// <returns>A byte[] representation of an RC4 password.</returns>
public static byte[] Encrypt(this string password)
{
try
{
// Encode the password
System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] encryptedPwd = encoding.GetBytes(password);
// encrypt password
Encrypt(encryptedPwd.Length, encryptedPwd);
return encryptedPwd;
}
catch (Exception ex)
{
throw ex;
}
}
/// <summary>
/// This adds a function to a byte[] object that decrypts an RC4 password.
/// and returns the password as a string.
/// </summary>
/// <param name="encryptedPwd">A byte[] representation of an RC4 password.</param>
/// <returns>The password as a string.</returns>
static public string Decrypt(this byte[] encryptedPwd)
{
string password = string.Empty;
try
{
// decrypt password
Decrypt(encryptedPwd.Length, encryptedPwd);
// convert from byte array to string
password = System.Text.ASCIIEncoding.Default.GetString(encryptedPwd);
password = password.Replace("\0", string.Empty);
}
catch (Exception ex)
{
throw ex;
}
return password;
}
public static string FirstLetterUpperCase(this string inString)
{
if (string.IsNullOrEmpty(inString))
return string.Empty;
string newString = inString.Substring(0, 1).ToUpper();
newString += inString.Substring(1, inString.Length - 1);
return newString;
}
public static string LimitTo(this string data, int length)
{
return data.Length < length ? data : data.Substring(0, length);
}
}
}
