C Common Common Methods
- 2021-10-27 08:34:20
- OfStack
C # Common common methods, as follows
1. Call weburl in the background
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. Check whether the input URL is legal
/// <summary>
/// Determine whether the website 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 ExportStu()
{
// Create Excel Objects of files
NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
// Add 1 A sheet
NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
int pager_totalcount = (int)Session["pager_totalcount"];
int totalCount = 0;
// Get list Data
List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", pager_totalcount, 1, out totalCount);
// To sheet1 Add Parts 1 Header header of row
NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
// Creation time Name Merchant order number | Transaction number The other side Amount ( Yuan ) Status
row1.CreateCell(0).SetCellValue(" Numbering ");
row1.CreateCell(1).SetCellValue(" Title ");
row1.CreateCell(2).SetCellValue(" Content ");
int Width = 256;
sheet1.SetColumnWidth(0, 10 * Width);
sheet1.SetColumnWidth(1, 25 * Width);
sheet1.SetColumnWidth(2, 60 * Width);
if (infoList != null)
{
var list = infoList.OrderByDescending(p => p.ID);
if (list != null)
{
int i = 0;
// Step-by-step writing of data to sheet1 Each row
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. Batch import
<
input name="file" type="file" id="file" /
>
<
input type= "submit" name= "Upload" value= "Upload"/
>
/// <summary>
/// Batch import
/// </summary>
/// <returns></returns>
[HttpPost]
public ActionResult ImportStu()
{
HttpPostedFileBase file = Request.Files["file"];
string FileName;
string savePath;
if (file == null || file.ContentLength <= 0)
{
return Content("<script>alert(' Upload failed , Please select 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
string fileEx = System.IO.Path.GetExtension(filename);// Get the extension of the uploaded file
string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);// Get a file name without extension
string FileType = ".xls,.xlsx";// Defines the type string of the uploaded file
if (FileType.Contains(".exe"))//EXCEL
{
return Content("<script>alert(' Upload file type format error , Import is not allowed exe File in format !');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=" + savePath + ";" + "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");
}
catch (Exception ex)
{
return Content("<script>alert(' Upload failed ," + ex.Message + "!');location.href='/MyTest/MVCPager';</script>");
}
// Column order Title Content
DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();
// Things 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 client's IP address
/// <summary>
/// Object of the client IP Address
/// </summary>
/// <returns> Client IP Address </returns>
public static string Get_ClientIP()
{
string result = string.Empty;
result = HttpContext.Current.Request.Headers["X-Real-IP"]; //Nginx Obtained when it is the front end IP Address method
if (result != null)
return result;
if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)// Of the remote host that made the request IP Address
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
}
else if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)// Determine whether to set the proxy, and if the proxy is used
{
if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)// Object of the proxy server IP
{
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString();
}
else
{
result = HttpContext.Current.Request.UserHostAddress;
}
}
else
{
result = HttpContext.Current.Request.UserHostAddress;
}
if (result == "::1")
result = string.Empty;
return result;
}
6. AES Symmetric Encryption
/// <summary>
/// Symmetric encryption class
/// </summary>
public class AES
{
/// <summary>
/// Decryption
/// </summary>
/// <param name="strDecrypt"></param>
/// <param name="strKey"></param>
/// <returns></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 static 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,
Padding = 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>
/// <param name="strKey"></param>
/// <returns></returns>
public static string Encrypt(string strEncrypt, string strKey)
{
try
{
byte[] bytes = Encoding.UTF8.GetBytes(FormsAuthentication.HashPasswordForStoringInConfigFile(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>
/// <param name="strKey"></param>
/// <returns></returns>
public static string Encrypt(string toEncrypt, 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,
Padding = 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(SourceString));
}
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(EncryptStrByCBC(SourceString));
}
}
7. Cookies Helper Class
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 = HttpContext.Current.Response;
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 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);
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)
{
HttpCookie 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, value), 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.Request;
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) && cookie.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.Response;
if (response != null)
{
HttpCookie cookie = response.Cookies[cookieName];
if (cookie != null)
{
if (!string.IsNullOrEmpty(key) && cookie.HasKeys)
{
cookie.Values.Remove(key);
}
else
{
response.Cookies.Remove(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 = 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) && cookie.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 the domain's cookie
/// </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);
}
}
8. DataTable to Entity Class
/// <summary>
/// #region DataTable Convert to Entity Class
/// </summary>
/// <typeparam name="T"></typeparam>
public class ModelUtil<T> where T : new()
{
/// <summary>
/// Fill in the list of objects: use DataSet The first part of 1 Tables populate entity classes
/// </summary>
/// <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>
/// Fill in the list of objects: use DataSet The first part of index Tables populate entity classes
/// </summary>
public static List<T> FillModel(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>
/// Fill in the list of objects: use DataTable Populating Entity Classes
/// </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);
}
catch
{
}
}
modelList.Add(model);
}
return modelList;
}
/// <summary>
/// Fill in an object: Use the DataRow Populating Entity Classes
/// </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 is converted to DataSet
/// </summary>
/// <param name="modelList"> Entity class list </param>
/// <returns></returns>
public static DataSet FillDataSet(List<T> modelList)
{
if (modelList == null || modelList.Count == 0)
{
return null;
}
else
{
DataSet ds = new DataSet();
ds.Tables.Add(FillDataTable(modelList));
return ds;
}
}
/// <summary>
/// Entity class is converted to DataTable
/// </summary>
/// <param name="modelList"> Entity class list </param>
/// <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>
/// 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())
{
dataTable.Columns.Add(new DataColumn(propertyInfo.Name, propertyInfo.PropertyType));
}
return dataTable;
}
/// <summary>
/// Will DataTable To convert List And Dictionary Nested collection saving
/// </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 && 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 Convert the contents of 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 = 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 1 Step is important for type conversion
else
pi.SetValue(t, value, null);
}
catch
{ }
}
}
return t;
}
}
9. SQL 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 = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;
// Empty structure
public SqlHelper() { }
//Hashtable to store cached parameters
private static Hashtable parmCache = Hashtable.Synchronized(new Hashtable());
/// <summary>
/// Implement additions, deletions and changes to "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 = cmd.ExecuteNonQuery();
cmd.Parameters.Clear(); // Empty parameter
return val;
}
}
/// <summary>
/// Perform additions and deletions (for existing database connections) "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 = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Execute multiple sql Statement ( List Generic collection) "transaction" (no parameters)
/// </summary>
/// <param name="connectionString"> Database connection string </param>
/// <param name="listSql"> Contains more than one sql Generic collection of statements </param>
/// <returns> Number of rows affected </returns>
public static int ExecuteNonQuery(string connectionString, List<string> listSql)
{
SqlCommand 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>
/// Execute multiple sql Statement ( Hashtable ) "Transaction" with 1 Group parameters, 1 Parameters 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))
{
conn.Open();
using (SqlTransaction trans = conn.BeginTransaction())
{
SqlCommand cmd = new SqlCommand();
try
{
foreach (DictionaryEntry item in sqlStringList)
{
string cmdText = item.Key.ToString(); // To be executed sql Statement
SqlParameter[] cmdParas = (SqlParameter[])item.Value; //sql Parameters corresponding to the statement
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>
/// Return 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 = cmd.ExecuteReader(CommandBehavior.CloseConnection);
cmd.Parameters.Clear();
return reader;
}
catch
{
conn.Close();
throw;
}
}
/// <summary>
/// Return to the 1 Line number 1 Column information (possibly 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 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
}
/// <summary>
/// Return to the 1 Line number 1 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 = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
/// <summary>
/// Return 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();
da.Fill(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();
da.Fill(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[cachedParms.Length];
for (int i = 0, j = cachedParms.Length; i < j; i++)
clonedParms[i] = (SqlParameter)((ICloneable)cachedParms[i]).Clone();
return clonedParms;
}
/// <summary>
/// Prepare 1 To be executed SqlCommand
/// </summary>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType commandType, string commandText, 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; // What is set here is T-Sql Statement or 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; // When inserting or modifying, if a parameter is an empty string, the NULL Insert the database in the form of
cmd.Parameters.Add(paras[i]);
}
}
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
/// <summary>
/// Universal 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"> Number of current records (page number * Number of records per page) </param>
/// <param name="TableName"> Table name </param>
/// <param name="Where"> Query criteria, for example: "ID>1000 AND Name like '%LiLinFeng%'" Sorting conditions are added directly after, for example: " ORDER BY ID DESC,NAME ASC"</param>
/// <param name="TotalCount"> Total number of records </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",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 logging
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 Return
DateTime dt = DateTime.Now; // Set log time
string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); // Year - Month - Day Hours: Minutes: Seconds
string logName = dt.ToString("yyyy-MM-dd"); // Log name
string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); // Log storage 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(" Brief description of anomaly: " + ex.Message);
write.WriteLine("\r\n----------------------------------\r\n");
write.Flush();
write.Close();
write.Dispose();
}
}
catch { }
}
/// <summary>
///
/// </summary>
/// <param name="fileName"> Filename </param>
/// <param name="message"></param>
public static void WriteMessage(string fileName, string message)
{
//ex = null Return
DateTime dt = DateTime.Now; // Set log time
string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); // Year - Month - Day Hours: Minutes: Seconds
string logName = dt.ToString("yyyy-MM-dd"); // Log name
string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); // Log storage 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(" Information: " + 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 Return
DateTime dt = DateTime.Now; // Set log time
string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); // Year - Month - Day Hours: Minutes: Seconds
string logName = dt.ToString("yyyy-MM-dd"); // Log name
string logPath = System.AppDomain.CurrentDomain.BaseDirectory; // Log storage 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(ex.Message);
write.WriteLine(" Exception information: " + ex);
write.WriteLine(" Exception stack: " + ex.StackTrace);
write.WriteLine(" Brief description of anomaly: " + message);
write.WriteLine("\r\n----------------------------------\r\n");
write.Flush();
write.Close();
write.Dispose();
}
}
catch { }
}
public static void WriteMessage(string message)
{
//ex = null Return
DateTime dt = DateTime.Now; // Set log time
string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); // Year - Month - Day Hours: Minutes: Seconds
string logName = dt.ToString("yyyy-MM-dd"); // Log name
string logPath = System.AppDomain.CurrentDomain.BaseDirectory; // Log storage 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(" Information: " + message);
write.WriteLine("\r\n----------------------------------\r\n");
write.Flush();
write.Close();
write.Dispose();
}
}
catch { }
}
}
11. JSON Help Class
/// <summary>
/// Determine whether the website 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;
}
0