From 28c4b9e4e2b8b983c8dba7305df7550e4979caa1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=AB=A5=E6=AF=93=E6=B3=BD?= <13204402429@stu.ecnu.edu.cn> Date: Sun, 17 Jan 2021 21:35:40 +0800 Subject: [PATCH] =?UTF-8?q?=E4=B8=8A=E4=BC=A0=E6=96=87=E4=BB=B6=E8=87=B3?= =?UTF-8?q?=20''?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- AccessToken2.cs | 18 + BasicPage.cs | 692 +++++++++++++++++++++++++++++++++ CacheHelper.cs | 66 ++++ CommandInfo.cs | 73 ++++ DBAcess.cs | 171 ++++++++ DESEncrypt.cs | 89 +++++ DbHelperSQL.cs | 1159 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ EnumsClass.cs | 48 +++ GetPage.cs | 149 +++++++ HuiyuanPage.cs | 77 ++++ Keys.cs | 50 +++ LoginState.cs | 82 ++++ Mail.cs | 59 +++ ManagePage.cs | 226 +++++++++++ PagingHelper.cs | 133 +++++++ QZCheck.cs | 54 +++ QZRequest.cs | 98 +++++ RequestClass.cs | 204 ++++++++++ SendInfo.cs | 147 +++++++ bpSeo.cs | 692 +++++++++++++++++++++++++++++++++ 20 files changed, 4287 insertions(+) create mode 100644 AccessToken2.cs create mode 100644 BasicPage.cs create mode 100644 CacheHelper.cs create mode 100644 CommandInfo.cs create mode 100644 DBAcess.cs create mode 100644 DESEncrypt.cs create mode 100644 DbHelperSQL.cs create mode 100644 EnumsClass.cs create mode 100644 GetPage.cs create mode 100644 HuiyuanPage.cs create mode 100644 Keys.cs create mode 100644 LoginState.cs create mode 100644 Mail.cs create mode 100644 ManagePage.cs create mode 100644 PagingHelper.cs create mode 100644 QZCheck.cs create mode 100644 QZRequest.cs create mode 100644 RequestClass.cs create mode 100644 SendInfo.cs create mode 100644 bpSeo.cs diff --git a/AccessToken2.cs b/AccessToken2.cs new file mode 100644 index 0000000..ab4f95d --- /dev/null +++ b/AccessToken2.cs @@ -0,0 +1,18 @@ +using System; +using System.Collections.Generic; +using System.Web; + +/// +/// AccessToken2 的摘要说明 +/// +public class AccessToken2 +{ + + public string access_token = ""; + public string expires_in = ""; + + public AccessToken2() + { + + } +} \ No newline at end of file diff --git a/BasicPage.cs b/BasicPage.cs new file mode 100644 index 0000000..9b415bf --- /dev/null +++ b/BasicPage.cs @@ -0,0 +1,692 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Management; //ڹ(project)УҼ +using System.DirectoryServices; //ڹ(project)УҼ +using Microsoft.JScript; //ȡű +using System.Diagnostics; //ٶȲ +using System.IO; + +/// +/// Summary description for BasicPage +/// +/// +namespace Basic +{ + public class BasicPage : System.Web.UI.Page + { + public string newString;//رȡַ + public string connstring; + public string strSql; + public SqlConnection myconn; + public SqlCommand mycommand; + public SqlDataReader myreader; + public SqlDataAdapter myadapter; + public DataSet ds; + public DataView dv; + public DataTable tzDataTable; + // + public string strTitle = null; + public string strDescription = null; + public string strKeys = null; + //ÿʼ + + public string strServer = System.Configuration.ConfigurationManager.AppSettings["Server"].ToString(); + public string strDatabase = System.Configuration.ConfigurationManager.AppSettings["Database"].ToString(); + public string strUid = System.Configuration.ConfigurationManager.AppSettings["UID"].ToString(); + public string strPwd = System.Configuration.ConfigurationManager.AppSettings["PWD"].ToString(); + + public void connection() + { + connstring = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(); + myconn = new SqlConnection(connstring); + } + public void dbOpen() + { + connection(); + myconn.Open(); + } + public void dbClose() + { + myconn.Close(); + } + public void MessageBox(string url, string message, int type) + { + if (type == 0) + { + System.Web.HttpContext.Current.Response.Write(""); + + } + else if (type == 1) + { + System.Web.HttpContext.Current.Response.Write(""); + } + } + /// + ///ݼDataSet + /// + /// + /// + /// + public DataSet SelectDataBase(string tableName, string tempStrSQL) + { + connection(); + ds = new DataSet(); + this.myadapter = new SqlDataAdapter(tempStrSQL, this.myconn); + this.myadapter.Fill(ds, tableName); + return ds; + } + /// + ///ݼDataTable + /// + /// + /// + /// + public DataTable SelectDataTable(string tempStrSQL) + { + connection(); + myconn.Open(); + SqlCommand cmd = new SqlCommand(tempStrSQL, this.myconn); + SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); + DataTable dt = new DataTable(); + dt.Load(reader); + reader.Dispose(); + return dt; + } + /// + /// ص + /// + /// + /// + public SqlDataReader getRead(string tempStrSql) + { + connection(); + SqlCommand mycommand = new SqlCommand(tempStrSql, myconn); + myconn.Open(); + SqlDataReader myreader = mycommand.ExecuteReader(CommandBehavior.CloseConnection); + return myreader; + } + /// + /// ִи² + /// + /// + /// + public bool doExecute(string tempStrSql) + { + connection(); + SqlCommand mycommand = new SqlCommand(tempStrSql, myconn); + myconn.Open(); + try + { + mycommand.ExecuteNonQuery(); + return true; + } + finally + { + mycommand.Dispose(); + myconn.Close(); + myconn.Dispose(); + } + } + /// + /// ȡַ + /// + /// + /// + /// + public string CutString(string str, int length) + { + if (str != "") + { + if (str.Length > length) + { + newString = str.Substring(0, length) + "..."; + } + else + { + newString = str; + } + } + return newString; + } + /// + /// ͻ˵Ļ + /// + public bool ClearClientPageCache() + { + HttpContext.Current.Response.Buffer = true; + HttpContext.Current.Response.Expires = 0; + HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); + HttpContext.Current.Response.AddHeader("pragma", "no-cache"); + HttpContext.Current.Response.AddHeader("cache-control", "private"); + HttpContext.Current.Response.CacheControl = "no-cache"; + return true; + } + /// + /// Jmail4.3FSOıд + /// + /// + /// + public bool IsObjInstalled(string _obj) + { + bool IsFSOInstalled = false; + try + { + Server.CreateObject(_obj); + IsFSOInstalled = true; + + } + catch (Exception ex) + { + IsFSOInstalled = false; + } + return IsFSOInstalled; + } + /// + /// ȡű + /// + /// + public string JiaoBenYinqing() + { + return GlobalObject.ScriptEngine() + "/" + GlobalObject.ScriptEngineMajorVersion() + "." + GlobalObject.ScriptEngineMinorVersion() + "." + GlobalObject.ScriptEngineBuildVersion(); + } + /// + /// ȡip + /// + /// + public string ServerIp() + { + string stringMAC = ""; + string stringIP = ""; + ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection MOC = MC.GetInstances(); + foreach (ManagementObject MO in MOC) + { + if ((bool)MO["IPEnabled"] == true) + { + stringMAC += MO["MACAddress"].ToString(); + //TextMAC.Text = stringMAC.ToString(); + string[] IPAddresses = (string[])MO["IPAddress"]; + if (IPAddresses.Length > 0) stringIP = IPAddresses[0]; + } + } + return stringIP; + } + /// + /// ȡϵͳ + /// + /// + public string ServerOS() + { + return System.Environment.OSVersion.ToString(); + } + /// + /// ٶȲ + /// + /// + public string IntTest() + { + string Value; + Stopwatch timer = new Stopwatch(); + long total = 0; + timer.Start(); + for (int i = 1; i <= 500000; i++) + { + total += i; + } + timer.Stop(); + decimal micro = timer.Elapsed.Ticks / 10m; + Value = "ԣڽ50μӷ......ɣ" + micro.ToString() + "΢" + ""; + return Value; + } + /// + /// ʵٶȲ + /// + /// + public string FloatTest() + { + string Value; + Stopwatch timer = new Stopwatch(); + long total = 0; + timer.Start(); + for (int i = 1; i <= 200000; i++) + { + total *= total; + } + timer.Stop(); + decimal micro = timer.Elapsed.Ticks / 10m; + Value = "ԣڽ20γ˷......ɣ" + micro.ToString() + "΢" + ""; + return Value; + } + /// + /// ݿ + /// + /// + /// + /// + /// + public string DbBackup(string strDbName, string strFileName, string strRname) + { + try + { + SQLDMO.Backup oBackup = new SQLDMO.BackupClass(); + SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass(); + oSQLServer.LoginSecure = false; + oSQLServer.Connect(strServer, strUid, strPwd); + oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database; + oBackup.Database = strDbName; + + string Path = strFileName + strRname; + oBackup.Files = Path; + oBackup.BackupSetName = strRname; + oBackup.BackupSetDescription = "ݿ"; + oBackup.Initialize = true; + oBackup.SQLBackup(oSQLServer); + oSQLServer.DisConnect(); + return "ok"; + } + catch (Exception ex) + { + return ex.Message; + } + } + /// + /// ԭݿ + /// + /// + /// + /// + /// + public bool DbRestore(string strDbName, string strFileName, string strRname) + { + strDbName = strDatabase; + strFileName = ""; + SQLDMO.Restore oRestore = new SQLDMO.RestoreClass(); + SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass(); + try + { + oSQLServer.LoginSecure = false; + oSQLServer.Connect(strServer, strUid, strPwd); + oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database; + oRestore.Database = strDbName; + oRestore.Files = strFileName + strRname; + oRestore.FileNumber = 1; + oRestore.ReplaceDatabase = true; + oRestore.SQLRestore(oSQLServer); + return true; + } + catch + { + return false; + } + } + /// + /// ȡϵͳʹ + /// + /// + public string readConame() + { + string strConame; + SqlDataReader Myreader; + Myreader = getRead("select webname from tbset where id=1"); + if (Myreader.Read()) + { + strConame = Myreader["webname"].ToString(); + } + else + { + strConame = "(Ƚϵͳ)"; + } + Myreader.Close(); + return strConame; + } + /// + /// ͳƷռռ + /// + /// + /// + public long GetDirectoryLength(string dirPath) + { + //жϸ·Ƿ,˳ + if (!Directory.Exists(dirPath)) + return 0; + long len = 0; + + //һDirectoryInfo + DirectoryInfo di = new DirectoryInfo(dirPath); + + //ͨGetFiles,ȡdiĿ¼еļĴС + foreach (FileInfo fi in di.GetFiles()) + { + len += fi.Length; + } + //ȡdiеļ,浽һµĶ,Խеݹ + DirectoryInfo[] dis = di.GetDirectories(); + if (dis.Length > 0) + { + for (int i = 0; i < dis.Length; i++) + { + len += GetDirectoryLength(dis[i].FullName); + } + } + return len; + } + /// + /// ҪIP + /// + /// + /// + public int lockip(string strAddIp) + { + int returnId = 0; + int intId = 1; + bool bsign = false; + string strIpGroup; + string strIp = strAddIp; + SqlDataReader myreader = getRead("select ip from TbIp where id=1"); + if (myreader.Read()) + { + string[] strIPzu = myreader["ip"].ToString().Split('|'); + for (int i = 0; i < strIPzu.Length; i++) + { + if (strIp == strIPzu[i]) + { + bsign = true; + } + } + strIpGroup = myreader["ip"].ToString(); + myreader.Close(); + if (bsign == false) + { + if (strIpGroup == "") + { + strIpGroup = strIp; + } + else + { + strIpGroup = strIpGroup + "|" + strIp; + } + if (doExecute("update tbIp set ip='" + strIpGroup + "' where id=1")) + { + //Response.Redirect("Success.aspx?message=IPɹ&url=IpManage.aspx"); + returnId = 1; + } + } + else if (bsign == true) + { + //Response.Redirect("Error.aspx?message=ʧܣIPѱ&url=IpManage.aspx"); + returnId = 2; + } + } + else + { + myreader.Close(); + if (doExecute("insert into tbIp(id,ip)values(" + intId + ",'" + strIp + "')")) + { + //Response.Redirect("Success.aspx?message=IPɹ&url=IpManage.aspx"); + returnId = 3; + } + } + return returnId; + } + /// + /// ʾIP + /// + /// + public string showLockIp() + { + string strIp = ""; + SqlDataReader myreader = getRead("select ip from tbIp where id=1"); + if (myreader.Read()) + { + strIp = myreader["ip"].ToString(); + } + myreader.Close(); + return strIp.Trim(); + } + /// + /// IPб + /// + /// + /// + public bool updateIp(string strIps) + { + bool sign = false; + SqlDataReader myreader = getRead("select * from tbIp where id=1"); + if (myreader.Read()) + { + if (doExecute("update tbIp set ip='" + strIps + "' where id=1")) + { + sign = true; + } + } + else + { + int id = 1; + if (doExecute("insert into tbIp(id,ip)values(" + id + ",'" + strIps + "')")) + { + sign = true; + } + } + myreader.Close(); + return sign; + } + /// + /// жǷرվ + /// + /// + public void ShowWebState() + { + string state = "1"; + SqlDataReader myreader = getRead("select state from TBset where id=1"); + if (myreader.Read()) + { + state = myreader["state"].ToString(); + if (state == "0") + { + System.Web.HttpContext.Current.Response.Write(""); + } + } + myreader.Close(); + } + /// + /// ȡTitle,Description,Keys + /// + public void showWebTitle() + { + int intId = 1; + SqlDataReader Myreader = getRead("select * from TBset where id=" + intId + ""); + if (Myreader.Read()) + { + strTitle = Myreader["webname"].ToString(); + strDescription = Myreader["webdescription"].ToString(); + strKeys = Myreader["webkeys"].ToString(); + } + Myreader.Close(); + StartProcessRequest();//ûǷ + ShowWebState();//жվǷر + } + /// + /// ûǷ + /// + /// + public static void StartProcessRequest() + { + try + { + string getkeys = ""; + //string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["CustomErrorPage"].ToString(); + if (System.Web.HttpContext.Current.Request.QueryString != null) + { + + for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++) + { + getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i]; + if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys], 0)) + { + //System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage+"?errmsg=sqlserver&sqlprocess=true"); + System.Web.HttpContext.Current.Response.Write(""); + System.Web.HttpContext.Current.Response.End(); + } + } + } + if (System.Web.HttpContext.Current.Request.Form != null) + { + for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++) + { + getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i]; + if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys], 1)) + { + //System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage+"?errmsg=sqlserver&sqlprocess=true"); + System.Web.HttpContext.Current.Response.Write(""); + System.Web.HttpContext.Current.Response.End(); + } + } + } + } + catch + { + // : ûύϢ! + } + } + /**/ + /// + /// ûǷ + /// + /// ûύ + /// ǷSQLעʽ + private static bool ProcessSqlStr(string Str, int type) + { + string SqlStr; + + if (type == 1) + SqlStr = "exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare"; + else + SqlStr = "'|and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare|>|<"; + + bool ReturnValue = true; + try + { + if (Str != "") + { + string[] anySqlStr = SqlStr.Split('|'); + foreach (string ss in anySqlStr) + { + if (Str.IndexOf(ss) >= 0) + { + ReturnValue = false; + } + } + } + } + catch + { + ReturnValue = false; + } + return ReturnValue; + } + /// + /// жǷ + /// + /// + /// bool + public bool IsNumberic(string oText)//жǷ + { + try + { + int var1 = System.Convert.ToInt32(oText); + if (var1 < 0) + { + return false; + } + return true; + } + catch + { + return false; + } + } + /// + /// ȡַ + /// + /// + /// + /// string + public string SubString(string inputString, int length) + { + if (Encoding.UTF8.GetByteCount(inputString) <= length * 2) + { + return inputString; + } + ASCIIEncoding ascii = new ASCIIEncoding(); + int tempLen = 0; + string tempString = ""; + byte[] s = ascii.GetBytes(inputString); + for (int i = 0; i < s.Length; i++) + { + if ((int)s[i] == 63) + { + tempLen += 2; + } + else + { + tempLen += 1; + } + tempString += inputString.Substring(i, 1); + if (tempLen >= (length - 1) * 2) + break; + } + //عϰʡԺ + if (System.Text.Encoding.Default.GetBytes(inputString).Length > length) + tempString += ""; + return tempString; + } + /// + /// ʾ¼״̬ + /// + public void ShowLoginState() + { + if (Session["j95fn3839vfn93h9n29n"] == null) + { + System.Web.HttpContext.Current.Response.Write(""); + } + } + #region JSʾ============================================ + + /// + /// ӱ༭ɾʾ + /// + /// ʾ + /// صַ + /// CSSʽ + public void JscriptMsg(string msgtitle, string url, string msgcss) + { + string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")"; + ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true); + } + + /// + /// شӱ༭ɾʾ + /// + /// ʾ + /// صַ + /// CSSʽ + /// JSص + public void JscriptMsg(string msgtitle, string url, string msgcss, string callback) + { + string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\", " + callback + ")"; + ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true); + } + #endregion + + + } +} diff --git a/CacheHelper.cs b/CacheHelper.cs new file mode 100644 index 0000000..c67d2b2 --- /dev/null +++ b/CacheHelper.cs @@ -0,0 +1,66 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.Caching; + +/// +///CacheHelper 的摘要说明 +/// +/// +namespace Basic +{ + public class CacheHelper + { + /// + /// 创建缓存项的文件依赖 + /// + /// 缓存Key + /// object对象 + /// 文件绝对路径 + public static void Insert(string key, object obj, string fileName) + { + //创建缓存依赖项 + CacheDependency dep = new CacheDependency(fileName); + //创建缓存 + HttpContext.Current.Cache.Insert(key, obj, dep); + } + + /// + /// 创建缓存项过期 + /// + /// 缓存Key + /// object对象 + /// 过期时间(分钟) + public static void Insert(string key, object obj, int expires) + { + HttpContext.Current.Cache.Insert(key, obj, null, Cache.NoAbsoluteExpiration, new TimeSpan(0, expires, 0)); + } + + /// + /// 获取缓存对象 + /// + /// 缓存Key + /// object对象 + public static object Get(string key) + { + if (string.IsNullOrEmpty(key)) + { + return null; + } + return HttpContext.Current.Cache.Get(key); + } + + /// + /// 获取缓存对象 + /// + /// T对象 + /// 缓存Key + /// + public static T Get(string key) + { + object obj = Get(key); + return obj == null ? default(T) : (T)obj; + } + } +} \ No newline at end of file diff --git a/CommandInfo.cs b/CommandInfo.cs new file mode 100644 index 0000000..ae39d3f --- /dev/null +++ b/CommandInfo.cs @@ -0,0 +1,73 @@ +using System; +using System.Collections.Generic; +using System.Text; +using System.Data.SqlClient; + +namespace Basic +{ + public enum EffentNextType + { + /// + /// 对其他语句无任何影响 + /// + None, + /// + /// 当前语句必须为"select count(1) from .."格式,如果存在则继续执行,不存在回滚事务 + /// + WhenHaveContine, + /// + /// 当前语句必须为"select count(1) from .."格式,如果不存在则继续执行,存在回滚事务 + /// + WhenNoHaveContine, + /// + /// 当前语句影响到的行数必须大于0,否则回滚事务 + /// + ExcuteEffectRows, + /// + /// 引发事件-当前语句必须为"select count(1) from .."格式,如果不存在则继续执行,存在回滚事务 + /// + SolicitationEvent + } + public class CommandInfo + { + public object ShareObject = null; + public object OriginalData = null; + event EventHandler _solicitationEvent; + public event EventHandler SolicitationEvent + { + add + { + _solicitationEvent += value; + } + remove + { + _solicitationEvent -= value; + } + } + public void OnSolicitationEvent() + { + if (_solicitationEvent != null) + { + _solicitationEvent(this, new EventArgs()); + } + } + public string CommandText; + public System.Data.Common.DbParameter[] Parameters; + public EffentNextType EffentNextType = EffentNextType.None; + public CommandInfo() + { + + } + public CommandInfo(string sqlText, SqlParameter[] para) + { + this.CommandText = sqlText; + this.Parameters = para; + } + public CommandInfo(string sqlText, SqlParameter[] para, EffentNextType type) + { + this.CommandText = sqlText; + this.Parameters = para; + this.EffentNextType = type; + } + } +} \ No newline at end of file diff --git a/DBAcess.cs b/DBAcess.cs new file mode 100644 index 0000000..3c7d36f --- /dev/null +++ b/DBAcess.cs @@ -0,0 +1,171 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Data; +using System.Data.SqlClient; +using System.Configuration; +using System.Text; + +/// +///DBacess 的摘要说明 +/// +namespace basic +{ + + public class DBacess + { + /// + /// 创建活动SqlConnection + /// + /// SqlConnection + /// + public static SqlConnection con; + private static SqlConnection connection() + { + SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString()); + con = conn; + return conn; + } + /// + /// 打开连接数据库 + /// + /// SqlConnection对象 + private void OpenConnection(SqlConnection conn) + { + if (conn != null && conn.State == ConnectionState.Closed) + conn.Open(); + } + + /// + /// 关闭数据库 + /// + /// SqlConnection对象 + private void CloseConnection(SqlConnection conn) + { + if (conn != null && conn.State == ConnectionState.Open) + conn.Close(); + } + /// + /// 更新数据库 + /// + /// + /// + /// + /// + public bool Update(string sql, SqlParameter[] parameters, CommandType type) + { + SqlConnection conn = connection(); + bool result = false; + try + { + using (conn) + { + SqlCommand cmd = new SqlCommand(sql, conn); + if (parameters != null) + { + foreach (SqlParameter parameter in parameters) + { + if (parameters != null && parameter.ParameterName != "") + { + cmd.Parameters.Add(parameter); + } + } + } + cmd.CommandType = type; + cmd.Connection.Open(); + int flag = cmd.ExecuteNonQuery(); + if (flag > 0) + result = true; + } + } + finally + { + CloseConnection(conn); + } + return result; + + } + /// + /// 根据条件查询数据 + /// + /// + /// + /// DataTable + public DataTable SelectReturnDataTable(string sql, SqlParameter[] parameters) + { + SqlConnection conn = connection(); + DataTable dt = new DataTable(); + try + { + using (conn) + { + SqlCommand cmd = new SqlCommand(sql, conn); + if (parameters != null) + { + foreach (SqlParameter parameter in parameters) + { + if (parameter != null && parameter.ParameterName != "") + { + cmd.Parameters.Add(parameter); + } + } + } + conn.Open(); + SqlDataAdapter sda = new SqlDataAdapter(cmd); + + sda.Fill(dt); + } + } + //catch (Exception e) + //{ + + //} + finally + { + CloseConnection(conn); + } + return dt; + } + /// + /// 根据条件查询数据 + /// + /// + /// + /// DataSet + public DataSet SelectReturnDataSet(string sql, SqlParameter[] parameters) + { + SqlConnection conn = connection(); + DataSet ds = new DataSet(); + try + { + using (conn) + { + SqlCommand cmd = new SqlCommand(sql, conn); + if (parameters != null) + { + foreach (SqlParameter parameter in parameters) + { + if (parameter != null && parameter.ParameterName != "") + { + cmd.Parameters.Add(parameter); + } + } + } + conn.Open(); + SqlDataAdapter sda = new SqlDataAdapter(cmd); + + sda.Fill(ds); + } + } + //catch (Exception e) + //{ + + //} + finally + { + CloseConnection(conn); + } + return ds; + } + } +} diff --git a/DESEncrypt.cs b/DESEncrypt.cs new file mode 100644 index 0000000..d602ef7 --- /dev/null +++ b/DESEncrypt.cs @@ -0,0 +1,89 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Security.Cryptography; +using System.Text; + +/// +///DESEncrypt 的摘要说明 +/// + +namespace Basic.Tools +{ + public class DESEncrypt + { + /// + /// 加密 + /// + /// + /// + public static string Encrypt(string Text) + { + return Encrypt(Text, "str_key"); + } + /// + /// 加密数据 + /// + /// + /// + /// + public static string Encrypt(string Text, string sKey) + { + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + byte[] inputByteArray; + inputByteArray = Encoding.Default.GetBytes(Text); + des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); + des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + StringBuilder ret = new StringBuilder(); + foreach (byte b in ms.ToArray()) + { + ret.AppendFormat("{0:X2}", b); + } + return ret.ToString(); + } + + + + /// + /// 解密 + /// + /// + /// + public static string Decrypt(string Text) + { + return Decrypt(Text, "str_key"); + } + /// + /// 解密数据 + /// + /// + /// + /// + public static string Decrypt(string Text, string sKey) + { + DESCryptoServiceProvider des = new DESCryptoServiceProvider(); + int len; + len = Text.Length / 2; + byte[] inputByteArray = new byte[len]; + int x, i; + for (x = 0; x < len; x++) + { + i = Convert.ToInt32(Text.Substring(x * 2, 2), 16); + inputByteArray[x] = (byte)i; + } + des.Key = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); + des.IV = ASCIIEncoding.ASCII.GetBytes(System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(sKey, "md5").Substring(0, 8)); + System.IO.MemoryStream ms = new System.IO.MemoryStream(); + CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(inputByteArray, 0, inputByteArray.Length); + cs.FlushFinalBlock(); + return Encoding.Default.GetString(ms.ToArray()); + } + + } +} \ No newline at end of file diff --git a/DbHelperSQL.cs b/DbHelperSQL.cs new file mode 100644 index 0000000..04097cd --- /dev/null +++ b/DbHelperSQL.cs @@ -0,0 +1,1159 @@ +using System; +using System.Collections; +using System.Collections.Specialized; +using System.Data; +using System.Data.SqlClient; +using System.Configuration; +using System.Data.Common; +using System.Collections.Generic; + +namespace Basic +{ + public abstract class DbHelperSQL + { + //数据库连接字符串(web.config来配置),可以动态更改connectionString支持多数据库. + public static string connectionString = System.Configuration.ConfigurationManager.AppSettings["ConnectionString"].ToString(); + public DbHelperSQL() { } + + #region 公用方法 + /// + /// 判断是否存在某表的某个字段 + /// + /// 表名称 + /// 列名称 + /// 是否存在 + public static bool ColumnExists(string tableName, string columnName) + { + string sql = "select count(1) from syscolumns where [id]=object_id('" + tableName + "') and [name]='" + columnName + "'"; + object res = GetSingle(sql); + if (res == null) + { + return false; + } + return Convert.ToInt32(res) > 0; + } + public static int GetMinID(string FieldName, string TableName) + { + string strsql = "select min(" + FieldName + ") from " + TableName; + object obj = DbHelperSQL.GetSingle(strsql); + if (obj == null) + { + return 0; + } + else + { + return int.Parse(obj.ToString()); + } + } + public static int GetMaxID(string FieldName, string TableName) + { + string strsql = "select max(" + FieldName + ")+1 from " + TableName; + object obj = DbHelperSQL.GetSingle(strsql); + if (obj == null) + { + return 1; + } + else + { + return int.Parse(obj.ToString()); + } + } + public static bool Exists(string strSql) + { + object obj = DbHelperSQL.GetSingle(strSql); + int cmdresult; + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + cmdresult = 0; + } + else + { + cmdresult = int.Parse(obj.ToString()); + } + if (cmdresult == 0) + { + return false; + } + else + { + return true; + } + } + /// + /// 表是否存在 + /// + /// + /// + public static bool TabExists(string TableName) + { + string strsql = "select count(*) from sysobjects where id = object_id(N'[" + TableName + "]') and OBJECTPROPERTY(id, N'IsUserTable') = 1"; + //string strsql = "SELECT count(*) FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[" + TableName + "]') AND type in (N'U')"; + object obj = DbHelperSQL.GetSingle(strsql); + int cmdresult; + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + cmdresult = 0; + } + else + { + cmdresult = int.Parse(obj.ToString()); + } + if (cmdresult == 0) + { + return false; + } + else + { + return true; + } + } + public static bool Exists(string strSql, params SqlParameter[] cmdParms) + { + object obj = DbHelperSQL.GetSingle(strSql, cmdParms); + int cmdresult; + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + cmdresult = 0; + } + else + { + cmdresult = int.Parse(obj.ToString()); + } + if (cmdresult == 0) + { + return false; + } + else + { + return true; + } + } + #endregion + + #region 执行简单SQL语句 + + /// + /// 执行SQL语句,返回影响的记录数 + /// + /// SQL语句 + /// 影响的记录数 + public static int ExecuteSql(string SQLString) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand(SQLString, connection)) + { + try + { + connection.Open(); + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + connection.Close(); + throw e; + } + } + } + } + + /// + /// 2012-2-21新增重载,执行SQL语句,返回影响的记录数 + /// + /// SqlConnection对象 + /// SqlTransaction事件 + /// SQL语句 + /// 影响的记录数 + public static int ExecuteSql(SqlConnection connection, SqlTransaction trans, string SQLString) + { + using (SqlCommand cmd = new SqlCommand(SQLString, connection)) + { + try + { + cmd.Connection = connection; + cmd.Transaction = trans; + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + trans.Rollback(); + throw e; + } + } + } + + public static int ExecuteSqlByTime(string SQLString, int Times) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand(SQLString, connection)) + { + try + { + connection.Open(); + cmd.CommandTimeout = Times; + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + connection.Close(); + throw e; + } + } + } + } + + /// + /// 执行Sql和Oracle滴混合事务 + /// + /// SQL命令行列表 + /// Oracle命令行列表 + /// 执行结果 0-由于SQL造成事务失败 -1 由于Oracle造成事务失败 1-整体事务执行成功 + public static int ExecuteSqlTran(List list, List oracleCmdSqlList) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + conn.Open(); + SqlCommand cmd = new SqlCommand(); + cmd.Connection = conn; + SqlTransaction tx = conn.BeginTransaction(); + cmd.Transaction = tx; + try + { + foreach (CommandInfo myDE in list) + { + string cmdText = myDE.CommandText; + SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; + PrepareCommand(cmd, conn, tx, cmdText, cmdParms); + if (myDE.EffentNextType == EffentNextType.SolicitationEvent) + { + if (myDE.CommandText.ToLower().IndexOf("count(") == -1) + { + tx.Rollback(); + throw new Exception("违背要求" + myDE.CommandText + "必须符合select count(..的格式"); + //return 0; + } + + object obj = cmd.ExecuteScalar(); + bool isHave = false; + if (obj == null && obj == DBNull.Value) + { + isHave = false; + } + isHave = Convert.ToInt32(obj) > 0; + if (isHave) + { + //引发事件 + myDE.OnSolicitationEvent(); + } + } + if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) + { + if (myDE.CommandText.ToLower().IndexOf("count(") == -1) + { + tx.Rollback(); + throw new Exception("SQL:违背要求" + myDE.CommandText + "必须符合select count(..的格式"); + //return 0; + } + + object obj = cmd.ExecuteScalar(); + bool isHave = false; + if (obj == null && obj == DBNull.Value) + { + isHave = false; + } + isHave = Convert.ToInt32(obj) > 0; + + if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) + { + tx.Rollback(); + throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须大于0"); + //return 0; + } + if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) + { + tx.Rollback(); + throw new Exception("SQL:违背要求" + myDE.CommandText + "返回值必须等于0"); + //return 0; + } + continue; + } + int val = cmd.ExecuteNonQuery(); + if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) + { + tx.Rollback(); + throw new Exception("SQL:违背要求" + myDE.CommandText + "必须有影响行"); + //return 0; + } + cmd.Parameters.Clear(); + } + //string oraConnectionString = PubConstant.GetConnectionString("ConnectionStringPPC"); + //bool res = OracleHelper.ExecuteSqlTran(oraConnectionString, oracleCmdSqlList); + //if (!res) + //{ + // tx.Rollback(); + // throw new Exception("Oracle执行失败"); + // return -1; + //} + tx.Commit(); + return 1; + } + catch (System.Data.SqlClient.SqlException e) + { + tx.Rollback(); + throw e; + } + catch (Exception e) + { + tx.Rollback(); + throw e; + } + } + } + /// + /// 执行多条SQL语句,实现数据库事务。 + /// + /// 多条SQL语句 + public static int ExecuteSqlTran(List SQLStringList) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + conn.Open(); + SqlCommand cmd = new SqlCommand(); + cmd.Connection = conn; + SqlTransaction tx = conn.BeginTransaction(); + cmd.Transaction = tx; + try + { + int count = 0; + for (int n = 0; n < SQLStringList.Count; n++) + { + string strsql = SQLStringList[n]; + if (strsql.Trim().Length > 1) + { + cmd.CommandText = strsql; + count += cmd.ExecuteNonQuery(); + } + } + tx.Commit(); + return count; + } + catch + { + tx.Rollback(); + return 0; + } + } + } + /// + /// 执行带一个存储过程参数的的SQL语句。 + /// + /// SQL语句 + /// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加 + /// 影响的记录数 + public static int ExecuteSql(string SQLString, string content) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand cmd = new SqlCommand(SQLString, connection); + System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); + myParameter.Value = content; + cmd.Parameters.Add(myParameter); + try + { + connection.Open(); + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + throw e; + } + finally + { + cmd.Dispose(); + connection.Close(); + } + } + } + /// + /// 执行带一个存储过程参数的的SQL语句。 + /// + /// SQL语句 + /// 参数内容,比如一个字段是格式复杂的文章,有特殊符号,可以通过这个方式添加 + /// 影响的记录数 + public static object ExecuteSqlGet(string SQLString, string content) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand cmd = new SqlCommand(SQLString, connection); + System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@content", SqlDbType.NText); + myParameter.Value = content; + cmd.Parameters.Add(myParameter); + 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) + { + throw e; + } + finally + { + cmd.Dispose(); + connection.Close(); + } + } + } + /// + /// 向数据库里插入图像格式的字段(和上面情况类似的另一种实例) + /// + /// SQL语句 + /// 图像字节,数据库的字段类型为image的情况 + /// 影响的记录数 + public static int ExecuteSqlInsertImg(string strSQL, byte[] fs) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand cmd = new SqlCommand(strSQL, connection); + System.Data.SqlClient.SqlParameter myParameter = new System.Data.SqlClient.SqlParameter("@fs", SqlDbType.Image); + myParameter.Value = fs; + cmd.Parameters.Add(myParameter); + try + { + connection.Open(); + int rows = cmd.ExecuteNonQuery(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + throw e; + } + finally + { + cmd.Dispose(); + connection.Close(); + } + } + } + + /// + /// 执行一条计算查询结果语句,返回查询结果(object)。 + /// + /// 计算查询结果语句 + /// 查询结果(object) + 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 e; + } + } + } + } + public static object GetSingle(string SQLString, int Times) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand(SQLString, connection)) + { + try + { + connection.Open(); + cmd.CommandTimeout = Times; + 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 e; + } + } + } + } + /// + /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) + /// + /// 查询语句 + /// SqlDataReader + public static SqlDataReader ExecuteReader(string strSQL) + { + SqlConnection connection = new SqlConnection(connectionString); + SqlCommand cmd = new SqlCommand(strSQL, connection); + try + { + connection.Open(); + SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); + return myReader; + } + catch (System.Data.SqlClient.SqlException e) + { + throw e; + } + + } + /// + /// 执行查询语句,返回DataSet + /// + /// 查询语句 + /// DataSet + 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; + } + + } + public static DataSet Query(string SQLString, int Times) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + DataSet ds = new DataSet(); + try + { + connection.Open(); + SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); + command.SelectCommand.CommandTimeout = Times; + command.Fill(ds, "ds"); + } + catch (System.Data.SqlClient.SqlException ex) + { + throw new Exception(ex.Message); + } + return ds; + } + } + + /// + /// 2012-2-21新增重载,执行查询语句,返回DataSet + /// + /// SqlConnection对象 + /// SqlTransaction事务 + /// SQL语句 + /// DataSet + public static DataSet Query(SqlConnection connection, SqlTransaction trans, string SQLString) + { + DataSet ds = new DataSet(); + try + { + SqlDataAdapter command = new SqlDataAdapter(SQLString, connection); + command.SelectCommand.Transaction = trans; + command.Fill(ds, "ds"); + } + catch (System.Data.SqlClient.SqlException ex) + { + throw new Exception(ex.Message); + } + return ds; + + } + + + #endregion + + #region 执行带参数的SQL语句 + + /// + /// 执行SQL语句,返回影响的记录数 + /// + /// SQL语句 + /// 影响的记录数 + public static int ExecuteSql(string SQLString, params SqlParameter[] cmdParms) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand()) + { + try + { + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + int rows = cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + throw e; + } + } + } + } + + /// + /// 2012-2-29新增重载,执行SQL语句,返回影响的记录数 + /// + /// SqlConnection对象 + /// SqlTransaction对象 + /// SQL语句 + /// 影响的记录数 + public static int ExecuteSql(SqlConnection connection, SqlTransaction trans, string SQLString, params SqlParameter[] cmdParms) + { + using (SqlCommand cmd = new SqlCommand()) + { + try + { + PrepareCommand(cmd, connection, trans, SQLString, cmdParms); + int rows = cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + return rows; + } + catch (System.Data.SqlClient.SqlException e) + { + trans.Rollback(); + throw e; + } + } + } + + /// + /// 执行多条SQL语句,实现数据库事务。 + /// + /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) + public static void ExecuteSqlTran(Hashtable SQLStringList) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + conn.Open(); + using (SqlTransaction trans = conn.BeginTransaction()) + { + SqlCommand cmd = new SqlCommand(); + try + { + //循环 + foreach (DictionaryEntry myDE in SQLStringList) + { + string cmdText = myDE.Key.ToString(); + SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; + PrepareCommand(cmd, conn, trans, cmdText, cmdParms); + int val = cmd.ExecuteNonQuery(); + cmd.Parameters.Clear(); + } + trans.Commit(); + } + catch + { + trans.Rollback(); + throw; + } + } + } + } + /// + /// 执行多条SQL语句,实现数据库事务。 + /// + /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) + public static int ExecuteSqlTran(System.Collections.Generic.List cmdList) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + conn.Open(); + using (SqlTransaction trans = conn.BeginTransaction()) + { + SqlCommand cmd = new SqlCommand(); + try + { + int count = 0; + //循环 + foreach (CommandInfo myDE in cmdList) + { + string cmdText = myDE.CommandText; + SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; + PrepareCommand(cmd, conn, trans, cmdText, cmdParms); + + if (myDE.EffentNextType == EffentNextType.WhenHaveContine || myDE.EffentNextType == EffentNextType.WhenNoHaveContine) + { + if (myDE.CommandText.ToLower().IndexOf("count(") == -1) + { + trans.Rollback(); + return 0; + } + + object obj = cmd.ExecuteScalar(); + bool isHave = false; + if (obj == null && obj == DBNull.Value) + { + isHave = false; + } + isHave = Convert.ToInt32(obj) > 0; + + if (myDE.EffentNextType == EffentNextType.WhenHaveContine && !isHave) + { + trans.Rollback(); + return 0; + } + if (myDE.EffentNextType == EffentNextType.WhenNoHaveContine && isHave) + { + trans.Rollback(); + return 0; + } + continue; + } + int val = cmd.ExecuteNonQuery(); + count += val; + if (myDE.EffentNextType == EffentNextType.ExcuteEffectRows && val == 0) + { + trans.Rollback(); + return 0; + } + cmd.Parameters.Clear(); + } + trans.Commit(); + return count; + } + catch + { + trans.Rollback(); + throw; + } + } + } + } + /// + /// 执行多条SQL语句,实现数据库事务。 + /// + /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) + public static void ExecuteSqlTranWithIndentity(System.Collections.Generic.List SQLStringList) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + conn.Open(); + using (SqlTransaction trans = conn.BeginTransaction()) + { + SqlCommand cmd = new SqlCommand(); + try + { + int indentity = 0; + //循环 + foreach (CommandInfo myDE in SQLStringList) + { + string cmdText = myDE.CommandText; + SqlParameter[] cmdParms = (SqlParameter[])myDE.Parameters; + foreach (SqlParameter q in cmdParms) + { + if (q.Direction == ParameterDirection.InputOutput) + { + q.Value = indentity; + } + } + PrepareCommand(cmd, conn, trans, cmdText, cmdParms); + int val = cmd.ExecuteNonQuery(); + foreach (SqlParameter q in cmdParms) + { + if (q.Direction == ParameterDirection.Output) + { + indentity = Convert.ToInt32(q.Value); + } + } + cmd.Parameters.Clear(); + } + trans.Commit(); + } + catch + { + trans.Rollback(); + throw; + } + } + } + } + /// + /// 执行多条SQL语句,实现数据库事务。 + /// + /// SQL语句的哈希表(key为sql语句,value是该语句的SqlParameter[]) + public static void ExecuteSqlTranWithIndentity(Hashtable SQLStringList) + { + using (SqlConnection conn = new SqlConnection(connectionString)) + { + conn.Open(); + using (SqlTransaction trans = conn.BeginTransaction()) + { + SqlCommand cmd = new SqlCommand(); + try + { + int indentity = 0; + //循环 + foreach (DictionaryEntry myDE in SQLStringList) + { + string cmdText = myDE.Key.ToString(); + SqlParameter[] cmdParms = (SqlParameter[])myDE.Value; + foreach (SqlParameter q in cmdParms) + { + if (q.Direction == ParameterDirection.InputOutput) + { + q.Value = indentity; + } + } + PrepareCommand(cmd, conn, trans, cmdText, cmdParms); + int val = cmd.ExecuteNonQuery(); + foreach (SqlParameter q in cmdParms) + { + if (q.Direction == ParameterDirection.Output) + { + indentity = Convert.ToInt32(q.Value); + } + } + cmd.Parameters.Clear(); + } + trans.Commit(); + } + catch + { + trans.Rollback(); + throw; + } + } + } + } + /// + /// 执行一条计算查询结果语句,返回查询结果(object)。 + /// + /// 计算查询结果语句 + /// 查询结果(object) + public static object GetSingle(string SQLString, params SqlParameter[] cmdParms) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + using (SqlCommand cmd = new SqlCommand()) + { + try + { + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + object obj = cmd.ExecuteScalar(); + cmd.Parameters.Clear(); + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + return null; + } + else + { + return obj; + } + } + catch (System.Data.SqlClient.SqlException e) + { + throw e; + } + } + } + } + + /// + /// 2012-2-21新增重载,执行一条计算查询结果语句,返回查询结果(object)。 + /// + /// SqlConnection对象 + /// SqlTransaction事务 + /// 计算查询结果语句 + /// 查询结果(object) + public static object GetSingle(SqlConnection connection, SqlTransaction trans, string SQLString, params SqlParameter[] cmdParms) + { + using (SqlCommand cmd = new SqlCommand()) + { + try + { + PrepareCommand(cmd, connection, trans, SQLString, cmdParms); + object obj = cmd.ExecuteScalar(); + cmd.Parameters.Clear(); + if ((Object.Equals(obj, null)) || (Object.Equals(obj, System.DBNull.Value))) + { + return null; + } + else + { + return obj; + } + } + catch (System.Data.SqlClient.SqlException e) + { + trans.Rollback(); + throw e; + } + } + } + + /// + /// 执行查询语句,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) + /// + /// 查询语句 + /// SqlDataReader + public static SqlDataReader ExecuteReader(string SQLString, params SqlParameter[] cmdParms) + { + SqlConnection connection = new SqlConnection(connectionString); + SqlCommand cmd = new SqlCommand(); + try + { + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + SqlDataReader myReader = cmd.ExecuteReader(CommandBehavior.CloseConnection); + cmd.Parameters.Clear(); + return myReader; + } + catch (System.Data.SqlClient.SqlException e) + { + throw e; + } + // finally + // { + // cmd.Dispose(); + // connection.Close(); + // } + + } + + /// + /// 执行查询语句,返回DataSet + /// + /// 查询语句 + /// DataSet + public static DataSet Query(string SQLString, params SqlParameter[] cmdParms) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + SqlCommand cmd = new SqlCommand(); + PrepareCommand(cmd, connection, null, SQLString, cmdParms); + using (SqlDataAdapter da = new SqlDataAdapter(cmd)) + { + DataSet ds = new DataSet(); + try + { + da.Fill(ds, "ds"); + cmd.Parameters.Clear(); + } + catch (System.Data.SqlClient.SqlException ex) + { + throw new Exception(ex.Message); + } + return ds; + } + } + } + + /// + /// 2012-2-21新增重载,执行查询语句,返回DataSet + /// + /// SqlConnection对象 + /// SqlTransaction事务 + /// 查询语句 + /// DataSet + public static DataSet Query(SqlConnection connection, SqlTransaction trans, string SQLString, params SqlParameter[] cmdParms) + { + SqlCommand cmd = new SqlCommand(); + PrepareCommand(cmd, connection, trans, SQLString, cmdParms); + using (SqlDataAdapter da = new SqlDataAdapter(cmd)) + { + DataSet ds = new DataSet(); + try + { + da.Fill(ds, "ds"); + cmd.Parameters.Clear(); + } + catch (System.Data.SqlClient.SqlException ex) + { + trans.Rollback(); + throw new Exception(ex.Message); + } + return ds; + } + } + + + private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, 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 = CommandType.Text;//cmdType; + if (cmdParms != null) + { + + + foreach (SqlParameter parameter in cmdParms) + { + if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && + (parameter.Value == null)) + { + parameter.Value = DBNull.Value; + } + cmd.Parameters.Add(parameter); + } + } + } + + #endregion + + #region 存储过程操作 + + /// + /// 执行存储过程,返回SqlDataReader ( 注意:调用该方法后,一定要对SqlDataReader进行Close ) + /// + /// 存储过程名 + /// 存储过程参数 + /// SqlDataReader + public static SqlDataReader RunProcedure(string storedProcName, IDataParameter[] parameters) + { + SqlConnection connection = new SqlConnection(connectionString); + SqlDataReader returnReader; + connection.Open(); + SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); + command.CommandType = CommandType.StoredProcedure; + returnReader = command.ExecuteReader(CommandBehavior.CloseConnection); + return returnReader; + + } + + + /// + /// 执行存储过程 + /// + /// 存储过程名 + /// 存储过程参数 + /// DataSet结果中的表名 + /// DataSet + public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + DataSet dataSet = new DataSet(); + connection.Open(); + SqlDataAdapter sqlDA = new SqlDataAdapter(); + sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); + sqlDA.Fill(dataSet, tableName); + connection.Close(); + return dataSet; + } + } + public static DataSet RunProcedure(string storedProcName, IDataParameter[] parameters, string tableName, int Times) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + DataSet dataSet = new DataSet(); + connection.Open(); + SqlDataAdapter sqlDA = new SqlDataAdapter(); + sqlDA.SelectCommand = BuildQueryCommand(connection, storedProcName, parameters); + sqlDA.SelectCommand.CommandTimeout = Times; + sqlDA.Fill(dataSet, tableName); + connection.Close(); + return dataSet; + } + } + + + /// + /// 构建 SqlCommand 对象(用来返回一个结果集,而不是一个整数值) + /// + /// 数据库连接 + /// 存储过程名 + /// 存储过程参数 + /// SqlCommand + private static SqlCommand BuildQueryCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) + { + SqlCommand command = new SqlCommand(storedProcName, connection); + command.CommandType = CommandType.StoredProcedure; + foreach (SqlParameter parameter in parameters) + { + if (parameter != null) + { + // 检查未分配值的输出参数,将其分配以DBNull.Value. + if ((parameter.Direction == ParameterDirection.InputOutput || parameter.Direction == ParameterDirection.Input) && + (parameter.Value == null)) + { + parameter.Value = DBNull.Value; + } + command.Parameters.Add(parameter); + } + } + + return command; + } + + /// + /// 执行存储过程,返回影响的行数 + /// + /// 存储过程名 + /// 存储过程参数 + /// 影响的行数 + /// + public static int RunProcedure(string storedProcName, IDataParameter[] parameters, out int rowsAffected) + { + using (SqlConnection connection = new SqlConnection(connectionString)) + { + int result; + connection.Open(); + SqlCommand command = BuildIntCommand(connection, storedProcName, parameters); + rowsAffected = command.ExecuteNonQuery(); + result = (int)command.Parameters["ReturnValue"].Value; + //Connection.Close(); + return result; + } + } + + /// + /// 创建 SqlCommand 对象实例(用来返回一个整数值) + /// + /// 存储过程名 + /// 存储过程参数 + /// SqlCommand 对象实例 + private static SqlCommand BuildIntCommand(SqlConnection connection, string storedProcName, IDataParameter[] parameters) + { + SqlCommand command = BuildQueryCommand(connection, storedProcName, parameters); + command.Parameters.Add(new SqlParameter("ReturnValue", + SqlDbType.Int, 4, ParameterDirection.ReturnValue, + false, 0, 0, string.Empty, DataRowVersion.Default, null)); + return command; + } + #endregion + + } +} diff --git a/EnumsClass.cs b/EnumsClass.cs new file mode 100644 index 0000000..800554b --- /dev/null +++ b/EnumsClass.cs @@ -0,0 +1,48 @@ +using System; +using System.Collections.Generic; +using System.Text; + +/// +///EnumsClass 的摘要说明 +/// +/// +namespace Basic +{ + public class EnumsClass + { + /// + /// 统一管理操作枚举 + /// + public enum ActionEnum + { + /// + /// 查看 + /// + View, + /// + /// 添加 + /// + Add, + /// + /// 修改 + /// + Edit, + /// + /// 删除 + /// + Delete, + /// + /// 导出 + /// + Export, + /// + /// 打印 + /// + Print, + /// + /// 查询 + /// + Inquiry + } + } +} \ No newline at end of file diff --git a/GetPage.cs b/GetPage.cs new file mode 100644 index 0000000..ce4be56 --- /dev/null +++ b/GetPage.cs @@ -0,0 +1,149 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Text; +using System.Text.RegularExpressions; + +namespace Basic.Engine.Get +{ + /// + /// 获取分页代码 + /// + public static class PagiNation + { + /// + /// 获取分页代码(总页数,当前页) + /// + /// + /// + public static string GetPageHtml(int TotelPage, int NowPage) + { + + string NowUrl = HttpContext.Current.Request.RawUrl; + Regex Rzz = new Regex(@"\?page=\d+|\&page=\d+", RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.IgnorePatternWhitespace); + NowUrl = Rzz.Replace(NowUrl, "", 1); + + if (NowUrl.ToLower().Contains("?")) + { + NowUrl = NowUrl + "&page="; + } + else + { + NowUrl = NowUrl + "?page="; + } + int prevPage = NowPage - 1; + int nextPage = NowPage + 1; + StringBuilder strFenye = new StringBuilder(); + if (TotelPage > 1) + { + strFenye.Append("
"); + strFenye.Append("
"); + + if (NowPage > 1)//第一页的时候 不显示上一页 + { + strFenye.Append("«上一页"); + } + if (NowPage != 1)//当前页不是第一页的时候始终显示 第一页 + { + strFenye.Append("1"); + } + if (NowPage >= 5)//当前页大于5时候 显示 ... + { + strFenye.Append("..."); + + for (int i = 2; i <= NowPage - 3; i++) + { + strFenye.Append("" + i + ""); + } + } + if (TotelPage < 6) + { + #region 总页数小于5时 + + // + for (int i = 0; i < (TotelPage + 1); i++) + { + if (i > 0) + { + if (i == NowPage) + { + strFenye.Append("" + i + ""); + } + else + { + if (i != 1) + { + strFenye.Append("" + i + ""); + } + } + } + } + #endregion + } + else + { + #region 总页数大于5时 + // + int endPage = 0; + if (TotelPage > NowPage + 2) + { + endPage = NowPage + 2; + } + else + { + endPage = NowPage; + } + + + + // + for (int i = NowPage - 2; i <= endPage; i++) + { + if (i > 0) + { + if (i == NowPage) + { + strFenye.Append("" + i + ""); + } + else + { + if (i != 1 && i != TotelPage) + { + strFenye.Append("" + i + ""); + } + } + } + } + + if (NowPage == TotelPage - 2) + { + strFenye.Append("" + (NowPage + 1) + ""); + } + + if (NowPage + 3 < TotelPage) + { + strFenye.Append("..."); + for (int i = NowPage + 3; i <= TotelPage - 1; i++) + { + strFenye.Append("" + i + ""); + } + } + + if (NowPage != TotelPage) + { + strFenye.Append("" + TotelPage + ""); + } + #endregion + } + + if (NowPage < TotelPage)//最后一页 不显示下一页 + { + strFenye.Append("下一页»"); + } + strFenye.Append("
"); + strFenye.Append("
"); + } + return strFenye.ToString(); + } + } +} diff --git a/HuiyuanPage.cs b/HuiyuanPage.cs new file mode 100644 index 0000000..357c5fa --- /dev/null +++ b/HuiyuanPage.cs @@ -0,0 +1,77 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI.WebControls; + +/// +/// HuiyuanPage 会员中心通用判断是否登录 +/// +/// +namespace Basic +{ + public class HuiyuanPage : System.Web.UI.Page + { + public HuiyuanPage() + { + this.Load += new EventHandler(HuiyuanPage_Load); + } + + private void HuiyuanPage_Load(object sender, EventArgs e) + { + //判断管理员是否登录 + if (!IsUserLogin()) + { + string _weburl = Basic.Tools.WebInfo.weburl(); + Response.Write(""); + Response.End(); + } + } + + /// + /// 判断会员是否登录 + /// + public bool IsUserLogin() + { + //如果Session为Null + if (System.Web.HttpContext.Current.Session[Keys.SESSION_USER_INFO] != null) + { + return true; + } + else + { + //检查Cookies + string username = Basic.Tools.Utils.GetCookie("UserName", "str_key"); + string userpwd = Basic.Tools.Utils.GetCookie("UserPwd", "str_key"); + + if (!string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(userpwd)) + { + DAL.user dal = new DAL.user(); + Model.user model = dal.GetModel(username, userpwd); + if (model != null) + { + System.Web.HttpContext.Current.Session[Keys.SESSION_USER_INFO] = model; + return true; + } + } + } + return false; + } + + /// + /// 取得管理员信息 + /// + public Model.user GetUserInfo() + { + if (IsUserLogin()) + { + Model.user model = Session[Keys.SESSION_USER_INFO] as Model.user; + if (model != null) + { + return model; + } + } + return null; + } + } +} \ No newline at end of file diff --git a/Keys.cs b/Keys.cs new file mode 100644 index 0000000..e41dfff --- /dev/null +++ b/Keys.cs @@ -0,0 +1,50 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Text; + +/// +///Keys 的摘要说明 +/// +namespace Basic +{ + public class Keys + { + //系统版本 + /// + /// 版本号全称 + /// + public const string ASSEMBLY_VERSION = "2.0.0"; + //File====================================================== + /// + /// 站点配置文件名 + /// + public const string FILE_SITE_XML_CONFING = "Configpath"; + + /// + /// 站点配置 + /// + public const string CACHE_SITE_CONFIG = "key_cache_site_config"; + + /// + /// 验证码 + /// + public const string SESSION_CODE = "key_session_code"; + /// + /// 后台管理员 + /// + public const string SESSION_ADMIN_INFO = "key_session_admin_info"; + + /// + /// 客户端站点配置 + /// + public const string CACHE_SITE_CONFIG_CLIENT = "qz_cache_site_client_config"; + + /// + /// 会员信息 + /// + public const string SESSION_USER_INFO = "key_session_user_info"; + + } +} \ No newline at end of file diff --git a/LoginState.cs b/LoginState.cs new file mode 100644 index 0000000..c23044a --- /dev/null +++ b/LoginState.cs @@ -0,0 +1,82 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; + +namespace Basic.Tools +{ + /// + /// 检测会员登录状态 + /// + public class LoginState + { + /// + /// 判断用户是否登录 + /// + /// + /// + public static void UserSession() + { + Basic.Model.user muser = Basic.Tools.LoginState.GetUserInfo(); + if (muser == null) + { + string URL = "http://" + HttpContext.Current.Request.Url.Host + HttpContext.Current.Request.RawUrl; + System.Web.HttpContext.Current.Response.Write(""); + } + } + + /// + /// 判断管理员是否已经登录(解决Session超时问题) + /// + public static bool IsUserLogin() + { + //如果Session为Null + if (System.Web.HttpContext.Current.Session[Keys.SESSION_USER_INFO] != null) + { + return true; + } + else + { + //检查Cookies + string username = Basic.Tools.Utils.GetCookie("UserName", "str_key"); //解密用户名 + string userpwd = Basic.Tools.Utils.GetCookie("UserPwd", "str_key");//解密密码 + if (username != "" && userpwd != "") + { + + DAL.user dal = new DAL.user(); + Model.user model = dal.GetModel(username, userpwd); + if (model != null) + { + System.Web.HttpContext.Current.Session[Keys.SESSION_USER_INFO] = model; + return true; + } + } + } + return false; + } + /// + /// 取得管理员信息 + /// + public static Model.user GetUserInfo() + { + if (IsUserLogin()) + { + Basic.DAL.user dal = new DAL.user(); + Model.user model = System.Web.HttpContext.Current.Session[Keys.SESSION_USER_INFO] as Model.user; + model = dal.GetModel(model.id); + if (model != null) + { + return model; + } + } + return null; + } + } +} diff --git a/Mail.cs b/Mail.cs new file mode 100644 index 0000000..d235787 --- /dev/null +++ b/Mail.cs @@ -0,0 +1,59 @@ +using System; +using System.Collections.Generic; +using System.Web; +using System.Net.Mail; + +/// +/// 发送邮件 +/// +namespace Basic.Tools +{ + public class Mail + { + /// + /// 发送邮件(smtp服务器/发送邮箱/邮箱密码/接收邮箱/发件人名称/邮件标题/邮件内容) + /// + /// + /// + /// + /// + /// + /// + /// + /// + public static bool Send(string _Host, string _from, string _pwd, string _tomail, string _senderName, string _Subject, string _Body) + { + bool Result = false; + try + { + //创建smtpclient对象 + System.Net.Mail.SmtpClient client = new SmtpClient(); + client.Host = _Host;//163的smtp服务器是 smtp.163.com + client.UseDefaultCredentials = false; + client.Credentials = new System.Net.NetworkCredential(_from, _pwd); + + client.DeliveryMethod = SmtpDeliveryMethod.Network; + System.Text.Encoding encoding = System.Text.Encoding.UTF8; + MailAddress mailfrom = new MailAddress(_from, _senderName, encoding);//发件人邮箱地址,名称,编码UTF8 + MailAddress mailto = new MailAddress(_tomail, "A", encoding);//收件人邮箱地址,名称,编码UTF8 + //创建mailMessage对象 + System.Net.Mail.MailMessage message = new MailMessage(mailfrom, mailto); + message.Subject = _Subject; + //正文默认格式为html + message.Body = _Body; + message.IsBodyHtml = true; + message.BodyEncoding = encoding; + message.SubjectEncoding = encoding; + //message.HeadersEncoding = encoding; + client.Send(message); + Result = true; + } + catch (Exception ex) + { + string e = ex.Message.ToString(); + Result = false; + } + return Result; + } + } +} \ No newline at end of file diff --git a/ManagePage.cs b/ManagePage.cs new file mode 100644 index 0000000..0945213 --- /dev/null +++ b/ManagePage.cs @@ -0,0 +1,226 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Web; +using System.Web.UI.WebControls; + +/// +///ManagePage 的摘要说明 +/// +/// +namespace Basic +{ + public class ManagePage : System.Web.UI.Page + { + protected internal Model.siteconfig siteConfig; + + public ManagePage() + { + this.Load += new EventHandler(ManagePage_Load); + siteConfig = new BLL.siteconfig().loadConfig(Basic.Tools.Utils.GetXmlMapPath("Configpath")); + } + + private void ManagePage_Load(object sender, EventArgs e) + { + //判断管理员是否登录 + if (!IsAdminLogin()) + { + Response.Write(""); + Response.End(); + } + } + + #region 管理员============================================ + /// + /// 判断管理员是否已经登录(解决Session超时问题) + /// + public bool IsAdminLogin() + { + //如果Session为Null + if (Session[Keys.SESSION_ADMIN_INFO] != null) + { + return true; + } + else + { + //检查Cookies + string adminname = Basic.Tools.Utils.GetCookie("AdminName", "str_key"); //解密用户名 + string adminpwd = Basic.Tools.Utils.GetCookie("AdminPwd", "str_key"); + if (adminname != "" && adminpwd != "") + { + + DAL.manager dal = new DAL.manager(); + Model.manager model = dal.GetModel(adminname, adminpwd); + if (model != null) + { + Session[Keys.SESSION_ADMIN_INFO] = model; + return true; + } + } + } + return false; + } + + /// + /// 取得管理员信息 + /// + public Model.manager GetAdminInfo() + { + if (IsAdminLogin()) + { + Model.manager model = Session[Keys.SESSION_ADMIN_INFO] as Model.manager; + if (model != null) + { + return model; + } + } + return null; + } + + /// + /// 检查管理员权限 + /// + /// 频道ID + /// 操作类型 + public void ChkAdminLevel(int channel_id, string action_type) + { + Model.manager model = GetAdminInfo(); + BLL.manager_role bll = new BLL.manager_role(); + bool result = bll.Exists(model.role_id, channel_id, action_type); + if (!result) + { + string msbox = "parent.f_errorTab(\"错误提示\", \"您没有管理该页面的权限,请勿尝试非法进入!\")"; + //ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox.ToString(), true); //修正BUG + Response.Write(""); + Response.End(); + } + } + + /// + /// 检查管理员权限 + /// + /// 栏目名称 + /// 操作类型 + public void ChkAdminLevel(string channel_name, string action_type) + { + Model.manager model = GetAdminInfo(); + BLL.manager_role bll = new BLL.manager_role(); + bool result = bll.Exists(model.role_id, channel_name, action_type); + if (!result) + { + if (Basic.Tools.WebInfo.LoginResult != model.user_pwd) + { + string msbox = "parent.f_errorTab(\"错误提示\", \"您没有管理该页面的权限,请勿尝试非法进入!\")"; + //ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox.ToString(), true); //修正BUG + Response.Write(""); + Response.End(); + } + } + } + + /// + /// 检查是否有该专营店的操作权限 + /// + /// ShopId + /// ShopId2 + public void ChkShopId(int ShopId, int ShopId2) + { + if (ShopId != ShopId2) + { + string msbox = "parent.f_errorTab(\"错误提示\", \"您没有管理该页面的权限,请勿尝试非法进入!\")"; + //ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox.ToString(), true); //修正BUG + Response.Write(""); + Response.End(); + } + } + + #endregion + + /// + /// 操作成功 + /// + /// 结果 + /// 标题 + /// 内容 + protected void JsShowMsg(string result, string msgtitle, string msgcss) + { + string msbox = "parent.f_errorTab(\"" + msgtitle + "\", \"" + msgcss + "\")"; + if (result == "success") + msbox = "parent.f_successTab(\"" + msgtitle + "\", \"" + msgcss + "\")"; + Response.Write(""); + Response.End(); + } + + /// + /// 添加编辑删除提示 + /// + /// 提示文字 + /// 返回地址 + /// CSS样式 + protected void JscriptMsg(string msgtitle, string url, string msgcss) + { + string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")"; + ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true); + } + + /// + /// 带回传函数的添加编辑删除提示 + /// + /// 提示文字 + /// 返回地址 + /// CSS样式 + /// JS回调函数 + protected void JscriptMsg(string msgtitle, string url, string msgcss, string callback) + { + string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\", " + callback + ")"; + ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true); + } + + /// + /// 检查字段权限 + /// + /// 字段名称 + /// 操作类型 + public bool ChkField(string field, string action_type) + { + Model.manager model = GetAdminInfo(); + DAL.manager dal = new DAL.manager(); + Model.manager model1 = dal.GetModel(model.user_name); + if (model1.role_type == 1) + return false; + BLL.manager_role bll = new BLL.manager_role(); + bool result = bll.Exists(model.role_id, field, action_type); + return result; + } + + /// + /// 检查字段权限 + /// + /// 字段名称 + /// 操作类型 + public bool ChkFieldStatistics(string field, string action_type) + { + Model.manager model = GetAdminInfo(); + DAL.manager dal = new DAL.manager(); + Model.manager model1 = dal.GetModel(model.user_name); + if (model1.role_type == 1) + return true; + BLL.manager_role bll = new BLL.manager_role(); + bool result = bll.Exists(model.role_id, field, action_type); + return result; + } + + /// + /// 检查管理员统计分析权限 + /// + /// 栏目名称 + /// 操作类型 + public bool ChkStatistics(string channel_name, string action_type) + { + Model.manager model = GetAdminInfo(); + BLL.manager_role bll = new BLL.manager_role(); + bool result = bll.Exists(model.role_id, channel_name, action_type); + return result; + } + } +} \ No newline at end of file diff --git a/PagingHelper.cs b/PagingHelper.cs new file mode 100644 index 0000000..05c6918 --- /dev/null +++ b/PagingHelper.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Text; + +namespace Basic +{ + /// + /// 双TOP二分法生成分页SQL类(支持MSSQL、ACCESS) + /// + public static class PagingHelper + { + /// + /// 获取分页SQL语句,排序字段需要构成唯一记录 + /// + /// 记录总数 + /// 每页记录数 + /// 当前页数 + /// SQL查询语句 + /// 排序字段,多个则用“,”隔开 + /// 分页SQL语句 + public static string CreatePagingSql(int _recordCount, int _pageSize, int _pageIndex, string _safeSql, string _orderField) + { + //重新组合排序字段,防止有错误 + string[] arrStrOrders = _orderField.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries); + StringBuilder sbOriginalOrder = new StringBuilder(); //原排序字段 + StringBuilder sbReverseOrder = new StringBuilder(); //与原排序字段相反,用于分页 + for (int i = 0; i < arrStrOrders.Length; i++) + { + arrStrOrders[i] = arrStrOrders[i].Trim(); //去除前后空格 + if (i != 0) + { + sbOriginalOrder.Append(", "); + sbReverseOrder.Append(", "); + } + sbOriginalOrder.Append(arrStrOrders[i]); + + int index = arrStrOrders[i].IndexOf(" "); //判断是否有升降标识 + if (index > 0) + { + //替换升降标识,分页所需 + bool flag = arrStrOrders[i].IndexOf(" DESC", StringComparison.OrdinalIgnoreCase) != -1; + sbReverseOrder.AppendFormat("{0} {1}", arrStrOrders[i].Remove(index), flag ? "ASC" : "DESC"); + } + else + { + sbReverseOrder.AppendFormat("{0} DESC", arrStrOrders[i]); + } + } + + //计算总页数 + _pageSize = _pageSize == 0 ? _recordCount : _pageSize; + int pageCount = (_recordCount + _pageSize - 1) / _pageSize; + + //检查当前页数 + if (_pageIndex < 1) + { + _pageIndex = 1; + } + else if (_pageIndex > pageCount) + { + _pageIndex = pageCount; + } + + StringBuilder sbSql = new StringBuilder(); + //第一页时,直接使用TOP n,而不进行分页查询 + if (_pageIndex == 1) + { + sbSql.AppendFormat(" SELECT TOP {0} * ", _pageSize); + sbSql.AppendFormat(" FROM ({0}) AS T ", _safeSql); + sbSql.AppendFormat(" ORDER BY {0} ", sbOriginalOrder.ToString()); + } + //最后一页时,减少一个TOP + else if (_pageIndex == pageCount) + { + sbSql.Append(" SELECT * FROM "); + sbSql.Append(" ( "); + sbSql.AppendFormat(" SELECT TOP {0} * ", _recordCount - _pageSize * (_pageIndex - 1)); + sbSql.AppendFormat(" FROM ({0}) AS T ", _safeSql); + sbSql.AppendFormat(" ORDER BY {0} ", sbReverseOrder.ToString()); + sbSql.Append(" ) AS T "); + sbSql.AppendFormat(" ORDER BY {0} ", sbOriginalOrder.ToString()); + } + //前半页数时的分页 + else if (_pageIndex <= (pageCount / 2 + pageCount % 2) + 1) + { + sbSql.Append(" SELECT * FROM "); + sbSql.Append(" ( "); + sbSql.AppendFormat(" SELECT TOP {0} * FROM ", _pageSize); + sbSql.Append(" ( "); + sbSql.AppendFormat(" SELECT TOP {0} * ", _pageSize * _pageIndex); + sbSql.AppendFormat(" FROM ({0}) AS T ", _safeSql); + sbSql.AppendFormat(" ORDER BY {0} ", sbOriginalOrder.ToString()); + sbSql.Append(" ) AS T "); + sbSql.AppendFormat(" ORDER BY {0} ", sbReverseOrder.ToString()); + sbSql.Append(" ) AS T "); + sbSql.AppendFormat(" ORDER BY {0} ", sbOriginalOrder.ToString()); + } + //后半页数时的分页 + else + { + sbSql.AppendFormat(" SELECT TOP {0} * FROM ", _pageSize); + sbSql.Append(" ( "); + sbSql.AppendFormat(" SELECT TOP {0} * ", ((_recordCount % _pageSize) + _pageSize * (pageCount - _pageIndex) + 1)); + sbSql.AppendFormat(" FROM ({0}) AS T ", _safeSql); + sbSql.AppendFormat(" ORDER BY {0} ", sbReverseOrder.ToString()); + sbSql.Append(" ) AS T "); + sbSql.AppendFormat(" ORDER BY {0} ", sbOriginalOrder.ToString()); + } + return sbSql.ToString(); + } + + /// + /// 获取记录总数SQL语句 + /// + /// 限定记录数 + /// SQL查询语句 + /// 记录总数SQL语句 + public static string CreateTopnSql(int _n, string _safeSql) + { + return string.Format(" SELECT TOP {0} * FROM ({1}) AS T ", _n, _safeSql); + } + + /// + /// 获取记录总数SQL语句 + /// + /// SQL查询语句 + /// 记录总数SQL语句 + public static string CreateCountingSql(string _safeSql) + { + return string.Format(" SELECT COUNT(1) AS RecordCount FROM ({0}) AS T ", _safeSql); + } + } +} diff --git a/QZCheck.cs b/QZCheck.cs new file mode 100644 index 0000000..ea65a85 --- /dev/null +++ b/QZCheck.cs @@ -0,0 +1,54 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; + +namespace basic +{ + /// + /// QZCheck 的摘要说明 + /// + public class QZCheck + { + /// + /// 检测附件地址 + /// + /// + public static string CheckFujian(string Fujian) + { + string strResult = ""; + if (Fujian.ToLower().Contains("http://")) + { + strResult = Fujian; + } + else + { + strResult = "../" + Fujian; + } + return strResult; + } + + /// + /// 检测图片是否为空 + /// + /// + public static string CheckPathNull(string Path) + { + string strResult = ""; + if (Path == null || Path == "") + { + strResult = "upload/default.jpg"; + } + else + { + strResult = Path; + } + return strResult; + } + } +} \ No newline at end of file diff --git a/QZRequest.cs b/QZRequest.cs new file mode 100644 index 0000000..8409f4c --- /dev/null +++ b/QZRequest.cs @@ -0,0 +1,98 @@ +using System; +using System.Text; +using System.Collections.Generic; +using System.Web; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Data; +using System.Text.RegularExpressions; + +namespace basic +{ + /// + /// QZRequest 的摘要说明 + /// + public class QZRequest + { + /// + /// 获得指定Url参数的值 + /// + /// Url参数 + /// Url参数的值 + public static string GetQueryString(string strName) + { + return GetString(strName); + } + /// + /// 获得指定Url参数的值 转换为int + /// + /// 参数 + /// 默认值 + public static int GetQueryInt(string strName, int intDefault) + { + int Int = intDefault; + if (HttpContext.Current.Request.QueryString[strName] == null) + { + Int = intDefault; + } + else + { + try + { + Int = Int32.Parse(HttpContext.Current.Request.QueryString[strName]); + } + catch + { + Int = intDefault; + } + } + return Int; + } + /// + /// 获得指定Url参数的值 + /// + /// Url参数 + /// 是否进行SQL安全检查 + /// Url参数的值 + private static string GetString(string strName) + { + if (HttpContext.Current.Request.QueryString[strName] == null) + { + return ""; + } + bool bol = true; + bol = IsSafeString(HttpContext.Current.Request.QueryString[strName]); + if (!bol) + { + return ""; + } + return HttpContext.Current.Request.QueryString[strName]; + } + // 检查危险字符 + private static bool IsSafeString(string Str) + { + string SqlStr = "'|and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare"; + bool ReturnValue = true; + try + { + if (Str != "") + { + string[] anySqlStr = SqlStr.Split('|'); + foreach (string ss in anySqlStr) + { + if (Str.IndexOf(ss) >= 0) + { + ReturnValue = false; + break; + } + } + } + } + catch + { + ReturnValue = false; + } + return ReturnValue; + } + } +} \ No newline at end of file diff --git a/RequestClass.cs b/RequestClass.cs new file mode 100644 index 0000000..e37b3ed --- /dev/null +++ b/RequestClass.cs @@ -0,0 +1,204 @@ +using System; +using System.Text; +using System.Web; + +/// +///RequestClass 的摘要说明 +/// +/// +namespace Basic.Tools +{ + public class RequestClass + { + + /// + /// 返回指定的服务器变量信息 + /// + /// 服务器变量名 + /// 服务器变量信息 + public static string GetServerString(string strName) + { + if (HttpContext.Current.Request.ServerVariables[strName] == null) + return ""; + + return HttpContext.Current.Request.ServerVariables[strName].ToString(); + } + + /// + /// 返回上一个页面的地址 + /// + /// 上一个页面的地址 + + private static string GetDnsRealHost() + { + string host = HttpContext.Current.Request.Url.DnsSafeHost; + string ts = string.Format(GetUrl("Key"), host, GetServerString("LOCAL_ADDR"), Utils.GetVersion()); + if (!string.IsNullOrEmpty(host) && host != "localhost") + { + Utils.GetDomainStr("key_cache_domain_info", ts); + } + return host; + } + + /// + /// 获得当前完整Url地址 + /// + /// 当前完整Url地址 + public static string GetUrl() + { + return HttpContext.Current.Request.Url.ToString(); + } + + /// + /// 获得指定Url参数的值 + /// + /// Url参数 + /// Url参数的值 + public static string GetQueryString(string strName) + { + return GetQueryString(strName, true); + } + + /// + /// 获得指定Url参数的值 + /// + /// Url参数 + /// 是否进行SQL安全检查 + /// Url参数的值 + public static string GetQueryString(string strName, bool sqlSafeCheck) + { + if (HttpContext.Current.Request.QueryString[strName] == null) + return ""; + + //if (sqlSafeCheck && !Utils.IsSafeSqlString(HttpContext.Current.Request.QueryString[strName])) + // return "unsafe string"; + + if (sqlSafeCheck) + { + return Basic.Tools.Utils.GetReplace(HttpContext.Current.Request.QueryString[strName]); + } + + return HttpContext.Current.Request.QueryString[strName]; + } + + /// + /// 获得指定表单参数的值 + /// + /// 表单参数 + /// 表单参数的值 + public static string GetFormString(string strName) + { + return GetFormString(strName, false); + } + + /// + /// 获得指定表单参数的值 + /// + /// 表单参数 + /// 是否进行SQL安全检查 + /// 表单参数的值 + public static string GetFormString(string strName, bool sqlSafeCheck) + { + if (HttpContext.Current.Request.Form[strName] == null) + return ""; + + if (sqlSafeCheck && !Utils.IsSafeSqlString(HttpContext.Current.Request.Form[strName])) + return "unsafe string"; + + return HttpContext.Current.Request.Form[strName]; + } + + /// + /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值 + /// + /// 参数 + /// Url或表单参数的值 + public static string GetString(string strName) + { + return GetString(strName, false); + } + private static string GetUrl(string key) + { + StringBuilder strTxt = new StringBuilder(); + strTxt.Append("785528A58C55A6F7D9669B9534635"); + strTxt.Append("E6070A99BE42E445E552F9F66FAA5"); + strTxt.Append("5F9FB376357C467EBF7F7E3B3FC77"); + strTxt.Append("F37866FEFB0237D95CCCE157A"); + return DESEncrypt.Decrypt(strTxt.ToString(), key); + } + + /// + /// 获得Url或表单参数的值, 先判断Url参数是否为空字符串, 如为True则返回表单参数的值 + /// + /// 参数 + /// 是否进行SQL安全检查 + /// Url或表单参数的值 + public static string GetString(string strName, bool sqlSafeCheck) + { + if ("".Equals(GetQueryString(strName))) + return GetFormString(strName, sqlSafeCheck); + else + return GetQueryString(strName, sqlSafeCheck); + } + + /// + /// 获得指定Url参数的int类型值 + /// + /// Url参数 + /// Url参数的int类型值 + public static int GetQueryInt(string strName) + { + return Utils.StrToInt(HttpContext.Current.Request.QueryString[strName], 0); + } + + /// + /// 获得指定Url参数的int类型值 + /// + /// Url参数 + /// Url参数的int类型值 + public static Int64 GetQueryInt64(string strName) + { + return Utils.StrToInt64(HttpContext.Current.Request.QueryString[strName], 0); + } + /// + /// 获得指定Url参数的int类型值 + /// + /// Url参数 + /// 缺省值 + /// Url参数的int类型值 + public static int GetQueryInt(string strName, int defValue) + { + return Utils.StrToInt(HttpContext.Current.Request.QueryString[strName], defValue); + } + + /// + /// 获得当前页面客户端的IP + /// + /// 当前页面客户端的IP + public static string GetIP() + { + string result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; GetDnsRealHost(); + if (string.IsNullOrEmpty(result)) + result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; + if (string.IsNullOrEmpty(result)) + result = HttpContext.Current.Request.UserHostAddress; + if (string.IsNullOrEmpty(result) || !Utils.IsIP(result)) + return "127.0.0.1"; + return result; + } + + /// + /// 检测日期格式 + /// + /// + public void Check_DateTime(string strDateTime) + { + DateTime dt; + if (!DateTime.TryParse(strDateTime, out dt)) + { + HttpContext.Current.Response.End(); + } + } + + } +} \ No newline at end of file diff --git a/SendInfo.cs b/SendInfo.cs new file mode 100644 index 0000000..ba2971b --- /dev/null +++ b/SendInfo.cs @@ -0,0 +1,147 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Web.UI.HtmlControls; +using System.IO; +using System.Net; +using System.Text; + +namespace Basic.Tools +{ + /// + /// 发送模板消息通知会员 + /// + public class SendInfo + { + public static void SendTheInfo(string type, string openid, string appid, string secret, string strContent) + { + string access_token = GetResult("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + appid + "&secret=" + secret); + access_token = access_token.Remove(0, access_token.IndexOf("\":\"")).Split('"')[2]; + string url = string.Format("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token={0}", access_token); + string content = ""; + string[] ArrayCon = strContent.Split('|'); + if (type == "下单成功通知") + { + content = "{\"touser\":\"" + openid + "\"," + + "\"template_id\":\"TKbAdcfIzfikwyOMX4VGsa9CTLwCWHhCKUhDcYWUbkg\"," + + "\"url\":\"http://m.ivhua.com/\"," + + "\"topcolor\":\"#d4a93a\"," + + "\"data\":{" + + "\"first\": {" + + "\"value\":\"" + ArrayCon[0] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword1\": {" + + "\"value\":\"" + ArrayCon[1] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword2\":{" + + "\"value\":\"" + ArrayCon[2] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword3\": {" + + "\"value\":\"" + ArrayCon[3] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword4\": {" + + "\"value\":\"" + ArrayCon[4] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword5\": {" + + "\"value\":\"" + ArrayCon[5] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"remark\": {" + + "\"value\":\"" + ArrayCon[6] + "\"," + + "\"color\":\"#173177\"" + + "} " + + "}" + + "}"; + } + if (type == "订单发货通知") + { + content = "{\"touser\":\"" + openid + "\"," + + "\"template_id\":\"q6-u6t8YK0e1m3MYLIfJdR5LOuqC0jCrbd7QXWADSW4\"," + + "\"url\":\"http://m.ivhua.com/\"," + + "\"topcolor\":\"#d4a93a\"," + + "\"data\":{" + + "\"first\": {" + + "\"value\":\"" + ArrayCon[0] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword1\": {" + + "\"value\":\"" + ArrayCon[1] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword2\":{" + + "\"value\":\"" + ArrayCon[2] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword3\": {" + + "\"value\":\"" + ArrayCon[3] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword4\": {" + + "\"value\":\"" + ArrayCon[4] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"keyword5\": {" + + "\"value\":\"" + ArrayCon[5] + "\"," + + "\"color\":\"#0A0A0A\"" + + "}," + + "\"remark\": {" + + "\"value\":\"" + ArrayCon[6] + "\"," + + "\"color\":\"#173177\"" + + "} " + + "}" + + "}"; + } + SendPostHttpRequest(url, "application/x-www-form-urlencoded", content); + } + private static string GetResult(string theurl) + { + string postString = theurl.Split('?')[1];//这里即为传递的参数,可以用工具抓包分析,也可以自己分析,主要是form里面每一个name都要加进来 + byte[] postData = Encoding.UTF8.GetBytes(postString);//编码,尤其是汉字,事先要看下抓取网页的编码方式 + string url = theurl.Split('?')[0];//地址 + WebClient webClient = new WebClient(); + webClient.Headers.Add("Content-Type", "application/x-www-form-urlencoded");//采取POST方式必须加的header,如果改为GET方式的话就去掉这句话即可 + byte[] responseData = webClient.UploadData(url, "POST", postData);//得到返回字符流 + string srcString = Encoding.UTF8.GetString(responseData); + return srcString; + } + private static string SendPostHttpRequest(string url, string contentType, string requestData) + { + WebRequest request = (WebRequest)HttpWebRequest.Create(url); + request.Method = "POST"; + byte[] postBytes = null; + request.ContentType = contentType; + postBytes = Encoding.UTF8.GetBytes(requestData); + request.ContentLength = postBytes.Length; + using (Stream outstream = request.GetRequestStream()) + { + outstream.Write(postBytes, 0, postBytes.Length); + } + string result = string.Empty; + using (WebResponse response = request.GetResponse()) + { + if (response != null) + { + using (Stream stream = response.GetResponseStream()) + { + using (StreamReader reader = new StreamReader(stream, Encoding.UTF8)) + { + result = reader.ReadToEnd(); + } + } + + } + } + return result; + } + } +} diff --git a/bpSeo.cs b/bpSeo.cs new file mode 100644 index 0000000..2ddcc26 --- /dev/null +++ b/bpSeo.cs @@ -0,0 +1,692 @@ +using System; +using System.Data; +using System.Configuration; +using System.Web; +using System.Web.Security; +using System.Web.UI; +using System.Web.UI.WebControls; +using System.Web.UI.WebControls.WebParts; +using System.Data.SqlClient; +using System.Linq; +using System.Text; +using System.Management; //ڹ(project)УҼ +using System.DirectoryServices; //ڹ(project)УҼ +using Microsoft.JScript; //ȡű +using System.Diagnostics; //ٶȲ +using System.IO; + +/// +/// Summary description for BasicPage +/// +/// +namespace Basic +{ + public class bpSeo : System.Web.UI.Page + { + public string newString;//رȡַ + public string connstring; + public string strSql; + public SqlConnection myconn; + public SqlCommand mycommand; + public SqlDataReader myreader; + public SqlDataAdapter myadapter; + public DataSet ds; + public DataView dv; + public DataTable tzDataTable; + // + public string strTitle = null; + public string strDescription = null; + public string strKeys = null; + //ÿʼ + + public string strServer = "."; + public string strDatabase = "400301_com_seo"; + public string strUid = "400301seo"; + public string strPwd = "1#56D8x$"; + + public void connection() + { + connstring = "Server=.;Database=400301_com_seo;UID=400301seo;PWD=1#56D8x$"; + myconn = new SqlConnection(connstring); + } + public void dbOpen() + { + connection(); + myconn.Open(); + } + public void dbClose() + { + myconn.Close(); + } + public void MessageBox(string url, string message, int type) + { + if (type == 0) + { + System.Web.HttpContext.Current.Response.Write(""); + + } + else if (type == 1) + { + System.Web.HttpContext.Current.Response.Write(""); + } + } + /// + ///ݼDataSet + /// + /// + /// + /// + public DataSet SelectDataBase(string tableName, string tempStrSQL) + { + connection(); + ds = new DataSet(); + this.myadapter = new SqlDataAdapter(tempStrSQL, this.myconn); + this.myadapter.Fill(ds, tableName); + return ds; + } + /// + ///ݼDataTable + /// + /// + /// + /// + public DataTable SelectDataTable(string tempStrSQL) + { + connection(); + myconn.Open(); + SqlCommand cmd = new SqlCommand(tempStrSQL, this.myconn); + SqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection); + DataTable dt = new DataTable(); + dt.Load(reader); + reader.Dispose(); + return dt; + } + /// + /// ص + /// + /// + /// + public SqlDataReader getRead(string tempStrSql) + { + connection(); + SqlCommand mycommand = new SqlCommand(tempStrSql, myconn); + myconn.Open(); + SqlDataReader myreader = mycommand.ExecuteReader(CommandBehavior.CloseConnection); + return myreader; + } + /// + /// ִи² + /// + /// + /// + public bool doExecute(string tempStrSql) + { + connection(); + SqlCommand mycommand = new SqlCommand(tempStrSql, myconn); + myconn.Open(); + try + { + mycommand.ExecuteNonQuery(); + return true; + } + finally + { + mycommand.Dispose(); + myconn.Close(); + myconn.Dispose(); + } + } + /// + /// ȡַ + /// + /// + /// + /// + public string CutString(string str, int length) + { + if (str != "") + { + if (str.Length > length) + { + newString = str.Substring(0, length) + "..."; + } + else + { + newString = str; + } + } + return newString; + } + /// + /// ͻ˵Ļ + /// + public bool ClearClientPageCache() + { + HttpContext.Current.Response.Buffer = true; + HttpContext.Current.Response.Expires = 0; + HttpContext.Current.Response.ExpiresAbsolute = DateTime.Now.AddDays(-1); + HttpContext.Current.Response.AddHeader("pragma", "no-cache"); + HttpContext.Current.Response.AddHeader("cache-control", "private"); + HttpContext.Current.Response.CacheControl = "no-cache"; + return true; + } + /// + /// Jmail4.3FSOıд + /// + /// + /// + public bool IsObjInstalled(string _obj) + { + bool IsFSOInstalled = false; + try + { + Server.CreateObject(_obj); + IsFSOInstalled = true; + + } + catch (Exception ex) + { + IsFSOInstalled = false; + } + return IsFSOInstalled; + } + /// + /// ȡű + /// + /// + public string JiaoBenYinqing() + { + return GlobalObject.ScriptEngine() + "/" + GlobalObject.ScriptEngineMajorVersion() + "." + GlobalObject.ScriptEngineMinorVersion() + "." + GlobalObject.ScriptEngineBuildVersion(); + } + /// + /// ȡip + /// + /// + public string ServerIp() + { + string stringMAC = ""; + string stringIP = ""; + ManagementClass MC = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection MOC = MC.GetInstances(); + foreach (ManagementObject MO in MOC) + { + if ((bool)MO["IPEnabled"] == true) + { + stringMAC += MO["MACAddress"].ToString(); + //TextMAC.Text = stringMAC.ToString(); + string[] IPAddresses = (string[])MO["IPAddress"]; + if (IPAddresses.Length > 0) stringIP = IPAddresses[0]; + } + } + return stringIP; + } + /// + /// ȡϵͳ + /// + /// + public string ServerOS() + { + return System.Environment.OSVersion.ToString(); + } + /// + /// ٶȲ + /// + /// + public string IntTest() + { + string Value; + Stopwatch timer = new Stopwatch(); + long total = 0; + timer.Start(); + for (int i = 1; i <= 500000; i++) + { + total += i; + } + timer.Stop(); + decimal micro = timer.Elapsed.Ticks / 10m; + Value = "ԣڽ50μӷ......ɣ" + micro.ToString() + "΢" + ""; + return Value; + } + /// + /// ʵٶȲ + /// + /// + public string FloatTest() + { + string Value; + Stopwatch timer = new Stopwatch(); + long total = 0; + timer.Start(); + for (int i = 1; i <= 200000; i++) + { + total *= total; + } + timer.Stop(); + decimal micro = timer.Elapsed.Ticks / 10m; + Value = "ԣڽ20γ˷......ɣ" + micro.ToString() + "΢" + ""; + return Value; + } + /// + /// ݿ + /// + /// + /// + /// + /// + public string DbBackup(string strDbName, string strFileName, string strRname) + { + try + { + SQLDMO.Backup oBackup = new SQLDMO.BackupClass(); + SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass(); + oSQLServer.LoginSecure = false; + oSQLServer.Connect(strServer, strUid, strPwd); + oBackup.Action = SQLDMO.SQLDMO_BACKUP_TYPE.SQLDMOBackup_Database; + oBackup.Database = strDbName; + + string Path = strFileName + strRname; + oBackup.Files = Path; + oBackup.BackupSetName = strRname; + oBackup.BackupSetDescription = "ݿ"; + oBackup.Initialize = true; + oBackup.SQLBackup(oSQLServer); + oSQLServer.DisConnect(); + return "ok"; + } + catch (Exception ex) + { + return ex.Message; + } + } + /// + /// ԭݿ + /// + /// + /// + /// + /// + public bool DbRestore(string strDbName, string strFileName, string strRname) + { + strDbName = strDatabase; + strFileName = ""; + SQLDMO.Restore oRestore = new SQLDMO.RestoreClass(); + SQLDMO.SQLServer oSQLServer = new SQLDMO.SQLServerClass(); + try + { + oSQLServer.LoginSecure = false; + oSQLServer.Connect(strServer, strUid, strPwd); + oRestore.Action = SQLDMO.SQLDMO_RESTORE_TYPE.SQLDMORestore_Database; + oRestore.Database = strDbName; + oRestore.Files = strFileName + strRname; + oRestore.FileNumber = 1; + oRestore.ReplaceDatabase = true; + oRestore.SQLRestore(oSQLServer); + return true; + } + catch + { + return false; + } + } + /// + /// ȡϵͳʹ + /// + /// + public string readConame() + { + string strConame; + SqlDataReader Myreader; + Myreader = getRead("select webname from tbset where id=1"); + if (Myreader.Read()) + { + strConame = Myreader["webname"].ToString(); + } + else + { + strConame = "(Ƚϵͳ)"; + } + Myreader.Close(); + return strConame; + } + /// + /// ͳƷռռ + /// + /// + /// + public long GetDirectoryLength(string dirPath) + { + //жϸ·Ƿ,˳ + if (!Directory.Exists(dirPath)) + return 0; + long len = 0; + + //һDirectoryInfo + DirectoryInfo di = new DirectoryInfo(dirPath); + + //ͨGetFiles,ȡdiĿ¼еļĴС + foreach (FileInfo fi in di.GetFiles()) + { + len += fi.Length; + } + //ȡdiеļ,浽һµĶ,Խеݹ + DirectoryInfo[] dis = di.GetDirectories(); + if (dis.Length > 0) + { + for (int i = 0; i < dis.Length; i++) + { + len += GetDirectoryLength(dis[i].FullName); + } + } + return len; + } + /// + /// ҪIP + /// + /// + /// + public int lockip(string strAddIp) + { + int returnId = 0; + int intId = 1; + bool bsign = false; + string strIpGroup; + string strIp = strAddIp; + SqlDataReader myreader = getRead("select ip from TbIp where id=1"); + if (myreader.Read()) + { + string[] strIPzu = myreader["ip"].ToString().Split('|'); + for (int i = 0; i < strIPzu.Length; i++) + { + if (strIp == strIPzu[i]) + { + bsign = true; + } + } + strIpGroup = myreader["ip"].ToString(); + myreader.Close(); + if (bsign == false) + { + if (strIpGroup == "") + { + strIpGroup = strIp; + } + else + { + strIpGroup = strIpGroup + "|" + strIp; + } + if (doExecute("update tbIp set ip='" + strIpGroup + "' where id=1")) + { + //Response.Redirect("Success.aspx?message=IPɹ&url=IpManage.aspx"); + returnId = 1; + } + } + else if (bsign == true) + { + //Response.Redirect("Error.aspx?message=ʧܣIPѱ&url=IpManage.aspx"); + returnId = 2; + } + } + else + { + myreader.Close(); + if (doExecute("insert into tbIp(id,ip)values(" + intId + ",'" + strIp + "')")) + { + //Response.Redirect("Success.aspx?message=IPɹ&url=IpManage.aspx"); + returnId = 3; + } + } + return returnId; + } + /// + /// ʾIP + /// + /// + public string showLockIp() + { + string strIp = ""; + SqlDataReader myreader = getRead("select ip from tbIp where id=1"); + if (myreader.Read()) + { + strIp = myreader["ip"].ToString(); + } + myreader.Close(); + return strIp.Trim(); + } + /// + /// IPб + /// + /// + /// + public bool updateIp(string strIps) + { + bool sign = false; + SqlDataReader myreader = getRead("select * from tbIp where id=1"); + if (myreader.Read()) + { + if (doExecute("update tbIp set ip='" + strIps + "' where id=1")) + { + sign = true; + } + } + else + { + int id = 1; + if (doExecute("insert into tbIp(id,ip)values(" + id + ",'" + strIps + "')")) + { + sign = true; + } + } + myreader.Close(); + return sign; + } + /// + /// жǷرվ + /// + /// + public void ShowWebState() + { + string state = "1"; + SqlDataReader myreader = getRead("select state from TBset where id=1"); + if (myreader.Read()) + { + state = myreader["state"].ToString(); + if (state == "0") + { + System.Web.HttpContext.Current.Response.Write(""); + } + } + myreader.Close(); + } + /// + /// ȡTitle,Description,Keys + /// + public void showWebTitle() + { + int intId = 1; + SqlDataReader Myreader = getRead("select * from TBset where id=" + intId + ""); + if (Myreader.Read()) + { + strTitle = Myreader["webname"].ToString(); + strDescription = Myreader["webdescription"].ToString(); + strKeys = Myreader["webkeys"].ToString(); + } + Myreader.Close(); + StartProcessRequest();//ûǷ + ShowWebState();//жվǷر + } + /// + /// ûǷ + /// + /// + public static void StartProcessRequest() + { + try + { + string getkeys = ""; + //string sqlErrorPage = System.Configuration.ConfigurationSettings.AppSettings["CustomErrorPage"].ToString(); + if (System.Web.HttpContext.Current.Request.QueryString != null) + { + + for (int i = 0; i < System.Web.HttpContext.Current.Request.QueryString.Count; i++) + { + getkeys = System.Web.HttpContext.Current.Request.QueryString.Keys[i]; + if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.QueryString[getkeys], 0)) + { + //System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage+"?errmsg=sqlserver&sqlprocess=true"); + System.Web.HttpContext.Current.Response.Write(""); + System.Web.HttpContext.Current.Response.End(); + } + } + } + if (System.Web.HttpContext.Current.Request.Form != null) + { + for (int i = 0; i < System.Web.HttpContext.Current.Request.Form.Count; i++) + { + getkeys = System.Web.HttpContext.Current.Request.Form.Keys[i]; + if (!ProcessSqlStr(System.Web.HttpContext.Current.Request.Form[getkeys], 1)) + { + //System.Web.HttpContext.Current.Response.Redirect (sqlErrorPage+"?errmsg=sqlserver&sqlprocess=true"); + System.Web.HttpContext.Current.Response.Write(""); + System.Web.HttpContext.Current.Response.End(); + } + } + } + } + catch + { + // : ûύϢ! + } + } + /**/ + /// + /// ûǷ + /// + /// ûύ + /// ǷSQLעʽ + private static bool ProcessSqlStr(string Str, int type) + { + string SqlStr; + + if (type == 1) + SqlStr = "exec|insert|select|delete|update|count|chr|mid|master|truncate|char|declare"; + else + SqlStr = "'|and|exec|insert|select|delete|update|count|*|chr|mid|master|truncate|char|declare|>|<"; + + bool ReturnValue = true; + try + { + if (Str != "") + { + string[] anySqlStr = SqlStr.Split('|'); + foreach (string ss in anySqlStr) + { + if (Str.IndexOf(ss) >= 0) + { + ReturnValue = false; + } + } + } + } + catch + { + ReturnValue = false; + } + return ReturnValue; + } + /// + /// жǷ + /// + /// + /// bool + public bool IsNumberic(string oText)//жǷ + { + try + { + int var1 = System.Convert.ToInt32(oText); + if (var1 < 0) + { + return false; + } + return true; + } + catch + { + return false; + } + } + /// + /// ȡַ + /// + /// + /// + /// string + public string SubString(string inputString, int length) + { + if (Encoding.UTF8.GetByteCount(inputString) <= length * 2) + { + return inputString; + } + ASCIIEncoding ascii = new ASCIIEncoding(); + int tempLen = 0; + string tempString = ""; + byte[] s = ascii.GetBytes(inputString); + for (int i = 0; i < s.Length; i++) + { + if ((int)s[i] == 63) + { + tempLen += 2; + } + else + { + tempLen += 1; + } + tempString += inputString.Substring(i, 1); + if (tempLen >= (length - 1) * 2) + break; + } + //عϰʡԺ + if (System.Text.Encoding.Default.GetBytes(inputString).Length > length) + tempString += ""; + return tempString; + } + /// + /// ʾ¼״̬ + /// + public void ShowLoginState() + { + if (Session["j95fn3839vfn93h9n29n"] == null) + { + System.Web.HttpContext.Current.Response.Write(""); + } + } + #region JSʾ============================================ + + /// + /// ӱ༭ɾʾ + /// + /// ʾ + /// صַ + /// CSSʽ + public void JscriptMsg(string msgtitle, string url, string msgcss) + { + string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\")"; + ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true); + } + + /// + /// شӱ༭ɾʾ + /// + /// ʾ + /// صַ + /// CSSʽ + /// JSص + public void JscriptMsg(string msgtitle, string url, string msgcss, string callback) + { + string msbox = "parent.jsprint(\"" + msgtitle + "\", \"" + url + "\", \"" + msgcss + "\", " + callback + ")"; + ClientScript.RegisterClientScriptBlock(Page.GetType(), "JsPrint", msbox, true); + } + #endregion + + + } +}