Click here to Skip to main content
15,895,841 members
Articles / All Topics

A common functions that use in mostly each projects in C#

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
22 Apr 2016CPOL 3.3K   1   3
As programmer we need some common functions, methods in every project like get encrypted sha1 hash, Send Emails, etc. I have listed some of common function here, you can copy it and add it to your project. If you want to add some more function please write it in comment I will update article with pr

As programmer we need some common functions, methods in every project like get encrypted sha1 hash, Send Emails, etc. I have listed some of common function here, you can copy it and add it to your project.
If you want to add some more function please write it in comment I will update article with proper credits.


Here is Github Gist Link:
https://gist.github.com/mayurlohite/8385cd9957c2483a54b71ea12199785c

public class GlobalCommonHelper
   {

       // This constant string is used as a "salt" value for the PasswordDeriveBytes function calls.
       // This size of the IV (in bytes) must = (keysize / 8).  Default keysize is 256, so the IV must be
       // 32 bytes long.  Using a 16 character string here gives us 32 bytes when converted to a byte array.
       private const string initVector = "<your salt>";


       // This constant is used to determine the keysize of the encryption algorithm.
       private const int keysize = 256;

       #region General Methods

       /// <summary>
       /// Take any string and encrypt it using SHA1 then
       /// return the encrypted data
       /// </summary>
       /// <param name="data">input text you will enterd to encrypt it</param>
       /// <returns>return the encrypted text as hexadecimal string</returns>
       public string GetSHA1HashData(string data)
       {
           string strResult = string.Empty;

           SHA1CryptoServiceProvider sha1Obj = new SHA1CryptoServiceProvider();
           byte[] bytesToHash = Encoding.ASCII.GetBytes(data);
           bytesToHash = sha1Obj.ComputeHash(bytesToHash);

           foreach (Byte b in bytesToHash)
           {
               strResult += b.ToString("x2");
           }

           return strResult;
       }

       /// <summary>
       /// Creates a slug url from string .
       /// </summary>
       /// <param name="phrase"></param>
       /// <returns></returns>
       public string GetSlugURLFromString(string phrase)
       {
           string str = RemoveAccent(phrase).ToLower();
           // invalid chars
           str = Regex.Replace(str, @"[^a-z0-9\s-]", "");
           // convert multiple spaces into one space
           str = Regex.Replace(str, @"\s+", " ").Trim();
           // cut and trim
           str = str.Substring(0, str.Length <= 45 ? str.Length : 45).Trim();
           str = Regex.Replace(str, @"\s", "-"); // hyphens
           return str;
       }

       /// <summary>
       /// Delete file by specified path.
       /// </summary>
       /// <param name="path">path of file.</param>
       public void DeleteTargetFile(string path)
       {
           if (File.Exists(path))
           {
               File.SetAttributes(path, FileAttributes.Normal);
               File.Delete(path);
           }
       }


       /// <summary>
       /// Sent email to target email address with attachment.
       /// </summary>
       /// <param name="toEmail">Email addresses of one or multiple receipients secolon (;) seperated values.</param>
       /// <param name="subject">Email subject</param>
       /// <param name="body">Email body</param>
       /// <param name="body">Email attachement file path</param>
       /// <returns>True | False</returns>

       public bool SendEmailToTarget(string toEmail, string subject, string body, string attachmentPath)
       {
           bool success = false;
           try
           {
               SmtpClient SmtpServer = new SmtpClient();
               MailMessage mail = new MailMessage();

               SmtpServer.Credentials = new NetworkCredential(
                   Convert.ToString(ConfigurationManager.AppSettings["fromEmail"]),
                   Convert.ToString(ConfigurationManager.AppSettings["fromPassword"]));

               SmtpServer.Host = Convert.ToString(ConfigurationManager.AppSettings["hostName"]);
               SmtpServer.Port = Convert.ToInt32(ConfigurationManager.AppSettings["portNumber"]);

               if (Convert.ToBoolean(ConfigurationManager.AppSettings["isEnableSSL"]) == true)
                   SmtpServer.EnableSsl = true;

               mail.From = new MailAddress(Convert.ToString(ConfigurationManager.AppSettings["senderName"]));

               string[] multiEmails = toEmail.Split(';');
               foreach (string email in multiEmails)
               {
                   mail.To.Add(email);
               }

               System.Net.Mail.Attachment attachment;
               attachment = new System.Net.Mail.Attachment(attachmentPath);
               mail.Attachments.Add(attachment);

               mail.Subject = subject;
               mail.IsBodyHtml = true;
               mail.Body = body;
               SmtpServer.Send(mail);
               mail.Dispose();
               success = true;
           }
           catch (Exception)
           {
               success = false;
           }
           return success;
       }

       /// <summary>
       /// Strips tags
       /// </summary>
       /// <param name="text">Text</param>
       /// <returns>Formatted text</returns>
       public string RemoveHtmlFromString(string text)
       {
           if (String.IsNullOrEmpty(text))
               return string.Empty;

           text = Regex.Replace(text, @"(>)(\r|\n)*(<)", "><");
           text = Regex.Replace(text, "(<[^>]*>)([^<]*)", "$2");
           text = Regex.Replace(text, "(&#x?[0-9]{2,4};|"|&| |<|>|€|©|®|‰|‡|†|‹|›|„|"|"|‚|’|‘|—|–|‏|‎|‍|‌| | | |˜|ˆ|Ÿ|š|Š)", "@");

           return text;
       }

       /// <summary>
       /// Verifies that a string is in valid e-mail format
       /// </summary>
       /// <param name="email">Email to verify</param>
       /// <returns>true if the string is a valid e-mail address and false if it's not</returns>
       public bool IsValidEmail(string email)
       {
           if (String.IsNullOrEmpty(email))
               return false;

           email = email.Trim();
           var result = Regex.IsMatch(email, "^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$", RegexOptions.IgnoreCase);
           return result;
       }

       /// <summary>
       /// Returns Allowed HTML only.
       /// </summary>
       /// <param name="text">Text</param>
       /// <returns>Allowed HTML</returns>
       public string EnsureOnlyAllowedHtml(string text)
       {
           if (String.IsNullOrEmpty(text))
               return string.Empty;

           const string allowedTags = "br,hr,b,i,u,a,div,ol,ul,li,blockquote,img,span,p,em," +
                                       "strong,font,pre,h1,h2,h3,h4,h5,h6,address,cite";

           var m = Regex.Matches(text, "<.*?>", RegexOptions.IgnoreCase);
           for (int i = m.Count - 1; i >= 0; i--)
           {
               string tag = text.Substring(m[i].Index + 1, m[i].Length - 1).Trim().ToLower();

               if (!IsValidTag(tag, allowedTags))
               {
                   text = text.Remove(m[i].Index, m[i].Length);
               }
           }

           return text;
       }

       /// <summary>
       /// Verifies that a uploading file is in valid Image format
       /// </summary>
       /// <param name="postedFile">File which is selected for upload</param>
       /// <param name="imageMinBytes">Minimum file size in byte</param>
       /// <param name="imageMaxBytes">Maximum file size in byte</param>
       /// <returns>true if the file is a valid image format and false if it's not</returns>
       public bool IsValidImageFormat(HttpPostedFileBase postedFile, int imageMinBytes, long imageMaxBytes)
       {

           //-------------------------------------------
           //  Check the image extension
           //-------------------------------------------
           if (Path.GetExtension(postedFile.FileName).ToLower() != ".jpg"
               && Path.GetExtension(postedFile.FileName).ToLower() != ".png"
               && Path.GetExtension(postedFile.FileName).ToLower() != ".gif"
               && Path.GetExtension(postedFile.FileName).ToLower() != ".jpeg")
           {
               return false;
           }

           //-------------------------------------------
           //  Check the image MIME types
           //-------------------------------------------
           if (postedFile.ContentType.ToLower() != "image/jpg" &&
                       postedFile.ContentType.ToLower() != "image/jpeg" &&
                       postedFile.ContentType.ToLower() != "image/pjpeg" &&
                       postedFile.ContentType.ToLower() != "image/gif" &&
                       postedFile.ContentType.ToLower() != "image/x-png" &&
                       postedFile.ContentType.ToLower() != "image/png")
           {
               return false;
           }



           //-------------------------------------------
           //  Attempt to read the file and check the first bytes
           //-------------------------------------------
           try
           {
               if (!postedFile.InputStream.CanRead)
               {
                   return false;
               }

               if (postedFile.ContentLength < imageMinBytes)
               {
                   return false;
               }

               byte[] buffer = new byte[512];
               postedFile.InputStream.Read(buffer, 0, 512);
               string content = System.Text.Encoding.UTF8.GetString(buffer);
               if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
                   RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
               {
                   return false;
               }
           }
           catch (Exception)
           {
               return false;
           }

           //-------------------------------------------
           //  Try to instantiate new Bitmap, if .NET will throw exception
           //  we can assume that it's not a valid image
           //-------------------------------------------

           try
           {
               using (var bitmap = new System.Drawing.Bitmap(postedFile.InputStream))
               {
               }
           }
           catch (Exception)
           {
               return false;
           }

           return true;
       }


       //for checking zip we need the reference of DotNetZip.
       //You can download it by Nuget with following command
       //PM > Install-Package DotNetZip


       /// <summary>
       /// Verifies that a uploading file is in valid Zip format
       /// </summary>
       /// <param name="postedFile">File which is selected for upload</param>
       /// <param name="imageMinBytes">Minimum file size in byte</param>
       /// <param name="imageMaxBytes">Maximum file size in byte</param>
       /// <returns>true if the file is a valid zip format and false if it's not</returns>
       public bool IsValidZipFormat(HttpPostedFileBase postedFile, int imageMinBytes, long imageMaxBytes)
       {

           //-------------------------------------------
           //  Check the file extension
           //-------------------------------------------
           if (Path.GetExtension(postedFile.FileName).ToLower() != ".zip")
           {
               return false;
           }

           //-------------------------------------------
           //  Check the file MIME types
           //-------------------------------------------
           if (postedFile.ContentType.ToLower() != "application/x-zip" &&
                       postedFile.ContentType.ToLower() != "application/zip" &&
                       postedFile.ContentType.ToLower() != "application/zip-compressed" &&
                       postedFile.ContentType.ToLower() != "application/x-zip-compressed" &&
                       postedFile.ContentType.ToLower() != "application/octet-stream")
           {
               return false;
           }



           //-------------------------------------------
           //  Attempt to read the file and check the first bytes
           //-------------------------------------------
           try
           {
               if (postedFile.ContentLength < imageMinBytes)
               {
                   return false;
               }

               byte[] buffer = new byte[512];
               postedFile.InputStream.Read(buffer, 0, 512);
               string content = System.Text.Encoding.UTF8.GetString(buffer);
               if (Regex.IsMatch(content, @"<script|<html|<head|<title|<body|<pre|<table|<a\s+href|<img|<plaintext|<cross\-domain\-policy",
                   RegexOptions.IgnoreCase | RegexOptions.CultureInvariant | RegexOptions.Multiline))
               {
                   return false;
               }
           }
           catch (Exception)
           {
               return false;
           }

           //-------------------------------------------
           //  Try to check zip file by dotnetzip library, if .NET will throw exception
           //  we can assume that it's not a valid zip file
           //-------------------------------------------

           try
           {
               ZipFile.CheckZip(postedFile.FileName); //just pass the name of the file
           }
           catch (Exception)
           {
               return false;
           }

           return true;
       }


       /// <summary>
       /// Encrypts the specified plain text.
       /// </summary>
       /// <param name="plainText">The plain text.</param>
       /// <param name="passPhrase">The pass phrase.</param>
       /// <returns>
       /// Encrypted string
       /// </returns>
       public string EncryptString(string plainText, string passPhrase)
       {
           byte[] initVectorBytes = Encoding.UTF8.GetBytes(initVector);
           byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
           PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
           byte[] keyBytes = password.GetBytes(keysize / 8);
           RijndaelManaged symmetricKey = new RijndaelManaged();
           symmetricKey.Mode = CipherMode.CBC;
           ICryptoTransform encryptor = symmetricKey.CreateEncryptor(keyBytes, initVectorBytes);
           MemoryStream memoryStream = new MemoryStream();
           CryptoStream cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write);
           cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
           cryptoStream.FlushFinalBlock();
           byte[] cipherTextBytes = memoryStream.ToArray();
           memoryStream.Close();
           cryptoStream.Close();
           return Convert.ToBase64String(cipherTextBytes);
       }

       /// <summary>
       /// Decrypts the specified cipher text.
       /// </summary>
       /// <param name="cipherText">The cipher text.</param>
       /// <param name="passPhrase">The pass phrase.</param>
       /// <returns>
       /// Decrypted string
       /// </returns>
       public string DecryptString(string cipherText, string passPhrase)
       {
           byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector);
           byte[] cipherTextBytes = Convert.FromBase64String(cipherText);
           PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null);
           byte[] keyBytes = password.GetBytes(keysize / 8);
           RijndaelManaged symmetricKey = new RijndaelManaged();
           symmetricKey.Mode = CipherMode.CBC;
           ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes);
           MemoryStream memoryStream = new MemoryStream(cipherTextBytes);
           CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read);
           byte[] plainTextBytes = new byte[cipherTextBytes.Length];
           int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length);
           memoryStream.Close();
           cryptoStream.Close();
           return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount);
       }

       /// <summary>
       /// Return Numeric digit to words.
       /// </summary>
       /// <param name="strToHash">The string which converts Numeric digit into words</param>
       /// <returns>Amount in words</returns>
       public string NumberToWords(long number)
       {
           if (number == 0)
               return "zero";

           if (number < 0)
               return "minus " + NumberToWords(Math.Abs(number));

           string words = "";

           if ((number / 100000) > 0)
           {
               words += NumberToWords(number / 100000) + " Lakh ";
               number %= 100000;
           }

           if ((number / 1000) > 0)
           {
               words += NumberToWords(number / 1000) + " Thousand ";
               number %= 1000;
           }

           if ((number / 100) > 0)
           {
               words += NumberToWords(number / 100) + " Hundred ";
               number %= 100;
           }

           if (number > 0)
           {
               if (words != "")
                   words += "and ";

               var unitsMap = new[] { "Zero", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen" };
               var tensMap = new[] { "Zero", "Ten", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety" };

               if (number < 20)
                   words += unitsMap[number];
               else
               {
                   words += tensMap[number / 10];
                   if ((number % 10) > 0)
                       words += "-" + unitsMap[number % 10];
               }
           }

           return words;
       }

       // Updated on 11 April, 2016
       /// <summary>
       /// Verifies that a string is in valid e-mail format
       /// </summary>
       /// <param name="email">Email to verify</param>
       /// <returns>true if the string is a valid e-mail address and false if it's not</returns>
       public bool IsValidEmail(string email)
       {
           if (String.IsNullOrEmpty(email))
               return false;

           email = email.Trim();
           var result = Regex.IsMatch(email, "^(?:[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+\\.)*[\\w\\!\\#\\$\\%\\&\\'\\*\\+\\-\\/\\=\\?\\^\\`\\{\\|\\}\\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!\\.)){0,61}[a-zA-Z0-9]?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\\[(?:(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\.){3}(?:[01]?\\d{1,2}|2[0-4]\\d|25[0-5])\\]))$", RegexOptions.IgnoreCase);
           return result;
       }

       /// <summary>
       /// Generate random digit code
       /// </summary>
       /// <param name="length">Length</param>
       /// <returns>Result string</returns>
       public string GenerateRandomDigitCode(int length)
       {
           var random = new Random();
           string str = string.Empty;
           for (int i = 0; i < length; i++)
               str = String.Concat(str, random.Next(10).ToString());
           return str;
       }

       /// <summary>
       /// Returns an random interger number within a specified rage
       /// </summary>
       /// <param name="min">Minimum number</param>
       /// <param name="max">Maximum number</param>
       /// <returns>Result</returns>
       public int GenerateRandomInteger(int min = 0, int max = int.MaxValue)
       {
           var randomNumberBuffer = new byte[10];
           new RNGCryptoServiceProvider().GetBytes(randomNumberBuffer);
           return new Random(BitConverter.ToInt32(randomNumberBuffer, 0)).Next(min, max);
       }

       /// <summary>
       /// Ensure that a string doesn't exceed maximum allowed length
       /// </summary>
       /// <param name="str">Input string</param>
       /// <param name="maxLength">Maximum length</param>
       /// <param name="postfix">A string to add to the end if the original string was shorten</param>
       /// <returns>Input string if its lengh is OK; otherwise, truncated input string</returns>
       public string EnsureMaximumLength(string str, int maxLength, string postfix = null)
       {
           if (String.IsNullOrEmpty(str))
               return str;

           if (str.Length > maxLength)
           {
               var result = str.Substring(0, maxLength);
               if (!String.IsNullOrEmpty(postfix))
               {
                   result += postfix;
               }
               return result;
           }
           else
           {
               return str;
           }
       }

       /// <summary>
       /// Ensures that a string only contains numeric values
       /// </summary>
       /// <param name="str">Input string</param>
       /// <returns>Input string with only numeric values, empty string if input is null/empty</returns>
       public string EnsureNumericOnly(string str)
       {
           if (String.IsNullOrEmpty(str))
               return string.Empty;

           var result = new StringBuilder();
           foreach (char c in str)
           {
               if (Char.IsDigit(c))
                   result.Append(c);
           }
           return result.ToString();
       }

       /// <summary>
       /// Ensure that a string is not null
       /// </summary>
       /// <param name="str">Input string</param>
       /// <returns>Result</returns>
       public string EnsureNotNull(string str)
       {
           if (str == null)
               return string.Empty;

           return str;
       }

       #endregion General Methods

       #region Internal Processing Private Methods

       private string RemoveAccent(string txt)
       {
           byte[] bytes = System.Text.Encoding.GetEncoding("Cyrillic").GetBytes(txt);
           return System.Text.Encoding.ASCII.GetString(bytes);
       }

       private bool IsValidTag(string tag, string tags)
       {
           string[] allowedTags = tags.Split(',');
           if (tag.IndexOf("javascript") >= 0) return false;
           if (tag.IndexOf("vbscript") >= 0) return false;
           if (tag.IndexOf("onclick") >= 0) return false;

           var endchars = new char[] { ' ', '>', '/', '\t' };

           int pos = tag.IndexOfAny(endchars, 1);
           if (pos > 0) tag = tag.Substring(0, pos);
           if (tag[0] == '/') tag = tag.Substring(1);

           foreach (string aTag in allowedTags)
           {
               if (tag == aTag) return true;
           }

           return false;
       }

       #endregion Internal Processing Private Methods
   }

 

Updates:

11 April, 2016 - Following functions added.

public bool IsValidEmail(string email){}
public string GenerateRandomDigitCode(int length){}
public int GenerateRandomInteger(int min = 0, int max = int.MaxValue){}
public string EnsureMaximumLength(string str, int maxLength, string postfix = null){}
public string EnsureNumericOnly(string str){}
public string EnsureNotNull(string str){}

 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
India India
My name is Mayur Lohite. I am Programmer and Web Developer also I am Interested in Web Application Security and penetration. From a young age I’ve been fascinated with building web application and breaking it. So I have choose the Information technology as my career and completed the Degree in Information technology.

I’m a interested in operating and design of large-scale web applications/infrastructure and I’m interested in web application security also I am interested in some networking setting up servers, domains experimenting with clouds(well I am not professional at it)

I am a big fan of Anime series (Naruto) and also love to playing games. In the mean time I love to watching movies specially action movies.

Now I’m a white hat penetration tester. bug hunter and all out security freak by profession and passion. I’ve listed many websites Hall of fame e.g. Microsoft, Yahoo, Apple, Adobe

Comments and Discussions

Discussions on this specific version of this article. Add your comments on how to improve this article here. These comments will not be visible on the final published version of this article.
 
QuestionMy Vote of 4 Pin
Karthik_Mahalingam22-Apr-16 21:04
professionalKarthik_Mahalingam22-Apr-16 21:04 
AnswerRe: My Vote of 4 Pin
Mayur V Lohite22-Apr-16 21:06
professionalMayur V Lohite22-Apr-16 21:06 
GeneralRe: My Vote of 4 Pin
Karthik_Mahalingam22-Apr-16 21:13
professionalKarthik_Mahalingam22-Apr-16 21:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.