private static void Maintain() { while (true) { try { string _mid = Cryptography.RandomString(5, false); byte[] packet = PublicTools.EncodeMessage(_mid, "HeartBeat"); if (CoreSend(packet, _mid, out string reply)) { LW.D("HeartBeat Succeed! " + reply); } else { throw new Exception("CoreSend Error: Timeout"); } Thread.Sleep(5000); } catch (Exception ex) { if (ex is ThreadAbortException) { return; } LW.E("Heartbeat Error! " + ex.Message); socketclient.CloseAndDispose(); stream.CloseAndDispose(); Initialise(remoteEndpoint.Address, remoteEndpoint.Port); Thread.Sleep(5000); } } }
//监听客户端发来的请求 private static void WatchConnecting() { while (true) { Socket connection = null; try { connection = socketwatch.Accept(); } catch (Exception ex) { LW.E(ex.Message); continue; } string remoteEndPoint = connection.RemoteEndPoint.ToString(); LW.D("Estalished a connection with " + remoteEndPoint); Thread thread = new Thread(new ParameterizedThreadStart(Recv)) { IsBackground = true, Name = remoteEndPoint + " Worker Thread" }; thread.Start(connection); } }
public static bool ChangePassWord(UserObject NowUser, string OriPasswrd, string NewPasswrd) { if (Cryptography.SHA256Encrypt(OriPasswrd) != CurrentUser.Password) { LW.E("ChangePassword Request Failed, Reason: Original Password Incorrect...."); return(false); } else { NowUser.Password = Cryptography.SHA256Encrypt(NewPasswrd); if (DataBaseOperation.UpdateData(ref NowUser, new DBQuery() .WhereEqualTo("objectId", CurrentUser.ObjectId) .WhereEqualTo("Password", Cryptography.SHA256Encrypt(OriPasswrd)) .WhereEqualTo("Username", CurrentUser.UserName)) == DBQueryStatus.ONE_RESULT) { LW.D("Change Password Success!"); return(true); } else { LW.D("Change Password Failed!"); return(false); } } }
public static void StartProcessThreads() { ProcessorSENTThread.Start(); LW.D("\tWeChatSendThread Started!"); ProcessorRCVDThread.Start(); LW.D("\tWeChatRcvdThread Started!"); }
public static bool Initialise(IPAddress ServerIP, int Port) { socketclient = new TcpClient(); remoteEndpoint = new IPEndPoint(ServerIP, Port); int FailedRetry = XConfig.Current.Database.FailedRetryTime; for (int i = 0; i < FailedRetry; i++) { try { socketclient.Connect(remoteEndpoint); stream = socketclient.GetStream(); LW.D("\tDatabase Connection Estabilished!"); if (IsFirstTimeInit) { ReceiverThread.Start(); DataBaseConnectionMaintainer.Start(); IsFirstTimeInit = false; } SendData("openConnection", "00000", out string token); LW.D("\tDatabase Connected! Identity: " + token); return(true); } catch (Exception ex) { LW.E("\t\tDatabase connection to server: " + ServerIP + " failed. " + ex.Message); Thread.Sleep(1000); } } return(false); }
static void Main(string[] args) { LW.InitLog(); LW.SetLogLevel(LogLevel.Dbg); DataBaseOperation.InitialiseClient(); LW.D(DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("realname", "刘浩宇"), out UserObject me)); LW.D(me); ClassObject co = new ClassObject() { CDepartment = "学部", CGrade = "1年级", CNumber = "5班", TeacherID = me.ObjectId }; LW.D(DataBaseOperation.CreateData(ref co)); me.ClassList.Add(co.ObjectId); LW.D(co); SchoolBusObject bo = new SchoolBusObject() { BusName = "校车方向1", TeacherID = me.ObjectId }; LW.D(DataBaseOperation.CreateData(ref bo)); LW.D(bo); for (int cn = 1; cn < 40; cn++) { StudentObject stu = new StudentObject() { BusID = bo.ObjectId, ClassID = co.ObjectId, Sex = "M", StudentName = "学生-" + cn.ToString("000"), AHChecked = false, CSChecked = false, LSChecked = false }; LW.D(DataBaseOperation.CreateData(ref stu)); LW.D(stu); if (cn < 21) { me.ChildList.Add(stu.ObjectId); } } me.HeadImagePath = "liuhaoyu.gif"; LW.D(DataBaseOperation.UpdateData(ref me)); LW.D(me); }
public static void InitialiseClient() { LW.D("Started Initialise Database Server Connection...."); bool conn = DatabaseSocketsClient.Initialise(IPAddress.Parse(XConfig.Current.Database.DBServerIP), XConfig.Current.Database.DBServerPort); while (!conn) { LW.E("DBServer Initial Connection Failed!"); conn = DatabaseSocketsClient.Initialise(IPAddress.Parse(XConfig.Current.Database.DBServerIP), XConfig.Current.Database.DBServerPort); } }
public static IWebHost BuildWebHost(string instrumentationKey, string[] args) { LW.D("Building WebHost...."); var host = WebHost.CreateDefaultBuilder(args) .UseIISIntegration() .UseKestrel() .UseApplicationInsights(instrumentationKey) .UseStartup <Startup>() .Build(); return(host); }
public static void InitialiseDBConnection() { SqlConnectionStringBuilder conn = new SqlConnectionStringBuilder(); LW.D("Start Initiallising Database Connections....."); conn.DataSource = XConfig.Current.Database.SQLServerIP + "," + XConfig.Current.Database.SQLServerPort; conn.UserID = XConfig.Current.Database.DatabaseUserName; conn.Password = XConfig.Current.Database.DatabasePassword; conn.TrustServerCertificate = true; LW.D("DB Connection String Loaded!"); sqlConnection = new SqlConnection(conn.ConnectionString); sqlConnection.Open(); LW.D("DB Connection Opened!"); }
public static void Main() { LW.SetLogLevel(LogLevel.Dbg); LW.InitLog(); LW.D("========= = Start WoodenBench for Schoolbus Windows Client = ========="); if (!XConfig.LoadConfig("XConfig.conf")) { LW.E("Config Loading Failed! Check file..."); return; } DataBaseOperation.InitialiseClient(); Application.EnableVisualStyles(); Application.Run(LoginWindow.Default); }
private void DoLogin(object sender, EventArgs e) { //Login the user UserNameTxt.Enabled = false; PswdTxt.Enabled = false; NewUserLabel.Visible = false; LoginResult.Text = ""; DoLoginBtn.Enabled = false; CancelBtn.Enabled = false; DoLoginBtn.Text = "登录中..."; Application.DoEvents(); if (UserActivity.Login(UserNameTxt.Text, PswdTxt.Text, out UserObject user)) { LW.D($"Login succeed using username {UserNameTxt.Text}"); if (user.UserGroup.IsAdmin || user.UserGroup.IsBusManager || user.UserGroup.IsClassTeacher) { DoLoginBtn.Enabled = true; CancelBtn.Enabled = true; UserNameTxt.Enabled = true; PswdTxt.Enabled = true; DoLoginBtn.Text = "登录(&L)"; CurrentUser = user; MainForm.Default.Show(); Hide(); } else if (user.UserGroup.IsParent) { MessageBox.Show("暂时不支持家长使用小板凳 Windows 客户端哦!"); } else { MessageBox.Show("用户组配置无效,请联系管理员。"); } } else { LW.E($"Login failed using username {UserNameTxt.Text} and password {PswdTxt.Text}."); LoginResult.Text = "用户名或密码不正确"; LoginResult.Visible = true; DoLoginBtn.Enabled = true; CancelBtn.Enabled = true; UserNameTxt.Enabled = true; PswdTxt.Enabled = true; DoLoginBtn.Text = "登录(&L)"; } }
private void buttonX1_Click(object sender, EventArgs e) { foreach (StudentObject item in studentDataObjectBindingSource) { var _item = item; if (Database.DataBaseOperation.UpdateData(ref _item) == DBQueryStatus.ONE_RESULT) { ExDescription.Text = "成功更新项:" + _item.StudentName; LW.D("BusCheck: Succeed Updated Record: " + item.ObjectId); } else { ExDescription.Text = "出现问题:" + _item.StudentName; LW.E("BusCheck: Failed to Update Record: " + item.ObjectId); } Application.DoEvents(); } }
private static Dictionary <string, string> SendMessageString(WeChatSMsg MessageType, string users, string Title, string Content, string URL = null) { WeChatMessageBackupService.AddToSendList(users, Title, Content); WeChatHelper.ReNewWCCodes(); string Message = "{\"touser\":\"" + users + "\",\"msgtype\":\"" + MessageType.ToString() + "\",\"agentid\":" + XConfig.Current.WeChat.AgentId + ",\"" + MessageType.ToString() + "\":"; switch (MessageType) { case WeChatSMsg.text: Message = Message + $"{{\"content\":\"{Content}\r\n\r\n MST: {DateTime.Now.ToNormalString()}\"}}"; break; case WeChatSMsg.textcard: Message = Message + $"{{\"title\":\"{Title}\",\"description\":\"{Content}\",\"url\":\"{URL}\"}}"; break; } Message = Message + "}"; LW.D("WeChat Message Sent: " + Message); return(PublicTools.HTTPPost("https://qyapi.weixin.qq.com/cgi-bin/message/send?access_token=" + WeChatHelper.AccessToken, Message)); }
public static void Main(string[] args) { LW.SetLogLevel(LogLevel.Dbg); LW.InitLog(); StartUpTime = DateTime.Now; LW.D("WoodenBench WebServer Starting...."); LW.D($"\t Startup Time {StartUpTime.ToString()}."); Version = new FileInfo(new string(Assembly.GetExecutingAssembly().CodeBase.Skip(8).ToArray())).LastWriteTime.ToString(); LW.D($"\t Version {Version}"); var v = XConfig.LoadAll(); if (!(v.Item1 && v.Item2)) { return; } StatusMonitor.StartMonitorThread(); WeChatHelper.ReNewWCCodes(); DataBaseOperation.InitialiseClient(); //DataBaseOperation.InitialiseClient(IPAddress.Loopback); WeChatHelper.InitialiseExcryptor(); LW.D("Initialising Core Messaging Systems....."); WeChatMessageSystem.StartProcessThreads(); WeChatMessageBackupService.StartBackupThread(); MessagingSystem.StartProcessThread(); var webHost = BuildWebHost(XConfig.Current.ApplicationInsightInstrumentationKey, args); LW.D("Starting WebHost...."); WebServerTask = webHost.RunAsync(ServerStopToken.Token); WebServerTask.Wait(); LW.E("WebServer Stoped! Cancellation Token = " + ServerStopToken.IsCancellationRequested); }
public static void ApplicationExit() { LW.D("Terminating Application....."); Database.Connection.DatabaseSocketsClient.KillConnection(); Application.Exit(); }
private static Dictionary <string, string> ResponceToMessage(WeChatRcvdMessage Message) { switch (Message.MessageType) { case WeChatRMsg.text: return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["DefaultReply_Text"] + Message.TextContent + "??")); case WeChatRMsg.image: return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["DefaultReply_Image"])); case WeChatRMsg.voice: return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["DefaultReply_Voice"])); case WeChatRMsg.location: return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["DefaultReply_Location"])); case WeChatRMsg.video: return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["DefaultReply_Video"])); case WeChatRMsg.link: return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["DefaultReply_WebLink"])); case WeChatRMsg.EVENT: switch (Message.Event) { case WeChatEvent.click: switch (Message.EventKey) { case "ADD_PASSWORD": string token = OnePassTicket.CreateTicket(); if (OnePassTicket.TryAdd(token, new TicketInfo(TicketUsage.AddPassword, "JumpToken_FreeLogin", Message.FromUser))) { //"要是想使用Windows 客户端登陆的话\r\n就点击<a href='" + XConfig.CurrentConfig.WebSiteAddress + "/Account/Register/?token={0}&_action=AddPassword&user={1}'>这里</a>给自己加一个密码吧!" string content = string.Format(XConfig.Messages["AddPasswordMessage"], token, Message.FromUser); var p = SendMessageString(WeChatSMsg.text, Message.FromUser, null, content); return(p); } else { return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, XConfig.Messages["CreateTokenError"])); } case "WEB_SERV_VER": return(SendMessageString(WeChatSMsg.textcard, Message.FromUser, "小板凳平台版本信息", "这是当前版本信息: \r\n" + "启动の时间: " + Program.StartUpTime.ToString() + "\r\n\r\n" + "服务端版本: " + Program.Version + "\r\n" + "核心库版本: " + WBConsts.CurrentCoreVersion + "\r\n" + "运行时版本: " + Assembly.GetCallingAssembly().ImageRuntimeVersion + "\r\n\r\n=点击查看系统状态>>", XConfig.Current.StatusPageAddress)); default: LW.E("Recieved Not Supported :::Wechat Event Click::: Key " + Message.EventKey); return(null); } case WeChatEvent.LOCATION: var Latitude = Message.Location.X; var Longitude = Message.Location.Y; var Precision = Message.Precision; var time = Message.RecievedTime; var toUser = Message.FromUser; LW.D($"WeChatMessageResp: Recieved Location: {Latitude}:{Longitude}%{Precision}@{time} form {toUser}"); if (DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("Username", toUser), out UserObject _user) == DBQueryStatus.ONE_RESULT) { _user.CurrentPoint = Message.Location; _user.Precision = Precision; if (DataBaseOperation.UpdateData(ref _user) != DBQueryStatus.ONE_RESULT) { LW.E("WeChatMessageResp: Cannot save User with new Position..."); } else { LW.D("WeChatMessageResp: Succeed Save User with New Position..."); } } else { LW.E("WeChatMessageResp: Cannot find user in Database...."); } return(null); } return(null); } return(SendMessageString(WeChatSMsg.text, Message.FromUser, null, "不支持的消息类型")); }
public static void StartMonitorThread() { LW.D("Starting Monitor Thread"); _MonitorThread.Start(); LW.D("Monitor Thread: Active"); }
private static void Recv(object socketclientpara) { Socket baseSocket = socketclientpara as Socket; NetworkStream stream = new NetworkStream(baseSocket); string remoteEP = baseSocket.RemoteEndPoint.ToString(); bool _connectionOpened = false; while (true) { try { string requestString = PublicTools.DecodeMessage(stream); LW.D("Recived Data: " + requestString); if (requestString.Length <= 5) { baseSocket.CloseAndDispose(); break; } string _MessageId = requestString.Substring(0, 5); requestString = requestString.Substring(5); if (requestString == "openConnection") { LW.D("C: Recieve an OpenConnection Request, from " + remoteEP); byte[] arrSendMsg = PublicTools.EncodeMessage(_MessageId, remoteEP); stream.Write(arrSendMsg, 0, arrSendMsg.Length); stream.Flush(); LW.D("C: Replied an OpenConnection Request, to " + remoteEP); _connectionOpened = true; } else if (_connectionOpened) { if (requestString == "HeartBeat") { LW.D("B: Recieve a HearBeat, from " + remoteEP); DateTime rtime = DateTime.Now; byte[] arrSendMsg = PublicTools.EncodeMessage(_MessageId, rtime.ToNormalString()); stream.Write(arrSendMsg, 0, arrSendMsg.Length); stream.Flush(); LW.D("C: Replied a HearBeat, to " + remoteEP); } else if (requestString.ToParsedObject(out DBInternal request)) { QueryStrings[remoteEP] = requestString; LW.D("Q: " + remoteEP + " :: " + requestString); //It takes Time..... string returnStr = DatabaseCore.ProcessRequest(request); byte[] arrSendMsg = PublicTools.EncodeMessage(_MessageId, returnStr); stream.Write(arrSendMsg, 0, arrSendMsg.Length); stream.Flush(); LW.D("P: " + remoteEP + " :: " + returnStr); } else { //Invalid Connection...... LW.E("E: " + remoteEP + " :: JSON Parse Exception!"); baseSocket.CloseAndDispose(); QueryStrings.Remove(remoteEP); break; } } else { LW.E("Connection to " + remoteEP + " is not marked as 'Opened'"); baseSocket.CloseAndDispose(); stream.CloseAndDispose(); QueryStrings.Remove(remoteEP); break; } } catch (Exception ex) { LW.E("Client " + remoteEP + " drops the connection. " + "\r\n" + ex.Message + "\r\n" + ex.StackTrace + "\r\n"); QueryStrings.Remove(remoteEP); stream.CloseAndDispose(); baseSocket.CloseAndDispose(); break; } } QueryStrings.Remove(remoteEP); LW.E("Client Connection Socket to " + remoteEP + " gonna Stop!"); Thread.CurrentThread.Abort(); return; }
private void helpTile_Click(object sender, EventArgs e) { LW.D("Clicked the Help Button, now navigating to the help page"); Process.Start("https://www.lhy0403.top/wb-help/"); }