// return user; //} public static string SendWX(string strUrl) { string content = ""; try { HttpWebRequest req = (HttpWebRequest)HttpWebRequest.Create(strUrl); //用GET形式请求指定的地址 req.Method = "GET"; using (WebResponse wr = req.GetResponse()) { StreamReader reader = new StreamReader(wr.GetResponseStream(), Encoding.UTF8); content = reader.ReadToEnd(); reader.Close(); reader.Dispose(); } } catch (Exception ex) { Log4Helper.WriteLog("SendWX错误", ex); } return(content); }
/// <summary> /// 成为开发者的第一步,验证并相应服务器的数据 /// </summary> public void Auth() { string token = Config.WeixinToken; if (string.IsNullOrEmpty(token)) { Log4Helper.Write(string.Format("WeixinToken 配置项没有配置!"), LogMessageType.Error); } string echoString = HttpContext.Current.Request.QueryString["echoStr"]; string signature = HttpContext.Current.Request.QueryString["signature"]; string timestamp = HttpContext.Current.Request.QueryString["timestamp"]; string nonce = HttpContext.Current.Request.QueryString["nonce"]; if (CheckSignature(token, signature, timestamp, nonce)) { if (!string.IsNullOrEmpty(echoString)) { HttpContext.Current.Response.Write(echoString); HttpContext.Current.Response.End(); } } }
public void DataReceived(byte[] by) { PortDataParameter param = DataParsing.Parsing(by); OverTimeManager.Stop(); try { if (param.FunctionAddress == PortEnums.DealFunctions.Ic && param.Command.ICommand == PortEnums.ICommands.EntryptIcDevice) { if (param.IcParam != null) { string msg = $"IC 设备加密{(param.IcParam.Result ? "成功" : "失败")}"; ViewCallFunction.ViewEncryptMessage(msg); ViewCallFunction.ViewEncryptOver(); } } } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }
private List <AdminUser> _Filter(string keyword, int limit, int pageSize) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectStr"]; string conStr = SysInfoManage.DENString(settings.ConnectionString); using (ULinker.Common.DB.DBHelper db = new Common.DB.DBHelper(conStr)) { List <AdminUser> list = new List <AdminUser>(); try { string strCmd = @"SELECT * FROM `user` WHERE 1=1"; if (!string.IsNullOrEmpty(keyword)) { strCmd += @" AND `Name` like " + string.Format("%{0}%", keyword); } strCmd += " ORDER BY CreateTime DESC"; strCmd += " LIMIT " + limit + "," + pageSize; DataTable dt = db.GetDataSet(strCmd); if (dt != null && dt.Rows.Count > 0) { foreach (DataRow row in dt.Rows) { AdminUser item = RowToObject(row); list.Add(item); } } } catch (Exception ex) { Log4Helper.Error(this.GetType(), String.Format("AdminUserDao.GetAll.{0}", ex.Message), new Exception("error")); } return(list); } }
public bool Create(UserPlatform model) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectStr"]; string conStr = SysInfoManage.DENString(settings.ConnectionString); using (ULinker.Common.DB.DBHelper db = new Common.DB.DBHelper(conStr)) { try { string strCmd = @"INSERT INTO `userplatform`(`CreatorId`,`PlatformId`,`AppId`,`AppKey`,`AppSecrect`,`CreateTime`,`ModifyTime`) VALUES(@CreatorId,@PlatformId,@AppId,@AppKey,@AppSecrect,NOW(),NOW())"; MySqlParameter[] paramters = new MySqlParameter[] { new MySqlParameter("@CreatorId", MySqlDbType.Int32), new MySqlParameter("@PlatformId", MySqlDbType.Int32), new MySqlParameter("@AppId", MySqlDbType.Int32), new MySqlParameter("@AppKey", MySqlDbType.String), new MySqlParameter("@AppSecrect", MySqlDbType.String) }; paramters[0].Value = model.CreatorId; paramters[1].Value = model.PlatformId; paramters[2].Value = model.AppId; paramters[3].Value = model.AppKey; paramters[4].Value = model.AppSecrect; int count = db.ExecuteNonQuery(strCmd, paramters); return(count > 0 ? true : false); } catch (Exception ex) { Log4Helper.Error(this.GetType(), String.Format("UserPlatformDao.Create.{0}", ex.Message), new Exception("error")); return(false); } } }
public bool Create(Api model) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectStr"]; string conStr = SysInfoManage.DENString(settings.ConnectionString); using (ULinker.Common.DB.DBHelper db = new Common.DB.DBHelper(conStr)) { try { string strCmd = @"INSERT INTO `api` (`PlatformId`,`Name`,`FunctionName`,`Url`,`Description`,`CreateTime`,`ModifyTime`) (@PlatformId,@Name,@FunctionName,@Url,@Description,NOW(),NOW())"; MySqlParameter[] paramters = new MySqlParameter[] { new MySqlParameter("@PlatformId", MySqlDbType.Int32), new MySqlParameter("@Name", MySqlDbType.String), new MySqlParameter("@FunctionName", MySqlDbType.String), new MySqlParameter("@Url", MySqlDbType.String), new MySqlParameter("@Description", MySqlDbType.String) }; paramters[0].Value = model.Id; paramters[1].Value = model.Name; paramters[2].Value = model.FunctionName; paramters[3].Value = model.Url; paramters[4].Value = model.Description; int count = db.ExecuteNonQuery(strCmd, paramters); return(count > 0 ? true : false); } catch (Exception ex) { Log4Helper.Error(this.GetType(), String.Format("AdminUserDao.Create.{0}", ex.Message), new Exception("error")); return(false); } } }
public static void GenerateTextXmlFromTable(TableInfo table, string outputPath) { if (table == null || !Directory.Exists(outputPath)) { return; } Log4Helper.Write("GenerateTextXmlFromTable", String.Format("Process of table {0} starts at {1}.", table.TableName, System.DateTime.Now.ToString("s")), LogSeverity.Info); string entityName = GetModelName(table.TableName); using (System.Xml.XmlTextWriter xtw = new System.Xml.XmlTextWriter(System.IO.Path.Combine(outputPath, String.Concat(entityName, ".xml")), System.Text.Encoding.UTF8)) { xtw.Formatting = System.Xml.Formatting.Indented; xtw.WriteProcessingInstruction("xml", "version=\"1.0\" encoding=\"UTF-8\""); //generate entity calss xtw.WriteStartElement("modeltext"); #region columns/properties foreach (ColumnInfo c in table.Columns) { xtw.WriteStartElement("field"); xtw.WriteAttributeString("key", entityName + "_" + c.ColumnName); xtw.WriteAttributeString("value", c.ColumnDescription); xtw.WriteEndElement(); } xtw.WriteEndElement(); #endregion xtw.Flush(); xtw.Close(); } Log4Helper.Write("GenerateTextXmlFromTable", String.Format("Process of table {0} ends at {1}.", table.TableName, System.DateTime.Now.ToString("s")), LogSeverity.Info); }
private static void Host_PostDistanceCardEncrypt(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { try { string oldpwd = e.Arguments[0].StringValue; string pwd = e.Arguments[1].StringValue; string clientnumber = e.Arguments[2].StringValue; byte[] bys = PortAgreement.DistanceDeviceEncryption(clientnumber, oldpwd); bool ret = SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, bys); if (ret) { ReceivedManager.SetReceivedFunction <DistanceCardEncrypt>(); DistanceCardEncrypt received = ReceivedManager.GetReceivedFun <DistanceCardEncrypt>(); received.ClientNumber = clientnumber; received.NewPwd = pwd; } } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }
private void GetRequestNumber(HttpContext context) { Hashtable map = new Hashtable(); DataTable dtTable = new DataTable(); string type = HttpUtility.UrlDecode(context.Request["type"]); try { SqlserverHelper helper = new SqlserverHelper(); dtTable = helper.GetRequestNumber(type); map.Add("state", "成功"); map.Add("msg", ""); } catch (Exception ex) { Log4Helper.Debug(ex.Message, ex); map.Add("state", "失败"); map.Add("msg", ex.Message); } map.Add("data", dtTable); string json = JsonConvert.SerializeObject(map); context.Response.Write(json); }
public override string Run() { if (ThreadUDP == null) { try { _Stop = false; IPEndPoint localIpep = new IPEndPoint(IPAddress.Parse(HostName), Port); // 设置IP和监听端口号 UCR = new UdpClient(localIpep); ThreadUDP = new Thread(new ThreadStart(ReceiveThread)); ThreadUDP.Name = "ReceiveThread"; ThreadUDP.Priority = ThreadPriority.Normal; ThreadUDP.IsBackground = true; //一定要加上,否则接收不到数据, ThreadUDP.Start(); return(null); } catch (Exception ex) { Log4Helper.Error(this.GetType(), "主机启动异常!", ex); return(ex.ToString()); } } return("主机正在运行!"); }
/// <summary> /// 网银在线异步回调异常日志 /// </summary> /// <param name="request">请求对象</param> /// <param name="folder">目录</param> /// <returns>void</returns> /// <remarks>2015-09-09 苟治国 创建</remarks> private void WriteRequestLog(HttpRequestBase request, string folder) { var sb = new StringBuilder("--------------------------------------------------------\r\n"); sb.AppendLine("order:" + Request["out_trade_no"] == "" ? Request["v_oid"] : Request["out_trade_no"]); sb.AppendLine("logtime:" + DateTime.Now); try { foreach (var key in request.Form.AllKeys) { sb.AppendLine(key + ":" + Request.Form[key]); } foreach (var key in request.QueryString.AllKeys) { sb.AppendLine(key + ":" + Request.QueryString[key]); } sb.AppendLine("REMOTE_ADDR:" + request.ServerVariables["REMOTE_ADDR"]); sb.AppendLine("REMOTE_HOST:" + request.ServerVariables["REMOTE_HOST"]); sb.AppendLine("REMOTE_PORT:" + request.ServerVariables["REMOTE_PORT"]); sb.AppendLine("REQUEST_METHOD:" + request.ServerVariables["REQUEST_METHOD"]); } catch { } Log4Helper.WriteInfoLog(sb.ToString(), folder); }
public void Clone(TaskBase source, bool ignoreValidateEvent) { try { this.MessageChanged += new MessageChangedEventHandler(source.SetMessageByParam); this.Task = source.Task; this.Caption = source.Caption; this.Key = source.Key; this.ExecutionLog = source.ExecutionLog; } catch (ThreadAbortException) { throw; } catch (ThreadInterruptedException) { throw; } catch (Exception ex) { Log4Helper.Write("KaixinBase.Clone", ex); throw; } }
protected void Application_Start() { string newdb = ConfigurationManager.AppSettings["CreateDatabaseIfNotExists"].ToLower(); if (newdb == "true") { Database.SetInitializer <DbContextManager>(new InitializeDataForCreateDatabaseIfNotExists()); } else { Database.SetInitializer <DbContextManager>(null); } //initialize engine context EngineContext.Initialize(false); //NopEngine ne = new NopEngine(); //ne.Initialize(); AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); AutoMapperConfig.RegisterObjects(); //RegisterCache("Heartbeat"); currentDate = DateTime.Now.Date; //JobQueue.Add(new UARCJob() { Frequency = JobFrequency.EveryDay }); //JobQueue.Add(new UARCUserJob { Frequency = JobFrequency.Immediately }); //DbInterception.Add(new Log4NetInterceptor()); //MiniProfilerEF6.Initialize(); Log4Helper.Initialize(Server.MapPath("log4net.config")); //注册数据库操作拦截器类 DbInterception.Add(new LogEFMonitor()); }
private static void Host_PostConfirmClientNumber(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { try { string strClientNumber = e.Arguments[0].StringValue; int clientNumber = Utility.StrToInt(strClientNumber); List <UserInfo> infos = UserManager.GetInfos(); int count = infos.Where(w => w.UserNumber == clientNumber).Count(); if (count == 0) { if (LimitManager.NumberInfos == null) { LimitManager.GetInfos(); } count = LimitManager.NumberInfos.Where(w => w.LimitNumber == clientNumber).Count(); } e.SetReturnValue(count > 0); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }
public bool Update(App model) { ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["connectStr"]; string conStr = SysInfoManage.DENString(settings.ConnectionString); using (ULinker.Common.DB.DBHelper db = new Common.DB.DBHelper(conStr)) { try { string strCmd = @"UPDATE `app` SET `AppTypeId`=@AppTypeId,`ManagerId`=@ManagerId,`Name`=@Name,`Description`=@Description,`ModifyTime`=NOW() WHERE `Id`=@Id"; MySqlParameter[] paramters = new MySqlParameter[] { new MySqlParameter("@AppTypeId", MySqlDbType.Int32), new MySqlParameter("@ManagerId", MySqlDbType.Int32), new MySqlParameter("@Name", MySqlDbType.String), new MySqlParameter("@Description", MySqlDbType.String), new MySqlParameter("@Id", MySqlDbType.Int32), }; paramters[0].Value = model.AppTypeId; paramters[1].Value = model.ManagerId; paramters[2].Value = model.Name; paramters[3].Value = model.Description; paramters[4].Value = model.Id; int count = db.ExecuteNonQuery(strCmd, paramters); return(count > 0 ? true : false); } catch (Exception ex) { Log4Helper.Error(this.GetType(), String.Format("AppDao.Update.{0}", ex.Message), new Exception("error")); return(false); } } }
public void DataReceived(byte[] by) { PortDataParameter param = DataParsing.Parsing(by); if (param.DistanceCardParam == null) { return; } if (param.DistanceCardParam.Command == PortEnums.DistanceCommands.WriteACard) { OverTimeManager.Stop(); if (RemoveLockInfo == null) { return; } try { if (param.DistanceCardParam.AuxiliaryCommand == PortEnums.AuxiliaryCommands.Success) { CardManager.Update(RemoveLockInfo); } else { RemoveLockInfo.CardLock = 1; } } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); } finally { RemoveLockInfo = null; } } }
public static Collection <TaskInfo> GetTasks() { try { XmlDocument objXmlDoc = GetCGConfigFile(); if (objXmlDoc == null) { return(null); } DataView dv = GetData(objXmlDoc, Constants.CONFIG_ROOT + Constants.CHAR_SLASH + Constants.TASK_TASKS); Collection <TaskInfo> tasks = new Collection <TaskInfo>(); for (int ix = 0; ix < dv.Table.Rows.Count; ix++) { try { TaskInfo task = new TaskInfo(); task = GetTask(dv.Table.Rows[ix][0].ToString(), dv.Table.Rows[ix][1].ToString()); tasks.Add(task); } catch { continue; } } return(tasks); } catch (Exception ex) { Log4Helper.Write("ConfigCtrl.GetTasks", ex, LogSeverity.Fatal); throw; } }
/// <summary> /// 获取OpenID /// </summary> /// <param name="code"></param> /// <returns></returns> public static string GetOpenID(string code) { string openid = ""; try { //获取token string url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + WeChatCommon.appid + "&secret=" + WeChatCommon.secret + "&code=" + code + "&grant_type=authorization_code"; string jsonText = SendWX(url); Log4Helper.WriteLog(jsonText); JObject obj = (JObject)JsonConvert.DeserializeObject(jsonText); if (obj != null && !string.IsNullOrEmpty(ConvertHelper.ToString(obj["openid"]))) { openid = ConvertHelper.ToString(obj["openid"]); } } catch (Exception ex) { Log4Helper.WriteLog("获取OpenID失败", ex); } return(openid); }
/// <summary> /// 微信回调普通日志 /// </summary> /// <param name="content">日志内容</param> /// <param name="param">微信支付回调请求对象</param> /// <returns>void</returns> private void WriteWeixinLog(string content, WeixinRequest param) { if (param == null) { param = new WeixinRequest(); } var sb = new StringBuilder("--------------------------------------------------------\r\n"); sb.AppendLine("order:" + param.out_trade_no); sb.AppendLine("logtime:" + DateTime.Now); try { sb.AppendLine("content:" + content); Log4Helper.WriteInfoLog(sb.ToString(), "PayNotify"); } catch { } LogApp.Instance.Info(new LogRequest() { Source = LogEnum.Source.前台, Message = sb.ToString(), Exception = null }); }
/// <summary> /// OAuthScope.snsapi_userinfo方式回调 /// </summary> /// <param name="code"></param> /// <param name="state"></param> /// <returns>视图</returns> public ActionResult Index(string code, string state) { if (string.IsNullOrEmpty(code)) { return(Content("您拒绝了授权!")); } if (string.IsNullOrEmpty(state)) { return(Content("验证失败!请从正规途径进入!")); } var result = OAuthApi.GetAccessToken(appKey, appSecret, code); if (result.errcode != ReturnCode.请求成功) { return(Content("错误:" + result.errmsg)); } try { //因为这里还不确定用户是否关注本微信,所以只能试探性地获取一下 var userInfo = OAuthApi.GetUserInfo(result.access_token, result.openid); if (userInfo != null) { //用户信息 var openId = userInfo.openid; var nickname = userInfo.nickname; var headimgurl = userInfo.headimgurl; //保存用户信息 CookieUtil.SetCookie("OpenId", openId); CookieUtil.SetCookie("HeadImgUrl", headimgurl); CookieUtil.SetCookie("Nickname", nickname); var customerExt = CustomerApp.Instance.GetByOpenId(openId); Log4Helper.WriteInfoLog(string.Format("OpenId:{0}", openId), "Login"); Log4Helper.WriteInfoLog(string.Format("会员对象:{0}", customerExt.ToJson2()), "Login"); if (customerExt == null) { return(RedirectToAction("Register", "Account")); } else { //登录成功 var response = CustomerApp.Instance.OpenIdLogin(new LoginRequest() { OpenId = openId }); Log4Helper.WriteInfoLog(string.Format("登录成功:{0}", response.ToJson()), "Login"); if (response.Status) { return(RedirectToAction("Index", "Me")); } else { return(RedirectToAction("MemberBind", "Account")); } } } else { return(Content("用户已授权,获取UserInfo失败")); } } catch (ErrorJsonResultException ex) { return(Content("用户已授权,授权Token:" + result)); } }
public Main() : base("http://res.app.local/main.html") { InitializeComponent(); GetMain = this; this.Load += OnLoadForm; LoadHandler.OnLoadEnd += (sender, args) => { PortMonitor.StartMonitor(); }; GlobalObject.AddFunction("ShowDevTools").Execute += (sender, args) => { Chromium.ShowDevTools(); }; GlobalObject.AddFunction("HostOpenAndCloseSerialDevice").Execute += (sender, args) => { try { var callback = args.Arguments.FirstOrDefault(e => e.IsFunction); string deviceName = args.Arguments[0].StringValue; SerialPortEx serial = SelectSerialDevice(deviceName); string portName = args.Arguments[1].StringValue; if (!serial.IsOpen) { SerialPortManager.OpenSerialPort(serial, portName); } else { SerialPortManager.CloseSerialPort(serial); } string json = Utility.JsonSerializerBySingleData(serial); callback.ExecuteFunction(null, new Chromium.Remote.CfrV8Value[] { json }); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }; GlobalObject.AddFunction("HostAutoConnectionDeviced").Execute += (sender, args) => { try { bool autoConnection = args.Arguments[0].BoolValue; if (autoConnection) { ConnectionSerialDevice.Start(); } else { ConnectionSerialDevice.Stop(); } ConnectionSerialDevice.AutoConnectioinDevice = autoConnection; } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }; CardManagerEvh.InitEvent(); PwdManagerEvh.InitEvent(); ConfigureManagerEvh.InitEvent(); WirelessManagerEvh.InitEvent(); UserManagerEvh.InitEvent(); }
private void StartDataBase() { string LocalSQLiteName = "Data\\Collection\\" + Model.TaskName + "\\SpiderResult.db"; DataTable dtData = DbHelper.Query(LocalSQLiteName, "Select * From Content").Tables[0]; int saveDateType = Model.SaveDataType3.Value; string connectionString = Model.SaveDataUrl3; string exeSQL = Model.SaveDataSQL3; string sql = string.Empty; DbHelperDapper.connectionString = Model.SaveDataUrl3; switch (saveDateType) { case 1: //ACCESS DbHelperDapper.dbType = DataBaseType.OleDb; break; case 2: //MSSQL DbHelperDapper.dbType = DataBaseType.SqlServer; break; case 3: //SQLITE DbHelperDapper.dbType = DataBaseType.SQLite; break; case 4: //MYSQL DbHelperDapper.dbType = DataBaseType.MySql; break; case 5: //Oracle DbHelperDapper.dbType = DataBaseType.Oracle; break; } using (var conn = DbHelperDapper.GetDbConnection(DbHelperDapper.dbType, Model.SaveDataUrl3)) { if (conn == null || conn.State != ConnectionState.Open) { MessageOut("数据库连接失败!不需要发布数据!"); return; } } foreach (DataRow dr in dtData.Rows) { try { sql = exeSQL; foreach (ModelTaskLabel mTaskLabel in Model.ListTaskLabel) { if (string.IsNullOrEmpty(dr[mTaskLabel.LabelName].ToString())) { break; } sql = sql.Replace("[" + mTaskLabel.LabelName + "]", dr[mTaskLabel.LabelName].ToString().Replace("'", "''").Replace("\\", "/")); } sql = sql.Replace("[Guid]", Guid.NewGuid().ToString()); sql = sql.Replace("[Url]", dr["HrefSource"].ToString()); DbHelperDapper.Execute(sql); MessageOut(dr["HrefSource"].ToString() + "发布成功!"); } catch (Exception ex) { Log4Helper.Write(LogLevel.Error, dr["HrefSource"].ToString() + ":保存数据库失败!", ex); MessageOut(dr["HrefSource"].ToString() + "发布失败!" + ex); continue; } } }
private void SendArticleContentByNetWork(DataTable dtClassList) { try { string Title = string.Empty, Content = string.Empty; if (ModelWebSite.DataSourceType == 4) { while (true) { foreach (DataRow dr in dtClassList.Rows) { ClassID = dr["ClassID"].ToString(); ClassName = dr["ClassName"].ToString(); string dataDir = ModelWebSite.ID + "-" + ClassID; string[] files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "\\Data\\NetWork\\" + dataDir + "\\", "*.html"); int lLen = files.Length; for (int i = 0; i < lLen; i++) { try { string file = files[i]; FileInfo fiFile = new FileInfo(file); Title = fiFile.Name.Replace(fiFile.Extension, ""); int l = fiFile.Name.LastIndexOf("_"); if (l > -1) { Title = Title.Substring(0, l); } StreamReader sr = new StreamReader(file, Encoding.Default); Content = sr.ReadToEnd(); sr.Close(); if (!CheckArticleContentIsSend(Title, Content)) { this.SendArticleContent(ModelWebSite, Title, Content, ClassName, ClassID); } else { MeOutPut.Message = string.Format("地址:{0} 分类:{1} 标题:{2} 文章存在!", ModelWebSite.WebSiteUrl, ClassName, Title); if (PublishOP != null) { PublishOP(this, MeOutPut); } } File.Delete(file); Thread.Sleep(1); } catch (Exception ex) { MeOutPut.Message = string.Format("网站名称:{0} 网站地址:{1} 信息:{2} 发布失败!", ModelWebSite.WebSiteName, ModelWebSite.WebSiteUrl, ex.Message); if (PublishOP != null) { PublishOP(this, MeOutPut); } } } if (OverOP != null) { OverOP(ModelWebSite); } Thread.Sleep(6000); } } } } catch (Exception ex) { Log4Helper.Write(LogLevel.Error, ex); } }
public MainWindow() { Log4Helper.Info(this.GetType(), "第一个日志记录"); InitializeComponent(); }
private static void Host_PostWirelessSetting(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { try { int wirelessNumber = e.Arguments[0].IntValue; int frequency = e.Arguments[1].IntValue; Task.Factory.StartNew(() => { SettingModule settingModule = SettingReceived(); try { ViewCallFunction.ViewWirelessMessage("打开模块设置功能。"); byte[] by = PortAgreement.OpenModular(); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(20); #region 设置模块发送ID for (int i = 0; i < 3; i++) { settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("设置模块发送ID(编号)。"); by = PortAgreement.SetModuleTid(wirelessNumber); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } for (int i = 0; i < 3; i++) { settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("设置模块接收ID(编号)。"); by = PortAgreement.SetModuleRid(wirelessNumber); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } for (int i = 0; i < 3; i++) { settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("设置模块频率。"); by = PortAgreement.SetModuleFrequency(frequency); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } for (int i = 0; i < 3; i++) { settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("设置模块回传功能。"); by = PortAgreement.SetModuleComesBack(1); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } ViewCallFunction.ViewWirelessMessage("关闭模块设置功能。"); by = PortAgreement.CloseModular(); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(20); for (int i = 0; i < 3; i++) { settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("发送数据测试。"); by = PortAgreement.SetModular("ABCDEF"); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } #endregion 设置模块发送ID } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } finally { OverTimeManager.Stop(); ViewCallFunction.ViewWirelessOver(); } }); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }
private static void Host_PostWirelessQuery(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { try { Task.Factory.StartNew(() => { ReceivedManager.SetReceivedFunction <WirelessQuery>(); WirelessQuery queryReceived = ReceivedManager.GetReceivedFun <WirelessQuery>(); try { ViewCallFunction.ViewWirelessMessage("打开模块设置功能。"); byte[] by = PortAgreement.OpenModular(); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(20); for (int i = 0; i < 3; i++) { queryReceived.SettingOver = false; ViewCallFunction.ViewWirelessMessage("关闭模块回传功能。"); by = PortAgreement.SetModuleComesBack(0); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (queryReceived.SettingOver) { break; } } ViewCallFunction.ViewWirelessMessage("关闭模块设置功能。"); by = PortAgreement.CloseModular(); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(20); ViewCallFunction.ViewWirelessMessage("查询无线ID(编号)。"); string strQueryFrequency = "AT+FREQ?"; by = PortAgreement.SetModular(strQueryFrequency); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); ViewCallFunction.ViewWirelessMessage("查询无线的频率。"); string strQueryRid = "AT+TID?"; by = PortAgreement.SetModular(strQueryRid); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } finally { OverTimeManager.Stop(); ViewCallFunction.ViewWirelessOver(); } }); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }
private static void Host_PostWirelessSearch(object sender, Chromium.Remote.Event.CfrV8HandlerExecuteEventArgs e) { try { Task.Factory.StartNew(() => { SettingModule settingModule = SettingReceived(); OverTimeManager.Stop(); byte[] by; try { for (int i = 1; i <= 64; i++) { if (m_StopWirelessSearch) { break; } ViewCallFunction.ViewWirelessMessage($"搜索目标频率{i}/64。"); //ViewCallFunction.ViewWirelessMessage("打开模块设置功能。"); by = PortAgreement.OpenModular(); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(20); for (int j = 0; j < 3; j++) { if (m_StopWirelessSearch) { break; } settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("设置模块频率。"); by = PortAgreement.SetModuleFrequency(i); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } for (int j = 0; j < 3; j++) { if (m_StopWirelessSearch) { break; } settingModule.SettingOver = false; //ViewCallFunction.ViewWirelessMessage("设置模块回传功能。"); by = PortAgreement.SetModuleComesBack(1); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { break; } } //ViewCallFunction.ViewWirelessMessage("关闭模块设置功能。"); by = PortAgreement.CloseModular(); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(20); for (int j = 0; j < 3; j++) { if (m_StopWirelessSearch) { break; } settingModule.SettingOver = false; ViewCallFunction.ViewWirelessMessage("发送数据测试。"); by = PortAgreement.SetModular("ABCDEF"); SerialPortManager.WriteSerialPortData(SerialPortManager.Device1, by); Thread.Sleep(250); if (settingModule.SettingOver) { ViewCallFunction.ViewWirelessMessage($"无线频率 {i} 发现设备。"); break; } } } } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } finally { m_StopWirelessSearch = false; ViewCallFunction.ViewWirelessOver(); } }); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); ViewCallFunction.ViewAlert(ex.Message); } }
public void DataReceived(byte[] by) { PortDataParameter param = DataParsing.Parsing(by); if (param.DistanceCardParam == null) { return; } if (param.DistanceCardParam.Command == PortEnums.DistanceCommands.ReadAllCard) { OverTimeManager.Stop(); if (param.DistanceCardParam.AuxiliaryCommand == PortEnums.AuxiliaryCommands.End) { ViewCallFunction.ViewCloseLoading(); return; } try { bool exists = CardManager.CardInfos.Exists(e => e.CardNumber == param.DistanceCardParam.CardNumber); if (exists) { return; } CardInfo info = CardManager.GetCardInfo(param.DistanceCardParam.CardNumber); if (info == null) { info = new CardInfo(); info.CardTime = DateTime.Now; } info.CardNumber = param.DistanceCardParam.CardNumber; info.CardType = (int)param.DistanceCardParam.CardTypeParameter.CardType; info.CardLock = param.DistanceCardParam.CardTypeParameter.CardLock; info.CardDistance = param.DistanceCardParam.CardTypeParameter.Distance; info.Electricity = param.DistanceCardParam.CardTypeParameter.Electricity; if (info.CardType <= 3) { if (param.DistanceCardParam.FunctionByteParam != null) { if (info.Id > 0 && info.CardType < 3) { info.CardType = (int)param.DistanceCardParam.FunctionByteParam.RegistrationType; if (info.CardType == 1)//人卡或组合卡 { info.ParkingRestrictions = param.DistanceCardParam.FunctionByteParam.ParkingRestrictions; } } info.CardReportLoss = param.DistanceCardParam.FunctionByteParam.Loss; info.ViceCardCount = param.DistanceCardParam.FunctionByteParam.ViceCardCount; info.Synchronous = param.DistanceCardParam.FunctionByteParam.Synchronous; info.InOutState = param.DistanceCardParam.FunctionByteParam.InOutState; info.CardCount = param.DistanceCardParam.Count; } } CardManager.CardInfos.Add(info); ViewCallFunction.ViewDisplayReadCardInfo(info); } catch (Exception ex) { Log4Helper.ErrorInfo(ex.Message, ex); } finally { OverTimeManager.Start(); } } }
protected void Application_Error() { Exception ex = Server.GetLastError().GetBaseException(); Log4Helper.WriteLog("程序错误", ex); }
private void GetBaiduUrlContent(string Url) { try { if (string.IsNullOrEmpty(Url)) { return; } Log4Helper.Write(LogLevel.Debug, Url); string EnCodeName = string.Empty; string path = this.BaseDir; WebClient client = new WebClient { Encoding = Encoding.GetEncoding("gbk") }; client.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); string input = client.DownloadString(Url); Match match = Regex.Match(input, "charset=\"?(.+?)\""); if (match.Success) { EnCodeName = match.Groups[1].Value; } if (EnCodeName != "gbk") { WebClient client2 = new WebClient { Encoding = Encoding.GetEncoding(EnCodeName) }; client2.Headers.Add("User-Agent", "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1)"); string str8 = Url; if (!str8.Contains("http://")) { str8 = "http://" + str8; } input = client2.DownloadString(Url); } string titlePattern = "<title>(.+?)</title>"; Match titleMatch = Regex.Match(input, titlePattern, RegexOptions.IgnoreCase); string Title = string.Empty; if (titleMatch.Success) { Title = titleMatch.Groups[1].Value.Replace('\\', ' ').Replace('/', ' ').Replace(' ', ' ').Split(new char[] { '_' })[0].Split(new char[] { '-' })[0]; } else { return; } string Content = GetMainContentHelper.GetMainContent(input); if (Content.Length < 300) { Log4Helper.Write(LogLevel.Error, "未能提取到正文线程号"); return; } Title = Title.Replace('\\', ' ').Replace('/', ' ').Split(new char[] { '_' })[0].Split(new char[] { '-' })[0]; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string strHtml = ".html"; Title = Title.Replace(".", ""); Title = Title.Replace(",", ""); Title = Title.Replace("、", ""); Title = Title.Replace(" ", ""); Title = Title.Replace("*", "_"); using (FileStream stream = new FileStream(path + @"\" + Title + strHtml, FileMode.Create)) { StreamWriter writer2 = new StreamWriter(stream, Encoding.GetEncoding("utf-8")); writer2.Write(Content); writer2.Dispose(); client.Dispose(); } } catch (Exception ex) { Log4Helper.Write(LogLevel.Error, ex); } }