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
<summary>///Batch Export///</summary>///<returns></returns> 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<articleentity> 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 => 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"/>
<summary>///Batch Import///</summary>///<returns></returns> [httppost] public Actionr
Esult Importstu () {httppostedfilebase file = request.files["file"];
String FileName;
String Savepath; if (file = = NULL | | file. ContentLength <= 0) {return Content (' <script>alert (' upload failed, please choose to upload file! ')
location.href= '/mytest/mvcpager ';</script> "); 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 (' <script>alert (' file type is malformed, import exe not allowed Format of the file! ');
location.href= '/mytest/mvcpager ';</script> ");
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 (' <script>alert (' upload failed, ' + ex. Message + "!");
location.href= '/mytest/mvcpager ';</script> "); }//Column order header content DataTable table = mydataset.tables["Excelinfo"].
Defaultview.totable (); Object exception rollback using (TransactionScope transaction = new TransactionScope ()) {for (int i = 0; i < 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
<summary>///Obtain the IP address of the client///</summary>///<returns> Client IP address </returns> 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
<summary>///symmetric encryption class///</summary> public class AES {///<summary>///decryption///</summ ary>///<param name= "Strdecrypt" ></param>///<param name= "strkey" ></param>///<retu rns></returns> 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; }///<summary>///decryption///</summary>///<param name= "StrdecRypt "></param>///<param name=" strkey "></param>///<returns></returns> 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; }///<summary>///encryption///</summary>///<param name= "Strencrypt" ></param>///<par Am Name= "strkey" ></param>///<returns></returns> 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; }///<summary>///encryption///</summary>///<param name= "Strencrypt" ></param>/// ;p Aram Name= "strkey" ></param>///<returns></returns> 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) && 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) && 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) && 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) && 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) && 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); {}}}///<summary>///set domain cookie///</summary>///<param name= "key" ></param>// /<param name= "value" ></param>///<param name= "Domain" ></param> public static void Setdomainc
Ookie (string key, String value, String Domain) {Setcookie (key, NULL, value, NULL, domain);
}
}
8.DataTable Convert to entity class
<summary>///#region DataTable into entity class///</summary>///<typeparam name= "T" ></typeparam> public class modelutil<t> where T:new () {///<summary>///populate object list: Populate entity classes with the first table of the dataset///</sum mary>///<param name= "ds" >DataSet</param>///<returns></returns> public static list< T> Fillmodel (DataSet ds) {if (ds = null | | ds. TABLES[0] = = NULL | | Ds. Tables[0].
Rows.Count = = 0) {return null; else {return Fillmodel (DS).
Tables[0]); ///<summary>///populating objects list: Populating entity classes with the index table of the dataset///</summary> public static list<t> Fi Llmodel (DataSet ds, int index) {if (ds = null | | ds. Tables.count <= Index | | Ds. Tables[index].
Rows.Count = = 0) {return null; else {return Fillmodel (DS).
Tables[index]); ///<summary>///populating objects list: Populating entity classes with DataTable///</summary> public static list<t> Fillmodel(DataTable DT) {if (dt = NULL | | | dt.
Rows.Count = = 0) {return null;
} list<t> modellist = new list<t> (); foreach (DataRow dr in Dt.
Rows) {//t model = (t) activator.createinstance (typeof (T));
T model = new T (); for (int i = 0; i < Dr. Table.Columns.Count; i++) {list<propertyinfo> Propertyinfos = model. GetType (). GetProperties ().
ToList (); PropertyInfo item = Propertyinfos.firstordefault (P => string.compare (p.name, Dr. Table.columns[i].
ColumnName, true) = = 0); if (item!= null && dr[i]!= dbnull.value) try {item.
SetValue (model, dr[i], NULL);
The catch {}} modellist.add (model);
return modellist;
///<summary>///padding objects: Populating entity classes with DataRow///</summary> 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 < Dr. Table.Columns.Count; i++) {list<propertyinfo> Propertyinfos = model. GetType (). GetProperties ().
ToList (); PropertyInfo item = Propertyinfos.firstordefault (P => string.compare (p.name, Dr. Table.columns[i].
ColumnName, true) = = 0); if (item!= null && dr[i]!= dbnull.value) try {item.
SetValue (model, dr[i], NULL);
' Catch {} ' return model; ///<summary>///entity class converted to DataSet///</summary>///<param name= "modellist" > Entity classes list </PARAM&G
T <returns></returns> public static DataSet FillDataSet (list<t> modellist) {if (modellist = = N ull | |
Modellist.count = = 0) {return null;
else {DataSet ds = new DataSet (); Ds.
Tables.add (Filldatatable (modellist));
return DS; }///<summary>///entity classes to DataTable///</summary>///<param name= "modellist" > Entity classes list </pa Ram>///<returns></returns> public static DataTable filldatatable (list<t> 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; ///<summary>///The table structure based on entity classes///</summary>///<param name= "Model" > Entity class </param>///& lt;returns></returns> 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; ///<summary>///The DataTable to list and dictionaryNested collection Save///</summary>///<param name= "DT" ></param>///<returns></returns> public s Tatic list<dictionary<string, string>> tolistdictionary (DataTable dt) {list<dictionary<string, str
ing>> list = null; if (dt!= null && dt.
Rows.Count > 0) {list = new list<dictionary<string, string>> ();
dictionary<string, string> dic = null; foreach (DataRow dr in Dt.
Rows) {dic = new dictionary<string, string> (); foreach (DataColumn dc in dt. Columns) {dic. ADD (DC. ColumnName, DR[DC. ColumnName].
ToString ()); } list.
ADD (DIC);
} return list; ///<summary>///requested request content converted to model///Cza///2016-5-30 19:06:21///</summary>///<p Aram name= ' context ' ></param>///<returns></returns> 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 && 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
<summary>///SQL Server database access class///</summary> 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 ()); <summary>///Implementation, change "common"///</summary> 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; }///<summary>///perform additions and deletions (to existing database connections) "Infrequently"///</summary> 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; ///<summary>///Execute multiple SQL statements (List generic collection) "Transaction" (no parameters)///</summary>///<param name= "ConnectionString" > Database connection string </param>///<param name= "listsql" > Generic set containing multiple SQL statements </param>///<returns> affected rows </returns> public static int ExecuteNonQuery (string connectionString, list<string> 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 < listsql.count; n++) {string strSQL = Listsql[n]; if (Strsql.trim (). LengtH > 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 (); }///<summary>///executes multiple SQL statements (Hashtable) "Transactions" (with a set of parameters, one parameter is encapsulated into a group)///</summary>///<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 = 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 > 0) trans.commit (); catch {trans.
Rollback ();
Throw ///<summary>///returns DataReader object///</summary> 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 }///<summary>///returns the first column of information in the first row (possibly a string so the return type is Object) "common"///</summary> 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; }///<summary>///returns the first column of information in the first row (for an existing database connection) "Not common"///</summary> 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; ///<summary>///return DataTable///</summary> 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; }}///<summary>///return DataSet///</summary> 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; }}///<summary>///add parameter array to cache///</summary>///<param name= "Cach EKey ' >key to the parameter cache</param>///<param name= ' cmdparms ' >an array of sqlparamters to be cached& lt;/param> public static void Cacheparameters (string cachekey, params sqlparameter[] commandparameters) {PARMCA
Che[cachekey] = commandparameters; ///<summary>///Retrieve Cached parameters///</summary>///<param name= "CacheKey" >key US Ed to lookup parameters</param>///<returns>cached sqlparamters array</returns> 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 < J; i++) clonedparms[i] = (SqlParameter) ((icloneable) cachedparms[i]).
Clone ();
return clonedparms; ///<summary>///prepares a pending SqlCommand///</summary> 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 && paras. Length > 0) {//cmd.
Parameters.addrange (paras); for (int i = 0; I < 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); }///<summary>///Common paging stored procedures, conditional queries, sorted fields, sorted by sort fields in descending order///</summary>///<paRam Name= "PageSize" > per-page records </param>///<param name= "Currentcount" > Current record Quantity (page number * per page record) </param>///& Lt;param name= "tablename" > table name </param>///<param name= "Where" > Query conditions, Example: "id>1000 and name like '% lilinfeng% ' "sort condition, directly followed by, example:" Order by ID desc,name ASC "</param>///<param name=" TotalCount "> Total Records </param >///<returns></returns> 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 {///<summary>//////</summary>///<param name= "filename" > FileName </
param>///<param name= "Ex" ></param> 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 &&!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 {}}///<summary>//////</summary>///<param name= ' filename ' > filename </pa ram>///<param name= ' message ' ></param> 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 &&!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 &&!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 &&!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
<summary>///JSON help class///</summary> public class Jsonhelper {#region common methods///<summary> Formatted character type, date type, Boolean///</summary> 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) && string.
IsNullOrEmpty (str)) {str = "\" + str + "\";
return str; ///<summary>///Filter string///</summary> public static string Stringfilter (String str) {STRINGB
Uilder sb = new StringBuilder (); for (int i = 0; i < 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 <summary>///column to JSON///</summary>///<param name= "dt" > table &
lt;/param>///<param name= "R" > Columns </param> public static string Columntojson (DataTable dt, int r) {
StringBuilder strSQL = new StringBuilder (); for (int i = 0; i < dt. Rows.Count; i++) {strsql.append (dt.
Rows[i][r]);
Strsql.append (","); Return strsql.tostring ().
Trim (', '); #endregion #region object to JSON///<summary>///object to JSON///</summary> public static string Tojson (Object JsonobjECT) {StringBuilder sb = new StringBuilder (); Sb.
Append ("{"); propertyinfo[] PropertyInfo = Jsonobject.gettype ().
GetProperties (); for (int i = 0; i < 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///<summary>///list goto JSON///</summary> public static string Li
Sttojson<t> (ilist<t> list) {Object obj = list[0]; return listtojson<t> (list, obj.) GetType ().
Name); private static string listtojson<t> (ilist<t> list, string jsonname) {StringBuilder Json = new Strin
Gbuilder (); if (string. IsNullOrEmpty (JsonnAME)) Jsonname = List[0]. GetType ().
Name;
Json.append ("{\" "+ Jsonname +" \ ": ["); if (list. Count > 0) {for (int i = 0; i < list. Count;
i++) {T obj = activator.createinstance<t> (); propertyinfo[] pi = obj. GetType ().
GetProperties ();
Json.append ("{"); for (int j = 0; J < 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 < Pi.
Length-1) {json.append (",");
} json.append ("}"); if (I < list.
Count-1) {json.append (",");
}} json.append ("]}");
return json.tostring (); Convert #endregion #region Object collection to JSON///<summary>///object collection convert to JSON///</summary>///<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 = jsonstring.substring (0, jsonstring.length-1);
return jsonstring + "]"; #endregion #region Normal collection convert JSON///<summary>///Normal collection convert JSON///</summary>///<param Name = "Array" > Collection Object </param>///<returns>json string </returns> 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///<summary>///DataSet to json///</summary>///<PA Ram Name= "DataSet" >dataset object </param>///<returns>json string </returns> 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///<summary>///DataTable to JSON///</summary> Publ IC static string Tojson (DataTable dt) {if (dt).
Rows.Count > 0) {StringBuilder jsonstring = new StringBuilder ();
Jsonstring.append ("["); DataRowCollection DRC = dt.
Rows; for (int i = 0; i < DRC. Count;
i++) {jsonstring.append ("{"); for (int j = 0; j < 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 < 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 "[]"; ///<summary>///DataTable converted to JSON///</summary> 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 > 0) {for (int i = 0; i < dt. Rows.Count;
i++) {json.append ("{"); for (int j = 0; j < 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 < dt.
columns.count-1) Json.append (",");
} json.append ("}"); if (i < dt.
rows.count-1) Json.append (",");
} json.append ("]}"); Return Json.tostring (); #endregion #region DataReader Convert to JSON///<summary>///DataReader convert to JSON///</summary>/ <param name= "DataReader" >datareader object </param>///<returns>json string </returns> public stat
IC string Tojson (DbDataReader dataReader) {StringBuilder jsonstring = new StringBuilder ();
Jsonstring.append ("[");
while (Datareader.read ()) {Jsonstring.append ("{");
for (int i = 0; i < 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 < 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 < 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 < 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 >= 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 > i) {str3 = str.
Substring (index + 1, i); } d = Decimal.
Parse (str2 + "." + STR3);
return D; public static double Round (double d, int i) {if (d >= 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 > 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.