© 2020, Developed by Hieu Dev

Các hàm static hữu ích trong lập trình C#

Để giảm bớt thời gian lập trình các hàm cơ bản, hôm nay mình sẽ chia sẻ các bạn các hàm static hữu ích trong lập trình c#, mà tùy theo từng trường hợp, từng nhu cầu mà các bạn áp dụng bất kì lúc nào bạn muốn.

Các hàm static hữu ích trong lập trình C#
Các hàm static hữu ích trong lập trình C#

Lấy số ngẫu nhiên

Đầu tiên là hàm lấy số ngẫu nhiên, với đầu vào là một giá trị min, và max và in ra giá trị ngẫu nhiên trong khoảng đó:

public static int RandomNumber(int min, int max)
{
    Random random = new Random(); return random.Next(1, 1000);
}

Lấy ngày giờ tại Server

Để viết hàm lấy ngày giờ hiện tại tại server, ta có hàm sau:

public static DateTime GetServerDateTime()
{
    return DateTime.Now.ToUniversalTime().AddHours(7);
}

Mã hóa thành chuỗi MD5

Mã hóa MD5 rất hữu ích và cần thiết khi các bạn làm việc với mật khẩu, để bảo mật:

public static string EncryptMD5(string sToEncrypt)
{
    System.Text.UTF8Encoding ue = new System.Text.UTF8Encoding();
    byte[] bytes = ue.GetBytes(sToEncrypt);
 
    // encrypt bytes
    System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
    byte[] hashBytes = md5.ComputeHash(bytes);
 
    // Convert the encrypted bytes back to a string (base 16)
    string hashString = "";
 
    for (int i = 0; i < hashBytes.Length; i++)
    {
        hashString += Convert.ToString(hashBytes[i], 16).PadLeft(2, '0');
    }
 
    return hashString.PadLeft(32, '0');
}

Chuẩn hóa chuỗi ký tự số

Ta chuẩn hóa bằng cách loại bỏ ngay các kí tự đặc biệt như hàm bên dưới:

public static string StandardNumber(string num)
{
    num = num.Replace("`", "");
    num = num.Replace("-", "");
    num = num.Replace("=", "");
    num = num.Replace("~", "");
    num = num.Replace("!", "");
    num = num.Replace("@", "");
    num = num.Replace("#", "");
    num = num.Replace("$", "");
    num = num.Replace("%", "");
    num = num.Replace("^", "");
    num = num.Replace("&", "");
    num = num.Replace("*", "");
    num = num.Replace("(", "");
    num = num.Replace(")", "");
    num = num.Replace("_", "");
    num = num.Replace("+", "");
    num = num.Replace("[", "");
    num = num.Replace("]", "");
    num = num.Replace(";", "");
    num = num.Replace("'", "");
    num = num.Replace(",", "");
    num = num.Replace(".", "");
    num = num.Replace("/", "");
    num = num.Replace("{", "");
    num = num.Replace("}", "");
    num = num.Replace(":", "");
    num = num.Replace("<", "");
    num = num.Replace(">", "");
    num = num.Replace("?", "");
    return num;
}


Chuẩn hóa chuỗi ký tự bảo mật

Đầu vào của các form rất quan trọng, vì chúng ta có thể bị tấn công bằng SQL Injection, vì thế hãy dùng hàm sau để chuẩn hóa, bảo mật các đầu vào:
public static string StandardString(string sContent)
{
    sContent = sContent.Trim();
    sContent = sContent.Replace("<", "");
    sContent = sContent.Replace(">", "");
    sContent = sContent.Replace("crack", "*****");
    sContent = sContent.Replace("key", "***");
    sContent = sContent.Replace("<td>", "");
    sContent = sContent.Replace("</td>", "");
    sContent = sContent.Replace("<tr>", "");
    sContent = sContent.Replace("</tr>", "");
    sContent = sContent.Replace("<table>", "");
    sContent = sContent.Replace("</table>", "");
    sContent = sContent.Replace("<script", "");
    sContent = sContent.Replace("</script>", "");
 
    sContent = sContent.Replace("OR", "");
    sContent = sContent.Replace("ALTER", "");
    sContent = sContent.Replace("DROP", "");
    return sContent;
}

Thay thế chữ cái có dấu thành không dấu

Hàm này rất là hữu dụng cho các bạn khi xử lý các chuỗi:

public static string RemapInternationalCharToAscii(char c)
{
    string s = c.ToString();
    Regex regex = new Regex("\\p{IsCombiningDiacriticalMarks}+");
    string temp = s.Normalize(NormalizationForm.FormD);
    return regex.Replace(temp, String.Empty).Replace('\u0111', 'd').Replace('\u0110', 'D');
}

Một "chiếc" Url thân thiện

Url một phần ảnh hưởng đến SEO của bạn, nên cần dùng hàm để convert sau đây:

public static string RewriteUrlFriendly(string title)
{
    if (title == null) return "";
 
    const int maxlen = 80;
    int len = title.Length;
    bool prevdash = false;
    var sb = new StringBuilder(len);
    char c;
 
    for (int i = 0; i < len; i++)
    {
        c = title[i];
        if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9'))
        {
            sb.Append(c);
            prevdash = false;
        }
        else if (c >= 'A' && c <= 'Z')
        {
            // tricky way to convert to lowercase
            sb.Append((char)(c | 64));
            prevdash = false;
        }
        else if (c == ' ' || c == ',' || c == '.' || c == '/' ||
            c == '\\' || c == '-' || c == '_' || c == '=')
        {
            if (!prevdash && sb.Length > 0)
            {
                sb.Append('-');
                prevdash = true;
            }
        }
        else if ((int)c >= 128)
        {
            int prevlen = sb.Length;
            sb.Append(RemapInternationalCharToAscii(c));
            if (prevlen != sb.Length) prevdash = false;
        }
        if (i == maxlen) break;
    }
 
    if (prevdash)
        return sb.ToString().Substring(0, sb.Length - 1);
    else
        return sb.ToString();
}

Phát hiện và gắn Url trong chuỗi ký tự

Khi bạn post một status trên facebook sẽ rõ, nếu trong caption đấy url, lập tức sẽ được gắn thành link màu xanh:

public static string DetectUrlText(string text)
{
    var textDetect = Regex.Replace(text, @"((http|ftp|https):\/\/[\w\-_]+(\.[\w\-_]+)+([\w\-\.,@?^=%&amp;:/~\+#]*[\w\-\@?^=%&amp;/~\+#])?)", "<a target='_blank' href='$1'>$1</a>");
    return textDetect;
}

Kiểm tra chuỗi chỉ chứa ký tự số int64

Một hàm hữu dụng trong việc kiểm tra chuỗi chỉ chứa ký tự int64 trong c#:

public static bool IsNumericInt64(string num)
{
    long n;
    return Int64.TryParse(num, out n);
}

Kiểm tra chuỗi chỉ chứa ký tự số int32

Và còn int32 cũng sẽ tương tự:

public static bool IsNumericInt32(string num)
{
    int n;
    return Int32.TryParse(num, out n);
}

Đây là các hàm thông dụng, mong là sẽ có ích với bạn, chúc các bạn thành công!

Hiếu Quốc.

Đăng nhận xét

Mới hơn Cũ hơn

TOGETHER

WE GROW