SoFunction
Updated on 2025-03-07

Commonly used public methods of C#

Commonly used public methods in C#, the specific content is as follows

1. Call weburl in the background

string hostUrl = "?id=123" ;
HttpWebRequest myReq = (HttpWebRequest)(hostUrl);
 = "GET";

HttpWebResponse HttpWResp = (HttpWebResponse)();
Stream myStream = ();
StreamReader sr = new StreamReader(myStream, Encoding.UTF8);
StringBuilder strBuilder = new StringBuilder();
while (-1 != ())
{
(());
}
();
();
();

 jo = ()(());
string resCode = jo["ReturnCode"].ToString();

2. Detect whether the input URL is legal 

/// <summary>
 /// Determine whether the URL is accessible /// </summary>
 /// <param name="Url"></param>
 /// <returns></returns>
 protected bool ChkPageUrl(string url)
 {
  bool result = false;
  try
  {
   HttpWebRequest myHttpWebRequest = (HttpWebRequest)(url);
    = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko";
    = "GET";
   HttpWebResponse myHttpWebResponse = (HttpWebResponse)();
   if ( == )
   {
    result = true;
   }
   ();
  }
  catch
  {
   result = false;
  }

  return result;
 }

3. Batch export

 /// <summary>
  /// Batch export  /// </summary>
  /// <returns></returns>
  public FileResult ExportStu()
  {
   //Create an Excel file object    book = new ();
   //Add a sheet    sheet1 = ("Sheet1");
   int pager_totalcount = (int)Session["pager_totalcount"];
   int totalCount = 0;
   //Get list data   List<ArticleEntity> infoList = new ().GetArticleList("", pager_totalcount, 1, out totalCount);

   //Add the header of the first line to sheet1    row1 = (0);
   //Creation time Name Merchant order number | Transaction number Opposite Amount (yuan) Status   (0).SetCellValue("serial number");
   (1).SetCellValue("title");
   (2).SetCellValue("content");
   int Width = 256;
   (0, 10 * Width);
   (1, 25 * Width);
   (2, 60 * Width);
   if (infoList != null)
   {
    var list = (p => );

    if (list != null)
    {
     int i = 0;
     //Steply write data to each row of sheet1     foreach (var item in list)
     {
      i = i + 1;
       rowtemp = (i);
      (0).SetCellValue(());
      (1).SetCellValue( == null ? "" : ());
      (2).SetCellValue( == null ? "" : ());
     }
    }
   }
   // Write to the client    ms = new ();
   (ms);
   (0, );
   return File(ms, "application/-excel", ("Export", Encoding.UTF8).ToString() + ("yyyyMMddHHmmss") + ".xls");

  }

4. Batch import 

 <input name="file" type="file" />
<input type="submit" name="Upload" value="Upload" />

/// &lt;summary&gt;
  /// Batch import  /// &lt;/summary&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  [HttpPost]
  public ActionResult ImportStu()
  {
   HttpPostedFileBase file = ["file"];
   string FileName;
   string savePath;
   if (file == null ||  &lt;= 0)
   {
    return Content("&lt;script&gt;alert('Upload failed, please select upload file!');='/MyTest/MVCPager';&lt;/script&gt;");
   }
   else
   {
    string filename = ();
    int filesize = ;//Get the size unit of uploaded file is byte byte    string fileEx = (filename);//Get the extension of the uploaded file    string NoFileName = (filename);//Get filename without extension    string FileType = ".xls,.xlsx";//Define the type string of uploaded file    if ((".exe"))//EXCEL
    {
     return Content("&lt;script&gt;alert('The upload file type is incorrect, and the import of exe format is not allowed!');='/MyTest/MVCPager';&lt;/script&gt;");
    }
    FileName = NoFileName + ("yyyyMMddhhmmss") + fileEx;
    string path =  + "uploads/";
    savePath = (path, FileName);
    (savePath);

    if ((fileEx))//EXCEL
    {
     string strConn = "Provider=.4.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 8.0";
     OleDbConnection conn = new OleDbConnection(strConn);
     ();
     OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn);
     DataSet myDataSet = new DataSet();
     try
     {
      (myDataSet, "ExcelInfo");
     }
     catch (Exception ex)
     {
      return Content("&lt;script&gt;alert('Upload failed," + + "!');='/MyTest/MVCPager';&lt;/script&gt;");
     }
     //Column order Title Content     DataTable table = ["ExcelInfo"].();

     //Things exception rollback     using (TransactionScope transaction = new TransactionScope())
     {
      for (int i = 0; i &lt; ; i++)
      {
       ArticleEntity model = new ArticleEntity();
        = [i][0].ToString();
        = [i][1].ToString();
       new ().AddArticle(model);
      }
      ();
     }
    }

    return RedirectToAction("MVCPager", "MyTest");
   }
  }

5. Get the IP address of the client 

/// &lt;summary&gt;
  /// Get the IP address of the client  /// &lt;/summary&gt;
  /// <returns>Client IP Address</returns>  public static string Get_ClientIP()
  {
   string result = ;
   result = ["X-Real-IP"]; //How to get IP address when Nginx is the front-end   if (result != null)
    return result;

   if (["REMOTE_ADDR"] != null)//The IP address of the remote host that issued the request   {
    result = ["REMOTE_ADDR"].ToString();
   }
   else if (["HTTP_VIA"] != null)//Discern whether to set up a proxy, if a proxy is used   {
    if (["HTTP_X_FORWARDED_FOR"] != null)//Get the proxy server's IP    {
     result = ["HTTP_X_FORWARDED_FOR"].ToString();
    }
    else
    {
     result = ;
    }
   }
   else
   {
    result = ;
   }
   if (result == "::1")
    result = ;
   return result;
  }

Symmetric encryption 

 /// &lt;summary&gt;
 /// Symmetric encryption class /// &lt;/summary&gt;
 public class AES
 {
  /// &lt;summary&gt;
  /// Decrypt  /// &lt;/summary&gt;
  /// &lt;param name="strDecrypt"&gt;&lt;/param&gt;
  /// &lt;param name="strKey"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static string Decrypt(string strDecrypt, string strKey)
  {
   try
   {
    byte[] bytes = Encoding.((strKey, "md5"));
    byte[] inputBuffer = Convert.FromBase64String(strDecrypt);
    byte[] buffer3 = null;
    using (RijndaelManaged managed = new RijndaelManaged())
    {
      = bytes;
      = ;
      = PaddingMode.PKCS7;
     buffer3 = ().TransformFinalBlock(inputBuffer, 0, );
    }
    return Encoding.(buffer3);
   }
   catch
   {
    return null;
   }
  }

  /// &lt;summary&gt;
  /// Decrypt  /// &lt;/summary&gt;
  /// &lt;param name="strDecrypt"&gt;&lt;/param&gt;
  /// &lt;param name="strKey"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static string Decrypt(string toDecrypt, string key, string iv)
  {
   byte[] bytes = Encoding.(key);
   byte[] buffer2 = Encoding.(iv);
   byte[] inputBuffer = Convert.FromBase64String(toDecrypt);
   RijndaelManaged managed = new RijndaelManaged
   {
    Key = bytes,
    IV = buffer2,
    Mode = ,
    Padding = 
   };
   byte[] buffer4 = ().TransformFinalBlock(inputBuffer, 0, );
   return Encoding.(buffer4);
  }

  public static string DecryptStr(string EncryptString)
  {
   string str = "";
   if (!(EncryptString))
   {
    string sSource = Decrypt(EncryptString, "");
    if ((sSource, 3) == "gk_")
    {
     str = (3);
    }
   }
   return str;
  }

  public static string DecryptStrByCBC(string EncryptString)
  {
   string str = "";
   if (!(EncryptString))
   {
    string sSource = Decrypt(EncryptString, "", "");
    if ((sSource, 3) == "gk_")
    {
     str = (3);
    }
   }
   return str;
  }

  /// &lt;summary&gt;
  /// Encryption  /// &lt;/summary&gt;
  /// &lt;param name="strEncrypt"&gt;&lt;/param&gt;
  /// &lt;param name="strKey"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static string Encrypt(string strEncrypt, string strKey)
  {
   try
   {
    byte[] bytes = Encoding.((strKey, "md5"));
    byte[] inputBuffer = Encoding.(strEncrypt);
    byte[] inArray = null;
    using (RijndaelManaged managed = new RijndaelManaged())
    {
      = bytes;
      = ;
      = PaddingMode.PKCS7;
     inArray = ().TransformFinalBlock(inputBuffer, 0, );
    }
    return Convert.ToBase64String(inArray, 0, );
   }
   catch
   {
    return null;
   }
  }

  /// &lt;summary&gt;
  /// Encryption  /// &lt;/summary&gt;
  /// &lt;param name="strEncrypt"&gt;&lt;/param&gt;
  /// &lt;param name="strKey"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static string Encrypt(string toEncrypt, string key, string iv)
  {
   byte[] bytes = Encoding.(key);
   byte[] buffer2 = Encoding.(iv);
   byte[] inputBuffer = Encoding.(toEncrypt);
   RijndaelManaged managed = new RijndaelManaged
   {
    Key = bytes,
    IV = buffer2,
    Mode = ,
    Padding = 
   };
   byte[] inArray = ().TransformFinalBlock(inputBuffer, 0, );
   return Convert.ToBase64String(inArray, 0, );
  }

  public static string EncryptStr(string SourceString)
  {
   return Encrypt("gk_" + SourceString, "");
  }

  public static string EncryptStr(string SourceString, bool UseInUrl)
  {
   return (EncryptStr(SourceString));
  }

  public static string EncryptStrByCBC(string SourceString)
  {
   return Encrypt("gk_" + SourceString, "", "");
  }

  public static string EncryptStrByCBC(string SourceString, bool UseInUrl)
  {
   return (EncryptStrByCBC(SourceString));
  }
 }

Help 

public class CookiesHelper
 {
  public static void AddCookie(string cookieName, DateTime expires)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   AddCookie(cookie, null);
  }

  public static void AddCookie(string key, string value)
  {
   AddCookie(new HttpCookie(key, value), null);
  }

  public static void AddCookie(HttpCookie cookie, string Domain)
  {
   HttpResponse response = ;
   if (response != null)
   {
     = true;
     = "/";
    if (!(Domain))
    {
      = Domain;
    }
    (cookie);
   }
  }

  public static void AddCookie(string cookieName, DateTime expires, string Domain)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   AddCookie(cookie, Domain);
  }

  public static void AddCookie(string key, string value, DateTime expires)
  {
   HttpCookie cookie = new HttpCookie(key, value)
   {
    Expires = expires
   };
   AddCookie(cookie, null);
  }

  public static void AddCookie(string cookieName, string key, string value)
  {
   HttpCookie cookie = new HttpCookie(cookieName);
   (key, value);
   AddCookie(cookie, null);
  }

  public static void AddCookie(string key, string value, bool withDomain, string Domain)
  {
   if (withDomain)
   {
    AddCookie(new HttpCookie(key, value), Domain);
   }
   else
   {
    AddCookie(new HttpCookie(key, value), null);
   }
  }

  public static void AddCookie(string key, string value, DateTime expires, string Domain)
  {
   HttpCookie cookie = new HttpCookie(key, value)
   {
    Expires = expires
   };
   AddCookie(cookie, Domain);
  }

  public static void AddCookie(string cookieName, string key, string value, DateTime expires)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   (key, value);
   AddCookie(cookie, null);
  }

  public static void AddCookie(string cookieName, string key, string value, string Domain)
  {
   HttpCookie cookie = new HttpCookie(cookieName);
   (key, value);
   AddCookie(cookie, Domain);
  }

  public static void AddCookie(string cookieName, string key, string value, DateTime expires, string Domain)
  {
   HttpCookie cookie = new HttpCookie(cookieName)
   {
    Expires = expires
   };
   (key, value);
   AddCookie(cookie, Domain);
  }

  public static void AddDomainCookie(string key, string value, string Domain)
  {
   AddCookie(new HttpCookie(key, value), Domain);
  }

  public static HttpCookie GetCookie(string cookieName)
  {
   HttpRequest request = ;
   if (request != null)
   {
    if ([cookieName] != null)
    {
     return [cookieName];
    }
    if ([", " + cookieName] != null)
    {
     return [", " + cookieName];
    }
   }
   return null;
  }

  public static string GetCookieValue(string cookieName)
  {
   return GetCookieValue(cookieName, null);
  }

  public static string GetCookieValue(string cookieName, string key)
  {
   HttpRequest request = ;
   if (request == null)
   {
    return "";
   }
   if ([cookieName] != null)
   {
    if (!(key) &amp;&amp; [cookieName].HasKeys)
    {
     return [cookieName].Values[key];
    }
    return [cookieName].Value;
   }
   string str = ", " + cookieName;
   if ([str] == null)
   {
    return "";
   }
   if (!(key) &amp;&amp; [str].HasKeys)
   {
    return [str].Values[key];
   }
   return [str].Value;
  }

  public static string GetCookieValue(HttpCookie cookie, string key)
  {
   if (cookie == null)
   {
    return "";
   }
   if (!(key) &amp;&amp; )
   {
    return [key];
   }
   return ;
  }

  public static void RemoveCookie(string cookieName)
  {
   RemoveCookie(cookieName, null);
  }

  public static void RemoveCookie(string cookieName, string key)
  {
   HttpResponse response = ;
   if (response != null)
   {
    HttpCookie cookie = [cookieName];
    if (cookie != null)
    {
     if (!(key) &amp;&amp; )
     {
      (key);
     }
     else
     {
      (cookieName);
     }
    }
   }
  }

  public static void SetCookie(string cookieName, DateTime expires)
  {
   SetCookie(cookieName, null, null, new DateTime?(expires), null);
  }

  public static void SetCookie(string key, string value)
  {
   SetCookie(key, null, value, null, null);
  }

  public static void SetCookie(string cookieName, DateTime expires, string Domain)
  {
   SetCookie(cookieName, null, null, new DateTime?(expires), Domain);
  }

  public static void SetCookie(string key, string value, DateTime expires)
  {
   SetCookie(key, null, value, new DateTime?(expires), null);
  }

  public static void SetCookie(string cookieName, string key, string value)
  {
   SetCookie(cookieName, key, value, null, null);
  }

  public static void SetCookie(string key, string value, bool withDomain, string Domain)
  {
   if (withDomain)
   {
    SetCookie(key, null, value, null, Domain);
   }
   else
   {
    SetCookie(key, null, value, null, null);
   }
  }

  public static void SetCookie(string key, string value, DateTime expires, string Domain)
  {
   SetCookie(key, null, value, new DateTime?(expires), Domain);
  }

  public static void SetCookie(string cookieName, string key, string value, string Domain)
  {
   SetCookie(cookieName, key, value, null, Domain);
  }

  public static void SetCookie(string cookieName, string key, string value, DateTime? expires, string Domain)
  {
   HttpResponse response = ;
   if (response != null)
   {
    HttpCookie cookie = [cookieName];
    if (cookie != null)
    {
      = "/";
     if (!(Domain))
     {
       = Domain;
     }
     if (!(key) &amp;&amp; )
     {
      (key, value);
     }
     else if (!(value))
     {
       = value;
     }
     if ()
     {
       = ;
     }
     (cookie);
    }
   }
  }
  /// &lt;summary&gt;
  /// Set domain cookies  /// &lt;/summary&gt;
  /// &lt;param name="key"&gt;&lt;/param&gt;
  /// &lt;param name="value"&gt;&lt;/param&gt;
  /// &lt;param name="Domain"&gt;&lt;/param&gt;
  public static void SetDomainCookie(string key, string value, string Domain)
  {
   SetCookie(key, null, value, null, Domain);
  }
 }

Convert to entity class

 /// &lt;summary&gt;
 /// #region DataTable converted to entity class /// &lt;/summary&gt;
 /// &lt;typeparam name="T"&gt;&lt;/typeparam&gt;
 public class ModelUtil&lt;T&gt; where T : new()
 {

  /// &lt;summary&gt;
  ///Fill object list: Fill the entity class with the first table of DataSet  /// &lt;/summary&gt;
  /// &lt;param name="ds"&gt;DataSet&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static List&lt;T&gt; FillModel(DataSet ds)
  {
   if (ds == null || [0] == null || [0]. == 0)
   {
    return null;
   }
   else
   {
    return FillModel([0]);
   }
  }

  /// &lt;summary&gt; 
  ///Fill object list: Fill the entity class with the index table of DataSet  /// &lt;/summary&gt; 
  public static List&lt;T&gt; FillModel(DataSet ds, int index)
  {
   if (ds == null ||  &lt;= index || [index]. == 0)
   {
    return null;
   }
   else
   {
    return FillModel([index]);
   }
  }

  /// &lt;summary&gt; 
  ///Fill the object list: Fill the entity class with DataTable  /// &lt;/summary&gt; 
  public static List&lt;T&gt; FillModel(DataTable dt)
  {
   if (dt == null ||  == 0)
   {
    return null;
   }
   List&lt;T&gt; modelList = new List&lt;T&gt;();
   foreach (DataRow dr in )
   {
    //T model = (T)(typeof(T)); 
    T model = new T();
    for (int i = 0; i &lt; ; i++)
    {
     List&lt;PropertyInfo&gt; propertyInfos = ().GetProperties().ToList();

     PropertyInfo item = (p =&gt; (, [i].ColumnName, true) == 0);
     if (item != null &amp;&amp; dr[i] != )
      try
      {
       (model, dr[i], null);
      }
      catch
      {
      }
    }

    (model);
   }
   return modelList;
  }

  /// &lt;summary&gt; 
  ///Fill object: Fill the entity class with DataRow  /// &lt;/summary&gt; 
  public static T FillModel(DataRow dr)
  {
   if (dr == null)
   {
    return default(T);
   }

   //T model = (T)(typeof(T)); 
   T model = new T();

   for (int i = 0; i &lt; ; i++)
   {
    List&lt;PropertyInfo&gt; propertyInfos = ().GetProperties().ToList();

    PropertyInfo item = (p =&gt; (, [i].ColumnName, true) == 0);
    if (item != null &amp;&amp; dr[i] != )
     try
     {
      (model, dr[i], null);
     }
     catch
     {
     }
   }
   return model;
  }


  /// &lt;summary&gt;
  /// Convert entity class to DataSet  /// &lt;/summary&gt;
  /// <param name="modelList">Entity Class List</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static DataSet FillDataSet(List&lt;T&gt; modelList)
  {
   if (modelList == null ||  == 0)
   {
    return null;
   }
   else
   {
    DataSet ds = new DataSet();
    (FillDataTable(modelList));
    return ds;
   }
  }

  /// &lt;summary&gt;
  /// Convert entity class to DataTable  /// &lt;/summary&gt;
  /// <param name="modelList">Entity Class List</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static DataTable FillDataTable(List&lt;T&gt; modelList)
  {
   if (modelList == null ||  == 0)
   {
    return null;
   }
   DataTable dt = CreateData(modelList[0]);

   foreach (T model in modelList)
   {
    DataRow dataRow = ();
    foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
    {
     dataRow[] = (model, null);
    }
    (dataRow);
   }
   return dt;
  }

  /// &lt;summary&gt;
  /// Get the table structure according to the entity class  /// &lt;/summary&gt;
  /// <param name="model">Entity class</param>  /// &lt;returns&gt;&lt;/returns&gt;
  private static DataTable CreateData(T model)
  {
   DataTable dataTable = new DataTable(typeof(T).Name);
   foreach (PropertyInfo propertyInfo in typeof(T).GetProperties())
   {
    (new DataColumn(, ));
   }
   return dataTable;
  }

  /// &lt;summary&gt;
  /// Convert DataTable to List and save Dictionary nested collection  /// &lt;/summary&gt;
  /// &lt;param name="dt"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static List&lt;Dictionary&lt;string, string&gt;&gt; ToListDictionary(DataTable dt)
  {
   List&lt;Dictionary&lt;string, string&gt;&gt; list = null;
   if (dt != null &amp;&amp;  &gt; 0)
   {
    list = new List&lt;Dictionary&lt;string, string&gt;&gt;();
    Dictionary&lt;string, string&gt; dic = null;
    foreach (DataRow dr in )
    {
     dic = new Dictionary&lt;string, string&gt;();
     foreach (DataColumn dc in )
     {
      (, dr[].ToString());
     }
     (dic);
    }
   }
   return list;
  }

  /// &lt;summary&gt;
  /// Convert the content of the request to model  /// cza
  /// 2016-5-30 19:06:21
  /// &lt;/summary&gt;
  /// &lt;param name="context"&gt;&lt;/param&gt;
  /// &lt;returns&gt;&lt;/returns&gt;
  public static T ConvertToModel(HttpContext context)
  {
   T t = new T();
   PropertyInfo[] propertys = ().GetProperties();
   foreach (PropertyInfo pi in propertys)
   {
    if (!)
     continue;
    object value = [];
    if (value != null &amp;&amp; value != )
    {
     try
     {
      if (() != "")
       (t, (value, ), null);//This step is very important for type conversion      else
       (t, value, null);
     }
     catch
     { }
    }
   }

   return t;
  }


 }

Server database access class 

 /// &lt;summary&gt;
 /// SQL Server database access class /// &lt;/summary&gt;
 public abstract class SqlHelper
 {
  //Read the database connection string in the configuration file  public static readonly string connStr = ["Conn"].ConnectionString;

  //Empty structure  public SqlHelper() { }

  //Hashtable to store cached parameters
  private static Hashtable parmCache = (new Hashtable());

  /// &lt;summary&gt;
  /// Execute addition, deletion and modification [commonly used]  /// &lt;/summary&gt;
  public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();
   using (SqlConnection conn = new SqlConnection(connectionString))
   {
    PrepareCommand(cmd, conn, null, commandType, commandText, paras);
    int val = ();
    ();   //Clear parameters    return val;
   }
  }

  /// &lt;summary&gt;
  /// Perform addition, deletion and modification (connection to existing databases) [not commonly used]  /// &lt;/summary&gt;
  public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();
   PrepareCommand(cmd, connection, null, commandType, commandText, paras);
   int val = ();
   ();
   return val;
  }

  /// &lt;summary&gt;
  /// Execute multiple sql statements (List generic collection) [Transaction] (no parameters)  /// &lt;/summary&gt;
  /// <param name="connectionString">Database connection string</param>  /// <param name="listSql">Generic collection containing multiple SQL statements</param>  /// <returns>Number of affected rows</returns>  public static int ExecuteNonQuery(string connectionString, List&lt;string&gt; listSql)
  {
   SqlCommand cmd = new SqlCommand();
   SqlConnection conn = new SqlConnection(connectionString);
   ();
   SqlTransaction trans = ();
   PrepareCommand(cmd, conn, trans, , null, null);
   try
   {
    int count = 0;
    for (int n = 0; n &lt; ; n++)
    {
     string strSql = listSql[n];
     if (().Length &gt; 1)
     {
       = strSql;
      count += ();
     }
    }
    ();
    ();
    return count;
   }
   catch
   {
    ();
    ();
    return 0;
   }
   finally
   {
    ();
   }
  }

  /// &lt;summary&gt;
  /// Execute multiple sql statements (Hashtable) [transaction] (with a set of parameters, one parameter must also be encapsulated into groups)  /// &lt;/summary&gt;
  /// <param name="connectionString">Database connection string</param>  /// <param name="sqlStringList">Hashtable table, key-value pair form</param>  public static void ExecuteNonQuery(string connectionString, Hashtable sqlStringList)
  {
   using (SqlConnection conn = new SqlConnection(connectionString))
   {
    ();
    using (SqlTransaction trans = ())
    {
     SqlCommand cmd = new SqlCommand();
     try
     {
      foreach (DictionaryEntry item in sqlStringList)
      {
       string cmdText = (); //Sql statement to be executed       SqlParameter[] cmdParas = (SqlParameter[]); //System corresponding to SQL statement       PrepareCommand(cmd, conn, trans, , cmdText, cmdParas);
       int val = ();
       ();
      }
      if ( &gt; 0)
       ();
     }
     catch
     {
      ();
      throw;
     }
    }
   }

  }

  /// &lt;summary&gt;
  /// Return the DataReader object  /// &lt;/summary&gt;
  public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string cmdText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();
   SqlConnection conn = new SqlConnection(connectionString);
   try
   {
    PrepareCommand(cmd, conn, null, commandType, cmdText, paras);
    SqlDataReader reader = ();
    ();
    return reader;
   }
   catch
   {
    ();
    throw;
   }
  }

  /// &lt;summary&gt;
  /// Return the first row and the first column information (may be a string, so the return type is object) [Commonly used]  /// &lt;/summary&gt;
  public static object ExecuteScalar(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();
   using (SqlConnection connection = new SqlConnection(connectionString))
   {
    PrepareCommand(cmd, connection, null, commandType, commandText, paras);
    object val = ();
    ();
    return val;
   }
  }

  /// &lt;summary&gt;
  /// Return the first row and first column information (for existing database connections) [not commonly used]  /// &lt;/summary&gt;
  public static object ExecuteScalar(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();

   PrepareCommand(cmd, connection, null, commandType, commandText, paras);
   object val = ();
   ();
   return val;
  }

  /// &lt;summary&gt;
  /// Return to DataTable  /// &lt;/summary&gt;
  public static DataTable GetDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();
   using (SqlConnection conn = new SqlConnection(connectionString))
   {
    PrepareCommand(cmd, conn, null, commandType, commandText, paras);
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
     DataTable dt = new DataTable();
     (dt);
     return dt;
    }
   }
  }

  /// &lt;summary&gt;
  /// Return DataSet  /// &lt;/summary&gt;
  public static DataSet GetDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   SqlCommand cmd = new SqlCommand();
   using (SqlConnection conn = new SqlConnection(connectionString))
   {
    PrepareCommand(cmd, conn, null, commandType, commandText, paras);
    using (SqlDataAdapter da = new SqlDataAdapter(cmd))
    {
     DataSet ds = new DataSet();
     (ds);
     return ds;
    }
   }
  }

  /// &lt;summary&gt;
  /// add parameter array to the cache
  /// &lt;/summary&gt;
  /// &lt;param name="cacheKey"&gt;Key to the parameter cache&lt;/param&gt;
  /// &lt;param name="cmdParms"&gt;an array of SqlParamters to be cached&lt;/param&gt;
  public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters)
  {
   parmCache[cacheKey] = commandParameters;
  }

  /// &lt;summary&gt;
  /// Retrieve cached parameters
  /// &lt;/summary&gt;
  /// &lt;param name="cacheKey"&gt;key used to lookup parameters&lt;/param&gt;
  /// &lt;returns&gt;Cached SqlParamters array&lt;/returns&gt;
  public static SqlParameter[] GetCachedParameters(string cacheKey)
  {
   SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey];

   if (cachedParms == null)
    return null;

   SqlParameter[] clonedParms = new SqlParameter[];

   for (int i = 0, j = ; i &lt; j; i++)
    clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();

   return clonedParms;
  }

  /// &lt;summary&gt;
  /// Prepare a SqlCommand to be executed  /// &lt;/summary&gt;
  private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, params SqlParameter[] paras)
  {
   try
   {
    if ( != )
    {
     ();
     ();
    }
     = conn;
    if (commandText != null)
      = commandText;
     = commandType;  //Is the T-Sql statement or stored procedure executed here?
    if (trans != null)
      = trans;

    if (paras != null &amp;&amp;  &gt; 0)
    {
     //(paras);
     for (int i = 0; i &lt; ; i++)
     {
      if (paras[i].Value == null || paras[i].() == "")
       paras[i].Value = ; //When inserting or modifying, if any parameter is an empty string, then insert the database in NULL form      (paras[i]);
     }
    }
   }
   catch (Exception ex)
   {
    throw new Exception();
   }
  }

  /// &lt;summary&gt;
  /// General paging stored procedure, conditional query, sorted fields, sorted in descending order of sorted fields  /// &lt;/summary&gt;
  /// <param name="PageSize">Number of records per page</param>  /// <param name="CurrentCount">Current number of records (page number * number of records per page)</param>  /// <param name="TableName">Table name</param>  /// <param name="Where">Query conditions, example: "ID>1000 AND Name like '%LiLinFeng%'" sorting conditions, directly added to the following, example: "ORDER BY ID DESC,NAME ASC"</param>  /// <param name="TotalCount">Total record number</param>  /// &lt;returns&gt;&lt;/returns&gt;
  public static DataSet GetList(string connectionString, string Order, int PageSize, int CurrentCount, string TableName, string Where, out int TotalCount)
  {
   SqlParameter[] parmList =
    {
     new SqlParameter("@PageSize",PageSize),
     new SqlParameter("@CurrentCount",CurrentCount),
     new SqlParameter("@TableName",TableName),
     new SqlParameter("@Where",Where),
     new SqlParameter("@Order",Order),
     new SqlParameter("@TotalCount",,4)
    };
   parmList[5].Direction = ;
   DataSet ds = GetDataset(connectionString, , "sp_MvcPager", parmList);
   TotalCount = Convert.ToInt32(parmList[5].Value);
   return ds;
  }
 }

10. Log file logging 

 public class WriteLog
 {
  /// &lt;summary&gt;
  /// 
  /// &lt;/summary&gt;
  /// <param name="fileName">File name</param>  /// &lt;param name="ex"&gt;&lt;/param&gt;
  public static void WriteErorrLog(string fileName, Exception ex)
  {
   if (ex == null) return; //ex = null return   DateTime dt = ; // Set log time   string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds   string logName = ("yyyy-MM-dd"); //Log name   string logPath = (, ("log", fileName)); //Log storage path   string log = (logPath, ("{0}.log", logName)); //Path + Name   try
   {
    FileInfo info = new FileInfo(log);
    if ( != null &amp;&amp; !)
    {
     ();
    }
    using (StreamWriter write = new StreamWriter(log, true, ("utf-8")))
    {
     (time);
     ();
     ("Exception message:" + ex);
     ("Exception stack:" + );
     ("Abnormal description:" + );
     ("\r\n----------------------------------\r\n");
     ();
     ();
     ();
    }
   }
   catch { }
  }

  /// &lt;summary&gt;
  /// 
  /// &lt;/summary&gt;
  /// <param name="fileName">File name</param>  /// &lt;param name="message"&gt;&lt;/param&gt;
  public static void WriteMessage(string fileName, string message)
  {
   //ex = null return   DateTime dt = ; // Set log time   string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds   string logName = ("yyyy-MM-dd"); //Log name   string logPath = (, ("log", fileName)); //Log storage path   string log = (logPath, ("{0}.log", logName)); //Path + Name   try
   {
    FileInfo info = new FileInfo(log);
    if ( != null &amp;&amp; !)
    {
     ();
    }
    using (StreamWriter write = new StreamWriter(log, true, ("utf-8")))
    {
     (time);
     ("information:" + message);
     ("\r\n----------------------------------\r\n");
     ();
     ();
     ();
    }
   }
   catch { }
  }


  public static void WriteErorrLog(Exception ex, string message)
  {
   if (ex == null) return; //ex = null return   DateTime dt = ; // Set log time   string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds   string logName = ("yyyy-MM-dd"); //Log name   string logPath = ; //Log storage path   string log = ((logPath, "log"), ("{0}.log", logName)); //Path + Name   try
   {
    FileInfo info = new FileInfo(log);
    if ( != null &amp;&amp; !)
    {
     ();
    }
    using (StreamWriter write = new StreamWriter(log, true, ("utf-8")))
    {
     (time);
     ();
     ("Exception message:" + ex);
     ("Exception stack:" + );
     ("Abnormal description:" + message);
     ("\r\n----------------------------------\r\n");
     ();
     ();
     ();
    }
   }
   catch { }
  }

  public static void WriteMessage(string message)
  {
   //ex = null return   DateTime dt = ; // Set log time   string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds   string logName = ("yyyy-MM-dd"); //Log name   string logPath = ; //Log storage path   string log = ((logPath, "log"), ("{0}.log", logName)); //Path + Name   try
   {
    FileInfo info = new FileInfo(log);
    if ( != null &amp;&amp; !)
    {
     ();
    }
    using (StreamWriter write = new StreamWriter(log, true, ("utf-8")))
    {
     (time);
     ("information:" + message);
     ("\r\n----------------------------------\r\n");
     ();
     ();
     ();
    }
   }
   catch { }
  }
 }

Help 

 /// &lt;summary&gt;
 /// JSON Help Class /// &lt;/summary&gt;
 public class JsonHelper
 {
  #region General Method  /// &lt;summary&gt;
  /// Format character type, date type, boolean type  /// &lt;/summary&gt;
  public static string StringFormat(string str, Type type)
  {
   if (type == typeof(string))
   {
    str = StringFilter(str);
    str = "\"" + str + "\"";
   }
   else if (type == typeof(DateTime) || type == typeof(DateTime?))
   {
    str = "\"" + str + "\"";
   }
   else if (type == typeof(bool))
   {
    str = ();
   }
   else if (type == typeof(Guid))
   {
    str = "\"" + str + "\"";
   }
   else if (type != typeof(string) &amp;&amp; (str))
   {
    str = "\"" + str + "\"";
   }
   return str;
  }

  /// &lt;summary&gt;
  /// Filter strings  /// &lt;/summary&gt;
  public static string StringFilter(string str)
  {
   StringBuilder sb = new StringBuilder();
   for (int i = 0; i &lt; ; i++)
   {
    char c = ()[i];
    switch (c)
    {
     case '\"':
      ("\\\""); break;
     case '\\':
      ("\\\\"); break;
     case '/':
      ("\\/"); break;
     case '\b':
      ("\\b"); break;
     case '\f':
      ("\\f"); break;
     case '\n':
      ("\\n"); break;
     case '\r':
      ("\\r"); break;
     case '\t':
      ("\\t"); break;
     default:
      (c); break;
    }
   }
   return ();
  }
  #endregion

  #region column to json  /// &lt;summary&gt;
  /// column to json  /// &lt;/summary&gt;
  /// <param name="dt">table</param>  /// <param name="r">Column</param>  public static string ColumnToJson(DataTable dt, int r)
  {
   StringBuilder strSql = new StringBuilder();
   for (int i = 0; i &lt; ; i++)
   {
    ([i][r]);
    (",");
   }
   return ().Trim(',');
  }
  #endregion

  #region object to json  /// &lt;summary&gt;
  /// Object to json  /// &lt;/summary&gt;
  public static string ToJson(object jsonObject)
  {
   StringBuilder sb = new StringBuilder();
   ("{");
   PropertyInfo[] propertyInfo = ().GetProperties();
   for (int i = 0; i &lt; ; i++)
   {
    object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null);
    Type type = propertyInfo[i].PropertyType;
    string strValue = ();
    strValue = StringFormat(strValue, type);
    ("\"" + propertyInfo[i].Name + "\":");
    (strValue + ",");
   }
   ( - 1, 1);
   ("}");
   return ();
  }
  #endregion

  #region list to json  /// &lt;summary&gt;
  /// list to json  /// &lt;/summary&gt;
  public static string ListToJson&lt;T&gt;(IList&lt;T&gt; list)
  {
   object obj = list[0];
   return ListToJson&lt;T&gt;(list, ().Name);
  }

  private static string ListToJson&lt;T&gt;(IList&lt;T&gt; list, string JsonName)
  {
   StringBuilder Json = new StringBuilder();
   if ((JsonName))
    JsonName = list[0].GetType().Name;
   ("{\"" + JsonName + "\":[");
   if ( &gt; 0)
   {
    for (int i = 0; i &lt; ; i++)
    {
     T obj = &lt;T&gt;();
     PropertyInfo[] pi = ().GetProperties();
     ("{");
     for (int j = 0; j &lt; ; j++)
     {
      Type type = pi[j].GetValue(list[i], null).GetType();
      ("\"" + pi[j].() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type));
      if (j &lt;  - 1)
      {
       (",");
      }
     }
     ("}");
     if (i &lt;  - 1)
     {
      (",");
     }
    }
   }
   ("]}");
   return ();
  }
  #endregion

  #region object collection converted to json  /// &lt;summary&gt;
  /// Convert object collection to json  /// &lt;/summary&gt;
  /// <param name="array">Object collection</param>  /// <returns>json string</returns>  public static string ToJson(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString += ToJson(item) + ",";
   }
   jsonString = (0,  - 1);
   return jsonString + "]";
  }
  #endregion

  #region Normal collection conversion Json  /// &lt;summary&gt; 
  /// Normal collection conversion Json  /// &lt;/summary&gt; 
  /// <param name="array">collection object</param>  /// <returns>Json string</returns>  public static string ToArrayString(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString = ToJson(()) + ",";
   }
   ( - 1, );
   return jsonString + "]";
  }
  #endregion

  #region DataSet convert to Json  /// &lt;summary&gt; 
  /// Convert DataSet to Json  /// &lt;/summary&gt; 
  /// <param name="dataSet">DataSet object</param>  /// <returns>Json string</returns>  public static string ToJson(DataSet dataSet)
  {
   string jsonString = "{";
   foreach (DataTable table in )
   {
    jsonString += "\"" +  + "\":" + ToJson(table) + ",";
   }
   jsonString = (',');
   return jsonString + "}";
  }
  #endregion

  #region Datatable to Json  /// &lt;summary&gt;  
  /// Convert Datatable to Json  /// &lt;/summary&gt; 
  public static string ToJson(DataTable dt)
  {
   if ( &gt; 0)
   {
    StringBuilder jsonString = new StringBuilder();
    ("[");
    DataRowCollection drc = ;
    for (int i = 0; i &lt; ; i++)
    {
     ("{");
     for (int j = 0; j &lt; ; j++)
     {
      string strKey = [j].ColumnName;
      string strValue = drc[i][j].ToString();

      Type type = [j].DataType;
      ("\"" + strKey + "\":");
      strValue = StringFormat(strValue, type);
      if (j &lt;  - 1)
       (strValue + ",");
      else
       (strValue);
     }
     ("},");
    }
    ( - 1, 1);
    ("]");
    return ();
   }
   else
    return "[]";
  }

  /// &lt;summary&gt; 
  /// Convert DataTable to Json  /// &lt;/summary&gt; 
  public static string ToJson(DataTable dt, string jsonName)
  {
   StringBuilder Json = new StringBuilder();
   if ((jsonName))
    jsonName = ;
   ("{\"" + jsonName + "\":[");
   if ( &gt; 0)
   {
    for (int i = 0; i &lt; ; i++)
    {
     ("{");
     for (int j = 0; j &lt; ; j++)
     {
      Type type = [i][j].GetType();
      ("\"" + [j].() + "\":" + StringFormat([i][j].ToString(), type));
      if (j &lt;  - 1)
       (",");
     }
     ("}");
     if (i &lt;  - 1)
      (",");
    }
   }
   ("]}");
   return ();
  }
  #endregion

  #region DataReader to Json  /// &lt;summary&gt;  
  /// Convert DataReader to Json  /// &lt;/summary&gt;  
  /// <param name="dataReader">DataReader object</param>  /// <returns>Json string</returns>  public static string ToJson(DbDataReader dataReader)
  {
   StringBuilder jsonString = new StringBuilder();
   ("[");
   while (())
   {
    ("{");
    for (int i = 0; i &lt; ; i++)
    {
     Type type = (i);
     string strKey = (i);
     string strValue = dataReader[i].ToString();
     ("\"" + strKey + "\":");
     strValue = StringFormat(strValue, type);
     if (i &lt;  - 1)
      (strValue + ",");
     else
      (strValue);
    }
    ("},");
   }
   ();
   ( - 1, 1);
   ("]");
   return ();
  }
  #endregion


  #region Returns an error  public static string error()
  {
   DataTable dt = new DataTable();
   ("error", typeof(int));
   DataRow dr = ();
   dr["error"] = 1;
   (dr);
   return ToJson(dt);
  }
  #endregion

 }


11.Convert help class
 


 public class ConvertHelper
 {
  public static int DateTimeToUnixInt(DateTime time)
  {
   DateTime time2 = (new DateTime(0x7b2, 1, 1));
   TimeSpan span = (TimeSpan)(time - time2);
   return (int);
  }

  public static decimal MoneyRound(decimal value, int decimals)
  {
   if (value &lt; 0M)
   {
    return ((decimal)(value + (5M / ((decimal)(10.0, (double)(decimals + 1))))), decimals, );
   }
   return (value, decimals, );
  }

  public static double MoneyRound(double value, int decimals)
  {
   if (value &lt; 0.0)
   {
    return ((double)(value + (5.0 / (10.0, (double)(decimals + 1)))), decimals, );
   }
   return (value, decimals, );
  }

  public static decimal MoneyToDecimal(string str)
  {
   try
   {
    str = (",", "");
    return (str);
   }
   catch
   {
    return 0M;
   }
  }

  public static decimal Round(decimal d, int i)
  {
   if (d &gt;= 0M)
   {
    d += 5M * ((decimal)(10.0, (double)-(i + 1)));
   }
   else
   {
    d += -5M * ((decimal)(10.0, (double)-(i + 1)));
   }
   string str = ();
   string[] strArray = (new char[] { '.' });
   int index = ('.');
   string str2 = strArray[0];
   string str3 = strArray[1];
   if ( &gt; i)
   {
    str3 = (index + 1, i);
   }
   d = (str2 + "." + str3);
   return d;
  }

  public static double Round(double d, int i)
  {
   if (d &gt;= 0.0)
   {
    d += 5.0 * (10.0, (double)-(i + 1));
   }
   else
   {
    d += -5.0 * (10.0, (double)-(i + 1));
   }
   string str = ();
   string[] strArray = (new char[] { '.' });
   int index = ('.');
   string str2 = strArray[0];
   string str3 = strArray[1];
   if ( &gt; i)
   {
    str3 = (index + 1, i);
   }
   d = (str2 + "." + str3);
   return d;
  }

  public static bool ToBool(object o)
  {
   return ToBool(o, false);
  }

  public static bool ToBool(object o, bool DefaultValue)
  {
   bool flag;
   if ((ToString(o, true), out flag))
   {
    return flag;
   }
   return DefaultValue;
  }

  public static DateTime ToDateTime(object o)
  {
   return ToDateTime(o, );
  }

  public static DateTime ToDateTime(object o, DateTime DefaultValue)
  {
   DateTime time;
   if ((ToString(o, true), out time))
   {
    return time;
   }
   return DefaultValue;
  }

  public static decimal ToDecimal(object o)
  {
   return ToDecimal(o, 0M);
  }

  public static decimal ToDecimal(object o, decimal DefaultValue)
  {
   decimal num;
   if ((ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }

  public static double ToDouble(object o)
  {
   return ToDouble(o, 0.0);
  }

  public static double ToDouble(object o, double DefaultValue)
  {
   double num;
   if ((ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }

  public static float ToFloat(object o)
  {
   return ToFloat(o, 0f);
  }

  public static float ToFloat(object o, float DefaultValue)
  {
   float num;
   if ((ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }

  public static int ToInt(object o)
  {
   return ToInt(o, 0);
  }

  public static int ToInt(object o, int DefaultValue)
  {
   int num;
   if ((ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }

  public static long ToLong(object o)
  {
   return ToLong(o, 0L);
  }

  public static long ToLong(object o, long DefaultValue)
  {
   long num;
   if ((ToString(o, true), out num))
   {
    return num;
   }
   return DefaultValue;
  }

  public static string ToMoney(object o)
  {
   return ToDecimal(o).ToString("###,###,###,###,###,##0.##");
  }

  public static string ToMoney(string str)
  {
   try
   {
    return (str).ToString("###,###,###,###,###,##0.##");
   }
   catch
   {
    return "0";
   }
  }

  public static string ToString(object o)
  {
   return ToString(o, "", false);
  }

  public static string ToString(object o, bool bTrim)
  {
   return ToString(o, "", bTrim);
  }

  public static string ToString(object o, string DefaultValue)
  {
   return ToString(o, DefaultValue, false);
  }

  public static string ToString(object o, string DefaultValue, bool bTrim)
  {
   if ((o, null) || (o))
   {
    return DefaultValue;
   }
   if (bTrim)
   {
    return ().Trim();
   }
   return ();
  }

  public static DateTime UnixIntToDateTime(string timeStamp)
  {
   DateTime time = (new DateTime(0x7b2, 1, 1));
   long ticks = (timeStamp + "0000000");
   TimeSpan span = new TimeSpan(ticks);
   return (span);
  }
 } 

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.