Skip to content

Instantly share code, notes, and snippets.

@jonasraoni
Created November 4, 2017 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jonasraoni/43749fe6b5e3b793e9d3bc8355c0d1a3 to your computer and use it in GitHub Desktop.
Save jonasraoni/43749fe6b5e3b793e9d3bc8355c0d1a3 to your computer and use it in GitHub Desktop.
Some C# extensions.
using System;
using System.IO;
using System.Web;
using System.Text;
using System.Collections.Generic;
using System.Collections;
namespace Raoni {
public delegate bool Generator<T>(out T value);
public delegate bool Enumerator<T>(T value);
public static class Extends {
//String
public static string toMD5(this String text) {
MD5 md5 = MD5.Create();
byte[] hash = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(text));
StringBuilder sb = new StringBuilder();
for(int i = 0; i < hash.Length; i++)
sb.Append(hash[i].ToString("x2"));
return sb.ToString();
}
public static bool isEmpty(this string s) {
return s == null || s == "";
}
public static bool isFilled(this string s) {
return !s.isEmpty();
}
public static string truncate(this string s, int l, string e = "...", bool isHTML = false, bool closeTags = true) {
int i = 0;
Stack<string> tags = new Stack<string>();
if(isHTML) {
foreach(Match o in Regex.Matches(s, "<[^>]+>([^<]*)")) {
if(o.Index - i >= l)
break;
string t = o.Value.Substring(1, o.Value.IndexOfAny(new char[] { ' ', '\t', '\n', '\r', '\0', '\x0b', '>' }) - 1);
if(t.Substring(0, 1) != "/")
tags.Push(t);
else if(tags.Peek() == t.Substring(1))
tags.Pop();
i += o.Groups[1].Index - o.Index;
}
}
return s.Substring(0, l = Math.Min(s.Length, l + i)) + (closeTags && tags.Count > 0 ? "</" + tags.join("></") + ">" : "") + (s.Length > l ? e : "");
}
public static string[] Split(this String s, string separator) {
return s.Split(new string[] { separator }, StringSplitOptions.None);
}
public static int toInt(this string s) {
int o;
int.TryParse(s, out o);
return o;
}
public static double toNumber(this string s, string decimalSeparator = "", double def = 0) {
string dec = decimalSeparator == "" ? (s.LastIndexOf(",") > -1 ? "," : s.LastIndexOf(".") > -1 ? "." : ",") : decimalSeparator;
NumberFormatInfo i = new NumberFormatInfo();
i.NumberDecimalSeparator = dec;
i.NumberGroupSeparator = dec == "." ? "," : ".";
s.Replace(i.NumberGroupSeparator, "");
double o;
return double.TryParse(s, NumberStyles.Any, i, out o) ? o : def;
}
public static string toURLFile(this String s) {
return Regex.Replace(Regex.Replace(s.removeAccents(), "[^a-zA-Z0-9_]", " ").Trim(), "\\s+", "-").ToLowerInvariant();
}
public static string mask(this String s, string mask) {
string h = "", r = "";
char[] ss = s.ToCharArray();
for(int l = mask.Length, j = 0, i = 0; i < l; i++) {
if(mask[i] != '#') {
if(mask[i] == '\\') {
h += mask[++i];
continue;
}
h += mask[i];
if(i + 1 == l) {
r += ss[j - 1] + h;
h = "";
};
}
else {
if(ss.Length <= j) {
h = "";
break;
}
r += h + ss[j];
h = "";
++j;
}
}
return r + h;
}
public static string toJS(this String s, bool quote = true, string quoteCharacter = "'") {
string p;
return (p = quote ? quoteCharacter : "") + Regex.Replace(s.Replace("\\", "\\\\").Replace(quoteCharacter, "\\" + quoteCharacter), "\r\n|\n\r|\r|\n", "\\n") + p;
}
public static string toSqlSearch(this String s) {
Dictionary<string, string> c = new Dictionary<string, string>(){
{"%", "\\%"},
{"_", "\\_"},
{"\"", "\"\""}
};
foreach(string i in c.Keys)
s = s.Replace(i, c[i]);
return s;
}
public static string toForm(this String s, bool br = false) {
return br ? Regex.Replace(s.Trim().toXML(), "\r\n|\n\r|\r", "<br>") : s.toXML();
}
public static string toEmail(this String s) {
StringBuilder r = new StringBuilder(s.Length * 2);
for(int i = -1, l = s.Length; ++i < l; ) {
ulong t = 0;
foreach(byte c in ASCIIEncoding.Unicode.GetBytes(s.Substring(i, 1)))
t += c;
r.Append("&#x" + t.ToString("x", CultureInfo.InvariantCulture) + ";");
}
return r.ToString();
}
public static string toDisplay(this String s, bool strip = false) {
s = Regex.Replace(s.Trim(), "\r\n|\n\r|\r|\n", "<br>");
return strip ? s.stripTags() : s;
}
public static string stripTags(this String s) {
return Regex.Replace(s, "<\\/?[^>]+>", "");
}
public static string toRegExp(this String s) {
return Regex.Escape(s);
}
public static string toXML(this String s) {
Dictionary<string, int> map = new Dictionary<string, int>(){
{"'", 39},
{"\"", 34},
{"<", 60},
{">", 62},
{"&", 38},
{"\a", 07}
};
return Regex.Replace(s, "[" + map.Keys.join("") + "]", o => "&#" + map[o.Value] + ";");
}
public static string toHTML(this String s) {
return HttpUtility.HtmlEncode(s);
}
public static string removeAccents(this String s) {
string normalized = s.Normalize(NormalizationForm.FormKD);
Encoding removal = Encoding.GetEncoding(Encoding.ASCII.CodePage, new EncoderReplacementFallback(""), new DecoderReplacementFallback(""));
return Encoding.ASCII.GetString(removal.GetBytes(normalized));
}
public static ulong parseInt(this String n, int b = 0, string c = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
ulong s = 0;
int l = n.Length, i = 0;
if(b == 0)
b = c.Length;
if(b > c.Length || b < 2)
throw new ArgumentException("Invalid arguments");
while(l-- > 0)
s += (ulong)c.IndexOf(n.Substring(i++, 1), StringComparison.Ordinal) * (ulong)Math.Pow(b, l);
return s;
}
//IEnumerable<T>
public static string join<T>(this IEnumerable<T> list, object separator) {
StringBuilder s = new StringBuilder();
using(IEnumerator<T> o = list.GetEnumerator()) {
if(o.MoveNext())
for(s.Append(o.Current); o.MoveNext(); s.Append(separator.ToString() + o.Current + ""))
;
return s.ToString();
}
}
//Boolean
public static int toInt(this bool o) {
return o ? 1 : 0;
}
//Stream
public static string toMD5(this Stream file) {
MD5 md5 = MD5.Create();
byte[] retVal = md5.ComputeHash(file);
StringBuilder sb = new StringBuilder();
for(int i = 0; i < retVal.Length; i++)
sb.Append(retVal[i].ToString("x2"));
return sb.ToString();
}
public static void WriteTo(this Stream source, Stream target) {
WriteTo(source, target, 1024);
}
public static void WriteTo(this Stream source, Stream target, int bufferLength) {
byte[] buffer = new byte[bufferLength];
int bytesRead = 0;
do {
bytesRead = source.Read(buffer, 0, buffer.Length);
target.Write(buffer, 0, bytesRead);
}
while(bytesRead > 0);
}
//Number
public static string toBase(this int n, int b = 0, string c = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") {
if(b == 0)
b = c.Length;
if(b > c.Length || b < 2)
throw new ArgumentException("Invalid arguments");
string s = "";
while(n > 0) {
s = c[n % b] + s;
n = (n / b);
}
return s;
}
public static bool isNumber(this object value) {
return value is sbyte
|| value is byte
|| value is short
|| value is ushort
|| value is int
|| value is uint
|| value is long
|| value is ulong
|| value is float
|| value is double
|| value is decimal;
}
public static string formatCurrency(this double s, int c = 2, string d = ",", string t = ".") {
NumberFormatInfo o = new NumberFormatInfo();
o.NumberDecimalDigits = c;
o.NumberDecimalSeparator = d;
o.NumberGroupSeparator = t;
o.NumberGroupSizes = new int[] { 3 };
o.NumberNegativePattern = 1;
return s.ToString("n", o);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment