Wednesday, April 1, 2015

Extension Methods Library

Extension methods are a compiler trick which allows static methods to be called using instance methods syntax. They are so convenient that LINQ is essentially a collection of extension methods. Extension methods are a good way to shrink your code and follow the DRY principle. For example, instead of the following long code
bool IsValidOs(string os)
{
    return os.Equals("Windows", StringComparison.OrdinalIgnoreCase) ||
           os.Equals("Linux", StringComparison.OrdinalIgnoreCase) ||
           os.Equals("Mac OS", StringComparison.OrdinalIgnoreCase);
}
The following version is much more readable:

bool IsValidOs(string os)
{
    return os.IsLikeAny("Windows", "Linux", "Mac OS");
}
To add the library to your project, open Package Manager Console, select your project and type

Install-Package ExtensionMethods
 


Import the namespace
using ExtensionMethods;
ToFormat()
Similar to string.Format
 "My name is {0} {1}".ToFormat("Nadeem", "Afana");  // My name is Nadeem Afana

You can even use it on nullable types:
int? value = 12700;
value.ToFormat("#,#"); // 12,700
    
value = null;
value.ToFormat("#,#"); // null


ToFormatNamed()
Similar to string.Format but uses named formats for better readability.
string firstName = "Nadeem";
string lastName = "Afana";
string language = "C#";
"My name is {first} {last}, and I like {lang}.".ToFormatNamed(firstName, lastName, language);
// My name is Nadeem Afana, and I like C#.

 It also supports composite formatting:
int kbps = 30000;
 
@"The day is {dayName:dddd} and the time is {hour:hh:mm}.
The Internet speed is {speed:#.0} mbps.
".ToFormatNamed(DateTime.Now, DateTime.Now, kbps/1000.0);
// The day is Sunday and the time is 05:31. The Internet speed is 30.0 mbps.

The variable names do not have to match the arguments,but the order of arguments is important.

 Reverse()
Reverses a string.
"The quick brown fox jumps over the lazy dog".Reverse();
// god yzal eht revo spmuj xof nworb kciuq ehT


Left()
Reads the first n characters from the left of a string.
"The quick brown fox jumps over the lazy dog".Left(9);
// The quick


Right()
Reads the first n characters from the right of a string.
"The quick brown fox jumps over the lazy dog".Right(3);
// dog


IsLike()
Determines whether two strings have the same value ignoring Case.
"STRING".IsLike("String"); // True


IsLikeAny()
Determines whether a string matches any value in a collection of strings ignoring case.
  
"c#".IsLikeAny("C++", "C#", "VB");  // True


IsLikeAll()

Determines whether a string matches all the values in a collection of strings ignoring case.
  
"internet".IsLikeAll("Internet", "INTERNET", "iNTerNet");  // True


StartsLike()

Determines whether the beginning of a string matches the specified string ignoring case.
  
string s = "The quick brown fox jumps over the lazy dog";
s.StartsLike("the"); // True


EndsLike()
Determines whether the end of a string matches the specified string ignoring case.

string s = "The quick brown fox jumps over the lazy dog";
s.EndsLike("DOG"); // True


TrimStart()
Removes a string from the beginning of another string.
string s = "The quick brown fox jumps over the lazy dog";
s.TrimStart("The"); //  quick brown fox jumps over the lazy dog

s.TrimStart("THE", false); // case insensitive
//  quick brown fox jumps over the lazy dog


TrimEnd()
Removes a string from the end of another string.

string s = "The quick brown fox jumps over the lazy dog";
s.TrimEnd("dog");
// The quick brown fox jumps over the lazy
s.TrimEnd("DOG", false); // case insensitive
// The quick brown fox jumps over the lazy


Capitalize()

Capitalizes the first letter of each word. Synonym for ToTitleCase()

string s = "the internet";
s.Capitalize(); // The Internet


ToTitleCase()
Capitalizes the first letter of each word. Synonym for Capitalize()
string s = "the internet";
s.ToTitleCase(); // The Internet


IsNullOrWhiteSpace()
Indicates whether a specified string is null, empty, or consists only of white-space characters.
string s = "       ";
s.IsNullOrWhiteSpace(); // True

s = null;
s.IsNullOrWhiteSpace(); // True

s = string.Empty;
s.IsNullOrWhiteSpace(); // True


IsNumeric()
Determines if a string can be parsed into a number.
"1253".IsNumeric(); // True

"Abc".IsNumeric(); // False


ToBase64()

Converts a string into Base64 encoding.
string s = "Hello World!";
s.ToBase64(); // SGVsbG8gV29ybGQh   (Utf8)

s.ToBase64(Encoding.UTF32); // Utf32
// SAAAAGUAAABsAAAAbAAAAG8AAAAgAAAAVwAAAG8AAAByAAAAbAAAAGQAAAAhAAAA

FromBase64()
Decodes a Base64-encoded string.
   
"SGVsbG8gV29ybGQh".FromBase64(); // Hello World!   (Utf8)
 "SAAAAGUAAABsAAAAbAAAAG8AAAAgAAAAVwAAAG8AAAByAAAAbAAAAGQAAAAhAAAA".FromBase64(Encoding.UTF32); //  Hello World! (Utf32)


ToMd5()
Computes MD5 hash of a string.
"Hello World!".ToMd5(); // ed076287532e86365e841e92bfc50d8c (Utf8)
 "Hello World!".ToMd5(Encoding.UTF32); // b090a014200184a82c6fff39816cb5bc (Utf32)


ToBytes()
Converts a string into an array of bytes.

"Hello World!".ToBytes(); // Utf8
// { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33};

"Hello World!".ToBytes(Encoding.UTF7);  // Utf7
// { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 43, 65, 67, 69, 45};


ToInt()
Parses an integer from a string.
   
"1500".ToInt(); // 1500


ToIntOrDefault()
Parses an integer from a string. If parsing fails, returns a default integer.

"1500".ToIntOrDefault(); // 1500
"Abc".ToIntOrDefault(0); // 0


ToDouble()
Parses a double from a string.
"3.14".ToDouble(); // 3.14


ToDoubleOrDefault()
Parses a double from a string. If parsing fails, returns a default double value.
   
"3.14".ToDoubleOrDefault(); // 3.14
"Abc".ToDoubleOrDefault(0.0); // 0.0


ToLink()
Scans a string for valid http Urls and converts them to Html links.
   
"My website is www.afana.me".ToLink();
// My website is <a href="http://www.afana.me/">www.afana.me</a>

"My website is www.afana.me".ToLink("click here");
// My website is <a href="http://www.afana.me/">click here</a>


ContainsAny()
Determines whether a string contains at least one of the specified strings.

string s = "The quick brown fox jumps over the lazy dog";
s.ContainsAny("a", "fox"); // True


ContainsAll()
Determines whether a string contains all the specified strings.
   
string s = "The quick brown fox jumps over the lazy dog";
s.ContainsAll("dog", "fox"); // True


bool.ToYesOrNo()
Returns Yes or No string if a boolean value is true or false, respectively. This can be very useful especially in MVC views.
bool isOpen = true;
"Is Open: {0}".ToFormat(isOpen.ToYesOrNo()); // Is Open: Yes


bytes[].ToHexString()
Converts a collection of bytes into hexadecimal string respresentation.
   
byte[] bytes = new byte[] { 72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33 };
bytes.ToHexString(); // 48656c6c6f20576f726c6421


IPrincipal.GetUserNameOnly()
Returns the user name without a domain name.
Thread.CurrentPrincipal.GetUserNameOnly(); // Domain\Nadeem => Nadeem


IPrincipal.IsInAnyRole()
Determines if a IPrincipal belongs to at least one of the specified roles.
var user = Thread.CurrentPrincipal;
user.IsInAnyRole("admin", "user");


IPrincipal.IsInAllRoles()
Determines if a IPrincipal belongs to all the specified roles.
   
var user = Thread.CurrentPrincipal;
user.IsInAllRoles("admin", "db_admin");




0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More