コード例 #1
0
 public static bool ChangePassWord(UserObject NowUser, string OriPasswrd, string NewPasswrd)
 {
     if (OriPasswrd.SHA256Encrypt() != CurrentUser.Password)
     {
         LW.E("ChangePassword Request Failed, Reason: Original Password Incorrect....");
         return(false);
     }
     else
     {
         NowUser.Password = NewPasswrd.SHA256Encrypt();
         if (DataBaseOperation.UpdateData(ref NowUser, new DBQuery()
                                          .WhereEqualTo("objectId", CurrentUser.ObjectId)
                                          .WhereEqualTo("Password", OriPasswrd.SHA256Encrypt())
                                          .WhereEqualTo("Username", CurrentUser.UserName)) == DBQueryStatus.ONE_RESULT)
         {
             LW.I("Change Password Success!");
             return(true);
         }
         else
         {
             LW.I("Change Password Failed!");
             return(false);
         }
     }
 }
コード例 #2
0
        static void Main()
        {
            LW.InitLog();
            if (!XConfig.LoadConfig("XConfig.conf"))
            {
                LW.E("Config File Not Loaded!");
                return;
            }
            DatabaseCore.InitialiseDBConnection();
            DatabaseSocketsServer.InitialiseSockets();

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            mainForm = new MainForm();
            try
            {
                Application.Run(mainForm);
            }
            catch (Exception ex)
            {
                LW.E(ex.Message);
                LW.E("MainForm disappeared caused by exception!");
                Thread.Sleep(1000);
                LW.E("DBServer is to be restarted to keep stability!");
            }
            Application.Restart();
        }
コード例 #3
0
 public IActionResult UserManage(string mode, string from, string uid, string msg)
 {
     ViewData["where"] = ControllerName;
     if (ValidateSession())
     {
         if (!CurrentUser.UserGroup.IsAdmin)
         {
             LW.E("Someone trying access illegal page!, Page: UserManage, user:"******", possible referer:" + Request.Headers["Referer"]);
             return(NotFound());
         }
         ViewData["mode"] = mode;
         if (mode == "edit")
         {
             ViewData["from"] = from;
             string targetId = uid;
             string message  = (string)PublicTools.DecodeObject(Encoding.UTF8.GetString(Convert.FromBase64String(msg ?? "")));
             ViewData["registerMsg"] = message;
             return(DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("objectId", uid), out UserObject _user) == DBQueryStatus.ONE_RESULT
                 ? View(_user)
                 : NotFoundError(ServerAction.INTERNAL_ERROR, XConfig.Messages["NoUserFoundByGivenID"]));
         }
         else if (mode == "query")
         {
             return(View());
         }
         else
         {
             throw new NotSupportedException("mode not supported!");
         }
     }
     else
     {
         return(LoginFailed($"/Manage/UserManage?mode={mode}&from={from}&uid={uid}&msg={msg}"));
     }
 }
コード例 #4
0
 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);
         }
     }
 }
コード例 #5
0
        public static bool Login(string xUserName, string xPassword, out UserObject user)
        {
            xUserName = xUserName.ToLower();
            string  HashedPs      = xPassword.SHA256Encrypt();
            DBQuery UserNameQuery = new DBQuery();

            UserNameQuery.WhereEqualTo("Username", xUserName);
            UserNameQuery.WhereEqualTo("Password", HashedPs);
            switch (DataBaseOperation.QuerySingleData(UserNameQuery, out user))
            {
            case DBQueryStatus.INTERNAL_ERROR:
                LW.E("Internal DataBase Error");
                break;

            case DBQueryStatus.NO_RESULTS:
                LW.E("No User Found");
                break;

            case DBQueryStatus.ONE_RESULT:
                LW.E("User Found");
                return(true);

            case DBQueryStatus.MORE_RESULTS:
                LW.E("WTF Exception....");
                break;

            default:
                break;
            }
            return(false);
        }
コード例 #6
0
        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);
        }
コード例 #7
0
        //监听客户端发来的请求
        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);
            }
        }
コード例 #8
0
        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);
            }
        }
コード例 #9
0
 //发送字符信息到服务端的方法
 public static bool SendData(string sendMsg, string MessageId, out string rcvdMessage)
 {
     rcvdMessage = "";
     byte[] mergedPackage = PublicTools.EncodeMessage(MessageId, sendMsg);
     while (!Connected)
     {
         LW.E("Message Sent Waiting for connection....");
         Thread.Sleep(500);
     }
     return(CoreSend(mergedPackage, MessageId, out rcvdMessage));
 }
コード例 #10
0
        public IActionResult RequestChange()
        {
            ViewData["where"] = ControllerName;
            if (ValidateSession())
            {
                if (Request.HasFormContentType)
                {
                    Microsoft.AspNetCore.Http.IFormCollection form = Request.Form;
                    UserChangeRequestTypes types = (UserChangeRequestTypes)Enum.Parse(typeof(UserChangeRequestTypes), form[nameof(UserChangeRequest.RequestTypes)][0]);
                    string            reason     = form[nameof(UserChangeRequest.DetailTexts)][0];
                    string            newVal     = form[nameof(UserChangeRequest.NewContent)][0];
                    UserChangeRequest request    = new UserChangeRequest()
                    {
                        DetailTexts  = reason,
                        SolverID     = "",
                        NewContent   = newVal,
                        Status       = UCRProcessStatus.NotSolved,
                        RequestTypes = types,
                        UserID       = CurrentUser.ObjectId
                    };

                    if (DataBaseOperation.CreateData(ref request) != DBQueryStatus.ONE_RESULT)
                    {
                        LW.E("AccountController->ProcessNewUCR: Create UCR Failed!");
                        return(DatabaseError(ServerAction.MyAccount_CreateChangeRequest, XConfig.Messages["CreateUCR_Failed"]));
                    }

                    InternalMessage messageAdmin = new InternalMessage()
                    {
                        _Type = GlobalMessageTypes.UCR_Created_TO_ADMIN, DataObject = request, User = CurrentUser, ObjectId = request.ObjectId
                    };
                    InternalMessage message_User = new InternalMessage()
                    {
                        _Type = GlobalMessageTypes.UCR_Created__TO_User, DataObject = request, User = CurrentUser, ObjectId = request.ObjectId
                    };
                    MessagingSystem.AddMessageProcesses(messageAdmin, message_User);

                    return(Redirect($"/{HomeController.ControllerName}/{nameof(HomeController.RequestResult)}?req=changereq&status=ok&callback=/Account/"));
                }
                else
                {
                    ViewData["cUser"] = CurrentUser.ToString();
                    return(View(new UserChangeRequest()
                    {
                        UserID = CurrentUser.ObjectId
                    }));
                }
            }
            else
            {
                return(LoginFailed("/" + ControllerName + "/" + nameof(RequestChange)));
            }
        }
コード例 #11
0
        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);
        }
コード例 #12
0
 // 接收服务端发来信息的方法
 static void Recv()
 {
     while (true)
     {
         while (Connected)
         {
             string requestString = PublicTools.DecodeMessage(stream);
             _messages.Add(requestString.Substring(0, 5), requestString.Substring(5));
         }
         while (!Connected)
         {
             LW.E("Message Recieve waiting for connection......");
             Thread.Sleep(500);
         }
     }
 }
コード例 #13
0
 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)";
     }
 }
コード例 #14
0
 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.I("BusCheck: Succeed Updated Record: " + item.ObjectId);
         }
         else
         {
             ExDescription.Text = "出现问题:" + _item.StudentName;
             LW.E("BusCheck: Failed to Update Record: " + item.ObjectId);
         }
         Application.DoEvents();
     }
 }
コード例 #15
0
        public static int Main(string[] args)
        {
            LW.SetLogLevel(LogLevel.D);
            LW.InitLog();
            LW.I("========= = Start WoodenBench for Schoolbus Windows Client = =========");
            if (!XConfig.LoadConfig("XConfig.conf"))
            {
                LW.E("Config Loading Failed! Check file...");
                return(0);
            }

            DataBaseOperation.InitialiseClient();
            Application.EnableVisualStyles();
            Application.Run(LoginWindow.Default);

            DatabaseSocketsClient.KillConnection();
            return(0);
        }
コード例 #16
0
        public override IActionResult Index()
        {
            ViewData["where"] = HomeController.ControllerName;
            if (ValidateSession())
            {
                if (!CurrentUser.UserGroup.IsAdmin)
                {
                    LW.E("Someone trying access illegal page!, Page: index, user:"******", possible referer:" + Request.Headers["Referer"]);
                    return(NotFound());
                }

                ViewData["cUser"] = CurrentUser.ToString();
                return(View(CurrentUser));
            }
            else
            {
                return(LoginFailed("/" + ControllerName));
            }
        }
コード例 #17
0
 public void Put(string column, object data)
 {
     if (data == null)
     {
         LW.E("DBOutput: Put " + column + " as null, drop it..."); return;
     }
     if (data is ICollection)
     {
         data = string.Join(",", (IEnumerable <string>)data);
     }
     if (Data.ContainsKey(column))
     {
         Data.Remove(column);
         Data.Add(column, data);
     }
     else
     {
         Data.Add(column, data);
     }
 }
        public void POST(string msg_signature, string timestamp, string nonce)
        {
            MemoryStream ms = new MemoryStream();

            Request.Body.CopyTo(ms);
            string XML_Message = "";
            string _message    = Encoding.UTF8.GetString(ms.ToArray());
            int    ret         = WeChatHelper.WeChatEncryptor.DecryptMsg(msg_signature, timestamp, nonce, _message, ref XML_Message);

            if (ret != 0)
            {
                Response.StatusCode = 200;
                LW.E("WeChat Message Decrypt Failed!! " + _message);
                Response.WriteAsync("");
                return;
            }
            WeChatMessageSystem.AddToRecvList(new WeChatRcvdMessage(XML_Message, DateTime.Now));
            Response.StatusCode = 200;
            Response.WriteAsync("");
        }
コード例 #19
0
        public static void GetStateString()
        {
            NamedPipeClientStream client = new NamedPipeClientStream("localhost", XConfig.Current.StatusReportNamedPipe, PipeDirection.In);

            while (true)
            {
                client.Connect();
                while (client.IsConnected)
                {
                    var data  = new byte[65535];
                    var count = client.Read(data, 0, data.Length);
                    if (count > 0)
                    {
                        HomeController.ServerStatus = Encoding.UTF8.GetString(data, 0, count);
                    }
                }
                LW.E("GetStateString: DisConnected from the WBWebServer....");
                Thread.Sleep(1000);
            }
        }
コード例 #20
0
        public static DBQueryStatus UpdateData <T>(ref T item, DBQuery query) where T : DataTableObject, new()
        {
            if (query == null)
            {
                query = new DBQuery().WhereEqualTo("objectId", item.ObjectId);
            }
            query.Limit(1);
            DataBaseIO output = new DataBaseIO();

            item.WriteObject(output, false);
            var _result = _DBRequestInternal(item.Table, DBVerbs.Update, query, output, out DataBaseIO[] inputs);

            if (_result != DBQueryStatus.ONE_RESULT)
            {
                LW.E("DBInternalLog: UpdateData Process Failed!");
                return(DBQueryStatus.INTERNAL_ERROR);
            }
            item = new T();
            item.ReadFields(inputs[0]);
            return(_result);
        }
コード例 #21
0
        public IActionResult WeChatLogin(string state, string code)
        {
            ViewData["where"] = ControllerName;
            if (string.IsNullOrEmpty(Request.Cookies["WB_WXLoginOption"]) || string.IsNullOrEmpty(state) || string.IsNullOrEmpty(code))
            {
                return(RequestIllegal(ServerAction.WeChatLogin_PreExecute, XConfig.Messages["WeChatRequestStatusUnexcepted"]));
            }
            else
            {
                WeChatHelper.ReNewWCCodes();
                //object LogonUser = null;
                Dictionary <string, string> JSON = PublicTools.HTTPGet("https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo?access_token=" + WeChatHelper.AccessToken + "&code=" + code);
                if (!JSON.ContainsKey("UserId"))
                {
                    LW.E("WeChat JSON doesnot Contain: UserID, " + JSON.ToParsedString());
                    return(null);
                }
                string WeiXinID = JSON["UserId"];
                switch (DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("Username", WeiXinID), out UserObject User))
                {
                case DBQueryStatus.INTERNAL_ERROR:
                    LW.E("SessionManager: Failed to get User by its UserName --> DataBase Inernal Error....");
                    return(DatabaseError(ServerAction.WeChatLogin_PostExecute, XConfig.Messages["InternalDataBaseError"]));

                case DBQueryStatus.NO_RESULTS:
                    string token = OnePassTicket.CreateTicket();
                    OnePassTicket.TryAdd(token, new TicketInfo(TicketUsage.UserRegister, Request.Headers["User-Agent"], WeiXinID));
                    return(Redirect($"/Account/Register?token={token}&user={WeiXinID}&_action=register"));

                case DBQueryStatus.ONE_RESULT:
                    UpdateUser(User);
                    Response.Cookies.Delete("WB_WXLoginOption");
                    return(Redirect("/Home/Index/"));

                default:
                    LW.E("HomeController: Unexpected Database Query Result for WeChatLogin...");
                    return(DatabaseError(ServerAction.WeChatLogin_PostExecute, XConfig.Messages["WrongDataReturnedFromDatabase"]));
                }
            }
        }
コード例 #22
0
        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);
        }
コード例 #23
0
        private void clientEnumTimer_Tick(object sender, EventArgs e)
        {
            try
            {
                Dictionary <string, string> clientConncetionQueryStrings;
                lock (DatabaseSocketsServer.QueryStrings)
                {
                    clientConncetionQueryStrings = DatabaseSocketsServer.QueryStrings;
                }

                listView1.Items.Clear();
                foreach (KeyValuePair <string, string> item in clientConncetionQueryStrings)
                {
                    listView1.Items.Add(new ListViewItem(new string[] { item.Key, item.Value }));
                }
                dbConnections.Text  = "1";
                currentClients.Text = listView1.Items.Count.ToString();
            }
            catch (Exception ex)
            {
                LW.E("TIMER ERROR: " + ex.Message);
            }
        }
コード例 #24
0
        private IActionResult _InternalError(ServerAction action, string info, ResponceCode respCode)
        {
            Exception ex   = HttpContext.Features.Get <ExceptionHandlerFeature>()?.Error;
            string    Page = HttpContext.Features.Get <IExceptionHandlerPathFeature>()?.Path;

            info = info + "\r\n" + ex?.ToString();

            Response.StatusCode = Response.StatusCode == 404 ? 404 : (int)respCode;

            ViewData["where"]        = HomeController.ControllerName;
            ViewData["DetailedInfo"] = respCode.ToString();
            ViewData["ErrorAT"]      = action.ToString();
            ViewData["RespCode"]     = Response.StatusCode.ToString();
            ViewData["ErrorMessage"] = info;
            ViewData["RAWResp"]      = Page;

            string content = string.Join("\r\n",
                                         "Error Report:",
                                         DateTime.Now.ToNormalString(),
                                         CurrentUser.GetFullIdentity(),
                                         Response.StatusCode,
                                         ViewData["RAWResp"],
                                         ViewData["ErrorMessage"],
                                         ViewData["ErrorAT"],
                                         ViewData["DetailedInfo"]);

            WeChatSentMessage _Message = new WeChatSentMessage(WeChatSMsg.text, null, content, null, "liuhaoyu");

            LW.E(content.Replace("\r\n", " -- "));

            if (respCode != ResponceCode.Default)
            {
                WeChatMessageSystem.AddToSendList(_Message);
            }
            return(View("Error"));
        }
コード例 #25
0
        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, "不支持的消息类型"));
        }
コード例 #26
0
        public static string ProcessRequest(DBInternal request)
        {
            DBInternal reply = new DBInternal();

            try
            {
                if (request == null)
                {
                    throw new NullReferenceException("Null Request....");
                }

                if (request.Verb != DBVerbs.Create)
                {
                    if (request.Query == null)
                    {
                        throw new ArgumentNullException("When using Query Single/Multi/Change/Delete. Arg: query cannot be null");
                    }
                }

                if (request.Verb == DBVerbs.Create || request.Verb == DBVerbs.Update)
                {
                    if (request.DBObjects == null)
                    {
                        throw new ArgumentNullException("When using Create and Update. Arg: output cannot be null");
                    }
                }

                int rowModified = 0;
                reply.Verb = request.Verb;
                switch (request.Verb)
                {
                case DBVerbs.Create:
                    rowModified      = CommandCreate(request.TableName, request.DBObjects[0]);
                    reply.ResultCode = (DBQueryStatus)rowModified;
                    reply.DBObjects  = GetFirstRecord(request.TableName, "objectId", request.DBObjects[0]["objectId"]);
                    break;

                case DBVerbs.QuerySingle:
                ///There shouldn't be QuerySingle... <see cref="DataBaseOperation.QueryMultipleData{T}(DBQuery, out List{T}, int, int)"/>
                case DBVerbs.QueryMulti:
                    var results = SQLQueryCommand(BuildQueryString(request.TableName, request.Query));
                    rowModified      = results.Length;
                    reply.DBObjects  = results.ToArray();
                    reply.ResultCode = results.Length >= 2 ? DBQueryStatus.MORE_RESULTS : (DBQueryStatus)results.Length;
                    break;

                case DBVerbs.Update:
                    //Only Support first thing....
                    var dict = SQLQueryCommand(BuildQueryString(request.TableName, request.Query));
                    if (dict.Length != 1)
                    {
                        throw new KeyNotFoundException("DBServerCore-->ProcessRequest->Update: Cannot find Specific Record by Query, so Failed to update....");
                    }
                    rowModified      = CommandUpdate(request.TableName, dict[0]["objectId"].ToString(), request.DBObjects[0]);
                    reply.ResultCode = (DBQueryStatus)rowModified;
                    reply.DBObjects  = GetFirstRecord(request.TableName, "objectId", dict[0]["objectId"]);

                    break;

                case DBVerbs.Delete:
                    rowModified      = CommandDelete(request.TableName, request.Query.EqualTo["objectId"].ToString());
                    reply.ResultCode = (DBQueryStatus)rowModified;
                    break;

                default:
                    //HttpUtility.UrlEncode("!@#$%^&*()_+");
                    //break;
                    throw new NotSupportedException("What The Hell you are doing....");
                }
                reply.Message = "操作成功完成(" + rowModified + ")";
            }
            catch (Exception ex)
            {
                reply.ResultCode = DBQueryStatus.INTERNAL_ERROR;
                reply.Message    = ex.Message;
                reply.Exception  = new DataBaseException("DBServer Process Exception", ex);
                LW.E("Exception! => \r\n" + ex);
            }
            return(reply.ToParsedString());
        }
コード例 #27
0
        //private void StuPartOS_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    ClassYear.Items.Clear();
        //    switch (ClassPartOS.Text)
        //    {
        //        case "小学部":
        //            ClassYear.Items.AddRange(new string[] { "一年级", "二年级", "三年级", "四年级", "五年级", "六年级" });
        //            break;
        //        case "初中部":
        //            ClassYear.Items.AddRange(new string[] { "初一", "初二", "初三" });
        //            break;
        //        case "普通高中部":
        //        case "中加高中部":
        //            ClassYear.Items.AddRange(new string[] { "高一", "高二", "高三" });
        //            break;
        //        case "剑桥高中部":
        //            ClassYear.Items.AddRange(new string[] { "Year 10", "Year 11", "Year 12", "Year 13" });
        //            break;
        //        default:
        //            ClassYear.Items.Add("请选择学部");
        //            break;
        //    }
        //    ClassYear.SelectedIndex = 0;
        //}
        #endregion

        private void SureAndUpload(object sender, EventArgs e)
        {
            statusPanel.Visible = true;
            for (int index = 0; index < StudentData.Rows.Count - 1; index++)
            {
                DoLog("正在校验数据完整性");
                statusLabel.Text = $"正在检测数据完整性......第{index}项,共{StudentData.Rows.Count - 2}项";
                DoLog("数据完整性校验完成");
                Application.DoEvents();
                DataGridViewRow StuRow = StudentData.Rows[index];
                StuRow.DefaultCellStyle.BackColor = Color.White;
                StuRow.DefaultCellStyle.ForeColor = Color.Black;
                if (string.IsNullOrEmpty((string)StuRow.Cells[2].Value) &&
                    string.IsNullOrEmpty((string)StuRow.Cells[3].Value))
                {
                    MessageBox.Show("这一行:" + StuRow.Cells[1].Value.ToString() + "还没有填写完整!");
                    return;
                }
            }

            statusLabel.Text = $"正在确认上传";
            Application.DoEvents();
            switch (MessageBox.Show("上传会改写已经存在的项,并且将重置学生签到信息,是否继续?", "提示", MessageBoxButtons.YesNo))
            {
            case DialogResult.Yes:
                break;

            case DialogResult.No:
            default:
                statusLabel.Text = $"上传数据已取消!";
                DoLog(statusLabel.Text);
                Thread.Sleep(1000);
                statusPanel.Visible = false;
                return;

                break;
            }
            foreach (DataGridViewRow StuRow in StudentData.Rows)
            {
                statusLabel.Text = $"正在处理校车ID";
                DoLog(statusLabel.Text);
                Application.DoEvents();
                //Combo Box is valueD, use the 2nd cell
                if (!string.IsNullOrEmpty((string)StuRow.Cells[2].Value))
                {
                    if (BusDataPair.ContainsKey((string)StuRow.Cells[2].Value))
                    {
                        StuRow.Cells[3].Value = BusDataPair[(string)StuRow.Cells[2].Value];
                    }
                    else
                    {
                        MessageBox.Show($"在数据库中找不到匹配的校车信息: {(string)StuRow.Cells[2].Value}");
                    }
                }
                else
                {
                    //Nothing to do for NOT GIVEN student Bus Direction
                }
            }
            statusLabel.Text = $"分配数据空间....";
            DoLog(statusLabel.Text);
            Application.DoEvents();

            StudentObject StudentObj = new StudentObject();

            StudentObj.CSChecked = false;
            StudentObj.LSChecked = false;
            StudentObj.AHChecked = false;
            this.Enabled         = false;
            statusLabel.Text     = $"开始上传....";
            DoLog(statusLabel.Text);
            this.SureAndUploadBtn.Text = "上传中...";
            Application.DoEvents();
            List <string> ErrDetail = new List <string>();

            for (int RowNum = 0; RowNum < (StudentData.RowCount - 1); RowNum++)
            {
                StudentObj.StudentName = (string)StudentData.Rows[RowNum].Cells[1].Value;
                StudentObj.BusID       = (string)StudentData.Rows[RowNum].Cells[3].Value;
                StudentObj.ClassID     = CurrentClass.ObjectId;

                statusLabel.Text = $"正在上传第{RowNum}项,共{StudentData.RowCount - 2}项。";
                DoLog("学生姓名:" + StudentObj.StudentName);
                Application.DoEvents();
                //If Record is NOT in the Server Database, SHOWN AS NO  "OBJECT ID" GIVEN
                if (string.IsNullOrEmpty((string)StudentData.Rows[RowNum].Cells[0].Value))
                {
                    if (Database.DataBaseOperation.CreateData(ref StudentObj) == DBQueryStatus.ONE_RESULT)
                    {
                        statusLabel.Text = $"正在上传第{RowNum}项,共{StudentData.RowCount - 2}项,完成!";
                        Application.DoEvents();
                        StudentData.Rows[RowNum].DefaultCellStyle.BackColor = Color.Green;
                        continue;
                    }
                    else
                    {
                        statusLabel.Text = $"正在上传第{RowNum}项,共{StudentData.RowCount - 2}项,出错!";
                        StudentData.Rows[RowNum].DefaultCellStyle.BackColor = Color.Red;
                        StudentData.Rows[RowNum].DefaultCellStyle.ForeColor = Color.White;
                    }
                }
                //Record is in the Database, only update needed
                else
                {
                    StudentObj.ObjectId = (string)StudentData.Rows[RowNum].Cells[0].Value;
                    if (Database.DataBaseOperation.UpdateData(ref StudentObj) == 0)
                    {
                        statusLabel.Text = $"正在上传第{RowNum}项,共{StudentData.RowCount - 2}项,完成!";
                        StudentData.Rows[RowNum].DefaultCellStyle.BackColor = Color.LawnGreen;
                        Application.DoEvents();
                        continue;
                    }
                    else
                    {
                        statusLabel.Text = $"正在上传第{RowNum}项,共{StudentData.RowCount - 2}项,出错!";
                        StudentData.Rows[RowNum].DefaultCellStyle.BackColor = Color.Red;
                        StudentData.Rows[RowNum].DefaultCellStyle.ForeColor = Color.White;
                    }
                }
            }
            statusLabel.Text = $"上传操作完成,正在处理后续工作。";
            Application.DoEvents();
            if (ErrDetail.Count == 0)
            {
                DoLog("成功完成操作!已经上传 " + (StudentData.RowCount - 1).ToString() + " 条数据");
                MessageBox.Show("所有项目已经成功上传!");
            }
            else
            {
                DoLog("上传部分失败!共 " + ErrDetail.Count.ToString() + " 条失败");
                string ErrMsg = "\r\n";
                foreach (string item in ErrDetail)
                {
                    ErrMsg = ErrMsg + item;
                }
                LW.E("Error when updating these students data: " + ErrMsg);
                MessageBox.Show("有部分内容上传失败,它们是:" + ErrMsg + "请尝试重新上传");
            }
            this.SureAndUploadBtn.Text = "确认并上传(&S)";
            statusPanel.Visible        = false;
            this.Enabled = true;
        }
コード例 #28
0
        public IActionResult ChangeRequest(string arg, string reqId)
        {
            if (ValidateSession())
            {
                if (!string.IsNullOrEmpty(arg))
                {
                    switch (arg)
                    {
                    case "my":
                        ViewData["mode"]  = "my";
                        ViewData["where"] = AccountController.ControllerName;
                        if (string.IsNullOrEmpty(reqId))
                        {
                            // MY LIST
                            switch (DataBaseOperation.QueryMultipleData(new DBQuery().WhereEqualTo("UserID", CurrentUser.ObjectId), out List <UserChangeRequest> requests))
                            {
                            case DBQueryStatus.INTERNAL_ERROR: return(DatabaseError(ServerAction.General_ViewChangeRequests, XConfig.Messages.InternalDataBaseError));

                            default:
                                ViewData["count"] = requests.Count;
                                ViewData["list"]  = requests.ToArray();
                                return(base.View());
                            }
                        }
                        else
                        {
                            // MY SINGLE Viewer
                            switch (DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("UserID", CurrentUser.ObjectId).WhereEqualTo("objectId", reqId), out UserChangeRequest requests))
                            {
                            case DBQueryStatus.INTERNAL_ERROR:
                            case DBQueryStatus.NO_RESULTS:
                            case DBQueryStatus.MORE_RESULTS:
                                return(DatabaseError(ServerAction.General_ViewChangeRequests, XConfig.Messages.InternalDataBaseError));

                            default:
                                return(base.View(requests));
                            }
                        }

                    case "manage":
                        ViewData["where"] = ControllerName;
                        ViewData["mode"]  = "manage";
                        if (!CurrentUser.UserGroup.IsAdmin)
                        {
                            LW.E("Someone trying access illegal page!, Page: changeRequest: arg=manage, user:"******", possible referer:" + Request.Headers["Referer"]);
                            return(NotFound());
                        }
                        if (string.IsNullOrEmpty(reqId))
                        {
                            switch (DataBaseOperation.QueryMultipleData(new DBQuery(), out List <UserChangeRequest> requests))
                            {
                            case DBQueryStatus.INTERNAL_ERROR:
                                return(DatabaseError(ServerAction.Manage_VerifyChangeRequest, XConfig.Messages.InternalDataBaseError));

                            default:
                                ViewData["list"] = requests.ToArray();
                                return(base.View());
                            }
                        }
                        else
                        {
                            switch (DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("objectId", reqId), out UserChangeRequest requests))
                            {
                            case DBQueryStatus.INTERNAL_ERROR:
                            case DBQueryStatus.NO_RESULTS:
                            case DBQueryStatus.MORE_RESULTS:
                                return(DatabaseError(ServerAction.Manage_VerifyChangeRequest, XConfig.Messages.InternalDataBaseError));

                            default:
                                return(base.View(requests));
                            }
                        }

                    default:
                        return(RequestIllegal(ServerAction.General_ViewChangeRequests, XConfig.Messages.ParameterUnexpected));
                    }
                }
                else
                {
                    return(RequestIllegal(ServerAction.General_ViewChangeRequests, XConfig.Messages.ParameterUnexpected));
                }
            }
            else
            {
                return(LoginFailed("/" + ControllerName + "/ChangeRequest?arg=" + arg + "&reqId=" + reqId));
            }
        }
コード例 #29
0
        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;
        }
コード例 #30
0
        public JsonResult Get(string reqId, string mode, string detail)
        {
            if (ValidateSession())
            {
                if (CurrentUser.UserGroup.IsAdmin)
                {
                    switch (DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("objectId", reqId), out UserChangeRequest request))
                    {
                    case DBQueryStatus.ONE_RESULT:
                        request.SolverID = CurrentUser.ObjectId;
                        switch (mode)
                        {
                        case "0":
                            //Accepted
                            request.Status = UCRProcessStatus.Accepted;
                            break;

                        case "1":
                            //Refused
                            UCRRefusedReasons reason = Enum.Parse <UCRRefusedReasons>(detail);
                            request.Status = UCRProcessStatus.Refused;
                            request.ProcessResultReason = reason;
                            break;

                        default: return(RequestIllegal);
                        }
                        if (DataBaseOperation.UpdateData(ref request) != DBQueryStatus.ONE_RESULT)
                        {
                            return(DataBaseError);
                        }
                        if (request.Status == UCRProcessStatus.Accepted)
                        {
                            switch (DataBaseOperation.QuerySingleData(new DBQuery().WhereEqualTo("objectId", request.UserID), out UserObject user))
                            {
                            case DBQueryStatus.ONE_RESULT:
                                switch (request.RequestTypes)
                                {
                                case UserChangeRequestTypes.真实姓名:
                                    user.RealName = request.NewContent;
                                    break;

                                case UserChangeRequestTypes.手机号码:
                                    user.PhoneNumber = request.NewContent;
                                    break;

                                default: return(SpecialisedInfo("提交成功,部分内容需要手动修改"));
                                }
                                if (DataBaseOperation.UpdateData(ref user) != DBQueryStatus.ONE_RESULT)
                                {
                                    LW.E("Admin->UCRProcess: Failed to Save user data");
                                    return(DataBaseError);
                                }

                                InternalMessage message_User = new InternalMessage()
                                {
                                    _Type = GlobalMessageTypes.UCR_Procceed_TO_User, DataObject = request, User = user, ObjectId = request.UserID
                                };
                                MessagingSystem.AddMessageProcesses(message_User);
                                break;

                            default: return(DataBaseError);
                            }
                        }
                        return(SpecialisedInfo("提交成功"));

                    default: return(DataBaseError);
                    }
                }
                else
                {
                    return(UserGroupError);
                }
            }
            else
            {
                return(SessionError);
            }
        }