C # Common Methods _c# Tutorial

Source: Internet
Author: User
Tags commit datetime flush httpcontext pkcs7 pow tojson urlencode

C # commonly used public methods, the specific contents are as follows

1. Background Call Weburl

String hosturl = "http://www.a.com?id=123";
HttpWebRequest Myreq = (HttpWebRequest) webrequest.create (hosturl);
Myreq.method = "Get";

HttpWebResponse Httpwresp = (HttpWebResponse) myreq.getresponse ();
Stream MyStream = Httpwresp.getresponsestream ();
StreamReader sr = new StreamReader (MyStream, Encoding.UTF8);
StringBuilder Strbuilder = new StringBuilder ();
while ( -1!= Sr. Peek ())
{
strbuilder.append (Sr. ReadLine ());
}
Sr. Close ();
Mystream.close ();
Httpwresp.close ();

Newtonsoft.Json.Linq.JObject Jo = (Newtonsoft.Json.Linq.JObject) Newtonsoft.Json.JsonConvert.DeserializeObject ( Strbuilder.tostring ());
String rescode = jo["ReturnCode"]. ToString ();

2. Detect if the input URL is legitimate

<summary>
 ///to determine if the URL can be accessed
 ///</summary>
 ///<param name= "Url" ></param>
 <returns></returns>
 protected bool Chkpageurl (string url)
 {
  bool result = false;
  Try
  {
   HttpWebRequest myhttpwebrequest = (HttpWebRequest) webrequest.create (URL);
   Myhttpwebrequest.useragent = "mozilla/5.0 (Windows NT 6.1; WOW64; trident/7.0; rv:11.0) Like Gecko ";
   Myhttpwebrequest.method = "Get";
   HttpWebResponse myhttpwebresponse = (HttpWebResponse) myhttpwebrequest.getresponse ();
   if (Myhttpwebresponse.statuscode = = Httpstatuscode.ok)
   {result
    = true;
   }
   Myhttpwebresponse.close ();
  }
  Catch
  {result
   = false;
  }

  return result;
 }

3. Bulk Export

 &lt;summary&gt;///Batch Export///&lt;/summary&gt;///&lt;returns&gt;&lt;/returns&gt; public Fileresult exportst U () {///Create object Npoi for Excel file. HSSF. Usermodel.hssfworkbook book = new Npoi. HSSF.
   Usermodel.hssfworkbook (); Add a sheet Npoi. Ss. Usermodel.isheet Sheet1 = Book.
   Createsheet ("Sheet1");
   int pager_totalcount = (int) session["Pager_totalcount"];
   int totalcount = 0; Gets the List data list&lt;articleentity&gt; infolist = new Achievedal.mytestdal ().

   Getarticlelist ("", Pager_totalcount, 1, out totalcount); Add the first row header Npoi to Sheet1. Ss. Usermodel.irow Row1 = Sheet1.
   CreateRow (0); Create Time name Merchant Order number | Transaction number The offset amount (yuan) status Row1. Createcell (0).
   Setcellvalue ("number"); Row1. Createcell (1).
   Setcellvalue ("title"); Row1. Createcell (2).
   Setcellvalue ("content");
   int Width = 256; Sheet1.
   Setcolumnwidth (0, * Width); Sheet1.
   Setcolumnwidth (1, * Width); Sheet1.
   Setcolumnwidth (2, * Width); if (infolist!= null) {var list = infolist.orderbydescending (P =&gt; p.id);
     if (list!= null) {int i = 0;
      Progressively writes data to Sheet1 each line foreach (var item in list) {i = i + 1; Npoi. Ss. Usermodel.irow rowtemp = Sheet1.
      CreateRow (i); Rowtemp. Createcell (0). Setcellvalue (item.id.
      ToString ()); Rowtemp. Createcell (1). Setcellvalue (item. Title = null? ": Item."
      Title.tostring ()); Rowtemp. Createcell (2). Setcellvalue (item. Content = null? ": Item."
     Content.tostring ());
   }}//write to client System.IO.MemoryStream ms = new System.IO.MemoryStream (); Book.
   Write (MS); Ms.
   Seek (0, System.IO.SeekOrigin.Begin); Return File (MS, "Application/vnd.ms-excel", Httputility.urlencode ("Export", Encoding.UTF8).

  ToString () + DateTime.Now.ToString ("YYYYMMDDHHMMSS") + ". xls");

 }

4. Bulk Import

<input name= "File" type= "file" id= "file"/>
<input type= "Submit" Name= "Upload" value= "Upload"/>

&lt;summary&gt;///Batch Import///&lt;/summary&gt;///&lt;returns&gt;&lt;/returns&gt; [httppost] public Actionr
   Esult Importstu () {httppostedfilebase file = request.files["file"];
   String FileName;
   String Savepath; if (file = = NULL | | file. ContentLength &lt;= 0) {return Content (' &lt;script&gt;alert (' upload failed, please choose to upload file! ')
   location.href= '/mytest/mvcpager ';&lt;/script&gt; "); else {string filename = path.getfilename (file.
    FileName); int filesize = file. contentlength;//gets the size of the uploaded file in bytes byte byte string Fileex = System.IO.Path.GetExtension (filename);//Get upload file extension string nofil ename = System.IO.Path.GetFileNameWithoutExtension (filename),//Get filename with no extension string FileType = ". Xls,.xlsx";/ Defines the type string for the upload file if (filetype.contains (". exe"))//excel {return Content (' &lt;script&gt;alert (' file type is malformed, import exe not allowed Format of the file! ');
    location.href= '/mytest/mvcpager ';&lt;/script&gt; ");
  FileName = Nofilename + DateTime.Now.ToString ("Yyyymmddhhmmss") + Fileex;  String path = AppDomain.CurrentDomain.BaseDirectory + "uploads/";
    Savepath = Path.Combine (Path, FileName); File.

    SaveAs (Savepath); if (Filetype.contains (Fileex))//excel {string strconn = "Provider=Microsoft.Jet.OLEDB.4.0;Data source=" + savePa
     th + ";" + "Extended properties=excel 8.0";
     OleDbConnection conn = new OleDbConnection (strconn); Conn.
     Open ();
     OleDbDataAdapter mycommand = new OleDbDataAdapter ("SELECT * from [sheet1$]", strconn);
     DataSet myDataSet = new DataSet ();
     try {Mycommand.fill (myDataSet, "excelinfo"); The catch (Exception ex) {return Content (' &lt;script&gt;alert (' upload failed, ' + ex. Message + "!");
     location.href= '/mytest/mvcpager ';&lt;/script&gt; "); }//Column order header content DataTable table = mydataset.tables["Excelinfo"].

     Defaultview.totable (); Object exception rollback using (TransactionScope transaction = new TransactionScope ()) {for (int i = 0; i &lt; table. Rows.Count;
       i++) {Articleentity model = new articleentity (); Model. Title = table. Rows[i][0].
       ToString (); Model. Content = table. ROWS[I][1].
       ToString (); New Achievedal.mytestdal ().
      Addarticle (model);
     } transaction.complete ();
   } return Redirecttoaction ("Mvcpager", "MyTest");

 }
  }

5. Get the IP address of the client

&lt;summary&gt;///Obtain the IP address of the client///&lt;/summary&gt;///&lt;returns&gt; Client IP address &lt;/returns&gt; public static String Get_clientip () {string result = string.
   Empty; result = httpcontext.current.request.headers["X-real-ip"];

   Nginx the method of obtaining an IP address for the front end if (result!= null) return result; if (httpcontext.current.request.servervariables["REMOTE_ADDR"]!= null)//The IP address of the remote host that issued the request {result = Httpcontext.curr Ent. request.servervariables["REMOTE_ADDR"].
   ToString (); else if (httpcontext.current.request.servervariables["Http_via"]!= null)//To determine whether the proxy is set, if the proxy {if (httpcontext.c Urrent. request.servervariables["http_x_forwarded_for"]!= null)//Get proxy server's IP {result = HttpContext.Current.Request.Serve rvariables["Http_x_forwarded_for"].
    ToString ();
    else {result = HttpContext.Current.Request.UserHostAddress;
   } else {result = HttpContext.Current.Request.UserHostAddress; The IF (result = =:: 1) result = string.Empty;
  return result;

 }

6.AES Symmetric encryption

 &lt;summary&gt;///symmetric encryption class///&lt;/summary&gt; public class AES {///&lt;summary&gt;///decryption///&lt;/summ ary&gt;///&lt;param name= "Strdecrypt" &gt;&lt;/param&gt;///&lt;param name= "strkey" &gt;&lt;/param&gt;///&lt;retu rns&gt;&lt;/returns&gt; public static string Decrypt (String strdecrypt, String strkey) {try {byte[] bytes
    = Encoding.UTF8.GetBytes (FormsAuthentication.HashPasswordForStoringInConfigFile (strkey, "MD5"));
    byte[] InputBuffer = convert.frombase64string (Strdecrypt);
    byte[] Buffer3 = null; using (rijndaelmanaged managed = new RijndaelManaged ()) {managed.
     Key = bytes; Managed.
     Mode = CIPHERMODE.ECB; Managed.
     Padding = PADDINGMODE.PKCS7; Buffer3 = managed. CreateDecryptor ().
    TransformFinalBlock (inputbuffer, 0, inputbuffer.length);
   Return Encoding.UTF8.GetString (BUFFER3);
   catch {return null; }///&lt;summary&gt;///decryption///&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 STA
   Tic String Decrypt (String todecrypt, String key, String iv) {byte[] bytes = Encoding.UTF8.GetBytes (key);
   byte[] Buffer2 = Encoding.UTF8.GetBytes (iv);
   byte[] InputBuffer = convert.frombase64string (Todecrypt); RijndaelManaged managed = new RijndaelManaged {Key = bytes, IV = buffer2, Mode = CIPHERMODE.CBC, Paddi
   ng = Paddingmode.zeros}; byte[] Buffer4 = managed. CreateDecryptor ().
   TransformFinalBlock (inputbuffer, 0, inputbuffer.length);
  Return Encoding.UTF8.GetString (BUFFER4);
   public static string Decryptstr (String encryptstring) {string str = ""; if (!string.
    IsNullOrEmpty (encryptstring)) {string ssource = Decrypt (encryptstring, "Cn.solefu");
    if (Utility.left (ssource, 3) = = "Gk_") {str = ssource.substring (3);
  } return str; public static string DECRYPTSTRBYCBC (String encryptstring) {String str = ""; if (!string.
    IsNullOrEmpty (encryptstring)) {string ssource = Decrypt (encryptstring, "Cn.solefu", "Cn.solefu");
    if (Utility.left (ssource, 3) = = "Gk_") {str = ssource.substring (3);
  } return str; }///&lt;summary&gt;///encryption///&lt;/summary&gt;///&lt;param name= "Strencrypt" &gt;&lt;/param&gt;///&lt;par  Am Name= "strkey" &gt;&lt;/param&gt;///&lt;returns&gt;&lt;/returns&gt; public static string Encrypt (String strencrypt, String strkey) {try {byte[] bytes = Encoding.UTF8.GetBytes (formsauthentication.hashpasswordforstoringinconf
    Igfile (strkey, "MD5"));
    byte[] InputBuffer = Encoding.UTF8.GetBytes (Strencrypt);
    byte[] InArray = null; using (rijndaelmanaged managed = new RijndaelManaged ()) {managed.
     Key = bytes; Managed.
     Mode = CIPHERMODE.ECB; Managed.
     Padding = PADDINGMODE.PKCS7; InArray = managed. CreateEncryptor (). TransformFinalBlock (inputbuffer, 0, InputbuffeR.length);
   Return convert.tobase64string (InArray, 0, inarray.length);
   catch {return null; }///&lt;summary&gt;///encryption///&lt;/summary&gt;///&lt;param name= "Strencrypt" &gt;&lt;/param&gt;/// ;p Aram Name= "strkey" &gt;&lt;/param&gt;///&lt;returns&gt;&lt;/returns&gt; public static string Encrypt (String toencry
   PT, string key, String iv) {byte[] bytes = Encoding.UTF8.GetBytes (key);
   byte[] Buffer2 = Encoding.UTF8.GetBytes (iv);
   byte[] InputBuffer = Encoding.UTF8.GetBytes (Toencrypt); RijndaelManaged managed = new RijndaelManaged {Key = bytes, IV = buffer2, Mode = CIPHERMODE.CBC, Paddi
   ng = Paddingmode.zeros}; byte[] InArray = managed. CreateEncryptor ().
   TransformFinalBlock (inputbuffer, 0, inputbuffer.length);
  Return convert.tobase64string (InArray, 0, inarray.length);
  public static string Encryptstr (String sourcestring) {return Encrypt ("Gk_" + sourcestring, "Cn.solefu"); } public STatic string Encryptstr (string sourcestring, bool Useinurl) {return Httputility.urlencode (ENCRYPTSTR));  public static string ENCRYPTSTRBYCBC (String sourcestring) {return Encrypt ("Gk_" + sourcestring, "Cn.solefu",
  "Cn.solefu"); public static string ENCRYPTSTRBYCBC (string sourcestring, bool Useinurl) {return Httputility.urlencode (encrypts
  TRBYCBC (sourcestring));

 }
 }

7.Cookies Help Class

public class Cookieshelper {public static void Addcookie (String cookiename, DateTime expires) {HttpCookie Cooki
   E = 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 = HttpContext.Current.Res
   Ponse; if (response!= null) {cookie.
    HttpOnly = true; Cookie.
    Path = "/"; if (!string. IsNullOrEmpty (Domain)) {cookie.
    domain = domain; } response.
   AppendCookie (cookie); } public static void Addcookie (String cookiename, DateTime expires, string Domain) {HttpCookie cookie = new H
   Ttpcookie (cookiename) {Expires = Expires};
  Addcookie (Cookie, Domain); public static void Addcookie (string key, String value, DateTime expires) {HttpCookie cookie = new HttpCookie (ke
 Y, value)  {Expires = Expires};
  Addcookie (cookie, NULL); public static void Addcookie (String cookiename, String key, String value) {HttpCookie cookie = new HttpCookie (c
   Ookiename); Cookie.
   Values.add (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}; Cookie.
   Values.add (key, value);
  Addcookie (cookie, NULL); } public static void Addcookie (sTring CookieName, String key, String value, String Domain) {HttpCookie cookie = new HttpCookie (cookiename); Cookie.
   Values.add (key, value);
  Addcookie (Cookie, Domain); public static void Addcookie (String cookiename, String key, String value, DateTime expires, string Domain) {Htt
   Pcookie cookie = new HttpCookie (cookiename) {Expires = Expires}; Cookie.
   Values.add (key, value);
  Addcookie (Cookie, Domain); public static void Adddomaincookie (string key, String value, String Domain) {Addcookie (new HttpCookie key, Valu
  e), Domain);
   public static HttpCookie GetCookie (String cookiename) {HttpRequest request = HttpContext.Current.Request; if (request!= null) {if (request). Cookies[cookiename]!= null) {return request.
    Cookies[cookiename]; } if (Request. Cookies["," + CookieName]!= null) {return request.
    Cookies["," + cookiename];
  } return null; } public static string GetcookievaluE (String cookiename) {return getcookievalue (cookiename, NULL); public static string Getcookievalue (string cookiename, String key) {HttpRequest request = HTTPCONTEXT.CURRENT.R
   Equest;
   if (request = = null) {return ""; } if (Request. Cookies[cookiename]!= null) {if (!string). IsNullOrEmpty (key) &amp;&amp; request. Cookies[cookiename]. HasKeys) {return request. Cookies[cookiename].
    Values[key]; Return request. Cookies[cookiename].
   Value;
   String str = "," + cookiename; if (request).
   COOKIES[STR] = = null) {return ""; } if (!string. IsNullOrEmpty (key) &amp;&amp; request. COOKIES[STR]. HasKeys) {return request. COOKIES[STR].
   Values[key]; Return request. COOKIES[STR].
  Value;
   public static string Getcookievalue (HttpCookie cookie, string key) {if (cookie = = null) {return "]; } if (!string. IsNullOrEmpty (key) &amp;&amp; cookies. HasKeys) {return cookie.
   Values[key]; } return Cookie.
  Value;
  public static void Removecookie (String cookiename) {Removecookie (cookiename, NULL); public static void Removecookie (String cookiename, String key) {HttpResponse response = HttpContext.Current.Res
   Ponse; if (response!= null) {HttpCookie cookie = response.
    Cookies[cookiename]; if (cookie!= null) {if (!string). IsNullOrEmpty (key) &amp;&amp; cookies. HasKeys) {cookie.
     Values.remove (key); else {response.
     Cookies.remove (CookieName); }}} public static void Setcookie (String cookiename, DateTime expires) {Setcookie (cookiename, NULL, n ull, 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, n ull, 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, Nu
  ll, 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, nul L, 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) {Ht
   Tpresponse response = HttpContext.Current.Response; if (response!= null) {
    HttpCookie cookie = response.
    Cookies[cookiename]; if (cookie!= null) {cookie.
     Path = "/"; if (!string. IsNullOrEmpty (Domain)) {cookie.
     domain = domain; } if (!string. IsNullOrEmpty (key) &amp;&amp; cookies. HasKeys) {cookie.
     Values.set (key, value); else if (!string. IsNullOrEmpty (value)) {cookie.
     Value = value; } if (expires. HasValue) {cookie. Expires = Expires.
     Value; } response.
    Setcookie (cookie); {}}}///&lt;summary&gt;///set domain cookie///&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 Setdomainc
  Ookie (string key, String value, String Domain) {Setcookie (key, NULL, value, NULL, domain);

 }
 }

8.DataTable Convert to entity class

 &lt;summary&gt;///#region DataTable into 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;///populate object list: Populate entity classes with the first table of the dataset///&lt;/sum mary&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 | | ds. TABLES[0] = = NULL | | Ds. Tables[0].
   Rows.Count = = 0) {return null; else {return Fillmodel (DS).
   Tables[0]); ///&lt;summary&gt;///populating objects list: Populating entity classes with the index table of the dataset///&lt;/summary&gt; public static list&lt;t&gt; Fi Llmodel (DataSet ds, int index) {if (ds = null | | ds. Tables.count &lt;= Index | | Ds. Tables[index].
   Rows.Count = = 0) {return null; else {return Fillmodel (DS).
   Tables[index]); ///&lt;summary&gt;///populating objects list: Populating entity classes with DataTable///&lt;/summary&gt; public static list&lt;t&gt; Fillmodel(DataTable DT) {if (dt = NULL | | | dt.
   Rows.Count = = 0) {return null;
   } list&lt;t&gt; modellist = new list&lt;t&gt; (); foreach (DataRow dr in Dt. 
    Rows) {//t model = (t) activator.createinstance (typeof (T));
    T model = new T (); for (int i = 0; i &lt; Dr. Table.Columns.Count; i++) {list&lt;propertyinfo&gt; Propertyinfos = model. GetType (). GetProperties ().

     ToList (); PropertyInfo item = Propertyinfos.firstordefault (P =&gt; string.compare (p.name, Dr. Table.columns[i].
     ColumnName, true) = = 0); if (item!= null &amp;&amp; dr[i]!= dbnull.value) try {item.
      SetValue (model, dr[i], NULL);
   The catch {}} modellist.add (model);
  return modellist;
   ///&lt;summary&gt;///padding objects: Populating entity classes with DataRow///&lt;/summary&gt; public static T Fillmodel (DataRow dr) {
   if (dr = = null) {return default (T); 
   //t model = (t) activator.createinstance (typeof (T)); T model = new T ();

   for (int i = 0; i &lt; Dr. Table.Columns.Count; i++) {list&lt;propertyinfo&gt; Propertyinfos = model. GetType (). GetProperties ().

    ToList (); PropertyInfo item = Propertyinfos.firstordefault (P =&gt; string.compare (p.name, Dr. Table.columns[i].
    ColumnName, true) = = 0); if (item!= null &amp;&amp; dr[i]!= dbnull.value) try {item.
     SetValue (model, dr[i], NULL);
  ' Catch {} ' return model; ///&lt;summary&gt;///entity class converted to DataSet///&lt;/summary&gt;///&lt;param name= "modellist" &gt; Entity classes list &LT;/PARAM&G
  T &lt;returns&gt;&lt;/returns&gt; public static DataSet FillDataSet (list&lt;t&gt; modellist) {if (modellist = = N ull | |
   Modellist.count = = 0) {return null;
    else {DataSet ds = new DataSet (); Ds.
    Tables.add (Filldatatable (modellist));
   return DS; }///&lt;summary&gt;///entity classes to DataTable///&lt;/summary&gt;///&lt;param name= "modellist" &gt; Entity classes list &lt;/pa Ram&gt;///&lt;returns&gt;&lt;/returns&gt; public static DataTable filldatatable (list&lt;t&gt; modellist) {if (modellist = null ||
   Modellist.count = = 0) {return null;

   } DataTable dt = Createdata (modellist[0]); foreach (T model in modellist) {DataRow DataRow = dt.
    NewRow (); foreach (PropertyInfo PropertyInfo in typeof (T).
    GetProperties ()) {Datarow[propertyinfo.name] = Propertyinfo.getvalue (model, NULL); } dt.
   Rows.Add (DataRow);
  } return DT; ///&lt;summary&gt;///The table structure based on entity classes///&lt;/summary&gt;///&lt;param name= "Model" &gt; Entity class &lt;/param&gt;///& lt;returns&gt;&lt;/returns&gt; private static DataTable Createdata (T model) {datatable datatable = new DataTable (t Ypeof (T).
   Name); foreach (PropertyInfo PropertyInfo in typeof (T).
   GetProperties ()) {DataTable.Columns.Add (new DataColumn (Propertyinfo.name, Propertyinfo.propertytype));
  return dataTable; ///&lt;summary&gt;///The DataTable to list and dictionaryNested collection Save///&lt;/summary&gt;///&lt;param name= "DT" &gt;&lt;/param&gt;///&lt;returns&gt;&lt;/returns&gt; public s Tatic list&lt;dictionary&lt;string, string&gt;&gt; tolistdictionary (DataTable dt) {list&lt;dictionary&lt;string, str
   ing&gt;&gt; list = null; if (dt!= null &amp;&amp; dt.
    Rows.Count &gt; 0) {list = new list&lt;dictionary&lt;string, string&gt;&gt; ();
    dictionary&lt;string, string&gt; dic = null; foreach (DataRow dr in Dt.
     Rows) {dic = new dictionary&lt;string, string&gt; (); foreach (DataColumn dc in dt. Columns) {dic. ADD (DC. ColumnName, DR[DC. ColumnName].
     ToString ()); } list.
    ADD (DIC);
  } return list; ///&lt;summary&gt;///requested request content converted to model///Cza///2016-5-30 19:06:21///&lt;/summary&gt;///&lt;p Aram name= ' context ' &gt;&lt;/param&gt;///&lt;returns&gt;&lt;/returns&gt; public static T Converttomodel (HttpContext c
   Ontext) {T t = new t (); propertyinfo[] Propertys =T.gettype ().
   GetProperties (); foreach (PropertyInfo pi in propertys) {if!pi.
    CanWrite) continue; Object value = Context. Request[pi.
    Name]; if (value!= null &amp;&amp; value!= dbnull.value) {try {if (value). ToString ()!= "") Pi. SetValue (t, Convert.changetype (value, pi.) PropertyType), null);//This step is important for type conversion else pi.
     SetValue (t, value, NULL);
  The catch {}} return t;

 }


 }

9.SQL Server database access classes

 &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 = configurationmanager.connectionstrings["Conn".

  ConnectionString; Empty construct public SqlHelper () {}//hashtable to store cached parameters private static Hashtable = Parmcache.

  Synchronized (New Hashtable ()); &lt;summary&gt;///Implementation, change "common"///&lt;/summary&gt; public static int ExecuteNonQuery (string connectionString, Co
   Mmandtype CommandType, String commandtext, params sqlparameter[] paras) {SqlCommand cmd = new SqlCommand (); using (SqlConnection conn = new SqlConnection (connectionString)) {PrepareCommand (CMD, conn, null, CommandType, com
    Mandtext, paras); int val = cmd.
    ExecuteNonQuery (); Cmd.   Parameters.clear ();
   Empty parameter return val; }///&lt;summary&gt;///perform additions and deletions (to existing database connections) "Infrequently"///&lt;/summary&gt; public static int ExecuteNonQuery (Sqlcon Nection ConnectioN, CommandType commandtype, string commandtext, params sqlparameter[] paras) {SqlCommand cmd = new SqlCommand ();
   PrepareCommand (cmd, connection, NULL, CommandType, CommandText, paras); int val = cmd.
   ExecuteNonQuery (); Cmd.
   Parameters.clear ();
  return Val; ///&lt;summary&gt;///Execute multiple SQL statements (List generic collection) "Transaction" (no parameters)///&lt;/summary&gt;///&lt;param name= "ConnectionString" &gt; Database connection string &lt;/param&gt;///&lt;param name= "listsql" &gt; Generic set containing multiple SQL statements &lt;/param&gt;///&lt;returns&gt; affected rows &lt;/returns&gt; public static int ExecuteNonQuery (string connectionString, list&lt;string&gt; listsql) {Sqlcomman
   d cmd = new SqlCommand ();
   SqlConnection conn = new SqlConnection (connectionString); Conn.
   Open (); SqlTransaction trans = conn.
   BeginTransaction ();
   PrepareCommand (CMD, conn, trans, commandtype.text, NULL, NULL);
    try {int count = 0;
     for (int n = 0; n &lt; listsql.count; n++) {string strSQL = Listsql[n]; if (Strsql.trim (). LengtH &gt; 1) {cmd.commandtext = strSQL; Count = cmd.
     ExecuteNonQuery ();
    } trans.commit (); Cmd.
    Parameters.clear ();
   return count; catch {trans.
    Rollback (); Cmd.
    Parameters.clear ();
   return 0; finally {Conn.
   Close (); }///&lt;summary&gt;///executes multiple SQL statements (Hashtable) "Transactions" (with a set of parameters, one parameter is encapsulated into a group)///&lt;/summary&gt;///&lt;param name=
  "ConnectionString" &gt; Database connection string &lt;/param&gt;///&lt;param name= "sqlstringlist" &gt;hashtable table, key-value pair form &lt;/param&gt; public static void ExecuteNonQuery (String connectionString, Hashtable sqlstringlist) {using (SqlConnection conn = NE W SqlConnection (ConnectionString)) {Conn.
    Open (); using (sqltransaction trans = conn.
     BeginTransaction ()) {SqlCommand cmd = new SqlCommand (); try {foreach (DictionaryEntry item in sqlstringlist) {string cmdtext = Item. Key.tostring (); SQL statement to execute sqlparameter[] Cmdparas = (sqlparameter[]) ITem. Value;
       SQL statements correspond to the parameters PrepareCommand (CMD, conn, trans, CommandType.Text, Cmdtext, Cmdparas); int val = cmd.
       ExecuteNonQuery (); Cmd.
      Parameters.clear ();
     if (Sqlstringlist.count &gt; 0) trans.commit (); catch {trans.
      Rollback ();
     Throw ///&lt;summary&gt;///returns DataReader object///&lt;/summary&gt; public static SqlDataReader Execute Reader (String connectionString, CommandType commandtype, String cmdtext, params sqlparameter[] paras) {SqlCommand cm
   D = new SqlCommand ();
   SqlConnection conn = new SqlConnection (connectionString);
    try {preparecommand (CMD, conn, null, CommandType, Cmdtext, paras); SqlDataReader reader = cmd.
    ExecuteReader (commandbehavior.closeconnection); Cmd.
    Parameters.clear ();
   return reader; catch {Conn.
    Close ();
   Throw }///&lt;summary&gt;///returns the first column of information in the first row (possibly a string so the return type is Object) "common"///&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, comm
    Andtype, CommandText, paras); Object val = cmd.
    ExecuteScalar (); Cmd.
    Parameters.clear ();
   return Val; }///&lt;summary&gt;///returns the first column of information in the first row (for an existing database connection) "Not common"///&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 = cmd.
   ExecuteScalar (); Cmd.
   Parameters.clear ();
  return Val; ///&lt;summary&gt;///return DataTable///&lt;/summary&gt; public static DataTable getdatatable (String connection String, CommandType commandtype, string CommandText, params sqlparameter[] paras) {SqlCommand cmd = new SqlCommand (); using (SqlConnection conn = new SqlConnection (connectionString)) {PrepareCommand (CMD, conn, null, CommandType, com
    Mandtext, paras);
     using (SqlDataAdapter da = new SqlDataAdapter (cmd)) {DataTable dt = new DataTable (); Da.
     Fill (DT);
    return DT; }}///&lt;summary&gt;///return DataSet///&lt;/summary&gt; public static DataSet GetDataSet (string connect Ionstring, CommandType commandtype, string commandtext, params sqlparameter[] paras) {SqlCommand cmd = new Sqlcomman
   D (); using (SqlConnection conn = new SqlConnection (connectionString)) {PrepareCommand (CMD, conn, null, CommandType, com
    Mandtext, paras);
     using (SqlDataAdapter da = new SqlDataAdapter (cmd)) {DataSet ds = new DataSet (); Da.
     Fill (DS);
    return DS; }}///&lt;summary&gt;///add parameter array to cache///&lt;/summary&gt;///&lt;param name= "Cach EKey ' &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) {PARMCA
  Che[cachekey] = commandparameters; ///&lt;summary&gt;///Retrieve Cached parameters///&lt;/summary&gt;///&lt;param name= "CacheKey" &gt;key US Ed to lookup parameters&lt;/param&gt;///&lt;returns&gt;cached sqlparamters array&lt;/returns&gt; public static SqlPa

   Rameter[] Getcachedparameters (string cachekey) {sqlparameter[] cachedparms = (sqlparameter[]) Parmcache[cachekey];

   if (cachedparms = null) return null;

   sqlparameter[] clonedparms = new Sqlparameter[cachedparms.length]; for (int i = 0, j = cachedparms.length I &lt; J; i++) clonedparms[i] = (SqlParameter) ((icloneable) cachedparms[i]).

   Clone ();
  return clonedparms; ///&lt;summary&gt;///prepares a pending SqlCommand///&lt;/summary&gt; PrivaTe static void PrepareCommand (SqlCommand cmd, SqlConnection Conn, SqlTransaction Trans, CommandType CommandType, String Co Mmandtext, params sqlparameter[] paras) {try {if (conn. State!= ConnectionState.Open) {conn.
     Close (); Conn.
    Open (); } cmd.
    Connection = conn;
    if (CommandText!= null) Cmd.commandtext = CommandText;  Cmd.commandtype = CommandType; This sets whether to execute a T-SQL statement or a stored procedure if (trans!= null) cmd.

    Transaction = trans; if (paras!= NULL &amp;&amp; paras. Length &gt; 0) {//cmd.
     Parameters.addrange (paras); for (int i = 0; I &lt; paras. Length; i++) {if (Paras[i]. Value = NULL | | Paras[i]. value.tostring () = = "") Paras[i]. Value = DBNull.Value; Insert or modify, if there is an empty string of parameters, then insert the database cmd in null form.
     Parameters.Add (Paras[i]); Exception ex) {throw new Exception (ex.
   message); }///&lt;summary&gt;///Common paging stored procedures, conditional queries, sorted fields, sorted by sort fields in descending order///&lt;/summary&gt;///&lt;paRam Name= "PageSize" &gt; per-page records &lt;/param&gt;///&lt;param name= "Currentcount" &gt; Current record Quantity (page number * per page record) &lt;/param&gt;///& Lt;param name= "tablename" &gt; table name &lt;/param&gt;///&lt;param name= "Where" &gt; Query conditions, Example: "id&gt;1000 and name like '% lilinfeng% ' "sort condition, directly followed by, example:" Order by ID desc,name ASC "&lt;/param&gt;///&lt;param name=" TotalCount "&gt; Total Records &lt;/param &gt;///&lt;returns&gt;&lt;/returns&gt; public static DataSet getlist (string connectionString, string, int Page Size, int currentcount, string tablename, String Where, out int totalcount) {sqlparameter[] parmlist = {NE W SqlParameter ("@PageSize", PageSize), New SqlParameter ("@CurrentCount", Currentcount), New SqlParameter ("@TableNa Me, TableName), New SqlParameter ("@Where", where), new SqlParameter ("@Order", order), New SqlParameter ("@Tota
   Lcount ", sqldbtype.int,4)}; PARMLIST[5].
   Direction = ParameterDirection.Output; DataSet ds = GetDataSet (connectionString, Commandtype.storedprocedurE, "Sp_mvcpager", parmlist); TotalCount = Convert.ToInt32 (parmlist[5].
   Value);
  return DS;

 }
 }

10. log file record

 public class Writelog {///&lt;summary&gt;//////&lt;/summary&gt;///&lt;param name= "filename" &gt; FileName &lt;/
  param&gt;///&lt;param name= "Ex" &gt;&lt;/param&gt; public static void Writeerorrlog (String fileName, Exception ex) {if (ex = = null) return;//EX = null returns DateTime dt = DateTime.Now;//set log times string time = dt. ToString ("Yyyy-mm-dd HH:mm:ss"); Year-month-day: minutes: sec string logName = dt. ToString ("Yyyy-mm-dd"); Log name string LogPath = Path.Combine (System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine ("Log", FileName)); Log store path string log = Path.Combine (LogPath, String. Format ("{0}.log", logName));
    Path + Name try {FileInfo info = new FileInfo (log); if (info. Directory!= null &amp;&amp;!info. directory.exists) {info.
    Directory.create (); using (StreamWriter write = new StreamWriter (log, True, Encoding.GetEncoding ("Utf-8")) {write.
     WriteLine (time); Write. WriteLine (ex.
     message); Write. WriteLine ("Exception information: "+ ex"; Write. WriteLine ("Exception stack:" + ex.)
     StackTrace); Write. WriteLine ("Exception brief:" + ex.)
     message); Write.
     WriteLine ("\ r \ n----------------------------------\ r \ n"); Write.
     Flush (); Write.
     Close (); Write.
    Dispose (); } catch {}}///&lt;summary&gt;//////&lt;/summary&gt;///&lt;param name= ' filename ' &gt; filename &lt;/pa ram&gt;///&lt;param name= ' message ' &gt;&lt;/param&gt; public static void Writemessage (string fileName, String message {//ex = null returns DateTime dt = DateTime.Now;//Set log time string = dt. ToString ("Yyyy-mm-dd HH:mm:ss"); Year-month-day: minutes: sec string logName = dt. ToString ("Yyyy-mm-dd"); Log name string LogPath = Path.Combine (System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine ("Log", FileName)); Log store path string log = Path.Combine (LogPath, String. Format ("{0}.log", logName));
    Path + Name try {FileInfo info = new FileInfo (log); if (info. Directory!= null &amp;&amp;!info. Directory.Exists) {
     Info.
    Directory.create (); using (StreamWriter write = new StreamWriter (log, True, Encoding.GetEncoding ("Utf-8")) {write.
     WriteLine (time); Write.
     WriteLine ("INFO:" + message); Write.
     WriteLine ("\ r \ n----------------------------------\ r \ n"); Write.
     Flush (); Write.
     Close (); Write.
    Dispose (); } catch {}} public static void Writeerorrlog (Exception Ex, string message) {if (ex = null) return; ex = NULL returns DATETIME dt = DateTime.Now; Set log Time string = dt. ToString ("Yyyy-mm-dd HH:mm:ss"); Year-month-day: minutes: sec string logName = dt. ToString ("Yyyy-mm-dd"); Log name string logPath = System.AppDomain.CurrentDomain.BaseDirectory; Log store path string log = Path.Combine (Path.Combine (LogPath, "Log"), String. Format ("{0}.log", logName));
    Path + Name try {FileInfo info = new FileInfo (log); if (info. Directory!= null &amp;&amp;!info. directory.exists) {info.
    Directory.create (); The Using (StreamwritEr write = new StreamWriter (log, True, Encoding.GetEncoding ("Utf-8")) {write.
     WriteLine (time); Write. WriteLine (ex.
     message); Write.
     WriteLine ("Exception information:" + ex); Write. WriteLine ("Exception stack:" + ex.)
     StackTrace); Write.
     WriteLine ("Exception Brief:" + message); Write.
     WriteLine ("\ r \ n----------------------------------\ r \ n"); Write.
     Flush (); Write.
     Close (); Write.
    Dispose (); } catch {}} public static void Writemessage (String message) {//ex = null returns DateTime dt = Datetim E.now; Set log Time string = dt. ToString ("Yyyy-mm-dd HH:mm:ss"); Year-month-day: minutes: sec string logName = dt. ToString ("Yyyy-mm-dd"); Log name string logPath = System.AppDomain.CurrentDomain.BaseDirectory; Log store path string log = Path.Combine (Path.Combine (LogPath, "Log"), String. Format ("{0}.log", logName));
    Path + Name try {FileInfo info = new FileInfo (log); if (info. Directory!= null &amp;&amp;!info. directory.exists) {info.
    Directory.create ();
}    using (StreamWriter write = new StreamWriter (log, True, Encoding.GetEncoding ("Utf-8")) {write.
     WriteLine (time); Write.
     WriteLine ("INFO:" + message); Write.
     WriteLine ("\ r \ n----------------------------------\ r \ n"); Write.
     Flush (); Write.
     Close (); Write.
    Dispose ();

 } \ Catch {}}}

11.JSON Help Class

 &lt;summary&gt;///JSON help class///&lt;/summary&gt; public class Jsonhelper {#region common methods///&lt;summary&gt; Formatted character type, date type, Boolean///&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 = str.
   ToLower ();
   else if (type = = typeof (Guid)) {str = "\" + str + "\"; else if (type!= typeof (String) &amp;&amp; string.
   IsNullOrEmpty (str)) {str = "\" + str + "\";
  return str; ///&lt;summary&gt;///Filter string///&lt;/summary&gt; public static string Stringfilter (String str) {STRINGB
   Uilder sb = new StringBuilder (); for (int i = 0; i &lt; str. Length; i++) {char c = str.
    ToCharArray () [i]; Switch (c) {case ' \ ': SB. Append ("\\\"");
     Break Case ' \ ': SB. Append ("\\\\");
     Break Case '/': SB. Append ("\\/");
     Break Case ' \b ': sb. Append ("\\b");
     Break Case ' \f ': sb. Append ("\\f");
     Break Case ' \ n ': sb. Append ("\\n");
     Break Case ' \ R ': SB. Append ("\ r");
     Break Case ' t ': sb. Append ("\\t");
     Break DEFAULT:SB. Append (c);
    Break } return SB.
  ToString (); #endregion #region///JSON &lt;summary&gt;///column to JSON///&lt;/summary&gt;///&lt;param name= "dt" &gt; table &
   lt;/param&gt;///&lt;param name= "R" &gt; Columns &lt;/param&gt; public static string Columntojson (DataTable dt, int r) {
   StringBuilder strSQL = new StringBuilder (); for (int i = 0; i &lt; dt. Rows.Count; i++) {strsql.append (dt.
    Rows[i][r]);
   Strsql.append (","); Return strsql.tostring ().
  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 (); Sb.
   Append ("{"); propertyinfo[] PropertyInfo = Jsonobject.gettype ().
   GetProperties (); for (int i = 0; i &lt; propertyinfo.length i++) {Object objectvalue = Propertyinfo[i]. Getgetmethod ().
    Invoke (jsonobject, NULL); Type type = Propertyinfo[i].
    PropertyType;
    string strvalue = Objectvalue.tostring ();
    strvalue = StringFormat (strvalue, type); Sb. Append ("\" "+ propertyinfo[i]."
    Name + "\": "); Sb.
   Append (strvalue + ","); } sb. Remove (sb.)
   Length-1, 1); Sb.
   Append ("}"); Return SB.
  ToString (); #endregion #region list to JSON///&lt;summary&gt;///list goto JSON///&lt;/summary&gt; public static string Li
   Sttojson&lt;t&gt; (ilist&lt;t&gt; list) {Object obj = list[0]; return listtojson&lt;t&gt; (list, obj.) GetType ().
  Name); private static string listtojson&lt;t&gt; (ilist&lt;t&gt; list, string jsonname) {StringBuilder Json = new Strin
   Gbuilder (); if (string. IsNullOrEmpty (JsonnAME)) Jsonname = List[0]. GetType ().
   Name;
   Json.append ("{\" "+ Jsonname +" \ ": ["); if (list. Count &gt; 0) {for (int i = 0; i &lt; list. Count;
     i++) {T obj = activator.createinstance&lt;t&gt; (); propertyinfo[] pi = obj. GetType ().
     GetProperties ();
     Json.append ("{"); for (int j = 0; J &lt; Pi.) Length; J + +) {Type type = Pi[j]. GetValue (List[i], null).
      GetType (); Json.append ("\" "+ pi[j]." Name.tostring () + "\": "+ StringFormat (Pi[j]." GetValue (List[i], null).
      ToString (), type)); if (J &lt; Pi.
      Length-1) {json.append (",");
     } json.append ("}"); if (I &lt; list.
     Count-1) {json.append (",");
   }} json.append ("]}");
  return json.tostring (); Convert #endregion #region Object collection to JSON///&lt;summary&gt;///object collection convert to JSON///&lt;/summary&gt;///&lt;param name= "Array" &gt; Object collection &lt;/param&gt;///&lt;returns&gt;json string &lt;/returns&gt; public static string Tojson (IenumerablE array) {string jsonstring = ' [';
   foreach (object item in array) {jsonstring + + Tojson (item) + ",";
   } jsonstring = jsonstring.substring (0, jsonstring.length-1);
  return jsonstring + "]"; #endregion #region Normal collection convert JSON///&lt;summary&gt;///Normal collection convert JSON///&lt;/summary&gt;///&lt;param Name = "Array" &gt; Collection Object &lt;/param&gt;///&lt;returns&gt;json string &lt;/returns&gt; public static string toarraystring (Ienumer
   Able Array) {string jsonstring = ' ['; foreach (object item in array) {jsonstring = Tojson (item.
   ToString ()) + ",";
   } jsonstring.remove (Jsonstring.length-1, jsonstring.length);
  return jsonstring + "]"; #endregion convert #region DataSet to JSON///&lt;summary&gt;///DataSet to json///&lt;/summary&gt;///&LT;PA Ram Name= "DataSet" &gt;dataset object &lt;/param&gt;///&lt;returns&gt;json string &lt;/returns&gt; public static string Tojson
  (DataSet DataSet)
   {String jsonstring = ' {'; foreach (DataTable table in Dataset.tables) {jsonstring + = "\" + table.
   TableName + "\": "+ tojson (table) +";
   } jsonstring = Jsonstring.trimend (', ');
  return jsonstring + "}"; #endregion #region DataTable converted to JSON///&lt;summary&gt;///DataTable to JSON///&lt;/summary&gt; Publ IC static string Tojson (DataTable dt) {if (dt).
    Rows.Count &gt; 0) {StringBuilder jsonstring = new StringBuilder ();
    Jsonstring.append ("["); DataRowCollection DRC = dt.
    Rows; for (int i = 0; i &lt; DRC. Count;
     i++) {jsonstring.append ("{"); for (int j = 0; j &lt; dt.) Columns.count; J + +) {string strkey = dt. COLUMNS[J].
      ColumnName; String strvalue = Drc[i][j].

      ToString (); Type type = dt. COLUMNS[J].
      DataType;
      Jsonstring.append ("\" "+ strkey +" \ ":");
      strvalue = StringFormat (strvalue, type); if (J &lt; dt.
      columns.count-1) Jsonstring.append (strvalue + ",");
    else Jsonstring.append (strvalue); } jsonstring.append ("},");
    } jsonstring.remove (jsonstring.length-1, 1);
    Jsonstring.append ("]");
   return jsonstring.tostring ();
  else return "[]"; ///&lt;summary&gt;///DataTable converted to JSON///&lt;/summary&gt; public static string Tojson (DataTable dt, Strin
   G jsonname) {StringBuilder Json = new StringBuilder (); if (string. IsNullOrEmpty (jsonname)) jsonname = dt.
   TableName;
   Json.append ("{\" "+ Jsonname +" \ ": ["); if (dt. Rows.Count &gt; 0) {for (int i = 0; i &lt; dt. Rows.Count;
     i++) {json.append ("{"); for (int j = 0; j &lt; dt.) Columns.count; J + +) {Type type = dt. ROWS[I][J].
      GetType (); Json.append ("\" "+ dt.) COLUMNS[J]. Columnname.tostring () + "\": "+ StringFormat" (dt. ROWS[I][J].
      ToString (), type)); if (J &lt; dt.
     columns.count-1) Json.append (",");
     } json.append ("}"); if (i &lt; dt.
    rows.count-1) Json.append (",");
   } json.append ("]}"); Return Json.tostring (); #endregion #region DataReader Convert to JSON///&lt;summary&gt;///DataReader convert to JSON///&lt;/summary&gt;/ &lt;param name= "DataReader" &gt;datareader object &lt;/param&gt;///&lt;returns&gt;json string &lt;/returns&gt; public stat
   IC string Tojson (DbDataReader dataReader) {StringBuilder jsonstring = new StringBuilder ();
   Jsonstring.append ("[");
    while (Datareader.read ()) {Jsonstring.append ("{");
     for (int i = 0; i &lt; Datareader.fieldcount i++) {Type type = Datareader.getfieldtype (i);
     String strkey = Datareader.getname (i); String strvalue = Datareader[i].
     ToString ();
     Jsonstring.append ("\" "+ strkey +" \ ":");
     strvalue = StringFormat (strvalue, type);
     if (i &lt; datareader.fieldcount-1) Jsonstring.append (strvalue + ",");
    else Jsonstring.append (strvalue);
   } jsonstring.append ("},");
   } datareader.close ();
   Jsonstring.remove (jsonstring.length-1, 1); Jsonstring.append ("]");
  return jsonstring.tostring ();
   #endregion #region return error public static string error () {DataTable dt = new DataTable (); Dt.
   Columns.Add ("Error", typeof (int)); DataRow dr = dt.
   NewRow ();
   dr["Error"] = 1; Dt.
   Rows.Add (DR);
  return Tojson (DT);
   #endregion} 11. Convert Help class public class Converthelper {public static int datetimetounixint (DateTime time) {
   DateTime time2 = TimeZone.CurrentTimeZone.ToLocalTime (New DateTime (0X7B2, 1, 1));
   TimeSpan span = (TimeSpan) (time-time2); return (int) span.
  TotalSeconds; public static decimal Moneyround (decimal value, int decimals) {if (value &lt; 0M) {return Math.Round (d
   Ecimal) (value + (5M/((decimal) Math.pow (10.0, (double) (decimals + 1))), decimals, Midpointrounding.awayfromzero);
  return Math.Round (value, decimals, Midpointrounding.awayfromzero); public static double Moneyround (double value, int decimals) {if (value &lt; 0.0) {return Math.round (double) (Value + (5.0/MATH.POW (10.0, (double) (decimals + 1))), decimals, Midpointrounding.awayfromzero);
  return Math.Round (value, decimals, Midpointrounding.awayfromzero); public static decimal Moneytodecimal (String str) {try {str = str.
    Replace (",", ""); return decimal.
   Parse (str);
   catch {return 0M; } public static decimal Round (decimal d, int i) {if (d &gt;= 0M) {d = + 5M * (decimal) Math.pow (10.0,
   (double)-(i + 1));
   else {d = -5m * ((decimal) Math.pow (10.0, double)-(i + 1));
   String str = d.tostring (); string[] Strarray = str.
   Split (new char[] {'. '}); int index = str.
   IndexOf ('. ');
   String str2 = Strarray[0];
   String str3 = Strarray[1]; if (STR3. Length &gt; i) {str3 = str.
   Substring (index + 1, i); } d = Decimal.
   Parse (str2 + "." + STR3);
  return D; public static double Round (double d, int i) {if (d &gt;= 0.0) {d = = 5.0 * MATH.POW (10.0, (double)-(i + 1));
   else {d = -5.0 * MATH.POW (10.0, double)-(i + 1));
   String str = d.tostring (); string[] Strarray = str.
   Split (new char[] {'. '}); int index = str.
   IndexOf ('. ');
   String str2 = Strarray[0];
   String str3 = Strarray[1]; if (STR3. Length &gt; i) {str3 = str.
   Substring (index + 1, i); } d = Double.
   Parse (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 (BOOL).
   TryParse (ToString (O, True), out flag)} {return flag;
  return defaultvalue;
  public static DateTime ToDateTime (object o) {return todatetime (o, DateTime.Now);
   public static datetime ToDateTime (Object o, datetime defaultvalue) {datetime;
   if (ToString (O, True), out time) {return datetime.tryparse;
  return defaultvalue; public static decimal ToDecimal (Object o) {return ToDecimal (o, 0M);
   public static decimal ToDecimal (object o, decimal defaultvalue) {decimal num; if (decimal.
   TryParse (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 (double.
   TryParse (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 (float.
   TryParse (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 (int.
   TryParse (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 (long.
   TryParse (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 decimal. Parse (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 (object). Equals (o, null) | | Convert.isdbnull (o)) {return defaultvalue;
   } if (Btrim) {return o.tostring ().
   Trim ();
  return o.tostring (); public static datetime Unixinttodatetime (String timeStamp) {DateTime = TimeZone.CurrentTimeZone.ToLocalTim
   E (New DateTime (0X7B2, 1, 1)); Long ticks = long.
   Parse (TimeStamp + "0000000");
   TimeSpan span = new TimeSpan (ticks); Return time.
  ADD (span); 

 }
 }

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.