完整代码:

using System;
using System.Collections.Specialized;
using System.IO;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;
using System.Reflection;
using System.ComponentModel; namespace DBUtility
{
public class DButility
{
private static Random ran = new Random();
private static readonly int TIMEOUT = ;
#region DBNull类型转换
public static long ToInt64(object value)
{
return (Convert.IsDBNull(value)) ? : Convert.ToInt64(value);
} public static int ToInt32(object value)
{
return (Convert.IsDBNull(value)) ? : Convert.ToInt32(value);
} public static short ToInt16(object value)
{
return (Convert.IsDBNull(value)) ? (short) : Convert.ToInt16(value);
} public static string ToString(object value)
{
return value.ToString();
} public static decimal ToDecimal(object value)
{
return (Convert.IsDBNull(value)) ? : Convert.ToDecimal(value);
} public static DateTime ToDateTime(object value)
{
return (Convert.IsDBNull(value)) ? DateTime.MinValue : Convert.ToDateTime(value);
}
#endregion #region AES 加密/解密
/// <summary>
/// AES 加密
/// </summary>
/// <param name="str">明文(待加密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesEncryptToHex(string str, string key)
{
if (string.IsNullOrEmpty(str)) return null;
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(str); //命名空间: using System.Text; System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = System.Security.Cryptography.CipherMode.ECB,
Padding = System.Security.Cryptography.PaddingMode.PKCS7
}; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length); var hex = BitConverter.ToString(resultArray, ).Replace("-", string.Empty).ToLower();
return hex;
} /// <summary>
/// AES 解密
/// </summary>
/// <param name="str">明文(待解密)</param>
/// <param name="key">密文</param>
/// <returns></returns>
public static string AesDecryptFromHex(string str, string key)
{
if (string.IsNullOrEmpty(str)) return null;
var toEncryptArray = new byte[str.Length / ];
for (var x = ; x < toEncryptArray.Length; x++)
{
var i = Convert.ToInt32(str.Substring(x * , ), );
toEncryptArray[x] = (byte)i;
} //Byte[] toEncryptArray = Convert.FromBase64String(str); System.Security.Cryptography.RijndaelManaged rm = new System.Security.Cryptography.RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(key),
Mode = System.Security.Cryptography.CipherMode.ECB,
Padding = System.Security.Cryptography.PaddingMode.PKCS7
}; System.Security.Cryptography.ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, , toEncryptArray.Length); return Encoding.UTF8.GetString(resultArray);
}
#endregion #region 获取时间戳,取随机数
/// <summary>
/// 获取时间戳
/// </summary>
/// <returns></returns>
public static long GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(, , , , , , );
return Convert.ToInt64(ts.TotalSeconds);
} /// <summary>
/// 取随机数
/// </summary>
/// <param name="min"></param>
/// <param name="max"></param>
/// <returns></returns>
public static int GetRandom(int min, int max)
{
return ran.Next(min, max);
} /// <summary>
/// 获取当前本地时间戳
/// </summary>
/// <returns></returns>
public static long GetCurrentTimeUnix()
{
TimeSpan cha = (DateTime.Now - TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(, , )));
long t = (long)cha.TotalSeconds;
return t;
} /// <summary>
/// 时间戳转换为本地时间对象
/// </summary>
/// <returns></returns>
public static DateTime GetUnixDateTime(long unix)
{
//long unix = 1500863191;
DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(, , ));
DateTime newTime = dtStart.AddSeconds(unix);
return newTime;
} /// <summary>
/// Unicode转字符串
/// </summary>
/// <param name="source">经过Unicode编码的字符串</param>
/// <returns>正常字符串</returns>
public static string UnicodeToString(string source)
{
return new Regex(@"\\u([0-9A-F]{4})", RegexOptions.IgnoreCase | RegexOptions.Compiled).Replace(
source, x => string.Empty + Convert.ToChar(Convert.ToUInt16(x.Result("$1"), )));
} /// <summary>
/// Stream流转化为字符串
/// </summary>
/// <returns></returns>
public static string StreamToString(Stream stream)
{
if (stream == null || stream.Length == )
{
return string.Empty;
}
StreamReader sr = new StreamReader(stream);
return sr.ReadToEnd();
} /// <summary>
/// RequestForm转换成String, key=value格式
/// </summary>
/// <returns></returns>
public static string RequestFormToString(NameValueCollection form)
{
if (form == null)
{
return null;
} string strTemp = string.Empty; String[] requestItem = form.AllKeys;
for (int i = ; i < requestItem.Length; i++)
{
strTemp += requestItem[i] + "=" + form[requestItem[i]] + "&";
} strTemp = strTemp.TrimEnd('&');
return strTemp;
}
#endregion #region HttpUtils public static string HttpPost(string Url, string mobiles, string content)
{
string postData = string.Format("mobiles={0}&content={1}", mobiles, content); HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url);
System.Net.ServicePointManager.DefaultConnectionLimit = ;
request.Method = "POST";
request.KeepAlive = false;
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = Encoding.UTF8.GetByteCount(postData);
Stream myRequestStream = request.GetRequestStream();
StreamWriter myStreamWriter = new StreamWriter(myRequestStream, Encoding.GetEncoding("gb2312"));
myStreamWriter.Write(postData, , postData.Length);
myStreamWriter.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close(); myResponseStream.Close(); response = null;
request = null;
return retString;
} /// <summary>
/// 指定Post地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Post(string url, Dictionary<string, string> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string mobiles = dic["mobiles"];
string content = dic["content"];
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
#region 添加Post 参数
StringBuilder builder = new StringBuilder();
int i = ;
foreach (var item in dic)
{
if (i > )
builder.Append("&");
builder.AppendFormat("{0}={1}", item.Key, item.Value);
i++;
}
byte[] data = Encoding.UTF8.GetBytes(builder.ToString());
req.ContentLength = data.Length;
using (Stream reqStream = req.GetRequestStream())
{
reqStream.Write(data, , data.Length);
reqStream.Close();
}
#endregion
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
} /// <summary>
/// 指定地址使用Get 方式获取全部字符串
/// </summary>
/// <param name="url">请求后台地址</param>
/// <returns></returns>
public static string Get(string url, Dictionary<string, string> dic)
{
string result = "";
HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
string uname = dic["username"];
string pwd = dic["password"];
req.Method = "GET";
req.ContentType = "application/x-www-form-urlencoded";
HttpWebResponse resp = (HttpWebResponse)req.GetResponse();
Stream stream = resp.GetResponseStream();
//获取响应内容
using (StreamReader reader = new StreamReader(stream, Encoding.UTF8))
{
result = reader.ReadToEnd();
}
return result;
} public static string PostSend(string url, string param)
{
return PostSend(url, "UTF-8", param);
} public static string PostSend(string url, string encoding, string param, string contentType = "application/x-www-form-urlencoded")
{
try
{
byte[] postData = Encoding.UTF8.GetBytes(param); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
Encoding myEncoding = Encoding.UTF8;
request.Method = "POST";
request.KeepAlive = false;
request.AllowAutoRedirect = true;
request.ContentType = contentType;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
request.ContentLength = postData.Length;
request.Timeout = TIMEOUT; System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, , postData.Length);
outputStream.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); string retVal = reader.ReadToEnd(); reader.Close(); return retVal;
}
catch (Exception ex)
{
LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message);
return ex.Message;
}
} public static string PostSendWithCert(string url, string param)
{
return PostSendWithCert(url, "UTF-8", param);
} public static string PostSendWithCert(string url, string encoding, string param, string contentType = "application/x-www-form-urlencoded")
{
try
{
string cert = System.Configuration.ConfigurationManager.AppSettings["CertPath"];
string password = System.Configuration.ConfigurationManager.AppSettings["xcxMchId"];
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
X509Certificate2 cer = new X509Certificate2(cert, password, X509KeyStorageFlags.PersistKeySet | X509KeyStorageFlags.MachineKeySet); byte[] postData = Encoding.UTF8.GetBytes(param); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
Encoding myEncoding = Encoding.UTF8;
request.ClientCertificates.Add(cer);
request.Method = "POST";
request.KeepAlive = false;
request.AllowAutoRedirect = true;
request.ContentType = contentType;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
request.ContentLength = postData.Length;
request.Timeout = TIMEOUT; System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, , postData.Length);
outputStream.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); StreamReader reader = new System.IO.StreamReader(responseStream, Encoding.GetEncoding("UTF-8")); string retVal = reader.ReadToEnd(); reader.Close(); return retVal;
}
catch (Exception ex)
{
LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message);
return ex.Message;
}
} /// <summary>
/// 发请求获取图片到本地路径
/// </summary>
/// <param name="url"></param>
/// <param name="param"></param>
/// <param name="pathName"></param>
/// <param name="contentType"></param>
public static void PostSaveToFile(string url, string param, string pathName, string contentType = "application/x-www-form-urlencoded")
{
try
{
byte[] postData = Encoding.UTF8.GetBytes(param); HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
Encoding myEncoding = Encoding.UTF8;
request.Method = "POST";
request.KeepAlive = false;
request.AllowAutoRedirect = true;
request.ContentType = contentType;
request.UserAgent = "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 3.0.04506.648; .NET CLR 3.5.21022; .NET CLR 3.0.4506.2152; .NET CLR 3.5.30729)";
request.ContentLength = postData.Length;
request.Timeout = TIMEOUT; System.IO.Stream outputStream = request.GetRequestStream();
outputStream.Write(postData, , postData.Length);
outputStream.Close(); HttpWebResponse response = request.GetResponse() as HttpWebResponse; Stream responseStream = response.GetResponseStream(); System.Drawing.Image.FromStream(responseStream).Save(pathName);
}
catch (Exception ex)
{
LogHelper.Error("PostSend [url:]" + url + " [params:]" + param + " [error:]" + ex.Message);
}
} public static string HttpGet(string Url, string postDataStr = "")
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url + (postDataStr == "" ? "" : "?") + postDataStr);
// https
if (Url.StartsWith("https", StringComparison.OrdinalIgnoreCase))
{
ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(CheckValidationResult);
request.ProtocolVersion = HttpVersion.Version10;
} request.Method = "GET";
request.ContentType = "text/html;charset=UTF-8";
request.Timeout = ; HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream myResponseStream = response.GetResponseStream();
StreamReader myStreamReader = new StreamReader(myResponseStream, Encoding.GetEncoding("utf-8"));
string retString = myStreamReader.ReadToEnd();
myStreamReader.Close();
myResponseStream.Close(); return retString;
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
} private static bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
{
return true; //总是接受
}
#endregion #region MD5加密 /// <summary>
///
/// </summary>
/// <param name="sDataIn"></param>
/// <param name="move">给空即可</param>
/// <returns></returns>
public static string GetMD532(string sDataIn, string move)
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] bytValue, bytHash;
bytValue = System.Text.Encoding.UTF8.GetBytes(move + sDataIn);
bytHash = md5.ComputeHash(bytValue);
md5.Clear();
string sTemp = "";
for (int i = ; i < bytHash.Length; i++)
{
sTemp += bytHash[i].ToString("x").PadLeft(, '');
}
return sTemp;
} public static string GetMD516(string ConvertString)
{
System.Security.Cryptography.MD5CryptoServiceProvider md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), , );
t2 = t2.Replace("-", ""); t2 = t2.ToLower(); return t2;
}
#endregion
}
#region log4net 日志类
public class LogHelper
{
//在 <configuration></configuration>里面添加下面配置 // <configSections>
// <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
//</configSections> // <log4net>
// <logger name="logerror">
// <level value="ERROR"/>
// <appender-ref ref="ErrorAppender"/>
// </logger>
// <logger name="loginfo">
// <level value="INFO"/>
// <appender-ref ref="InfoAppender"/>
// </logger>
// <appender name="ErrorAppender" type="log4net.Appender.RollingFileAppender">
// <param name="File" value="Log\Error\"/>
// <param name="AppendToFile" value="true"/>
// <param name="CountDirection" value="-1"/>
// <param name="MaxSizeRollBackups" value="15"/>
// <param name="MaximumFileSize" value="5MB"/>
// <param name="lockingModel" type="log4net.Appender.FileAppender+MinimalLock"/>
// <rollingStyle value="Date"/>
// <datePattern value="yyyyMMdd'.txt'"/>
// <staticLogFileName value="false"/>
// <layout type="log4net.Layout.PatternLayout">
// <conversionPattern value="%d [%t]%c %m%n"/>
// </layout>
// </appender>
// <appender name="InfoAppender" type="log4net.Appender.RollingFileAppender">
// <param name="File" value="Log\Info\"/>
// <param name="AppendToFile" value="true"/>
// <param name="CountDirection" value="-1"/>
// <param name="MaxSizeRollBackups" value="15"/>
// <param name="MaximumFileSize" value="5MB"/>
// <param name="lockingModel" type="log4net.Appender.FileAppender+MinimalLock"/>
// <rollingStyle value="Date"/>
// <datePattern value="yyyyMMdd'.txt'"/>
// <staticLogFileName value="false"/>
// <layout type="log4net.Layout.PatternLayout">
// <conversionPattern value="%d [%t]%c %m%n"/>
// </layout>
// </appender>
//</log4net> private static readonly log4net.ILog ILogInfo = log4net.LogManager.GetLogger("loginfo"); //添加log4net 引用 public static readonly log4net.ILog ILogError = log4net.LogManager.GetLogger("logerror"); public static void Info(string msg)
{
ILogInfo.Info(msg);
} public static void Error(string msg)
{
ILogError.Error(msg);
} /// <summary>
/// 废弃 改用FileNameError
/// </summary>
/// <param name="type"></param>
/// <param name="msg"></param>
public static void TypeError(string type, string msg)
{
// eg: type=Order, msg=数据库更新失败, OrderId:111222333
// msg:[Order] 数据库更新失败, OrderId:111222333
ILogError.Error("[" + type + "] " + msg);
} public static void FileNameInfo(string fileName, string msg)
{
ILogInfo.Info(fileName + " " + msg);
} public static void FileNameError(string fileName, string msg)
{
ILogError.Error(fileName + " " + msg);
}
}
#endregion #region DataTable,DataSet,list集合 互转
public class ModelHandler<T> where T : new()
{
#region DataSet=>List
/// <summary>
/// 填充对象列表:用DataSet的第一个表填充实体类
/// </summary>
/// <param name="ds">DataSet</param>
/// <returns></returns>
public List<T> FillModelByDataSet(DataSet ds)
{
if (ds == null || ds.Tables[] == null || ds.Tables[].Rows.Count == )
{
return null;
}
else
{
return FillModelByDataTable(ds.Tables[]);
}
}
#endregion #region DataTable=>List #region /// <summary>
/// 类型枚举
/// </summary>
private enum ModelType
{
//值类型
Struct, Enum, //引用类型
String, Object,
Else
} private static ModelType GetModelType(Type modelType)
{
//值类型
if (modelType.IsEnum)
{
return ModelType.Enum;
}
//值类型
if (modelType.IsValueType)
{
return ModelType.Struct;
}
//引用类型 特殊类型处理
if (modelType == typeof(string))
{
return ModelType.String;
}
//引用类型 特殊类型处理
return modelType == typeof(object) ? ModelType.Object : ModelType.Else;
} #endregion /// <summary>
/// 填充对象列表:用DataTable填充实体类
/// </summary>
public List<T> FillModelByDataTable(DataTable dt)
{
if (dt == null || dt.Rows.Count == )
{
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 = ; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (propertyInfo != null && dr[i] != DBNull.Value)
propertyInfo.SetValue(model, dr[i], null);
} modelList.Add(model);
}
return modelList;
} /// <summary>
/// datatable转换为List<T>集合
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="table"></param>
/// <returns></returns>
public static List<T> DataTableToList<T>(DataTable table)
{
var list = new List<T>();
foreach (DataRow item in table.Rows)
{
list.Add(DataRowToModel<T>(item));
}
return list;
}
#endregion #region DataRow=>Model
/// <summary>
/// 填充对象:用DataRow填充实体类
/// </summary>
public T FillModelByDataRow(DataRow dr)
{
if (dr == null)
{
return default(T);
} //T model = (T)Activator.CreateInstance(typeof(T));
T model = new T(); for (int i = ; i < dr.Table.Columns.Count; i++)
{
PropertyInfo propertyInfo = model.GetType().GetProperty(dr.Table.Columns[i].ColumnName);
if (propertyInfo != null && dr[i] != DBNull.Value)
propertyInfo.SetValue(model, dr[i], null);
}
return model;
} public static T DataRowToModel<T>(DataRow row)
{
T model;
var type = typeof(T);
var modelType = GetModelType(type);
switch (modelType)
{
//值类型
case ModelType.Struct:
{
model = default(T);
if (row[] != null)
model = (T)row[];
}
break;
//值类型
case ModelType.Enum:
{
model = default(T);
if (row[] != null)
{
var fiType = row[].GetType();
if (fiType == typeof(int))
{
model = (T)row[];
}
else if (fiType == typeof(string))
{
model = (T)Enum.Parse(typeof(T), row[].ToString());
}
}
}
break;
//引用类型 c#对string也当做值类型处理
case ModelType.String:
{
model = default(T);
if (row[] != null)
model = (T)row[];
}
break;
//引用类型 直接返回第一行第一列的值
case ModelType.Object:
{
model = default(T);
if (row[] != null)
model = (T)row[];
}
break;
//引用类型
case ModelType.Else:
{
//引用类型 必须对泛型实例化
model = Activator.CreateInstance<T>();
//获取model中的属性
var modelPropertyInfos = type.GetProperties();
//遍历model每一个属性并赋值DataRow对应的列
foreach (var pi in modelPropertyInfos)
{
//获取属性名称
var name = pi.Name;
if (!row.Table.Columns.Contains(name) || row[name] == null || row[name] == DBNull.Value) continue;
var piType = GetModelType(pi.PropertyType);
switch (piType)
{
case ModelType.Struct:
{
object value;
if (!pi.PropertyType.Name.ToLower().Contains("nullable"))
value = Convert.ChangeType(row[name], pi.PropertyType);
else
value = new NullableConverter(pi.PropertyType).ConvertFromString(row[name].ToString());
pi.SetValue(model, value, null);
}
break; case ModelType.Enum:
{
var fiType = row[].GetType();
if (fiType == typeof(int))
{
pi.SetValue(model, row[name], null);
}
else if (fiType == typeof(string))
{
var value = (T)Enum.Parse(typeof(T), row[name].ToString());
if (value != null)
pi.SetValue(model, value, null);
}
}
break; case ModelType.String:
{
var value = Convert.ChangeType(row[name], pi.PropertyType);
pi.SetValue(model, value, null);
}
break; case ModelType.Object:
{
pi.SetValue(model, row[name], null);
}
break; case ModelType.Else:
throw new Exception("不支持该类型转换");
default:
throw new Exception("未知类型");
}
}
}
break; default:
model = default(T);
break;
}
return model;
} #endregion
}
#endregion #region SqlHelper
public class SqlHelper
{
/// <summary>
/// 从配置文件中读取数据库连接字符串
/// </summary>
public static string ConnectionString = ConfigurationManager.ConnectionStrings["constr"].ConnectionString; private static SqlConnection conn; #region 公共静态方法 /// <summary>
/// 填充DataTable
/// </summary>
/// <param name="spname">存储过程名</param>
/// <param name="sqlParams">参数集</param>
/// <returns>结果datatable</returns>
public static DataTable FillDataTable(string spname, params SqlParameter[] sqlParams)
{
conn = new SqlConnection(ConnectionString);
using (SqlDataAdapter adapter = new SqlDataAdapter(spname, conn))
{
adapter.SelectCommand.CommandType = CommandType.StoredProcedure;
if (sqlParams != null && sqlParams.Length > )
{
for (int i = ; i < sqlParams.Length; i++)
{
adapter.SelectCommand.Parameters.Add(sqlParams[i]);
}
}
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
} /// <summary>
/// 执行一条SQL的select语句,用返回的结果填充DataTable
/// </summary>
/// <param name="sql">要执行的SQL语句</param>
/// <param name="oParams">SQL语句中的参数</param>
/// <returns>已填充数据的DataTable</returns>
public static DataTable FillSqlDataTable(string sql, params SqlParameter[] oParams)
{
using (conn = new SqlConnection(ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
if (oParams != null && oParams.Length > )
{
foreach (SqlParameter prm in oParams)
{
adapter.SelectCommand.Parameters.Add(prm);
}
}
DataTable table = new DataTable();
adapter.Fill(table);
return table;
}
} /// <summary>
/// 执行一条存储过程,返回SqlDataReader
/// </summary>
/// <param name="spname">存储过程名称</param>
/// <param name="sqlParams">存储过程参数集合</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(string spname, params SqlParameter[] sqlParams)
{
return ExecuteReader(CommandType.StoredProcedure, spname, sqlParams);
} /// <summary>
/// 执行一条存储过程或SQL语句,返回SqlDataReader
/// </summary>
/// <param name="cmdText">SQL语句或存储过程名称</param>
/// <param name="sqlParams">SQL参数集合</param>
/// <returns>SqlDataReader</returns>
public static SqlDataReader ExecuteReader(CommandType cmdType, string cmdText, params SqlParameter[] sqlParams)
{
conn = new SqlConnection(ConnectionString);
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (sqlParams != null && sqlParams.Length > )
{
for (int i = ; i < sqlParams.Length; i++)
{
cmd.Parameters.Add(sqlParams[i]);
}
}
try
{
cmd.Connection.Open();
return cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
catch
{
cmd.Connection.Close();
throw;
}
}
} /// <summary>
/// 执行存储过程
/// </summary>
/// <param name="spname">存储过程名称</param>
/// <param name="sqlParams">存储过程参数集合</param>
/// <returns>受影响的记录行数</returns>
public static int ExecuteNonQuery(string spname, params SqlParameter[] sqlParams)
{
return ExecuteNonQuery(CommandType.StoredProcedure, spname, sqlParams);
} /// <summary>
/// 执行一条SQL语句,获取受SQL语句中delete、update和insert语句影响的行数
/// </summary>
/// <param name="sql">要执行的SQL语句</param>
/// <param name="oParams">SQL语句中的参数</param>
/// <returns>受SQL语句中delete、update和insert语句影响的行数</returns>
public static int ExecuteSqlNonQuery(string sql, params SqlParameter[] oParams)
{
using (conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
if (oParams != null && oParams.Length > )
{
foreach (SqlParameter prm in oParams)
{
cmd.Parameters.Add(prm);
}
}
int reslt = cmd.ExecuteNonQuery();
conn.Close();
return reslt;
}
} /// <summary>
/// 执行SQL语句或存储过程
/// </summary>
/// <param name="cmdType">执行类型:SQL语句或存储过程</param>
/// <param name="cmdText">要执行的SQL语句或存储过程名</param>
/// <param name="sqlParams">SQL参数集合</param>
/// <returns>受影响的记录行数</returns>
public static int ExecuteNonQuery(CommandType cmdType, string cmdText, params SqlParameter[] sqlParams)
{
conn = new SqlConnection(ConnectionString); using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (sqlParams != null && sqlParams.Length > )
{
for (int i = ; i < sqlParams.Length; i++)
{
cmd.Parameters.Add(sqlParams[i]);
}
}
conn.Open();
int j = cmd.ExecuteNonQuery();
conn.Close();
return j;
}
} /// <summary>
/// 执行SQL语句或存储过程返回第一行第一列的数据
/// </summary>
/// <param name="cmdType">执行类型:SQL语句或存储过程</param>
/// <param name="sqlParams">参数集</param>
/// <param name="cmdText">执行语句</param>
/// <returns>返回第一行第一列的数据</returns>
public static object ExecuteScalar(CommandType cmdType, string cmdText, params SqlParameter[] sqlParams)
{
conn = new SqlConnection(ConnectionString);
using (SqlCommand cmd = new SqlCommand(cmdText, conn))
{
cmd.CommandType = cmdType;
if (sqlParams != null && sqlParams.Length > )
{
for (int i = ; i < sqlParams.Length; i++)
{
cmd.Parameters.Add(sqlParams[i]);
}
}
conn.Open();
object obj = null;
try
{
obj = cmd.ExecuteScalar();
}
catch
{
conn.Close();
conn.Open();
obj = cmd.ExecuteScalar();
}
conn.Close();
return obj;
}
} /// <summary>
/// 执行存储过程,填充DataRow,若无数据则返回null
/// </summary>
/// <param name="spname">执行语句</param>
/// <param name="sqlParams">参数集</param>
/// <returns>返回DataRow</returns>
public static DataRow FillDataRow(string spname, params SqlParameter[] sqlParams)
{
DataTable table = FillDataTable(spname, sqlParams);
if (table.Rows.Count > )
return table.Rows[];
return null;
} /// <summary>
/// 向数据库中插入或更新数据时,设置存储过程参数
/// </summary>
/// <param name="pName">存储过程参数名</param>
/// <param name="pValue">参数值</param>
/// <returns>返回SqlParameter</returns>
public static SqlParameter SetParam(string pName, object pValue)
{
//如果pValue为null,则直接返回 2004-12-6
if (pValue == null)
return new SqlParameter(pName, pValue);
switch (Type.GetTypeCode(pValue.GetType()))
{
case TypeCode.String:
string tempStr = (string)pValue;
if (tempStr.Equals(null) || tempStr.Trim().Length.Equals())
{
return new SqlParameter(pName, DBNull.Value);
}
return new SqlParameter(pName, tempStr); case TypeCode.DateTime:
DateTime tempdt = (DateTime)pValue;
if (tempdt.Equals(DateTime.MinValue))
{
return new SqlParameter(pName, DBNull.Value);
}
return new SqlParameter(pName, tempdt); default:
return new SqlParameter(pName, pValue);
}
} /// <summary>
/// 获取SqlDataReader中指定字符串字段的值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">字段名</param>
/// <returns>字段值,若字段为空则返回空字符串</returns>
public static string GetStringFieldValue(SqlDataReader reader, string fieldName)
{
if (Convert.IsDBNull(reader[fieldName]))
{
return String.Empty;
}
return reader[fieldName].ToString();
} /// <summary>
/// 获取SqlDataReader中指定Int字段的值,若该字段为空则返回指定的替换值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">字段名</param>
/// <param name="replaceValue">要替换值为空的字段的值</param>
/// <returns>字段值,若该字段为空则返回replaceValue</returns>
public static int GetIntFieldValue(SqlDataReader reader, string fieldName, int replaceValue)
{
if (Convert.IsDBNull(reader[fieldName]))
{
return replaceValue;
}
object obj = reader[fieldName];
return Convert.ToInt32(reader[fieldName]);
} /// <summary>
/// 获取SqlDataReader中指定Int字段的值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">字段名</param>
/// <returns>字段值,若该字段为空则返回0</returns>
public static int GetIntFieldValue(SqlDataReader reader, string fieldName)
{
return GetIntFieldValue(reader, fieldName, );
} /// <summary>
/// 获取SqlDataReader中指定byte字段(SQL Server中为tinyint类型)的值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">要取值的字段名</param>
/// <returns>返回byte类型结果</returns>
public static byte GetByteFieldValue(SqlDataReader reader, string fieldName)
{
if (Convert.IsDBNull(reader[fieldName]))
return ;
return (byte)reader[fieldName];
} /// <summary>
/// 获取SqlDataReader中指定decimal字段的值,若该字段为空则返回指定的替换值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">要取值的字段名</param>
/// <param name="replaceValue">要替换值为空的字段的值</param>
/// <returns>返回double类型结果</returns>
public static Double GetDoubleFieldValue(SqlDataReader reader, string fieldName, Double replaceValue)
{
if (Convert.IsDBNull(reader[fieldName]))
return replaceValue;
return (Double)reader[fieldName];
} /// <summary>
/// 获取SqlDataReader中指定Int字段的值,若该字段为空则返回0
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">要取值的字段名</param>
/// <returns>返回double类型结果</returns>
public static Double GetDoubleFieldValue(SqlDataReader reader, string fieldName)
{
return GetDoubleFieldValue(reader, fieldName, );
} /// <summary>
/// 获取SqlDataReader中指定float字段的值,若该字段为空则返回0
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">要取值的字段名</param>
/// <returns>返回double类型结果</returns>
public static float GetFloatFieldValue(SqlDataReader reader, string fieldName)
{
return GetFloatFieldValue(reader, fieldName, );
} /// <summary>
/// 获取SqlDataReader中指定decimal字段的值,若该字段为空则返回指定的替换值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">要取值的字段名</param>
/// <param name="replaceValue">要替换值为空的字段的值</param>
/// <returns>返回double类型结果</returns>
public static float GetFloatFieldValue(SqlDataReader reader, string fieldName, float replaceValue)
{
if (Convert.IsDBNull(reader[fieldName]))
return replaceValue;
return float.Parse(reader[fieldName].ToString());
} /// <summary>
/// 获取SqlDataReader中指定Int字段的值,若该字段为空则返回DateTime的最小值
/// </summary>
/// <param name="reader">包含数据的SqlDataReader</param>
/// <param name="fieldName">要取值的字段名</param>
/// <returns>返回DateTime类型结果</returns>
public static DateTime GetDateTimeFieldValue(SqlDataReader reader, string fieldName)
{
if (Convert.IsDBNull(reader[fieldName]))
return DateTime.MinValue;
return (DateTime)reader[fieldName];
} #region 仅用于综合查询 /// <summary>
/// 执行查询语句,返回DataSet(zhaibl 09-11-04添加此方法)
/// </summary>
/// <param name="SQLString">查询语句</param>
/// <returns>DataSet</returns>
public static DataSet Query(string SQLString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
DataSet ds = new DataSet();
try
{
connection.Open();
SqlDataAdapter command = new SqlDataAdapter(SQLString, connection);
command.Fill(ds, "ds");
}
catch (System.Data.SqlClient.SqlException ex)
{
throw new Exception(ex.Message);
}
return ds;
}
} /// <summary>
/// 执行一条计算查询结果语句,返回查询结果(object)。
/// </summary>
/// <param name="SQLString">计算查询结果语句</param>
/// <returns>查询结果(object)</returns>
public static object GetSingle(string SQLString)
{
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
using (SqlCommand cmd = new SqlCommand(SQLString, connection))
{
try
{
connection.Open();
object obj = cmd.ExecuteScalar();
if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value)))
{
return null;
}
else
{
return obj;
}
}
catch (System.Data.SqlClient.SqlException e)
{
connection.Close();
throw new Exception(e.Message);
}
}
}
} /// <summary>
/// 填充数据集(执行带参的sql),返回DataSet
/// </summary>
/// <param name="sql">sql语句</param>
/// <param name="oParams">参数集</param>
/// <returns>datasat</returns>
public static DataSet FillDataSet(string sql, params SqlParameter[] oParams)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
if (oParams != null && oParams.Length > )
{
foreach (SqlParameter prm in oParams)
{
adapter.SelectCommand.Parameters.Add(prm);
}
}
DataSet ds = new DataSet();
adapter.Fill(ds);
return ds;
}
} /// <summary>
/// 执行一条SQL语句,获取受SQL语句中delete、update和insert语句影响的行数
/// </summary>
/// <param name="sql">要执行的SQL语句</param>
/// <param name="oParams">SQL语句中的参数</param>
/// <returns>受SQL语句中delete、update和insert语句影响的行数</returns>
public static int ExecuteSqlNonQuery1(string sql, params SqlParameter[] oParams)
{
int reslt = ;
try
{
using (conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddRange(oParams);
reslt = cmd.ExecuteNonQuery();
conn.Close();
}
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return reslt;
} /// <summary>
/// 获取查询结果
/// </summary>
/// <param name="sql">要执行的SQL语句</param>
/// <returns>DataTable</returns>
public static DataTable GetQueryResult(string sql)
{
DataTable tbl = new DataTable();
conn = new SqlConnection(ConnectionString);
using (SqlDataAdapter adapter = new SqlDataAdapter(sql, conn))
{
adapter.Fill(tbl);
}
conn.Close();
return tbl;
} #endregion 仅用于综合查询 #endregion 公共静态方法 #region 事务--Bao--2017-08-17 /// <summary>
/// 创建一个事务
/// </summary>
/// <returns></returns>
public static SqlTransaction CreateTrans()
{
conn = new SqlConnection(ConnectionString);
conn.Open();
return conn.BeginTransaction();
} /// <summary>
/// 关闭并释放与事务有关的资源
/// </summary>
/// <param name="trans"></param>
public static void CloseTrans(SqlTransaction trans)
{
if (trans == null) return; trans.Dispose(); if (conn == null || conn.State != ConnectionState.Open) return;
conn.Close();
conn.Dispose();
} /// <summary>
/// 执行一条不返回结果的SqlCommand,通过一个已经存在的数据库事物处理
/// 使用参数数组提供参数
/// </summary>
/// <param name="trans">一个存在的 sql 事物处理</param>
/// <param name="commandType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="commandText">存储过程的名字或者 T-SQL 语句</param>
/// <param name="sqlParams">以数组形式提供SqlCommand命令中用到的参数列表</param>
/// <returns>返回一个数值表示此SqlCommand命令执行后影响的行数</returns>
public static int ExecuteNonQuery(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] sqlParams)
{
if (trans == null) return ExecuteNonQuery(cmdType, cmdText, sqlParams); using (SqlCommand cmd = new SqlCommand())
{
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, sqlParams);
int val = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
return val;
}
} /// <summary>
/// 执行SQL语句或存储过程返回第一行第一列的数据
/// </summary>
/// <param name="trans">一个存在的 sql 事物处理</param>
/// <param name="cmdType">执行类型:SQL语句或存储过程</param>
/// <param name="sqlParams">参数集</param>
/// <param name="cmdText">执行语句</param>
/// <returns>返回第一行第一列的数据</returns>
public static object ExecuteScalar(SqlTransaction trans, CommandType cmdType, string cmdText, params SqlParameter[] sqlParams)
{
if (trans == null) return ExecuteScalar(cmdType, cmdText, sqlParams); using (SqlCommand cmd = new SqlCommand())
{
PrepareCommand(cmd, trans.Connection, trans, cmdType, cmdText, sqlParams);
object val = cmd.ExecuteScalar();
cmd.Parameters.Clear();
return val;
}
} /// <summary>
/// 为执行命令准备参数
/// </summary>
/// <param name="cmd">SqlCommand 命令</param>
/// <param name="conn">已经存在的数据库连接</param>
/// <param name="trans">数据库事物处理</param>
/// <param name="cmdType">SqlCommand命令类型 (存储过程, T-SQL语句, 等等。)</param>
/// <param name="cmdText">Command text,T-SQL语句 例如 Select * from Products</param>
/// <param name="cmdParms">返回带参数的命令</param>
private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms)
{
//判断数据库连接状态
if (conn.State != ConnectionState.Open)
conn.Open(); cmd.Connection = conn;
cmd.CommandText = cmdText; //判断是否需要事物处理
if (trans != null)
cmd.Transaction = trans; cmd.CommandType = cmdType; if (cmdParms != null)
{
foreach (SqlParameter parm in cmdParms)
cmd.Parameters.Add(parm);
}
} #endregion 事务--Bao--2017-08-17 public static void LogInfo(string msg)
{
string FilePath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "log\\";
if (!System.IO.Directory.Exists(FilePath))
{
System.IO.Directory.CreateDirectory(FilePath);
}
try
{
string fileName = FilePath + DateTime.Now.ToString("yyyyMMdd") + ".log";
var logStreamWriter = new System.IO.StreamWriter(fileName, true, Encoding.GetEncoding("gb2312")); logStreamWriter.WriteLine(msg);
logStreamWriter.Close();
}
catch
{ }
} #region 标准MD5加密
/// <summary>
/// MD5加密字符串
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Md5String(string str)
{
string pwd = String.Empty;
MD5 md5 = MD5.Create();
// 编码UTF8/Unicode 
byte[] s = md5.ComputeHash(Encoding.UTF8.GetBytes(str));
// 转换成字符串
for (int i = ; i < s.Length; i++)
{
//格式后的字符是小写的字母
//如果使用大写(X)则格式后的字符是大写字符
pwd = pwd + s[i].ToString("x2");
}
return pwd;
}
#endregion #region 分页 /// <summary>
/// 获取分页数据
/// </summary>
/// <param name="tableName">表名</param>
/// <param name="primaryKey">主键字段名</param>
/// <param name="pageIndex">页码</param>
/// <param name="pageSize">页尺寸</param>
/// <param name="isReCount">返回记录总数, 非 0 值则返回</param>
/// <param name="orderType">设置排序类型, 非 0 值则降序</param>
/// <param name="where">查询条件 (注意: 不要加 where)</param>
/// <param name="recount">返回记录总数</param>
/// <param name="pageCount">返回总页数</param>
/// <returns></returns>
public static DataTable GetPage(string tableName, string primaryKey, int pageIndex, int pageSize, int isReCount, int orderType, string where, out int recount, out int pageCount)
{
string procName = "SP_Page";
SqlParameter[] paras = new SqlParameter[]{
new SqlParameter("@Recount",SqlDbType.Int),
new SqlParameter("@PageCount",SqlDbType.Int),
new SqlParameter("@tblName",tableName),
new SqlParameter("@fldName",primaryKey),
new SqlParameter("@PageSize",pageSize),
new SqlParameter("@PageIndex",pageIndex),
new SqlParameter("@IsReCount",isReCount),
new SqlParameter("@OrderType",orderType),
new SqlParameter("@strWhere",where)
}; paras[].Direction = ParameterDirection.Output;
paras[].Direction = ParameterDirection.Output; DataTable dt = SqlHelper.FillDataTable(procName, paras); recount = int.Parse(paras[].Value.ToString());
pageCount = int.Parse(paras[].Value.ToString()); return dt;
} public static string newShowPageNavNew(int pageCurrent, int totalCount, int pageSize = , string methodName = "getlist")
{
var totalPage = Math.Max((totalCount + pageSize - ) / pageSize, );
//if (totalPage >= 1)
//{
//要输出的超链接字符串
var pageNav = new StringBuilder();
//左边代码
//无数据
if (totalCount == )
{
pageNav.AppendFormat("<div class='col-sm-4'><div class='dataTables_info' id='editable_info' role='alert' aria-live='polite' aria-relevant='all'>显示 0 项,共 0 项</div></div>");
}
else
{
//最后一页文件数量
if (pageCurrent == totalPage)
{
pageNav.AppendFormat("<div class='col-sm-4'><div class='dataTables_info' id='editable_info' role='alert' aria-live='polite' aria-relevant='all'>显示 " + ((pageCurrent - ) * pageSize + ) + " 到 " + totalCount + " 项,共 " + totalCount + " 项</div></div>");
}
else
{
pageNav.AppendFormat("<div class='col-sm-4'><div class='dataTables_info' id='editable_info' role='alert' aria-live='polite' aria-relevant='all'>显示 " + ((pageCurrent - ) * pageSize + ) + " 到 " + (pageCurrent * pageSize) + " 项,共 " + totalCount + " 项</div></div>");
}
} //右边代码
pageNav.AppendFormat("<div class='col-sm-8'><div class='dataTables_paginate paging_simple_numbers' id='editable_paginate'><ul class='pagination'>"); //如果当前是第一页,则“上一页”不可点
if (pageCurrent == )
{
pageNav.AppendFormat("<li class='paginate_button previous disabled' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)'>上一页</a></li>");
}
else
{
pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", pageCurrent - , pageSize, "上一页");
} //中间页码
if (pageCurrent <= )
{
for (int i = ; i < ; i++)
{
if (i <= totalPage)
{
if (pageCurrent == i) //当前页处理
{
pageNav.AppendFormat("<li class='paginate_button active' aria-controls='editable' tabindex='0'><a href='javascript:void(0)'>{0}</a></li>", pageCurrent);
}
else //一般页处理
{
pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", i, pageSize, i);
}
}
}
}
else if (pageCurrent > && pageCurrent < totalPage - )
{
int current = ;
for (int i = ; i < ; i++)
{
if ((pageCurrent + i - current) >= && (pageCurrent + i - current) <= totalPage)
{
if (current == i) //当前页处理
{
pageNav.AppendFormat("<li class='paginate_button active' aria-controls='editable' tabindex='0'><a href='javascript:void(0)'>{0}</a></li>", pageCurrent);
}
else //一般页处理
{
pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", pageCurrent + i - current, pageSize, pageCurrent + i - current);
}
}
} }
else
{
for (int i = totalPage - ; i <= totalPage; i++)
{
if (i <= totalPage && i > )
{
if (pageCurrent == i) //当前页处理
{
pageNav.AppendFormat("<li class='paginate_button active' aria-controls='editable' tabindex='0'><a href='javascript:void(0)'>{0}</a></li>", pageCurrent);
}
else //一般页处理
{
pageNav.AppendFormat("<li class='paginate_button previous' aria-controls='editable' tabindex='0' id='editable_previous'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", i, pageSize, i);
}
}
}
} //如果当前是最后一页,则“下一页”不可点
if (pageCurrent == totalPage)
{
pageNav.AppendFormat("<li class='paginate_button next disabled' aria-controls='editable' tabindex='0' id='editable_next'><a href='javascript:void(0)'>下一页</a></li>");
}
else
{
pageNav.AppendFormat("<li class='paginate_button next' aria-controls='editable' tabindex='0' id='editable_next'><a href='javascript:void(0)' onclick='" + methodName + "({0},{1})'>{2}</a></li>", pageCurrent + , pageSize, "下一页");
}
pageNav.AppendFormat("</ul></div></div>");
return pageNav.ToString();
//}
//else
//{
// return string.Empty;
//}
}
#endregion
}
#endregion
}

C# 最牛逼的Utility工具类的更多相关文章

  1. 最牛逼的任务调度工具 | Quartz

    Quartz 是一个完全由 Java 编写的开源作业调度框架,不要让作业调度这个术语吓着你,其实不难.尽管 Quartz 框架整合了许多额外功能,但就我们使用来说,你会发现它易用得简直让人受不了! 简 ...

  2. vim牛逼的code工具: ctags+ cscope

    自己总结 在我的工作目录里的.vimrc中做了这样的配置:   set tags=tags;   set autochdir 在项目根目录里利用"sudo ctags -R *", ...

  3. 玩转type类型(牛逼克拉斯 )

    一.前言 一说起type()方法肯定有很多人都知道这不就是查看某个对象类型的嘛,其实不然,他还有更牛逼的应用------创建类 >>> type(1) <class 'int' ...

  4. SNF开发平台WinForm-EasyQuery统计分析-效果-非常牛逼的报表查询工具

    无论是单轴曲线 .双轴曲线 .柱形图 .饼图 .雷达图 .仪表图.图表引擎全能为您轻松实现.您只需要 3 步操作(数据源准备,设计图表,挂接到您想要展示的位置)便可完成 BI 的设计. 无论是普通报表 ...

  5. 推荐 2 款超牛逼、炫酷、实用的Docker管理工具!

    Docker技术的火热程度,想必每个互联网IT技术人员都能时时感受的到,的确,近些年,国内对于Docker容器技术的应用需求越来越强烈!! 人均年薪80万以上,docker到底是什么?为什么这么火? ...

  6. 不推荐别的了,IDEA 自带的数据库工具就很牛逼!

    MySQL 等数据库客户端软件市面上非常多了,别的栈长就不介绍了, 其实 IntelliJ IDEA 自带的数据库工具就很牛逼,不信你继续往下看. 本文以 IntelliJ IDEA/ Mac 版本作 ...

  7. js深入研究之牛逼的类封装设计

    <script type="text/javascript"> var Book = function(newIsbn, newTitle, newAuthor) { ...

  8. C# 中那些常用的工具类(Utility Class)(二)

    今天按照这一年来经常用到的那些静态的工具类再来做一次总结,这些小的工具来可以作为自己学习的很好的例子,通过总结这些东西,能够很大程度上梳理自己的知识体系,当然这个是经常用到的,接下来就一个个去分析这些 ...

  9. Expo大作战(二十七)--expo sdk api之Util(expo自带工具类),tackSnapshotAsync,Svg,SQLite

    简要:本系列文章讲会对expo进行全面的介绍,本人从2017年6月份接触expo以来,对expo的研究断断续续,一路走来将近10个月,废话不多说,接下来你看到内容,讲全部来与官网 我猜去全部机翻+个人 ...

随机推荐

  1. 2019微信公开课 同行With Us 听课笔记及演讲全文

    [2019WeChat 微信公开课] 产品理念: 微信启动页 一个小人站在地球前面,每个人都有自己的理解和解读 所谓异类,表示与别人与众不同,即优秀的代名词. 微信的与众不同体现在尊重用户对产品的感受 ...

  2. 2019阿里P7最新总结Spring Boot面试问题

        Spring Boot一直是Spring生态系统的关键参与者.该项目通过其自动配置功能使我们的生活更加轻松.在本教程中,我们将介绍在求职面试中可能出现的一些与Spring Boot相关的最常见 ...

  3. Announcing the public preview of Azure Dev Spaces

    Today, we are excited to announce the public preview of Azure Dev Spaces, a cloud-native development ...

  4. Azure - Create your first function using Visual Studio

    Azure Functions lets you execute your code in a serverless environment without having to first creat ...

  5. poj3436(拆点最大流)

    题意:给你p和n,p代表每台计算器需要几个部分组成,n代表有几个组装机器,接下来n行,每行第一个数代表这台机器能够每小时组装几台,剩下前三个数字表示使用这台机器需要的前置条件(0代表当前组装不能有这个 ...

  6. BZOJ4817[Sdoi2017]树点涂色——LCT+线段树

    题目描述 Bob有一棵n个点的有根树,其中1号点是根节点.Bob在每个点上涂了颜色,并且每个点上的颜色不同.定义一条路 径的权值是:这条路径上的点(包括起点和终点)共有多少种不同的颜色.Bob可能会进 ...

  7. macOS 上编译 Dynamips

    Dynamips 是一个Cisco 路由器模拟软件. 安装过程: git clone git://github.com/GNS3/dynamips.git cd dynamips mkdir buil ...

  8. Vue+koa2开发一款全栈小程序(6.个人中心)

    1.用户信息的获取和展示 1.初始化数据库 cd到server目录下,执行 node tools/initdb.js 登录mysql控制界面,查看初始化以后生成的表 show databases; u ...

  9. Swagger - ui 学习

    今天同组的打伙伴给介绍了 Swagger-ui 这个 自动生成 接口文档的 工具,感觉比较方便好用, 遂决定 学习一下, 开个随笔进行随时记录,同时也是提醒自己 先保存两篇感觉还不错的文章 : htt ...

  10. Numpy系列(十)- 掩码数组

    简介 有时候数据集中存在缺失.异常或者无效的数值,我们可以标记该元素为被屏蔽(无效)状态. import numpy as np import numpy.ma as ma x = np.array( ...