程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> C# >> C#入門知識 >> C# 經常使用公共辦法

C# 經常使用公共辦法

編輯:C#入門知識

C# 經常使用公共辦法。本站提示廣大學習愛好者:(C# 經常使用公共辦法)文章只能為提供參考,不一定能成為您想要的結果。以下是C# 經常使用公共辦法正文


C# 經常使用公共辦法,詳細內容以下

1.後台挪用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.檢測輸出URL能否正當 

/// <summary>
 /// 斷定網址能否可以拜訪
 /// </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.批量導出

 /// <summary>
  /// 批量導出
  /// </summary>
  /// <returns></returns>
  public FileResult ExportStu()
  {
   //創立Excel文件的對象
   NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook();
   //添加一個sheet
   NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("Sheet1");
   int pager_totalcount = (int)Session["pager_totalcount"];
   int totalCount = 0;
   //獲得list數據
   List<ArticleEntity> infoList = new AchieveDAL.MyTestDAL().GetArticleList("", pager_totalcount, 1, out totalCount);

   //給sheet1添加第一行的頭部題目
   NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0);
   //創立時光 稱號 商戶定單號 | 生意業務號 對方 金額(元) 狀況
   row1.CreateCell(0).SetCellValue("編號");
   row1.CreateCell(1).SetCellValue("題目");
   row1.CreateCell(2).SetCellValue("內容");
   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;
     //將數據慢慢寫入sheet1各個行
     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());
     }
    }
   }
   // 寫入到客戶端 
   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("導出", Encoding.UTF8).ToString() + DateTime.Now.ToString("yyyyMMddHHmmss") + ".xls");

  }

4.批量導入 

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

/// <summary>
  /// 批量導入
  /// </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('上傳掉敗,請選擇上傳文件!');location.href='/MyTest/MVCPager';</script>");
   }
   else
   {
    string filename = Path.GetFileName(file.FileName);
    int filesize = file.ContentLength;//獲得上傳文件的年夜小單元為字節byte
    string fileEx = System.IO.Path.GetExtension(filename);//獲得上傳文件的擴大名
    string NoFileName = System.IO.Path.GetFileNameWithoutExtension(filename);//獲得無擴大名的文件名
    string FileType = ".xls,.xlsx";//界說上傳文件的類型字符串
    if (FileType.Contains(".exe"))//EXCEL
    {
     return Content("<script>alert('上傳文件類型格局毛病,不許可導入exe格局的文件!');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('上傳掉敗," + ex.Message + "!');location.href='/MyTest/MVCPager';</script>");
     }
     //列次序 題目 內容
     DataTable table = myDataSet.Tables["ExcelInfo"].DefaultView.ToTable();

     //事物 異常回滾
     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.獲得客戶真個IP地址 

/// <summary>
  /// 獲得客戶真個IP地址
  /// </summary>
  /// <returns>客戶端IP地址</returns>
  public static string Get_ClientIP()
  {
   string result = string.Empty;
   result = HttpContext.Current.Request.Headers["X-Real-IP"]; //Nginx 為前端時獲得IP地址的辦法
   if (result != null)
    return result;

   if (HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"] != null)//收回要求的長途主機的IP地址
   {
    result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"].ToString();
   }
   else if (HttpContext.Current.Request.ServerVariables["HTTP_VIA"] != null)//斷定能否設置署理,若應用了署理
   {
    if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null)//獲得署理辦事器的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對稱加密 

 /// <summary>
 /// 對稱加密類
 /// </summary>
 public class AES
 {
  /// <summary>
  /// 解密
  /// </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>
  /// 解密
  /// </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>
  /// 加密
  /// </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>
  /// 加密
  /// </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贊助類 

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>
  /// 設置域的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轉換成實體類

 /// <summary>
 /// #region DataTable轉換成實體類
 /// </summary>
 /// <typeparam name="T"></typeparam>
 public class ModelUtil<T> where T : new()
 {

  /// <summary>
  /// 填充對象列表:用DataSet的第一個表填充分體類
  /// </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> 
  /// 填充對象列表:用DataSet的第index個表填充分體類
  /// </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> 
  /// 填充對象列表:用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);
      }
      catch
      {
      }
    }

    modelList.Add(model);
   }
   return modelList;
  }

  /// <summary> 
  /// 填充對象:用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>
  /// 實體類轉換成DataSet
  /// </summary>
  /// <param name="modelList">實體類列表</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>
  /// 實體類轉換成DataTable
  /// </summary>
  /// <param name="modelList">實體類列表</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>
  /// 依據實體類獲得表構造
  /// </summary>
  /// <param name="model">實體類</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>
  /// 將DataTable以轉為List與Dictionary嵌套聚集保留
  /// </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>
  /// 要求的request的內容轉換為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);//這一步很主要,用於類型轉換
      else
       pi.SetValue(t, value, null);
     }
     catch
     { }
    }
   }

   return t;
  }


 }

9.SQL Server數據庫拜訪類 

 /// <summary>
 /// SQL Server數據庫拜訪類
 /// </summary>
 public abstract class SqlHelper
 {
  //讀取設置裝備擺設文件裡的數據庫銜接字符串
  public static readonly string connStr = ConfigurationManager.ConnectionStrings["Conn"].ConnectionString;

  //空結構
  public SqlHelper() { }

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

  /// <summary>
  /// 履行增刪改【經常使用】
  /// </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();   //清空參數
    return val;
   }
  }

  /// <summary>
  /// 履行增刪改(對現有的數據庫銜接)【不經常使用】
  /// </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>
  /// 履行多條sql語句(List泛型聚集)【事務】(無參數)
  /// </summary>
  /// <param name="connectionString">數據庫銜接字符串</param>
  /// <param name="listSql">包括多條sql語句的泛型聚集</param>
  /// <returns>受影響行數</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>
  /// 履行多條sql語句(Hashtable)【事務】(帶一組參數,一個參數也得封裝成組)
  /// </summary>
  /// <param name="connectionString">數據庫銜接字符串</param>
  /// <param name="sqlStringList">Hashtable表,鍵值對情勢</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(); //要履行的sql語句
       SqlParameter[] cmdParas = (SqlParameter[])item.Value; //sql語句對應的參數
       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>
  /// 前往DataReader對象
  /// </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>
  /// 前往第一行第一列信息(能夠是字符串 所以前往類型是object)【經常使用】
  /// </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>
  /// 前往第一行第一列信息(針對現有的數據庫銜接)【不經常使用】
  /// </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>
  /// 前往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>
  /// 前往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>
  /// 預備一個待履行的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;  //這裡設置履行的是T-Sql語句照樣存儲進程

    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; //拔出或修正時,假如有參數是空字符串,那末以NULL的情勢拔出數據庫
      cmd.Parameters.Add(paras[i]);
     }
    }
   }
   catch (Exception ex)
   {
    throw new Exception(ex.Message);
   }
  }

  /// <summary>
  /// 通用分頁存儲進程,有前提查詢,有排序字段,依照排序字段的降序分列
  /// </summary>
  /// <param name="PageSize">每頁記載數</param>
  /// <param name="CurrentCount">以後記載數目(頁碼*每頁記載數)</param>
  /// <param name="TableName">表稱號</param>
  /// <param name="Where">查詢前提,例:"ID>1000 AND Name like '%LiLinFeng%'" 排序前提,直接在前面加,例:" ORDER BY ID DESC,NAME ASC"</param>
  /// <param name="TotalCount">記載總數</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.日記文件記載 

 public class WriteLog
 {
  /// <summary>
  /// 
  /// </summary>
  /// <param name="fileName">文件名</param>
  /// <param name="ex"></param>
  public static void WriteErorrLog(string fileName, Exception ex)
  {
   if (ex == null) return; //ex = null 前往 
   DateTime dt = DateTime.Now; // 設置日記時光 
   string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 時:分:秒 
   string logName = dt.ToString("yyyy-MM-dd"); //日記稱號 
   string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日記寄存途徑 
   string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //途徑 + 稱號
   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("異常信息:" + ex);
     write.WriteLine("異常客棧:" + ex.StackTrace);
     write.WriteLine("異常簡述:" + ex.Message);
     write.WriteLine("\r\n----------------------------------\r\n");
     write.Flush();
     write.Close();
     write.Dispose();
    }
   }
   catch { }
  }

  /// <summary>
  /// 
  /// </summary>
  /// <param name="fileName">文件名</param>
  /// <param name="message"></param>
  public static void WriteMessage(string fileName, string message)
  {
   //ex = null 前往 
   DateTime dt = DateTime.Now; // 設置日記時光 
   string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 時:分:秒 
   string logName = dt.ToString("yyyy-MM-dd"); //日記稱號 
   string logPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, Path.Combine("log", fileName)); //日記寄存途徑 
   string log = Path.Combine(logPath, string.Format("{0}.log", logName)); //途徑 + 稱號
   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("信息:" + 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 前往 
   DateTime dt = DateTime.Now; // 設置日記時光 
   string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 時:分:秒 
   string logName = dt.ToString("yyyy-MM-dd"); //日記稱號 
   string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日記寄存途徑 
   string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //途徑 + 稱號
   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("異常信息:" + ex);
     write.WriteLine("異常客棧:" + ex.StackTrace);
     write.WriteLine("異常簡述:" + message);
     write.WriteLine("\r\n----------------------------------\r\n");
     write.Flush();
     write.Close();
     write.Dispose();
    }
   }
   catch { }
  }

  public static void WriteMessage(string message)
  {
   //ex = null 前往 
   DateTime dt = DateTime.Now; // 設置日記時光 
   string time = dt.ToString("yyyy-MM-dd HH:mm:ss"); //年-月-日 時:分:秒 
   string logName = dt.ToString("yyyy-MM-dd"); //日記稱號 
   string logPath = System.AppDomain.CurrentDomain.BaseDirectory; //日記寄存途徑 
   string log = Path.Combine(Path.Combine(logPath, "log"), string.Format("{0}.log", logName)); //途徑 + 稱號
   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("信息:" + message);
     write.WriteLine("\r\n----------------------------------\r\n");
     write.Flush();
     write.Close();
     write.Dispose();
    }
   }
   catch { }
  }
 }

11.JSON贊助類 

 /// <summary>
 /// JSON贊助類
 /// </summary>
 public class JsonHelper
 {
  #region 通用辦法
  /// <summary>
  /// 格局化字符型、日期型、布爾型
  /// </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>
  /// 過濾字符串
  /// </summary>
  public static string StringFilter(string str)
  {
   StringBuilder 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>
  /// 列轉json
  /// </summary>
  /// <param name="dt">表</param>
  /// <param name="r">列</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 對象轉json
  /// <summary>
  /// 對象轉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轉json
  /// <summary>
  /// list轉json
  /// </summary>
  public static string ListToJson<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 StringBuilder();
   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();
  }
  #endregion

  #region 對象聚集轉換為json
  /// <summary>
  /// 對象聚集轉換為json
  /// </summary>
  /// <param name="array">對象聚集</param>
  /// <returns>json字符串</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 通俗聚集轉換Json
  /// <summary> 
  /// 通俗聚集轉換Json 
  /// </summary> 
  /// <param name="array">聚集對象</param> 
  /// <returns>Json字符串</returns> 
  public static string ToArrayString(IEnumerable array)
  {
   string jsonString = "[";
   foreach (object item in array)
   {
    jsonString = ToJson(item.ToString()) + ",";
   }
   jsonString.Remove(jsonString.Length - 1, jsonString.Length);
   return jsonString + "]";
  }
  #endregion

  #region DataSet轉換為Json
  /// <summary> 
  /// DataSet轉換為Json 
  /// </summary> 
  /// <param name="dataSet">DataSet對象</param> 
  /// <returns>Json字符串</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轉換為Json
  /// <summary>  
  /// Datatable轉換為Json  
  /// </summary> 
  public 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轉換為Json
  /// </summary> 
  public static string ToJson(DataTable dt, string 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轉換為Json
  /// <summary>  
  /// DataReader轉換為Json  
  /// </summary>  
  /// <param name="dataReader">DataReader對象</param>  
  /// <returns>Json字符串</returns> 
  public static 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 前往毛病
  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.轉換贊助類
 


 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((decimal)(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.WordStr(",", "");
    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 time;
   if (DateTime.TryParse(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 (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 time = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(0x7b2, 1, 1));
   long ticks = long.Parse(timeStamp + "0000000");
   TimeSpan span = new TimeSpan(ticks);
   return time.Add(span);
  }
 } 

以上就是本文的全體內容,願望對年夜家的進修有所贊助,也願望年夜家多多支撐。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved