Commonly used public methods in C#, the specific content is as follows
1. Call weburl in the background
string hostUrl = "?id=123" ; HttpWebRequest myReq = (HttpWebRequest)(hostUrl); = "GET"; HttpWebResponse HttpWResp = (HttpWebResponse)(); Stream myStream = (); StreamReader sr = new StreamReader(myStream, Encoding.UTF8); StringBuilder strBuilder = new StringBuilder(); while (-1 != ()) { (()); } (); (); (); jo = ()(()); string resCode = jo["ReturnCode"].ToString();
2. Detect whether the input URL is legal
/// <summary> /// Determine whether the URL is accessible /// </summary> /// <param name="Url"></param> /// <returns></returns> protected bool ChkPageUrl(string url) { bool result = false; try { HttpWebRequest myHttpWebRequest = (HttpWebRequest)(url); = "Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; rv:11.0) like Gecko"; = "GET"; HttpWebResponse myHttpWebResponse = (HttpWebResponse)(); if ( == ) { result = true; } (); } catch { result = false; } return result; }
3. Batch export
/// <summary> /// Batch export /// </summary> /// <returns></returns> public FileResult ExportStu() { //Create an Excel file object book = new (); //Add a sheet sheet1 = ("Sheet1"); int pager_totalcount = (int)Session["pager_totalcount"]; int totalCount = 0; //Get list data List<ArticleEntity> infoList = new ().GetArticleList("", pager_totalcount, 1, out totalCount); //Add the header of the first line to sheet1 row1 = (0); //Creation time Name Merchant order number | Transaction number Opposite Amount (yuan) Status (0).SetCellValue("serial number"); (1).SetCellValue("title"); (2).SetCellValue("content"); int Width = 256; (0, 10 * Width); (1, 25 * Width); (2, 60 * Width); if (infoList != null) { var list = (p => ); if (list != null) { int i = 0; //Steply write data to each row of sheet1 foreach (var item in list) { i = i + 1; rowtemp = (i); (0).SetCellValue(()); (1).SetCellValue( == null ? "" : ()); (2).SetCellValue( == null ? "" : ()); } } } // Write to the client ms = new (); (ms); (0, ); return File(ms, "application/-excel", ("Export", Encoding.UTF8).ToString() + ("yyyyMMddHHmmss") + ".xls"); }
4. Batch import
<input name="file" type="file" />
<input type="submit" name="Upload" value="Upload" />
/// <summary> /// Batch import /// </summary> /// <returns></returns> [HttpPost] public ActionResult ImportStu() { HttpPostedFileBase file = ["file"]; string FileName; string savePath; if (file == null || <= 0) { return Content("<script>alert('Upload failed, please select upload file!');='/MyTest/MVCPager';</script>"); } else { string filename = (); int filesize = ;//Get the size unit of uploaded file is byte byte string fileEx = (filename);//Get the extension of the uploaded file string NoFileName = (filename);//Get filename without extension string FileType = ".xls,.xlsx";//Define the type string of uploaded file if ((".exe"))//EXCEL { return Content("<script>alert('The upload file type is incorrect, and the import of exe format is not allowed!');='/MyTest/MVCPager';</script>"); } FileName = NoFileName + ("yyyyMMddhhmmss") + fileEx; string path = + "uploads/"; savePath = (path, FileName); (savePath); if ((fileEx))//EXCEL { string strConn = "Provider=.4.0;Data Source=" + savePath + ";" + "Extended Properties=Excel 8.0"; OleDbConnection conn = new OleDbConnection(strConn); (); OleDbDataAdapter myCommand = new OleDbDataAdapter("select * from [Sheet1$]", strConn); DataSet myDataSet = new DataSet(); try { (myDataSet, "ExcelInfo"); } catch (Exception ex) { return Content("<script>alert('Upload failed," + + "!');='/MyTest/MVCPager';</script>"); } //Column order Title Content DataTable table = ["ExcelInfo"].(); //Things exception rollback using (TransactionScope transaction = new TransactionScope()) { for (int i = 0; i < ; i++) { ArticleEntity model = new ArticleEntity(); = [i][0].ToString(); = [i][1].ToString(); new ().AddArticle(model); } (); } } return RedirectToAction("MVCPager", "MyTest"); } }
5. Get the IP address of the client
/// <summary> /// Get the IP address of the client /// </summary> /// <returns>Client IP Address</returns> public static string Get_ClientIP() { string result = ; result = ["X-Real-IP"]; //How to get IP address when Nginx is the front-end if (result != null) return result; if (["REMOTE_ADDR"] != null)//The IP address of the remote host that issued the request { result = ["REMOTE_ADDR"].ToString(); } else if (["HTTP_VIA"] != null)//Discern whether to set up a proxy, if a proxy is used { if (["HTTP_X_FORWARDED_FOR"] != null)//Get the proxy server's IP { result = ["HTTP_X_FORWARDED_FOR"].ToString(); } else { result = ; } } else { result = ; } if (result == "::1") result = ; return result; }
Symmetric encryption
/// <summary> /// Symmetric encryption class /// </summary> public class AES { /// <summary> /// Decrypt /// </summary> /// <param name="strDecrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Decrypt(string strDecrypt, string strKey) { try { byte[] bytes = Encoding.((strKey, "md5")); byte[] inputBuffer = Convert.FromBase64String(strDecrypt); byte[] buffer3 = null; using (RijndaelManaged managed = new RijndaelManaged()) { = bytes; = ; = PaddingMode.PKCS7; buffer3 = ().TransformFinalBlock(inputBuffer, 0, ); } return Encoding.(buffer3); } catch { return null; } } /// <summary> /// Decrypt /// </summary> /// <param name="strDecrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Decrypt(string toDecrypt, string key, string iv) { byte[] bytes = Encoding.(key); byte[] buffer2 = Encoding.(iv); byte[] inputBuffer = Convert.FromBase64String(toDecrypt); RijndaelManaged managed = new RijndaelManaged { Key = bytes, IV = buffer2, Mode = , Padding = }; byte[] buffer4 = ().TransformFinalBlock(inputBuffer, 0, ); return Encoding.(buffer4); } public static string DecryptStr(string EncryptString) { string str = ""; if (!(EncryptString)) { string sSource = Decrypt(EncryptString, ""); if ((sSource, 3) == "gk_") { str = (3); } } return str; } public static string DecryptStrByCBC(string EncryptString) { string str = ""; if (!(EncryptString)) { string sSource = Decrypt(EncryptString, "", ""); if ((sSource, 3) == "gk_") { str = (3); } } return str; } /// <summary> /// Encryption /// </summary> /// <param name="strEncrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Encrypt(string strEncrypt, string strKey) { try { byte[] bytes = Encoding.((strKey, "md5")); byte[] inputBuffer = Encoding.(strEncrypt); byte[] inArray = null; using (RijndaelManaged managed = new RijndaelManaged()) { = bytes; = ; = PaddingMode.PKCS7; inArray = ().TransformFinalBlock(inputBuffer, 0, ); } return Convert.ToBase64String(inArray, 0, ); } catch { return null; } } /// <summary> /// Encryption /// </summary> /// <param name="strEncrypt"></param> /// <param name="strKey"></param> /// <returns></returns> public static string Encrypt(string toEncrypt, string key, string iv) { byte[] bytes = Encoding.(key); byte[] buffer2 = Encoding.(iv); byte[] inputBuffer = Encoding.(toEncrypt); RijndaelManaged managed = new RijndaelManaged { Key = bytes, IV = buffer2, Mode = , Padding = }; byte[] inArray = ().TransformFinalBlock(inputBuffer, 0, ); return Convert.ToBase64String(inArray, 0, ); } public static string EncryptStr(string SourceString) { return Encrypt("gk_" + SourceString, ""); } public static string EncryptStr(string SourceString, bool UseInUrl) { return (EncryptStr(SourceString)); } public static string EncryptStrByCBC(string SourceString) { return Encrypt("gk_" + SourceString, "", ""); } public static string EncryptStrByCBC(string SourceString, bool UseInUrl) { return (EncryptStrByCBC(SourceString)); } }
Help
public class CookiesHelper { public static void AddCookie(string cookieName, DateTime expires) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; AddCookie(cookie, null); } public static void AddCookie(string key, string value) { AddCookie(new HttpCookie(key, value), null); } public static void AddCookie(HttpCookie cookie, string Domain) { HttpResponse response = ; if (response != null) { = true; = "/"; if (!(Domain)) { = Domain; } (cookie); } } public static void AddCookie(string cookieName, DateTime expires, string Domain) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; AddCookie(cookie, Domain); } public static void AddCookie(string key, string value, DateTime expires) { HttpCookie cookie = new HttpCookie(key, value) { Expires = expires }; AddCookie(cookie, null); } public static void AddCookie(string cookieName, string key, string value) { HttpCookie cookie = new HttpCookie(cookieName); (key, value); AddCookie(cookie, null); } public static void AddCookie(string key, string value, bool withDomain, string Domain) { if (withDomain) { AddCookie(new HttpCookie(key, value), Domain); } else { AddCookie(new HttpCookie(key, value), null); } } public static void AddCookie(string key, string value, DateTime expires, string Domain) { HttpCookie cookie = new HttpCookie(key, value) { Expires = expires }; AddCookie(cookie, Domain); } public static void AddCookie(string cookieName, string key, string value, DateTime expires) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; (key, value); AddCookie(cookie, null); } public static void AddCookie(string cookieName, string key, string value, string Domain) { HttpCookie cookie = new HttpCookie(cookieName); (key, value); AddCookie(cookie, Domain); } public static void AddCookie(string cookieName, string key, string value, DateTime expires, string Domain) { HttpCookie cookie = new HttpCookie(cookieName) { Expires = expires }; (key, value); AddCookie(cookie, Domain); } public static void AddDomainCookie(string key, string value, string Domain) { AddCookie(new HttpCookie(key, value), Domain); } public static HttpCookie GetCookie(string cookieName) { HttpRequest request = ; if (request != null) { if ([cookieName] != null) { return [cookieName]; } if ([", " + cookieName] != null) { return [", " + cookieName]; } } return null; } public static string GetCookieValue(string cookieName) { return GetCookieValue(cookieName, null); } public static string GetCookieValue(string cookieName, string key) { HttpRequest request = ; if (request == null) { return ""; } if ([cookieName] != null) { if (!(key) && [cookieName].HasKeys) { return [cookieName].Values[key]; } return [cookieName].Value; } string str = ", " + cookieName; if ([str] == null) { return ""; } if (!(key) && [str].HasKeys) { return [str].Values[key]; } return [str].Value; } public static string GetCookieValue(HttpCookie cookie, string key) { if (cookie == null) { return ""; } if (!(key) && ) { return [key]; } return ; } public static void RemoveCookie(string cookieName) { RemoveCookie(cookieName, null); } public static void RemoveCookie(string cookieName, string key) { HttpResponse response = ; if (response != null) { HttpCookie cookie = [cookieName]; if (cookie != null) { if (!(key) && ) { (key); } else { (cookieName); } } } } public static void SetCookie(string cookieName, DateTime expires) { SetCookie(cookieName, null, null, new DateTime?(expires), null); } public static void SetCookie(string key, string value) { SetCookie(key, null, value, null, null); } public static void SetCookie(string cookieName, DateTime expires, string Domain) { SetCookie(cookieName, null, null, new DateTime?(expires), Domain); } public static void SetCookie(string key, string value, DateTime expires) { SetCookie(key, null, value, new DateTime?(expires), null); } public static void SetCookie(string cookieName, string key, string value) { SetCookie(cookieName, key, value, null, null); } public static void SetCookie(string key, string value, bool withDomain, string Domain) { if (withDomain) { SetCookie(key, null, value, null, Domain); } else { SetCookie(key, null, value, null, null); } } public static void SetCookie(string key, string value, DateTime expires, string Domain) { SetCookie(key, null, value, new DateTime?(expires), Domain); } public static void SetCookie(string cookieName, string key, string value, string Domain) { SetCookie(cookieName, key, value, null, Domain); } public static void SetCookie(string cookieName, string key, string value, DateTime? expires, string Domain) { HttpResponse response = ; if (response != null) { HttpCookie cookie = [cookieName]; if (cookie != null) { = "/"; if (!(Domain)) { = Domain; } if (!(key) && ) { (key, value); } else if (!(value)) { = value; } if () { = ; } (cookie); } } } /// <summary> /// Set domain cookies /// </summary> /// <param name="key"></param> /// <param name="value"></param> /// <param name="Domain"></param> public static void SetDomainCookie(string key, string value, string Domain) { SetCookie(key, null, value, null, Domain); } }
Convert to entity class
/// <summary> /// #region DataTable converted to entity class /// </summary> /// <typeparam name="T"></typeparam> public class ModelUtil<T> where T : new() { /// <summary> ///Fill object list: Fill the entity class with the first table of DataSet /// </summary> /// <param name="ds">DataSet</param> /// <returns></returns> public static List<T> FillModel(DataSet ds) { if (ds == null || [0] == null || [0]. == 0) { return null; } else { return FillModel([0]); } } /// <summary> ///Fill object list: Fill the entity class with the index table of DataSet /// </summary> public static List<T> FillModel(DataSet ds, int index) { if (ds == null || <= index || [index]. == 0) { return null; } else { return FillModel([index]); } } /// <summary> ///Fill the object list: Fill the entity class with DataTable /// </summary> public static List<T> FillModel(DataTable dt) { if (dt == null || == 0) { return null; } List<T> modelList = new List<T>(); foreach (DataRow dr in ) { //T model = (T)(typeof(T)); T model = new T(); for (int i = 0; i < ; i++) { List<PropertyInfo> propertyInfos = ().GetProperties().ToList(); PropertyInfo item = (p => (, [i].ColumnName, true) == 0); if (item != null && dr[i] != ) try { (model, dr[i], null); } catch { } } (model); } return modelList; } /// <summary> ///Fill object: Fill the entity class with DataRow /// </summary> public static T FillModel(DataRow dr) { if (dr == null) { return default(T); } //T model = (T)(typeof(T)); T model = new T(); for (int i = 0; i < ; i++) { List<PropertyInfo> propertyInfos = ().GetProperties().ToList(); PropertyInfo item = (p => (, [i].ColumnName, true) == 0); if (item != null && dr[i] != ) try { (model, dr[i], null); } catch { } } return model; } /// <summary> /// Convert entity class to DataSet /// </summary> /// <param name="modelList">Entity Class List</param> /// <returns></returns> public static DataSet FillDataSet(List<T> modelList) { if (modelList == null || == 0) { return null; } else { DataSet ds = new DataSet(); (FillDataTable(modelList)); return ds; } } /// <summary> /// Convert entity class to DataTable /// </summary> /// <param name="modelList">Entity Class List</param> /// <returns></returns> public static DataTable FillDataTable(List<T> modelList) { if (modelList == null || == 0) { return null; } DataTable dt = CreateData(modelList[0]); foreach (T model in modelList) { DataRow dataRow = (); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { dataRow[] = (model, null); } (dataRow); } return dt; } /// <summary> /// Get the table structure according to the entity class /// </summary> /// <param name="model">Entity class</param> /// <returns></returns> private static DataTable CreateData(T model) { DataTable dataTable = new DataTable(typeof(T).Name); foreach (PropertyInfo propertyInfo in typeof(T).GetProperties()) { (new DataColumn(, )); } return dataTable; } /// <summary> /// Convert DataTable to List and save Dictionary nested collection /// </summary> /// <param name="dt"></param> /// <returns></returns> public static List<Dictionary<string, string>> ToListDictionary(DataTable dt) { List<Dictionary<string, string>> list = null; if (dt != null && > 0) { list = new List<Dictionary<string, string>>(); Dictionary<string, string> dic = null; foreach (DataRow dr in ) { dic = new Dictionary<string, string>(); foreach (DataColumn dc in ) { (, dr[].ToString()); } (dic); } } return list; } /// <summary> /// Convert the content of the request to model /// cza /// 2016-5-30 19:06:21 /// </summary> /// <param name="context"></param> /// <returns></returns> public static T ConvertToModel(HttpContext context) { T t = new T(); PropertyInfo[] propertys = ().GetProperties(); foreach (PropertyInfo pi in propertys) { if (!) continue; object value = []; if (value != null && value != ) { try { if (() != "") (t, (value, ), null);//This step is very important for type conversion else (t, value, null); } catch { } } } return t; } }
Server database access class
/// <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 = ["Conn"].ConnectionString; //Empty structure public SqlHelper() { } //Hashtable to store cached parameters private static Hashtable parmCache = (new Hashtable()); /// <summary> /// Execute addition, deletion and modification [commonly used] /// </summary> public static int ExecuteNonQuery(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, commandType, commandText, paras); int val = (); (); //Clear parameters return val; } } /// <summary> /// Perform addition, deletion and modification (connection to existing databases) [not commonly used] /// </summary> public static int ExecuteNonQuery(SqlConnection connection, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); PrepareCommand(cmd, connection, null, commandType, commandText, paras); int val = (); (); return val; } /// <summary> /// Execute multiple sql statements (List generic collection) [Transaction] (no parameters) /// </summary> /// <param name="connectionString">Database connection string</param> /// <param name="listSql">Generic collection containing multiple SQL statements</param> /// <returns>Number of affected rows</returns> public static int ExecuteNonQuery(string connectionString, List<string> listSql) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); (); SqlTransaction trans = (); PrepareCommand(cmd, conn, trans, , null, null); try { int count = 0; for (int n = 0; n < ; n++) { string strSql = listSql[n]; if (().Length > 1) { = strSql; count += (); } } (); (); return count; } catch { (); (); return 0; } finally { (); } } /// <summary> /// Execute multiple sql statements (Hashtable) [transaction] (with a set of parameters, one parameter must also be encapsulated into groups) /// </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 = new SqlConnection(connectionString)) { (); using (SqlTransaction trans = ()) { SqlCommand cmd = new SqlCommand(); try { foreach (DictionaryEntry item in sqlStringList) { string cmdText = (); //Sql statement to be executed SqlParameter[] cmdParas = (SqlParameter[]); //System corresponding to SQL statement PrepareCommand(cmd, conn, trans, , cmdText, cmdParas); int val = (); (); } if ( > 0) (); } catch { (); throw; } } } } /// <summary> /// Return the DataReader object /// </summary> public static SqlDataReader ExecuteReader(string connectionString, CommandType commandType, string cmdText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); SqlConnection conn = new SqlConnection(connectionString); try { PrepareCommand(cmd, conn, null, commandType, cmdText, paras); SqlDataReader reader = (); (); return reader; } catch { (); throw; } } /// <summary> /// Return the first row and the first column information (may be a string, so the return type is object) [Commonly used] /// </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, commandType, commandText, paras); object val = (); (); return val; } } /// <summary> /// Return the first row and first column information (for existing database connections) [not commonly used] /// </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 = (); (); return val; } /// <summary> /// Return to DataTable /// </summary> public static DataTable GetDataTable(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, commandType, commandText, paras); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataTable dt = new DataTable(); (dt); return dt; } } } /// <summary> /// Return DataSet /// </summary> public static DataSet GetDataset(string connectionString, CommandType commandType, string commandText, params SqlParameter[] paras) { SqlCommand cmd = new SqlCommand(); using (SqlConnection conn = new SqlConnection(connectionString)) { PrepareCommand(cmd, conn, null, commandType, commandText, paras); using (SqlDataAdapter da = new SqlDataAdapter(cmd)) { DataSet ds = new DataSet(); (ds); return ds; } } } /// <summary> /// add parameter array to the cache /// </summary> /// <param name="cacheKey">Key to the parameter cache</param> /// <param name="cmdParms">an array of SqlParamters to be cached</param> public static void CacheParameters(string cacheKey, params SqlParameter[] commandParameters) { parmCache[cacheKey] = commandParameters; } /// <summary> /// Retrieve cached parameters /// </summary> /// <param name="cacheKey">key used to lookup parameters</param> /// <returns>Cached SqlParamters array</returns> public static SqlParameter[] GetCachedParameters(string cacheKey) { SqlParameter[] cachedParms = (SqlParameter[])parmCache[cacheKey]; if (cachedParms == null) return null; SqlParameter[] clonedParms = new SqlParameter[]; for (int i = 0, j = ; i < j; i++) clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone(); return clonedParms; } /// <summary> /// Prepare a SqlCommand to be executed /// </summary> private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, params SqlParameter[] paras) { try { if ( != ) { (); (); } = conn; if (commandText != null) = commandText; = commandType; //Is the T-Sql statement or stored procedure executed here? if (trans != null) = trans; if (paras != null && > 0) { //(paras); for (int i = 0; i < ; i++) { if (paras[i].Value == null || paras[i].() == "") paras[i].Value = ; //When inserting or modifying, if any parameter is an empty string, then insert the database in NULL form (paras[i]); } } } catch (Exception ex) { throw new Exception(); } } /// <summary> /// General paging stored procedure, conditional query, sorted fields, sorted in descending order of sorted fields /// </summary> /// <param name="PageSize">Number of records per page</param> /// <param name="CurrentCount">Current number of records (page number * number of records per page)</param> /// <param name="TableName">Table name</param> /// <param name="Where">Query conditions, example: "ID>1000 AND Name like '%LiLinFeng%'" sorting conditions, directly added to the following, example: "ORDER BY ID DESC,NAME ASC"</param> /// <param name="TotalCount">Total record number</param> /// <returns></returns> public static DataSet GetList(string connectionString, string Order, int PageSize, int CurrentCount, string TableName, string Where, out int TotalCount) { SqlParameter[] parmList = { new SqlParameter("@PageSize",PageSize), new SqlParameter("@CurrentCount",CurrentCount), new SqlParameter("@TableName",TableName), new SqlParameter("@Where",Where), new SqlParameter("@Order",Order), new SqlParameter("@TotalCount",,4) }; parmList[5].Direction = ; DataSet ds = GetDataset(connectionString, , "sp_MvcPager", parmList); TotalCount = Convert.ToInt32(parmList[5].Value); return ds; } }
10. Log file logging
public class WriteLog { /// <summary> /// /// </summary> /// <param name="fileName">File name</param> /// <param name="ex"></param> public static void WriteErorrLog(string fileName, Exception ex) { if (ex == null) return; //ex = null return DateTime dt = ; // Set log time string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds string logName = ("yyyy-MM-dd"); //Log name string logPath = (, ("log", fileName)); //Log storage path string log = (logPath, ("{0}.log", logName)); //Path + Name try { FileInfo info = new FileInfo(log); if ( != null && !) { (); } using (StreamWriter write = new StreamWriter(log, true, ("utf-8"))) { (time); (); ("Exception message:" + ex); ("Exception stack:" + ); ("Abnormal description:" + ); ("\r\n----------------------------------\r\n"); (); (); (); } } catch { } } /// <summary> /// /// </summary> /// <param name="fileName">File name</param> /// <param name="message"></param> public static void WriteMessage(string fileName, string message) { //ex = null return DateTime dt = ; // Set log time string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds string logName = ("yyyy-MM-dd"); //Log name string logPath = (, ("log", fileName)); //Log storage path string log = (logPath, ("{0}.log", logName)); //Path + Name try { FileInfo info = new FileInfo(log); if ( != null && !) { (); } using (StreamWriter write = new StreamWriter(log, true, ("utf-8"))) { (time); ("information:" + message); ("\r\n----------------------------------\r\n"); (); (); (); } } catch { } } public static void WriteErorrLog(Exception ex, string message) { if (ex == null) return; //ex = null return DateTime dt = ; // Set log time string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds string logName = ("yyyy-MM-dd"); //Log name string logPath = ; //Log storage path string log = ((logPath, "log"), ("{0}.log", logName)); //Path + Name try { FileInfo info = new FileInfo(log); if ( != null && !) { (); } using (StreamWriter write = new StreamWriter(log, true, ("utf-8"))) { (time); (); ("Exception message:" + ex); ("Exception stack:" + ); ("Abnormal description:" + message); ("\r\n----------------------------------\r\n"); (); (); (); } } catch { } } public static void WriteMessage(string message) { //ex = null return DateTime dt = ; // Set log time string time = ("yyyy-MM-dd HH:mm:ss"); //Year-Month-Day Time: Minutes: Seconds string logName = ("yyyy-MM-dd"); //Log name string logPath = ; //Log storage path string log = ((logPath, "log"), ("{0}.log", logName)); //Path + Name try { FileInfo info = new FileInfo(log); if ( != null && !) { (); } using (StreamWriter write = new StreamWriter(log, true, ("utf-8"))) { (time); ("information:" + message); ("\r\n----------------------------------\r\n"); (); (); (); } } catch { } } }
Help
/// <summary> /// JSON Help Class /// </summary> public class JsonHelper { #region General Method /// <summary> /// Format character type, date type, boolean type /// </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 = (); } else if (type == typeof(Guid)) { str = "\"" + str + "\""; } else if (type != typeof(string) && (str)) { str = "\"" + str + "\""; } return str; } /// <summary> /// Filter strings /// </summary> public static string StringFilter(string str) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < ; i++) { char c = ()[i]; switch (c) { case '\"': ("\\\""); break; case '\\': ("\\\\"); break; case '/': ("\\/"); break; case '\b': ("\\b"); break; case '\f': ("\\f"); break; case '\n': ("\\n"); break; case '\r': ("\\r"); break; case '\t': ("\\t"); break; default: (c); break; } } return (); } #endregion #region column to json /// <summary> /// column to json /// </summary> /// <param name="dt">table</param> /// <param name="r">Column</param> public static string ColumnToJson(DataTable dt, int r) { StringBuilder strSql = new StringBuilder(); for (int i = 0; i < ; i++) { ([i][r]); (","); } return ().Trim(','); } #endregion #region object to json /// <summary> /// Object to json /// </summary> public static string ToJson(object jsonObject) { StringBuilder sb = new StringBuilder(); ("{"); PropertyInfo[] propertyInfo = ().GetProperties(); for (int i = 0; i < ; i++) { object objectValue = propertyInfo[i].GetGetMethod().Invoke(jsonObject, null); Type type = propertyInfo[i].PropertyType; string strValue = (); strValue = StringFormat(strValue, type); ("\"" + propertyInfo[i].Name + "\":"); (strValue + ","); } ( - 1, 1); ("}"); return (); } #endregion #region list to json /// <summary> /// list to json /// </summary> public static string ListToJson<T>(IList<T> list) { object obj = list[0]; return ListToJson<T>(list, ().Name); } private static string ListToJson<T>(IList<T> list, string JsonName) { StringBuilder Json = new StringBuilder(); if ((JsonName)) JsonName = list[0].GetType().Name; ("{\"" + JsonName + "\":["); if ( > 0) { for (int i = 0; i < ; i++) { T obj = <T>(); PropertyInfo[] pi = ().GetProperties(); ("{"); for (int j = 0; j < ; j++) { Type type = pi[j].GetValue(list[i], null).GetType(); ("\"" + pi[j].() + "\":" + StringFormat(pi[j].GetValue(list[i], null).ToString(), type)); if (j < - 1) { (","); } } ("}"); if (i < - 1) { (","); } } } ("]}"); return (); } #endregion #region object collection converted to json /// <summary> /// Convert object collection 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 = (0, - 1); return jsonString + "]"; } #endregion #region Normal collection conversion Json /// <summary> /// Normal collection conversion Json /// </summary> /// <param name="array">collection object</param> /// <returns>Json string</returns> public static string ToArrayString(IEnumerable array) { string jsonString = "["; foreach (object item in array) { jsonString = ToJson(()) + ","; } ( - 1, ); return jsonString + "]"; } #endregion #region DataSet convert to Json /// <summary> /// Convert DataSet to Json /// </summary> /// <param name="dataSet">DataSet object</param> /// <returns>Json string</returns> public static string ToJson(DataSet dataSet) { string jsonString = "{"; foreach (DataTable table in ) { jsonString += "\"" + + "\":" + ToJson(table) + ","; } jsonString = (','); return jsonString + "}"; } #endregion #region Datatable to Json /// <summary> /// Convert Datatable to Json /// </summary> public static string ToJson(DataTable dt) { if ( > 0) { StringBuilder jsonString = new StringBuilder(); ("["); DataRowCollection drc = ; for (int i = 0; i < ; i++) { ("{"); for (int j = 0; j < ; j++) { string strKey = [j].ColumnName; string strValue = drc[i][j].ToString(); Type type = [j].DataType; ("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (j < - 1) (strValue + ","); else (strValue); } ("},"); } ( - 1, 1); ("]"); return (); } else return "[]"; } /// <summary> /// Convert DataTable to Json /// </summary> public static string ToJson(DataTable dt, string jsonName) { StringBuilder Json = new StringBuilder(); if ((jsonName)) jsonName = ; ("{\"" + jsonName + "\":["); if ( > 0) { for (int i = 0; i < ; i++) { ("{"); for (int j = 0; j < ; j++) { Type type = [i][j].GetType(); ("\"" + [j].() + "\":" + StringFormat([i][j].ToString(), type)); if (j < - 1) (","); } ("}"); if (i < - 1) (","); } } ("]}"); return (); } #endregion #region DataReader to Json /// <summary> /// Convert DataReader to Json /// </summary> /// <param name="dataReader">DataReader object</param> /// <returns>Json string</returns> public static string ToJson(DbDataReader dataReader) { StringBuilder jsonString = new StringBuilder(); ("["); while (()) { ("{"); for (int i = 0; i < ; i++) { Type type = (i); string strKey = (i); string strValue = dataReader[i].ToString(); ("\"" + strKey + "\":"); strValue = StringFormat(strValue, type); if (i < - 1) (strValue + ","); else (strValue); } ("},"); } (); ( - 1, 1); ("]"); return (); } #endregion #region Returns an error public static string error() { DataTable dt = new DataTable(); ("error", typeof(int)); DataRow dr = (); dr["error"] = 1; (dr); return ToJson(dt); } #endregion } 11.Convert help class public class ConvertHelper { public static int DateTimeToUnixInt(DateTime time) { DateTime time2 = (new DateTime(0x7b2, 1, 1)); TimeSpan span = (TimeSpan)(time - time2); return (int); } public static decimal MoneyRound(decimal value, int decimals) { if (value < 0M) { return ((decimal)(value + (5M / ((decimal)(10.0, (double)(decimals + 1))))), decimals, ); } return (value, decimals, ); } public static double MoneyRound(double value, int decimals) { if (value < 0.0) { return ((double)(value + (5.0 / (10.0, (double)(decimals + 1)))), decimals, ); } return (value, decimals, ); } public static decimal MoneyToDecimal(string str) { try { str = (",", ""); return (str); } catch { return 0M; } } public static decimal Round(decimal d, int i) { if (d >= 0M) { d += 5M * ((decimal)(10.0, (double)-(i + 1))); } else { d += -5M * ((decimal)(10.0, (double)-(i + 1))); } string str = (); string[] strArray = (new char[] { '.' }); int index = ('.'); string str2 = strArray[0]; string str3 = strArray[1]; if ( > i) { str3 = (index + 1, i); } d = (str2 + "." + str3); return d; } public static double Round(double d, int i) { if (d >= 0.0) { d += 5.0 * (10.0, (double)-(i + 1)); } else { d += -5.0 * (10.0, (double)-(i + 1)); } string str = (); string[] strArray = (new char[] { '.' }); int index = ('.'); string str2 = strArray[0]; string str3 = strArray[1]; if ( > i) { str3 = (index + 1, i); } d = (str2 + "." + str3); return d; } public static bool ToBool(object o) { return ToBool(o, false); } public static bool ToBool(object o, bool DefaultValue) { bool flag; if ((ToString(o, true), out flag)) { return flag; } return DefaultValue; } public static DateTime ToDateTime(object o) { return ToDateTime(o, ); } public static DateTime ToDateTime(object o, DateTime DefaultValue) { DateTime time; if ((ToString(o, true), out time)) { return time; } return DefaultValue; } public static decimal ToDecimal(object o) { return ToDecimal(o, 0M); } public static decimal ToDecimal(object o, decimal DefaultValue) { decimal num; if ((ToString(o, true), out num)) { return num; } return DefaultValue; } public static double ToDouble(object o) { return ToDouble(o, 0.0); } public static double ToDouble(object o, double DefaultValue) { double num; if ((ToString(o, true), out num)) { return num; } return DefaultValue; } public static float ToFloat(object o) { return ToFloat(o, 0f); } public static float ToFloat(object o, float DefaultValue) { float num; if ((ToString(o, true), out num)) { return num; } return DefaultValue; } public static int ToInt(object o) { return ToInt(o, 0); } public static int ToInt(object o, int DefaultValue) { int num; if ((ToString(o, true), out num)) { return num; } return DefaultValue; } public static long ToLong(object o) { return ToLong(o, 0L); } public static long ToLong(object o, long DefaultValue) { long num; if ((ToString(o, true), out num)) { return num; } return DefaultValue; } public static string ToMoney(object o) { return ToDecimal(o).ToString("###,###,###,###,###,##0.##"); } public static string ToMoney(string str) { try { return (str).ToString("###,###,###,###,###,##0.##"); } catch { return "0"; } } public static string ToString(object o) { return ToString(o, "", false); } public static string ToString(object o, bool bTrim) { return ToString(o, "", bTrim); } public static string ToString(object o, string DefaultValue) { return ToString(o, DefaultValue, false); } public static string ToString(object o, string DefaultValue, bool bTrim) { if ((o, null) || (o)) { return DefaultValue; } if (bTrim) { return ().Trim(); } return (); } public static DateTime UnixIntToDateTime(string timeStamp) { DateTime time = (new DateTime(0x7b2, 1, 1)); long ticks = (timeStamp + "0000000"); TimeSpan span = new TimeSpan(ticks); return (span); } }
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.