using BizCom; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Runtime.InteropServices; using System.Text; using System.Web; using Utils; namespace SiteCore { public class WebHelper { static int exp_page_size = 9999; public static List> getComReportData(string url, string parms) { HttpCookie lcCookie = HttpContext.Current.Request.Cookies[webConfig.CookieName]; string name = HttpUtility.UrlDecode(lcCookie.Values["User"]); string ticket = lcCookie.Values["Ticket"]; if (parms == "") parms = "pageSize=" + exp_page_size; else parms += "&pageSize=" + exp_page_size; parms += "&_expt=1"; //parms = HttpUtility.UrlEncode(parms); HttpHelper http = new HttpHelper(); HttpItem item = new HttpItem() { URL = url, Method = "POST", ContentType = "application/x-www-form-urlencoded; charset=UTF-8", Cookie = webConfig.CookieName + "=user=" + name + "&ticket=" + ticket, Postdata = parms }; HttpResult hresult = http.GetHtml(item); string html = hresult.Html; JObject jobj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(html); if (jobj["total"] != null) { List> lists_sec; List> lists = JsonConvert.DeserializeObject>>(jobj["data"].ToString()); int pg = (Convert.ToInt32(jobj["total"]) - 1) / exp_page_size + 1; // exp_page_size; if (pg > 1) { for (int i = 2; i <= pg; i++) { if (i == 2) parms = parms.Replace("pageIndex=0", "pageIndex=" + i); parms = parms.Replace("pageIndex=" + (i - 1), "pageIndex=" + i); item = new HttpItem() { URL = url, Method = "POST", ContentType = "application/x-www-form-urlencoded; charset=UTF-8", Cookie = webConfig.CookieName + "=user=" + name + "&ticket=" + ticket, Postdata = parms }; hresult = http.GetHtml(item); html = hresult.Html; jobj = (JObject)Newtonsoft.Json.JsonConvert.DeserializeObject(html); if (jobj["total"] != null) { lists_sec = JsonConvert.DeserializeObject>>(jobj["data"].ToString()); lists.AddRange(lists_sec); } } } return lists; //Hashtable htable= JsonConvert.DeserializeObject(jobj["data"].ToString()); } return null; } public static object GetReflectionObject(string className) { if (string.IsNullOrEmpty(className)) return null; string tmpName = "BizCom." + className; return Assembly.Load("BizCom").CreateInstance(tmpName); } private static void sendSign(string str, ref StringBuilder sql) { if (str != "" && str != "|") { List lst = new List(); string[] sArr = str.Split('|'); string[] tArr; for (int i = 0; i < sArr.Length; i++) { tArr = sArr[i].Split(','); if (tArr.Length < 7 || tArr[6] == "") continue; //WxPush.sendSignMsg(tArr, lst); } if (lst.Count > 0) { sql.AppendFormat("delete from S_WxFormId where formids in ({0}) ;", string.Join(",", lst.ToArray())); } } } private static void sendExpire(string str, ref StringBuilder sql) { if (str != "" && str != "|") { List lst = new List(); string[] sArr = str.Split('|'); string[] tArr; for (int i = 0; i < sArr.Length; i++) { tArr = sArr[i].Split(','); if (tArr.Length < 7 || tArr[6] == "") continue; //WxPush.sendExpireMsg(tArr, lst); } if (lst.Count > 0) { sql.AppendFormat("delete from S_WxFormId where formids in ({0}) ;", string.Join(",", lst.ToArray())); } } } /// /// 重置密码发送邮件 /// /// /// /// /// /// public static bool SendResetPwdMail(string to, string userName, string rkey, out string errMsg) { errMsg = ""; StringBuilder str = new StringBuilder(); str.Append("
"); str.AppendFormat("
{0}您好,
", userName); str.Append("
 
"); str.Append("
请点击下面链接进行密码重置:
"); str.Append("
 
"); //str.AppendFormat("
您在城市便签的密码已经重置为:{0}(注意大小写)
", pwd); //str.Append("
 
"); string url = webConfig.SiteUrl + "resetpwd.aspx?acc=" + to + "&key=" + rkey; str.AppendFormat("", url); str.Append("
 
"); str.Append("
2小时内有效
"); str.AppendFormat("", webConfig.SiteUrl, webConfig.SiteName); str.Append("
"); MailService service = new MailService(); try { service.enableSsl(false); return service.send(to, webConfig.SiteName + "重置密码邮件", str.ToString()); } catch (Exception ex) { errMsg = ex.Message; return false; } } //public static string GetUserPic(string path,object pic) //{ // GetUserPic() // if (pic.ToString() == "") // { // return "../img/dp3.png"; // } // else // { // return path + pic; // } //} /// /// 将c# DateTime时间格式转换为Unix时间戳格式 /// /// 时间 /// long public static long ConvertDateTimeToInt(System.DateTime time) { System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0)); long t = (time.Ticks - startTime.Ticks) / 10000000; //除10000调整为13位 return t; } public static string GetUserPic(string path, object pic, string def) { if (pic.ToString() == "") { return def;// "../img/dp3.png"; } else { return path + pic; } } public static string DateStringFromNow(object dt) { DateTime nDt = Convert.ToDateTime(dt); TimeSpan span = DateTime.Now - nDt; if (span.TotalDays > 30) { return nDt.ToString("yyyy.MM.dd"); } else if (span.TotalDays > 14) { return "2周前"; } else if (span.TotalDays > 7) { return "1周前"; } else if (span.TotalDays > 1) { return string.Format("{0}天前", (int)Math.Floor(span.TotalDays)); } else if (span.TotalHours > 1) { return string.Format("{0}小时前", (int)Math.Floor(span.TotalHours)); } else if (span.TotalMinutes > 1) { return string.Format("{0}分钟前", (int)Math.Floor(span.TotalMinutes)); } else if (span.TotalSeconds >= 1) { return string.Format("{0}秒前", (int)Math.Floor(span.TotalSeconds)); } else { return "1秒前"; } } public static string getLoginTicket(string acc, string ip) { return SecurityHelper.EncryptMD5(acc + "-" + DateTime.Now.ToString("yyMMdd") + "|" + ip); } public static string getLoginTicket(string acc) { //FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, acc, DateTime.Now, DateTime.Now.AddDays(2), false, Environment.MachineName); //FormsAuthentication.Encrypt return SecurityHelper.EncryptMD5(acc + "-" + getLoginMac()); } [DllImport("Iphlpapi.dll")] private static extern int SendARP(Int32 dest, Int32 host, ref Int64 mac, ref Int32 length); [DllImport("Ws2_32.dll")] private static extern Int32 inet_addr(string ip); /// /// 获取客户端IP地址 /// /// 若失败则返回回送地址 public static string GetIP() { string userHostAddress = ""; //如果客户端使用了代理服务器,则利用HTTP_X_FORWARDED_FOR找到客户端IP地址 if (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null) { userHostAddress = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim(); } //否则直接读取REMOTE_ADDR获取客户端IP地址 if (string.IsNullOrEmpty(userHostAddress)) { userHostAddress = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; } //前两者均失败,则利用Request.UserHostAddress属性获取IP地址,但此时无法确定该IP是客户端IP还是代理IP if (string.IsNullOrEmpty(userHostAddress)) { userHostAddress = HttpContext.Current.Request.UserHostAddress; } //最后判断获取是否成功,并检查IP地址的格式(检查其格式非常重要) if (!string.IsNullOrEmpty(userHostAddress) && IsIP(userHostAddress)) { return userHostAddress; } string hostName = Dns.GetHostName(); IPHostEntry ipEntry = Dns.GetHostEntry(hostName); for (int i = 0; i < ipEntry.AddressList.Length; i++) { if (ipEntry.AddressList[i].AddressFamily == AddressFamily.InterNetwork) { userHostAddress = ipEntry.AddressList[i].ToString(); } } return userHostAddress;// "127.0.0.1"; } /// /// 检查IP地址格式 /// /// /// public static bool IsIP(string ip) { return System.Text.RegularExpressions.Regex.IsMatch(ip, @"^((2[0-4]\d|25[0-5]|[01]?\d\d?)\.){3}(2[0-4]\d|25[0-5]|[01]?\d\d?)$"); } public static string getLoginMac() { // 在此处放置用户代码以初始化页面 try { string userip = GetIP(); string strClientIP = HttpContext.Current.Request.UserHostAddress.ToString().Trim(); Int32 ldest = inet_addr(strClientIP); //目的地的ip Int32 lhost = inet_addr(""); //本地服务器的ip Int64 macinfo = new Int64(); Int32 len = 6; int res = SendARP(ldest, 0, ref macinfo, ref len); string mac_src = macinfo.ToString("X"); if (mac_src == "0") { //if (userip == "127.0.0.1") // Response.Write("正在访问Localhost!"); //else // Response.Write("欢迎来自IP为" + userip + "的朋友!" + "
"); return ""; } while (mac_src.Length < 12) { mac_src = mac_src.Insert(0, "0"); } string mac_dest = ""; for (int i = 0; i < 11; i++) { if (0 == (i % 2)) { if (i == 10) { mac_dest = mac_dest.Insert(0, mac_src.Substring(i, 2)); } else { mac_dest = "-" + mac_dest.Insert(0, mac_src.Substring(i, 2)); } } } return userip + mac_dest; } catch (Exception err) { XLog.SaveLog(0, err.Message); return ""; } } //public static int ConvertDateTimeToInt(System.DateTime time) //{ // System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1)); // return (int)(time - startTime).TotalSeconds; //} public static DateTime ConvertStringToDateTime(string timeStamp) { DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1)); long lTime = long.Parse(timeStamp + "0000000"); TimeSpan toNow = new TimeSpan(lTime); return dtStart.Add(toNow); } private static string getRandNum(int s, int e) { Random rd = new Random((int)DateTime.Now.Ticks); return rd.Next(s, e).ToString(); } public static string EnscryptNumber(string code) { if (code == "") return ""; if (code.Length > 6) code = code.Substring(4); string ct = ConvertDateTimeToInt(DateTime.Now).ToString(); code = ct.Substring(5) + getRandNum(1, 9) + code + ct.Substring(0, 5); int r = getSeed(); return EnscryptNumber(r, code); } public static int getSeed() { return Convert.ToInt32(getRandNum(2, 9)); } public static string EnscryptNumber(int r, string code) { List lst = new List(); for (int i = 0; i < code.Length; i++) { int c = Convert.ToInt32(code[i].ToString()) + r; if (c >= 10) c = c - 10; lst.Add(c.ToString()); } string v = string.Join("", lst.ToArray()); v = v.Insert(0, r.ToString()); return v; } public static string DescryptNumber(string code) { int len = code.Length; int r = Convert.ToInt32(code.Substring(0, 1)); code = code.Remove(0, 1); List lst = new List(); for (int i = 0; i < code.Length; i++) { int c = Convert.ToInt32(code[i].ToString()) - r; if (c < 0) c = c + 10; lst.Add(c.ToString()); } return string.Join("", lst.ToArray()); } public static string getUserCode(string code) { if (code.Length < 8) return ""; return code.Substring(6, 6); } //判断时间 public static bool isLegalTime(string code) { if (code.Length < 8) return false; string timeStamp = code.Substring(code.Length - 5) + code.Substring(0, 5); DateTime dTime = ConvertStringToDateTime(timeStamp); if (DateTime.Now.Subtract(dTime).TotalMinutes <= 5) { return true; } return false; } public static bool isWeiXinAgent(string userAgent) { if (userAgent.ToLower().Contains("micromessenger")) { return true; } return false; } public static string getEncodeCode(int id, int state) { string uid = SecurityHelper.EncryptSymmetric(id.ToString()); string con = DecryptHelper.Encrypt(getRandNum(1, 5000) + "|" + uid + "|" + state + "|" + ConvertDateTimeToInt(DateTime.Now) + "|" + getRandNum(1000, 3000)); return con; } public static string getEncodeCodeByEUser(object uid, object state) { string con = DecryptHelper.Encrypt(getRandNum(1, 5000) + "|" + uid + "|" + state + "|" + ConvertDateTimeToInt(DateTime.Now) + "|" + getRandNum(1000, 3000)); return HttpUtility.UrlEncode(con); } public static string getCodeByEUser(object uid, object state) { string con = DecryptHelper.Encrypt(getRandNum(1, 5000) + "|" + uid + "|" + state + "|" + ConvertDateTimeToInt(DateTime.Now) + "|" + getRandNum(1000, 3000)); return con; } public static string getEncodeCodeByNormal(string code) { string[] sArr = code.ToString().Split('|'); return getEncodeCode(Convert.ToInt32(sArr[0]), Convert.ToInt32(sArr[1])); } public static int getUid(string tmp) { string uid = SecurityHelper.DecryptSymmetric(tmp); return Convert.ToInt32(uid); } //public static string getEncodeCodeUnUser(string code) //{ // string[] sArr = code.ToString().Split('|'); // return getEncodeCodeUnUser(sArr[0], sArr[1]); //} public static int getDecodeUid(string tmp) { try { string t = HttpUtility.UrlDecode(tmp); t = DecryptHelper.Decrypt(t); string[] tArr = t.Split('|'); tArr[0] = SecurityHelper.DecryptSymmetric(tArr[0]); return Convert.ToInt32(tArr[0]); } catch { } return 0; } public static string[] getDecodeArr(string tmp) { try { string t = DecryptHelper.Decrypt(tmp); string[] tArr = t.Split('|'); return tArr; } catch { } return null; } static string cname = "wx_quduba"; public static void addCookie(string key, string value) { HttpCookie cookie = new HttpCookie(cname); cookie.Values.Clear(); cookie.Values.Add(key, value); cookie.Path = "/"; cookie.Domain = webConfig.SiteDomain; cookie.Expires = DateTime.Now.AddDays(2); HttpContext.Current.Response.Cookies.Add(cookie); } public static string getCookie(string key) { HttpCookie cookie = HttpContext.Current.Request.Cookies[cname]; if (cookie != null) return cookie.Values[key]; return ""; } public static void delCookie(string key) { if (key == "") return; HttpCookie cookie = new HttpCookie(key); cookie.Expires = DateTime.Now.AddDays(-1d); HttpContext.Current.Response.Cookies.Add(cookie); } public static List GetStartEndDateTime(string dateType = "") { List RetDT = new List(); switch (dateType) { case "Today": case "0": RetDT = GetTodayStartEndTime(); break; case "1": case "Week": RetDT = GetWeekStartEndTime(); break; case "2": case "Month": RetDT = GetMonthStartEndTime(); break; default: RetDT = GetTodayStartEndTime(); break; } return RetDT; } public static List GetTodayStartEndTime() { List RetDT = new List(); RetDT.Add(DateTime.Now.Date); RetDT.Add(DateTime.Parse(DateTime.Now.ToString("yyyy-MM-dd") + " 23:59:59")); return RetDT; } public static List GetWeekStartEndTime() { DateTime dt = DateTime.Now; int dayOfWeek = (int)dt.Date.DayOfWeek; //Sunday = 0,Monday = 1,Tuesday = 2,Wednesday = 3,Thursday = 4,Friday = 5,Saturday = 6, DateTime weekStartTime = dt.AddDays(-1 * dayOfWeek + 1);//取本周一 if (dayOfWeek == 0) //如果今天是周日,则开始时间是上周一 { weekStartTime = weekStartTime.AddDays(-7); } DateTime weekEndTime = dt.AddDays(7 - dayOfWeek);//取本周日 if (dayOfWeek == 0) //如果今天是周日,则开始时间是上周一 { weekEndTime = weekEndTime.AddDays(-7); } List RetDT = new List(); RetDT.Add(weekStartTime.Date); RetDT.Add(DateTime.Parse(weekEndTime.ToString("yyyy-MM-dd") + " 23:59:59")); return RetDT; } public static List GetMonthStartEndTime() { DateTime dt = DateTime.Now; //本月第一天时间 DateTime dt_First = dt.AddDays(1 - (dt.Day)); //获得某年某月的天数 int year = dt.Date.Year; int month = dt.Date.Month; int dayCount = DateTime.DaysInMonth(year, month); //本月最后一天时间 DateTime dt_Last = dt_First.AddDays(dayCount - 1); List RetDT = new List(); RetDT.Add(dt_First.Date); RetDT.Add(DateTime.Parse(dt_Last.ToString("yyyy-MM-dd") + " 23:59:59")); return RetDT; } } }