| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547 |
- <%@ Application Language="C#" %>
- <%@ Import Namespace="Castle.ActiveRecord" %>
- <%@ Import Namespace="Castle.ActiveRecord.Framework.Config" %>
- <%@ Import Namespace="BizCom" %>
- <%@ Import Namespace="SiteCore" %>
- <%@ Import Namespace="Utils" %>
- <%@ Import Namespace="System.Threading" %>
- <%@ Import Namespace="System.IO" %>
- <%@ Import Namespace="System.Data" %>
- <%@ Import Namespace="System.Data.SqlClient" %>
- <%@ Import Namespace="System.Web" %>
- <%@ Import Namespace="System.Security.Cryptography" %>
- <%@ Import Namespace="Newtonsoft.Json" %>
- <script RunAt="server">
- static HttpHelper tb_http = new HttpHelper();
- static string api_url = "http://xy.ifireant.com/taobaoapi";
- string conn = "";
- System.Threading.Timer gtimer;
- int BeginInterval = 100;
- System.Timers.Timer timerGetRefundsData;
- System.Timers.Timer timerCheckUnusualOrder;
- System.Timers.Timer timerAutoDispatch;
- System.Timers.Timer timerDayClear;
- void Application_Start(object sender, EventArgs e)
- {
- log4net.Config.XmlConfigurator.Configure();
- // Code that runs on application startup
- InPlaceConfigurationSource source = new InPlaceConfigurationSource();
- System.Collections.Generic.IDictionary<string, string> properties = new System.Collections.Generic.Dictionary<string, string>();
- properties.Add("connection.driver_class", "NHibernate.Driver.SqlClientDriver");
- properties.Add("proxyfactory.factory_class", "NHibernate.ByteCode.Castle.ProxyFactoryFactory,NHibernate.ByteCode.Castle");
- properties.Add("dialect", "NHibernate.Dialect.MsSql2005Dialect");
- properties.Add("connection.provider", "NHibernate.Connection.DriverConnectionProvider");
- properties.Add("show_sql", "true");
- conn = ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString;
- properties.Add("connection.connection_string", conn);
- source.Add(typeof(ActiveRecordBase), properties);
- source.IsRunningInWebApp = true;
- //IConfigurationSource source =ConfigurationManager.GetSection("activerecord") as IConfigurationSource;
- Type[] acTypes = new[]
- {
- typeof(XUser),
- typeof(XModular),
- typeof(CeErpModular),
- typeof(CeErpUser),
- typeof(CeErpPost),
- //typeof(CeErpPersonPost),
- typeof(CeErpUserInfo),
- typeof(CeErpOrderFormData),
- typeof(CeErpOrganization),
- typeof(CeErpShop),
- typeof(CeErpSupplier),
- typeof(CeErpProduct),
- typeof(CeErpProductHour),
- typeof(CeErpSupplierProduct),
- typeof(CeErpTrade),
- typeof(CeErpTradeOrder),
- typeof(CeErpTradeCell),
- typeof(CeErpTradeLog),
- typeof(CeErpTradeResponsible),
- typeof(CeErpTradeAfterSaleLog),
- typeof(CeErpTradeAfterSaleExtend),
- typeof(CeErpTradeCellExtend),
- typeof(CeErpTradeRefund),
- typeof(CeErpTradeSample),
- typeof(CeErpBill),
- typeof(CeErpReturnCash),
- typeof(CeErpExpressInfo),
- typeof(CeErpUserPost),
- typeof(CeErpZhangDan),
- typeof(CeErpInvoicingInfo),
- typeof(CeErpCustomer),
- typeof(CeErpTmcLog),
- typeof(XPermission),
- typeof(XLog),
- typeof(Log_Login),
- typeof(LogOperate),
- typeof(SiteInfo),
- typeof(CEErpPrintModel),
- typeof(CeErpNotice),
- typeof(CeErpNoticeCell),
- typeof(CeErpDesignerFinishRate),
- typeof(CeErpPlaceRegister),
- typeof(CeErpPersuade),
- typeof(CeErpProcessList),
- typeof(CeErpMethod),
- typeof(CeErpStayGoods),
- typeof(CeErpProfession),
- typeof(CeErpDesignerBill),
- typeof(CeErpDesignerBillLog),
- typeof(CeErpProductPrice),
- typeof(CeErpMailInfo),
- typeof(SupplierLog),
- typeof(CeErpMessageTip),
- typeof(CeErpToManagement),
- typeof(CeErpSpecialRefund),
- typeof(CeErpMessageAPI),
- typeof(CeErpDesignerFinishRateNew),
- typeof(CeWithdraw),
- typeof(CeErpDesignInfo),
- typeof(CeErpSampleCustomer),
- typeof(CeErpTradeSpu),
- typeof(CeErpSukuraData),
- typeof(CeErpDeliverMark),
- typeof(CeErpDataSendOrderInfo)
- };
- ActiveRecordStarter.Initialize(source, acTypes);
- //gtimer = new System.Threading.Timer(new TimerCallback(global_elapsed), null, 5000, 5000);//每5秒钟运行一次
- ////初始化获取退款数据定时任务定时器
- //InitGetRefundsDataTimer();
- ////初始化更新异常订单状态定时器
- //InitCheckUnusualOrderTimer();
- //初始化自动派单定时器
- //InitAutoDispatchTimer();
- //初始化每日清除数据定时器
- //InitDayClearTimer();
- }
- #region 获取退款数据定时任务
- //初始化获取退款数据定时器
- private void InitGetRefundsDataTimer()
- {
- timerGetRefundsData = new System.Timers.Timer();
- timerGetRefundsData.Interval = BeginInterval;
- timerGetRefundsData.Elapsed += new System.Timers.ElapsedEventHandler(GetRefundsData);
- timerGetRefundsData.Enabled = true;
- }
- //退款任务改为定时查看是否有责任人为确认 认可责任,大于48小时自动确认
- private void GetRefundsData(object sender, System.Timers.ElapsedEventArgs e)
- {
- timerGetRefundsData.Enabled = false;
- if (webConfig.Refund_Switch == "1")
- {
- timerGetRefundsData.Interval = int.Parse(webConfig.Refund_Interval);
- //每天获取退款信息的时间
- if (webConfig.Refund_Time.Contains(DateTime.Now.ToString("HH")))
- {
- commonHelper.autoRefreshRefundState();
- }
- }
- //if (webConfig.Refund_Switch == "1")
- //{
- // timerGetRefundsData.Interval = int.Parse(webConfig.Refund_Interval);
- // //每天获取退款信息的时间
- // if (DateTime.Now.ToString("HH:mm") == webConfig.Refund_Time)
- // {
- // WriteLog(string.Format("退款 | {0} | {1}", DateTime.Now.ToString(), "开始获取退款数据!"));
- // SqlConnection sqlCnt = new SqlConnection(conn);
- // sqlCnt.Open();
- // //按店铺获取退款信息
- // string sql = "select * from CE_ErpShop";
- // SqlDataAdapter myDataAdapter = new SqlDataAdapter(sql, sqlCnt);
- // DataSet myDataSet = new DataSet();
- // myDataAdapter.Fill(myDataSet, "Shop");
- // DataTable myTable = myDataSet.Tables[0];
- // foreach (DataRow Dr in myTable.Rows)
- // {
- // string shopname = Dr["ShopName"].ToString();
- // string sessionKey = Dr["AppSecret"].ToString();
- // if (sessionKey == null || sessionKey == "")
- // {
- // continue;
- // }
- // DateTime stime = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 00:00:00"));
- // DateTime etime = DateTime.Parse(DateTime.Now.AddDays(-1).ToString("yyyy-MM-dd 23:59:59"));
- // string res = RefundsReceiveGet(sessionKey, stime, etime);
- // //判断是否获取有效的退款信息
- // if (res == "") return;
- // if (res.Contains("error_response"))
- // {
- // WriteLog(string.Format("退款 | {0} | {1}" , DateTime.Now.ToString(), res));
- // continue;
- // }
- // try
- // {
- // SiteCore.taoObj.Refunds_receive_get_response_Obj reObj = null;
- // res = GetUTF8String2(Encoding.UTF8.GetBytes(res));
- // reObj = JsonConvert.DeserializeObject<SiteCore.taoObj.Refunds_receive_get_response_Obj>(res);
- // List<SiteCore.taoObj.Refunds_receive_get_response_Obj.Refund> reItemList = reObj.refunds_receive_get_response.refunds.refund;
- // foreach (SiteCore.taoObj.Refunds_receive_get_response_Obj.Refund item in reItemList)
- // {
- // //若退款信息已存在则遍历下一条数据
- // string RefundExistSQL = string.Format("SELECT * FROM CE_ErpTradeRefund WHERE refund_id = '{0}'", item.refund_id);
- // SqlDataAdapter adRefundExist = new SqlDataAdapter(RefundExistSQL, sqlCnt);
- // DataSet dsRefundExist = new DataSet();
- // adRefundExist.Fill(dsRefundExist, "Refund");
- // if (dsRefundExist.Tables[0].Rows.Count > 0)
- // continue;
- // //插入退款数据
- // string RefundInsertSQL = string.Format("INSERT INTO CE_ErpTradeRefund " +
- // "(refund_id,tid,oid,created,modified,status,order_status,good_status,payment,refund_fee,refund_phase,reason,describe,buyer_nick,seller_nick,total_fee,has_good_return,RefundState) " +
- // "VALUES ('{0}','{1}','{2}','{3}','{4}','{5}'," +
- // "'{6}','{7}','{8}','{9}','{10}','{11}'," +
- // "'{12}','{13}','{14}','{15}',{16},{17})",
- // item.refund_id, item.tid, item.oid, item.created.ToString(), item.modified.ToString(), item.status,
- // item.order_status, item.good_status, item.payment, item.refund_fee, item.refund_phase, item.reason,
- // item.desc, item.buyer_nick, item.seller_nick, item.total_fee, item.has_good_return ? "1" : "0", 1);
- // SqlCommand insertCMD = sqlCnt.CreateCommand(); //创建SqlCommand对象
- // insertCMD.CommandType = CommandType.Text;
- // insertCMD.CommandText = RefundInsertSQL;
- // insertCMD.ExecuteNonQuery();
- // insertCMD.CommandText = "insert into CE_ErpTradeLog(tid,OrderState,UserId,OperateTime,Con,AfterSaleState)"
- // + string.Format(" Values('{0}',9, 0 ,getdate(),'{1}',0);", item.tid, "退款完成"); ;
- // insertCMD.ExecuteNonQuery();
- // }
- // WriteLog(string.Format("退款 | {0} | {1}", DateTime.Now.ToString(), "结束获取退款数据!"));
- // }
- // catch (Exception ex)
- // {
- // WriteLog(string.Format("退款 | {0} | {1}", DateTime.Now.ToString(), ex.Message));
- // }
- // finally
- // {
- // if (sqlCnt.State == ConnectionState.Open)
- // sqlCnt.Close();
- // }
- // }
- // }
- //}
- timerGetRefundsData.Enabled = true;
- }
- /// <summary>
- /// 查询退款列表(根据开始结束时间)
- /// </summary>
- /// <param name="sessionKey"></param>
- /// <param name="orderid"></param>
- /// <returns></returns>
- public static string RefundsReceiveGet(string sessionKey, DateTime stime, DateTime etime)
- {
- //json参数
- var res_obj = new
- {
- fields = "refund_id,tid,title,buyer_nick,seller_nick,total_fee,status,created,refund_fee,oid,good_status,company_name,sid,payment,reason,desc,has_good_return,modified,order_status,refund_phase",
- start_modified = stime,
- end_modified = etime
- };
- string ro_json = JsonConvert.SerializeObject(res_obj);
- //post参数
- List<string> postLst = new List<string>();
- setParmsHead(sessionKey, ref postLst);
- postLst.Add("methodName=taobao.refunds.receive.get");
- postLst.Add("requestObjectJson=" + HttpUtility.UrlEncode(ro_json));
- HttpItem item = new HttpItem()
- {
- URL = api_url,
- Method = "POST",
- ContentType = "application/x-www-form-urlencoded",
- Postdata = string.Join("&", postLst.ToArray())
- };
- HttpResult hResult = tb_http.GetHtml(item);
- return hResult.Html;
- //return html;
- }
- private static void setParmsHead(string session, ref List<string> lst)
- {
- lst.Add("action=executeTopApi");
- lst.Add("format=1");
- lst.Add("SessionKey=" + session);
- lst.Add("sign=" + GetSign());
- lst.Add("isItemApi=3");
- }
- public static string GetSign()
- {
- string code = "";
- int sc = DateTimeToUnixTime(DateTime.Now) / 60;
- code = Md5(Md5(sc + "1b46af52a8dcaa822b98b1be9d447bb2").ToLower()).ToLower();
- code = System.Convert.ToBase64String(System.Text.Encoding.Default.GetBytes(code));
- return code;
- }
- /// <summary>
- /// MD5加密
- /// </summary>
- /// <param name="s"></param>
- /// <returns></returns>
- private static string Md5(string s)
- {
- using (var md5 = MD5.Create())
- {
- var result = md5.ComputeHash(Encoding.Default.GetBytes(s));
- var strResult = BitConverter.ToString(result);
- return strResult.Replace("-", "").ToUpper();
- }
- }
- public static int DateTimeToUnixTime(DateTime dateTime)
- {
- return (int)(dateTime - TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1))).TotalSeconds;
- }
- public static string GetUTF8String2(byte[] buffer)
- {
- if (buffer == null)
- return null;
- if (buffer.Length <= 3)
- {
- return Encoding.UTF8.GetString(buffer);
- }
- byte[] bomBuffer = new byte[] { 0xef, 0xbb, 0xbf };
- if (buffer[0] == bomBuffer[0] && buffer[1] == bomBuffer[1] && buffer[2] == bomBuffer[2])
- {
- return new UTF8Encoding(false).GetString(buffer, 3, buffer.Length - 3);
- }
- return Encoding.UTF8.GetString(buffer);
- }
- #endregion
- #region 更新异常订单状态
- //初始化更新异常订单状态定时器
- private void InitCheckUnusualOrderTimer()
- {
- timerCheckUnusualOrder = new System.Timers.Timer();
- timerCheckUnusualOrder.Interval = BeginInterval;
- timerCheckUnusualOrder.Elapsed += new System.Timers.ElapsedEventHandler(CheckUnusualOrder);
- timerCheckUnusualOrder.Enabled = true;
- }
- private void CheckUnusualOrder(object sender, System.Timers.ElapsedEventArgs e)
- {
- timerCheckUnusualOrder.Enabled = false;
- if (webConfig.UnusualOrder_Switch == "1")
- {
- WriteLog(string.Format("异常 | {0} | {1}", DateTime.Now.ToString(), "开始更新异常订单状态!"));
- //定时器轮询间隔(毫秒)
- timerCheckUnusualOrder.Interval = int.Parse(webConfig.UnusualOrder_Interval);
- SqlConnection sqlCnt = new SqlConnection(conn);
- try
- {
- sqlCnt.Open();
- SqlCommand updCMD = sqlCnt.CreateCommand();
- //更新设计异常订单状态
- string UnusualSQL = webConfig.UnusualOrder_CheckDesignSQL;
- if (UnusualSQL != "")
- {
- updCMD.CommandType = CommandType.Text;
- updCMD.CommandText = UnusualSQL;
- updCMD.ExecuteNonQuery();
- }
- //更新下单异常订单状态
- UnusualSQL = webConfig.UnusualOrder_CheckPlaceSQL;
- if (UnusualSQL != "")
- {
- updCMD = sqlCnt.CreateCommand();
- updCMD.CommandType = CommandType.Text;
- updCMD.CommandText = UnusualSQL;
- updCMD.ExecuteNonQuery();
- }
- //更新发货异常订单状态
- UnusualSQL = webConfig.UnusualOrder_CheckDeliverySQL;
- if (UnusualSQL != "")
- {
- updCMD = sqlCnt.CreateCommand();
- updCMD.CommandType = CommandType.Text;
- updCMD.CommandText = UnusualSQL;
- updCMD.ExecuteNonQuery();
- }
- WriteLog(string.Format("异常 | {0} | {1}", DateTime.Now.ToString(), "结束更新异常订单状态!"));
- }
- catch (Exception ed)
- {
- WriteLog(string.Format("异常 | {0} | {1}", DateTime.Now.ToString(), ed.Message));
- }
- finally
- {
- if (sqlCnt.State == ConnectionState.Open)
- sqlCnt.Close();
- }
- }
- timerCheckUnusualOrder.Enabled = true;
- }
- #endregion
- #region 自动派单
- private void InitAutoDispatchTimer()
- {
- timerAutoDispatch = new System.Timers.Timer();
- timerAutoDispatch.Interval = BeginInterval;
- timerAutoDispatch.Elapsed += new System.Timers.ElapsedEventHandler(AutoDispatch);
- timerAutoDispatch.Enabled = true;
- }
- private void AutoDispatch(object sender, System.Timers.ElapsedEventArgs e)
- {
- timerAutoDispatch.Enabled = false;
- if (webConfig.Dispatch_Switch == "1")
- {
- //定时器轮询间隔(毫秒)
- timerAutoDispatch.Interval = int.Parse(webConfig.Dispatch_Interval);
- commonHelper.DoAutoDispatch2(conn);
- }
- timerAutoDispatch.Enabled = true;
- }
- #endregion
- #region 每日清除数据
- private void InitDayClearTimer()
- {
- timerDayClear = new System.Timers.Timer();
- timerDayClear.Interval = BeginInterval;
- timerDayClear.Elapsed += new System.Timers.ElapsedEventHandler(DayClear);
- timerDayClear.Enabled = true;
- }
- private void DayClear(object sender, System.Timers.ElapsedEventArgs e)
- {
- timerDayClear.Enabled = false;
- if (webConfig.DayClear_Switch == "1")
- {
- //定时器轮询间隔(毫秒)
- timerDayClear.Interval = int.Parse(webConfig.DayClear_Interval);
- //当前时间在自动派单时间列表内
- if (webConfig.DayClear_Time.Contains(DateTime.Now.ToString("HH:mm")))
- {
- WriteLog(string.Format("清除 | {0} | {1}", DateTime.Now.ToString(), "开始自动清除数据!"));
- SqlConnection sqlCnt = new SqlConnection(conn);
- try
- {
- sqlCnt.Open();
- SqlCommand updCMD = sqlCnt.CreateCommand();
- updCMD.CommandType = CommandType.Text;
- updCMD.CommandText = webConfig.DayClear_ClearSQL;
- updCMD.ExecuteNonQuery();
- WriteLog(string.Format("清除 | {0} | {1}", DateTime.Now.ToString(), "结束自动清除数据!"));
- }
- catch (Exception ed)
- {
- WriteLog(string.Format("清除 | {0} | {1}", DateTime.Now.ToString(), ed.Message));
- }
- finally
- {
- if (sqlCnt.State == ConnectionState.Open)
- sqlCnt.Close();
- }
- }
- }
- timerDayClear.Enabled = true;
- }
- #endregion
- void global_elapsed(object state)
- {
- try
- {
- DateTime curTime = DateTime.Now;
- int day = curTime.Day;
- int hour = curTime.Hour;
- int minute = curTime.Minute;
- if (webConfig.GetTmc == "1")
- {
- taobaoTmcTest.getInfo();
- }
- }
- catch (Exception ex)
- {
- XLog.SaveLog(0, ex.Message);
- }
- }
- void Application_End(object sender, EventArgs e)
- {
- // 在应用程序关闭时运行的代码
- // 解决应用池回收问题
- //System.Threading.Thread.Sleep(5000);
- ////http://localhost:911/login.aspx
- //string strUrl = CommonHelper.GetPrePath() + "login.aspx";
- //System.Net.HttpWebRequest _HttpWebRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(strUrl);
- //System.Net.HttpWebResponse _HttpWebResponse = (System.Net.HttpWebResponse)_HttpWebRequest.GetResponse();
- //System.IO.Stream _Stream = _HttpWebResponse.GetResponseStream();//得到回写的字节流
- }
- void Application_BeginRequest(Object sender, EventArgs e)
- {
- //if (CommonHelper.CheckUrlQuerySqlStr())
- //{
- // Response.Redirect(CommonHelper.GetPrePath() + "ErrorPage.htm");
- // Response.End();
- //}
- }
- void Application_Error(object sender, EventArgs e)
- {
- // Code that runs when an unhandled error occurs
- //if (config.Instance.Site.SpiderIp.Contains(CommonHelper.ClientIP))return;
- //SyLog.WriteLog(Server.GetLastError());
- }
- void Session_Start(object sender, EventArgs e)
- {
- // Code that runs when a new session is started
- }
- void Session_End(object sender, EventArgs e)
- {
- // Code that runs when a session ends.
- // Note: The Session_End event is raised only when the sessionstate mode
- // is set to InProc in the Web.config file. If session mode is set to StateServer
- // or SQLServer, the event is not raised.
- }
- //写入日志
- private void WriteLog(string LogText)
- {
- string sDir = System.IO.Path.GetTempPath() + @"Log\" + DateTime.Now.ToString("yyyyMM");
- if (!Directory.Exists(sDir))
- Directory.CreateDirectory(sDir);
- using (StreamWriter sw = new StreamWriter(sDir + @"\Log_" + DateTime.Now.ToString("dd") + ".txt", true, Encoding.UTF8))
- {
- sw.Write(LogText + System.Environment.NewLine);
- }
- }
- </script>
|