Ejemplo n.º 1
0
        private void IgnoreDataHandler(Recv recv)
        {
            lock (_sonarDatas)
            {
                _sonarDatas.Clear();
            }

            lock (_directionDatas)
            {
                _directionDatas.Clear();
            }

            lock (_accelDatas)
            {
                _accelDatas.Clear();
            }

            lock (_proxiDatas)
            {
                _proxiDatas.Clear();
            }

            lock (_parkingSensorsDatas)
            {
                _parkingSensorsDatas.Clear();
            }
        }
Ejemplo n.º 2
0
        private async Task <IActionResult> MessengerProductListResult(Type childType, int minPrice, int maxPrice)
        {
            var msgs = (await new CutieshopContext().Product
                        .Include(x => x.ProductForPetType)
                        .ThenInclude(x => x.PetType)
                        .Include(x => x.Accessory)
                        .Include(x => x.Cage)
                        .Include(x => x.Food)
                        .Include(x => x.Toy)
                        .ToArrayAsync())
                       .Where(x => ProductEqualTypeNotNull(x, childType) &&
                              x.Price >= minPrice &&
                              x.Price <= maxPrice &&
                              x.ProductForPetType.Any(y => y.PetType.Name == Storage[MsgId, 1]))
                       .Select(x => new { x.Name, Price = x.Price.ToString(), x.ProductId, x.ImgUrl, BtnText = "Đặt liền" })
                       .Select(ele => (ele.Name, ele.Price, ele.ProductId, ele.ImgUrl, ele.BtnText))
                       .ToArray();

            //Return message
            if (msgs.Any())
            {
                return(Recv.Json(RespObj(RespType.Cards, "", cards: msgs)));
            }

            //Require user to choose another price
            //Storage.RemoveId(MsgId);
            Storage.StepBack(MsgId);
            return(Recv.Json(RespObj(RespType.QuickReplies,
                                     "Xin lỗi bạn. Chúng mình tạm thời không còn bán loại hàng này. Bạn vui lòng chọn mức giá khác",
                                     new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" })));
        }
Ejemplo n.º 3
0
        void IgnoreDataHandler(Recv recv)
        {
            if (_port == null ||
                _port.BytesToRead <= 0)
            {
                return;
            }
            byte[] buffer = new byte[_port.BytesToRead];

            _port.Read(buffer, 0, buffer.Length);
        }
Ejemplo n.º 4
0
        public UDPClient(string ip, int port, int maxBufferSize, int closeTimeout, Recv recv)
        {
            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
            this.socket.Bind(new IPEndPoint(IPAddress.Any, 0));
            this.remote        = new IPEndPoint(IPAddress.Parse(ip), port);
            this.maxBufferSize = maxBufferSize;
            this.translators   = new Dictionary <uint, StatusTranslator> ();
            this.generators    = new Dictionary <uint, OperationGenerator> ();
            this.recv          = recv;
            this.closed        = false;

            this.socket.ReceiveTimeout = closeTimeout;            //毫秒
        }
Ejemplo n.º 5
0
        void DataHandler(Recv recv)
        {
            while (DataPort.Test() != null)
            {
                ;
            }

            if (_port == null ||
                _port.BytesToRead <= 0)
            {
                return;
            }
            byte[] buffer = new byte[_port.BytesToRead];

            int read = _port.Read(buffer, 0, buffer.Length);

            if (read == 0)
            {
                return;
            }

            _builder.Add(buffer, read);
            while (_builder.HasPacket)
            {
                Responses.Post(_builder.RemovePacket());
            }
            if (_builder.BadPackets > 0)
            {
                if (_builder.BadPackets != _badCount)
                {
                    //
                    // only report bad packets if the number has changed.
                    //
                    _badCount = _builder.BadPackets;
                    Responses.Post(new BadPacketException(_builder.BadPackets));
                }
            }
            else
            {
                _badCount = 0;
            }
        }
Ejemplo n.º 6
0
        private void OnReceiveFromServer(Recv nextDispatch)
        {
            switch (nextDispatch.Id)
            {
            case RecvId.Event:
            {
                // enter code to handle events received in a SIMCONNECT_RECV_EVENT structure.
                var evt = nextDispatch as RecvEvent;

                switch ((MyEvents)evt.EventId)
                {
                case MyEvents.Brakes:
                    Console.WriteLine("MyEvents.Brakes {0}", evt.Data);
                    break;

                case MyEvents.ElevatorTrimSet:
                    Console.WriteLine("MyEvents.ElevatorTrimSet {0}", (int)evt.Data);
                    client.RequestDataOnSimObject(MyRequests.One, MyDefinitions.One, Constants.ObjectIdUser, Period.Once, DataRequestFlag.Default);
                    break;

                case MyEvents.ElevTrimUp:
                    Console.WriteLine("MyEvents.ElevTrimUp {0}", (int)evt.Data);
                    client.RequestDataOnSimObject(MyRequests.One, MyDefinitions.One, Constants.ObjectIdUser, Period.Once, DataRequestFlag.Default);
                    break;

                case MyEvents.ElevTrimDown:
                    Console.WriteLine("MyEvents.ElevTrimDown {0}", (int)evt.Data);
                    client.RequestDataOnSimObject(MyRequests.One, MyDefinitions.One, Constants.ObjectIdUser, Period.Once, DataRequestFlag.Default);
                    break;

                default:
                    break;
                }
                break;
            }

            case RecvId.SimobjectData:
            {
                var data = nextDispatch as RecvSimObjectData;

                switch ((MyRequests)data.RequestId)
                {
                case MyRequests.One:
                    var myStruct = (Struct1)data.Data;
                    Console.WriteLine("TrimIndicator  = {0};		TrimPosition  = {1}", myStruct.TrimIndicator, myStruct.TrimPosition);
                    break;

                case MyRequests.Two:
                    var myStruct2 = (Struct2)data.Data;
                    Console.WriteLine($"Speed:{myStruct2.VerticalSpeed * 60}, Trim:{myStruct2.TrimPosition}");
                    break;

                default:
                    break;
                }

                break;
            }


            case RecvId.Quit:
                // enter code to handle exiting the application
                running = false;
                break;

            default:
                break;
            }
        }
Ejemplo n.º 7
0
        public override async Task <IActionResult> Result()
        {
            var currentStep = Storage.GetCurrentStep(MsgId);

            //Switch to next step = currentStep + 1
            switch (currentStep + 1)
            {
                #region step 1
            case 1:
                Storage.AddOrUpdate(MsgId, 1, null);
                using (var petTypeDAO = new PetTypeDAO())
                {
                    var allPetTypes = (await petTypeDAO
                                       .ReadAll(false))
                                      .Select(x => x.Name)
                                      .ToArray();

                    return(Recv.Json(RespObj(RespType.QuickReplies,
                                             "Bạn muốn sản phẩm cho thú cưng nào ạ?", allPetTypes)));
                }

                #endregion
                #region Step 2
            case 2:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var petTypeDAO = new PetTypeDAO())
                    {
                        if (await(await petTypeDAO.ReadAll(false))
                            .Select(x => x.Name)
                            .AllAsync(x => x != MsgReply))
                        {
                            _isSkipValidation = true;
                            goto case 1;
                        }
                    }
                }

                Storage.AddOrUpdate(MsgId, 2, null);
                Storage.AddOrUpdate(MsgId, 1, MsgReply);
                return(Recv.Json(RespObj(RespType.QuickReplies, "Bạn muốn mua gì cho bé ạ?",
                                         new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" })));

                #endregion
                #region Step 3
            case 3:
                //Check if answer is valid
                // ReSharper disable once InvertIf
                if (!_isSkipValidation)
                {
                    if (new[] { "Đồ chơi", "Thức ăn", "Lồng", "phụ kiện" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 2;
                    }

                    Storage.AddOrUpdateAndMoveNext(MsgId, MsgReply);
                }

                return(Recv.Json(RespObj(RespType.QuickReplies,
                                         "Bạn có thể cho mình biết mức giá bạn muốn tìm kiếm?",
                                         new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" })));

                #endregion
                #region Step 4
            case 4:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    if (new[] { "<100000", "100000 - 300000", ">300000 - 500000", ">500000" }.All(x => x != MsgReply))
                    {
                        _isSkipValidation = true;
                        goto case 3;
                    }

                    Storage.AddOrUpdateAndMoveNext(MsgId, MsgReply);
                }

                //Find minimum and maximum price from step 3
                int minimumPrice, maximumPrice;

                switch (Storage[MsgId, 3])
                {
                case "<100000":
                    minimumPrice = 0;
                    maximumPrice = 99999;
                    break;

                case "100000 - 300000":
                    minimumPrice = 100000;
                    maximumPrice = 300000;
                    break;

                case ">300000 - 500000":
                    minimumPrice = 300001;
                    maximumPrice = 500000;
                    break;

                default:
                    minimumPrice = 500001;
                    maximumPrice = int.MaxValue;
                    break;
                }

                //Find product in step 2, for pet in step 1
                return(await MessengerProductListResult(GetProductType(), minimumPrice, maximumPrice));

                #endregion
                #region Step 5
            case 5:
                //Check if answer is valid
                if (!_isSkipValidation)
                {
                    using (var productDAO = new ProductDAO())
                        if (await productDAO.Read(MsgQuery, false) == null)
                        {
                            _isSkipValidation = true;
                            goto case 4;
                        }
                }

                Storage.AddOrUpdateAndMoveNext(MsgId, MsgQuery);

                return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập số lượng sản phẩm bạn muốn mua")));

                #endregion
                #region Step 6
            case 6:
                if (!int.TryParse(MsgReply, out var res) || res < 1)
                {
                    return(Recv.Json(RespObj(RespType.Text,
                                             "Số lượng nhập vào không hợp lệ. Vui lòng nhập lại")));
                }

                Storage.AddOrUpdateAndMoveNext(MsgId, MsgQuery);

                return(Recv.Json(MultiResp(RespObj(RespType.Text,
                                                   "Bạn có thể cho mình biết tên đăng nhập trên hệ thống Cutieshop được không ạ?\nNếu chưa có, bạn có thể gõ tên đăng nhập mới để chúng mình tạo tài khoản cho bạn"),
                                           RespUndo())));

                #endregion
                #region Step 7
            case 7:
                if (_isUndoRequested && Storage[MsgId, 6] == null)
                {
                    Storage.StepBack(MsgId);
                    return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập số lượng sản phẩm bạn muốn mua")));
                }

                //This step receive username first, then the email and address. So we need to keep the username to the storage for further uses, email will be used once in this step and can be queried by DAO easily in the future.
                //Checking null will prevent email from being overwritten to username in Storage

                if (Storage[MsgId, 6] == null)
                {
                    if (!MsgReply.IsPureAscii() || MsgReply.Contains(' '))
                    {
                        return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập tên đăng nhập hợp lệ (không dấu, khoảng cách)")));
                    }
                    Storage.AddOrUpdate(MsgId, 6, MsgReply);
                }

                using (var userDAO = new UserDAO())
                {
                    var user = await userDAO.ReadChild(Storage[MsgId, 6], true);

                    //If user is null, create a user, then ask customer their email
                    if (user == null)
                    {
                        Storage.AddOrUpdate(MsgId, 7, "userPassword", NewGuid().ToString().Substring(0, 6));
                        await userDAO.Create(new Auth
                        {
                            Username = Storage[MsgId, 6],
                            Password = Storage[MsgId, 7, "userPassword"]
                        });

                        await userDAO.CreateChild(new User
                        {
                            Username = Storage[MsgId, 6],
                            Email    = string.Empty,
                            Address  = string.Empty
                        });

                        await userDAO.Context.SaveChangesAsync();
                    }

                    user = await userDAO.ReadChild(Storage[MsgId, 6], true);

                    if (Storage[MsgId, 7, "fullName"] == null)
                    {
                        if (Storage[MsgId, 7, "isAskFullName"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskFullName", "1");
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        if (MsgReply.Trim().Count(x => x == ' ') == 0)
                        {
                            return(Recv.Json(RespObj(RespType.Text, "Vui lòng nhập đầy đủ họ tên")));
                        }

                        Storage.AddOrUpdate(MsgId, 7, "fullName", MsgReply);
                    }

                    //If email is empty, ask for email
                    if (user.Email == string.Empty)
                    {
                        if (Storage[MsgId, 7, "isAskForEmail"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForEmail", "1");
                            return(Recv.Json(MultiResp(
                                                 RespObj(RespType.Text, "Bạn hãy cho mình biết email nhé"), RespUndo())));
                        }

                        //Undo handling
                        if (_isUndoRequested)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "fullName", null);
                            Storage.AddOrUpdate(MsgId, 7, "isAskForEmail", null);
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        //Validate email
                        if (!MsgReply.IsEmail())
                        {
                            return(Recv.Json(MultiResp(RespObj(RespType.Text, "Email không hợp lệ\nVui lòng nhập lại email"), RespUndo())));
                        }

                        user.Email = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    if (Storage[MsgId, 7, "phoneNo"] == null)
                    {
                        if (Storage[MsgId, 7, "isAskForPhoneNo"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForPhoneNo", "1");
                            return(Recv.Json(MultiResp(
                                                 RespObj(RespType.Text, "Bạn cho mình xin số điện thoại ạ"), RespUndo())));
                        }

                        if (_isUndoRequested)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForPhoneNo", null);

                            if (Storage[MsgId, 7, "isAskForEmail"] != null)
                            {
                                user.Email = "";
                                await userDAO.Context.SaveChangesAsync();

                                return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn hãy cho mình biết email nhé"), RespUndo())));
                            }

                            Storage.AddOrUpdate(MsgId, 7, "fullName", null);
                            return(Recv.Json(RespObj(RespType.Text, "Cho mình xin họ tên người nhận hàng?")));
                        }

                        if (Storage[MsgId, 7, "isAskForPhoneNo"] == "1")
                        {
                            Storage.AddOrUpdate(MsgId, 7, "phoneNo", MsgReply);
                        }
                    }

                    if (_isUndoRequested)
                    {
                        user.Address = "";
                        await userDAO.Context.SaveChangesAsync();

                        Storage.AddOrUpdate(MsgId, 7, "phoneNo", null);
                        Storage.AddOrUpdate(MsgId, 7, "isAskForAddress", null);
                        return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn cho mình xin số điện thoại ạ"), RespUndo())));
                    }

                    if (user.Address == string.Empty)
                    {
                        if (Storage[MsgId, 7, "isAskForAddress"] == null)
                        {
                            Storage.AddOrUpdate(MsgId, 7, "isAskForAddress", "1");
                            return(Recv.Json(MultiResp(RespObj(RespType.Text, "Bạn cho mình xin địa chỉ"), RespUndo())));
                        }

                        user.Address = MsgReply;
                        await userDAO.Context.SaveChangesAsync();
                    }

                    //Ready to jump into step 8 (if exists) after this
                    Storage.AddOrUpdate(MsgId, 7, null);

                    using (var orderDAO = new OnlineOrderProductDAO(userDAO.Context))
                    {
                        var orderId = NewGuid().ToString();
                        await orderDAO.Create(orderId, Storage[MsgId, 7, "fullName"], user.Address, "10000", user.City, Storage[MsgId, 7, "phoneNo"], user.Email, user.Username, 0);

                        await orderDAO.CreateChild(Storage[MsgId, 4], orderId, int.Parse(Storage[MsgId, 5]));

                        Product buyProd;
                        using (var prdctDAO = new ProductDAO())
                            buyProd = await prdctDAO.Read(Storage[MsgId, 4], false);

                        var mailPrdctTbl = _mailContent.BuyReq.TableRow
                                           .MultiReplace(("{0}", buyProd.Name), ("{1}", buyProd.Description), ("{2}", Storage[MsgId, 5]));

                        var mailBody = _mailContent.BuyReq.Body
                                       .MultiReplace(
                            ("{0}", user.Username),
                            ("{1}", mailPrdctTbl),
                            ("{2}", orderId),
                            ("{3}", (buyProd.Price * int.Parse(Storage[MsgId, 5])).ToString()));

                        MailUtils.Send(user.Email, _mailContent.BuyReq.Subject, mailBody);

                        var reply = $"Mail xác nhận đã được gửi đến {user.Email}. Hãy xác nhận qua mail để hoàn tất đặt hàng nhé!";

                        //Send temporary password if customer create new account
                        if (Storage[MsgId, 7, "userPassword"] != null)
                        {
                            reply = $"Password tạm thời của bạn là {Storage[MsgId, 7, "userPassword"]}. Bạn nên vào trang chủ để thay đổi mật khẩu mặc định\n" + reply;
                        }

                        //Remove data in storage
                        Storage.RemoveId(MsgId);
                        return(Recv.Json(RespObj(RespType.Text, reply)));
                    }
                }
                #endregion
            }

            Storage.RemoveId(MsgId);
            throw new UnhandledChatException();
        }
Ejemplo n.º 8
0
        // =================================================================================================================

        #region DataReadyPort handlers

        /// <summary>
        /// This handler is activated by empty Recv messages coming to internal DataReadyPort.
        /// The data comes here from pmFrameCompleteHandler
        /// This is our opportunity to purge stale data from the queues.
        /// The data posted to Responses port is then picked up by ProximityBoardCcrServiceCommander:SonarDataHandler() and others,
        /// to be later passed to TrackRoamerBrickProximityBoard.
        /// </summary>
        /// <param name="recv"></param>
        private void DataHandler(Recv recv)
        {
            /*
             * if(_sonarDatas.Count > 1 || _directionDatas.Count > 1 || _accelDatas.Count > 1 || _proxDatas.Count > 1 || _parkingSensorsDatas.Count > 1)
             * {
             *  // for debugging, log if queues get more than 1 piece of each data type:
             *  Tracer.Trace("ProximityBoardManager: DataHandler()  sonars: " + _sonarDatas.Count + "  compass: "******"  accels: " + _accelDatas.Count + "  proxs: " + _proxDatas.Count + "  parking: " + _parkingSensorsDatas.Count);
             * }
             */

            if (_sonarDatas.Count > 0)
            {
                SonarData sonarData = null;

                lock (_sonarDatas)
                {
                    while (_sonarDatas.Count > 0)
                    {
                        sonarData = _sonarDatas.Last();
                        _sonarDatas.Clear();
                    }
                }

                if (sonarData != null)
                {
                    MeasurementsPort.Post(sonarData);
                }
            }

            if (_directionDatas.Count > 0)
            {
                DirectionData directionData = null;

                lock (_directionDatas)
                {
                    while (_directionDatas.Count > 0)
                    {
                        directionData = _directionDatas.Last();
                        _directionDatas.Clear();
                    }
                }

                if (directionData != null)
                {
                    MeasurementsPort.Post(directionData);
                }
            }

            if (_accelDatas.Count > 0)
            {
                AccelerometerData accelerometerData = null;

                lock (_accelDatas)
                {
                    while (_accelDatas.Count > 0)
                    {
                        accelerometerData = _accelDatas.Last();
                        _accelDatas.Clear();
                    }
                }

                if (accelerometerData != null)
                {
                    MeasurementsPort.Post(accelerometerData);
                }
            }

            if (_proxiDatas.Count > 0)
            {
                ProximityData proximityData = null;

                lock (_proxiDatas)
                {
                    while (_proxiDatas.Count > 0)
                    {
                        proximityData = _proxiDatas.Last();
                        _proxiDatas.Clear();
                    }
                }

                if (proximityData != null)
                {
                    MeasurementsPort.Post(proximityData);
                }
            }

            if (_parkingSensorsDatas.Count > 0)
            {
                ParkingSensorData psiData = null;

                lock (_parkingSensorsDatas)
                {
                    while (_parkingSensorsDatas.Count > 0)
                    {
                        psiData = _parkingSensorsDatas.Last();
                        _parkingSensorsDatas.Clear();
                    }
                }

                if (psiData != null)
                {
                    MeasurementsPort.Post(psiData);
                }
            }

            //Tracer.Trace("AnalogData:  current=" + AnalogValue1 + "    prev=" + AnalogValue1Prev);

            // and last but not least - post AnalogData - only if any of the values changed:
            if (AnalogValue1 != AnalogValue1Prev)
            {
                AnalogValue1Prev = AnalogValue1;
                AnalogData analogData = new AnalogData()
                {
                    analogValue1 = AnalogValue1,
                    TimeStamp    = DateTime.Now.Ticks
                };
                MeasurementsPort.Post(analogData);
            }
        }
Ejemplo n.º 9
0
 private static void OnRecv(object sender, MyEventArgs e)
 {
     Recv?.Invoke(sender, e);
     History.Add(new HistoryItem(DateTime.Now, e.Mqtt));
 }
Ejemplo n.º 10
0
        public static void Init(Func <string, UIElement, bool, UIElement> updateMainPage)
        {
            _updateMain = updateMainPage;

            #region DataBase

            if (!File.Exists(AppDomain.CurrentDomain.BaseDirectory + "\\AppData\\hjudgeData.db"))
            {
                SQLiteConnection.CreateFile(AppDomain.CurrentDomain.BaseDirectory + "\\AppData\\hjudgeData.db");
            }
            //var DbSQLiteConnection = new SQLiteConnection("Data Source=" +
            //                                  $"{AppDomain.CurrentDomain.BaseDirectory + "\\AppData\\hjudgeData.db"};Initial Catalog=sqlite;Integrated Security=True;");
            if (DbSQLiteConnection.State == ConnectionState.Closed)
            {
                DbSQLiteConnection.Open();
            }

            if (!CreateJudgeTable(DbSQLiteConnection))
            {
                if (MessageBox.Show("版本升级需要清空所有评测记录,是否继续?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                    MessageBoxResult.Yes)
                {
                    DropTable(DbSQLiteConnection, "Judge");
                    CreateJudgeTable(DbSQLiteConnection);
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            if (!CreateUserTable(DbSQLiteConnection))
            {
                if (MessageBox.Show("版本升级需要清空所有用户信息,是否继续?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                    MessageBoxResult.Yes)
                {
                    DropTable(DbSQLiteConnection, "User");
                    CreateUserTable(DbSQLiteConnection);
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            if (!CreateProblemTable(DbSQLiteConnection))
            {
                if (MessageBox.Show("版本升级需要清空所有题目信息,是否继续?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                    MessageBoxResult.Yes)
                {
                    DropTable(DbSQLiteConnection, "Problem");
                    CreateProblemTable(DbSQLiteConnection);
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            if (!CreateMessageTable(DbSQLiteConnection))
            {
                if (MessageBox.Show("版本升级需要清空所有消息记录,是否继续?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                    MessageBoxResult.Yes)
                {
                    DropTable(DbSQLiteConnection, "Message");
                    CreateMessageTable(DbSQLiteConnection);
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            if (!CreateCompetitionTable(DbSQLiteConnection))
            {
                if (MessageBox.Show("版本升级需要清空所有比赛信息,是否继续?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
                    MessageBoxResult.Yes)
                {
                    DropTable(DbSQLiteConnection, "Competition");
                    CreateCompetitionTable(DbSQLiteConnection);
                }
                else
                {
                    Environment.Exit(0);
                }
            }
            DbSQLiteConnection.Close();
            #endregion

            #region Network

            HServer.OnAccept += (id, client) =>
            {
                var    ip   = string.Empty;
                ushort port = 0;
                if (!HServer.GetRemoteAddress(id, ref ip, ref port))
                {
                    return(HandleResult.Ignore);
                }
                var clientInfo = new ClientInfo
                {
                    UserId    = 0,
                    ConnId    = id,
                    IpAddress = ip,
                    Port      = port,
                    PkgInfo   = new PkgInfo
                    {
                        IsHeader = true,
                        Length   = PkgHeaderSize
                    }
                };
                HServer.SetExtra(id, clientInfo);
                Recv.Add(new ClientData {
                    Info = clientInfo
                });
                SendData("Version", Assembly.GetExecutingAssembly().GetName().Version.ToString(), id, null);
                return(HandleResult.Ok);
            };
            HServer.OnClose += (id, operation, code) =>
            {
                HServer.RemoveExtra(id);
                var t = (from c in Recv where c.Info.ConnId == id select c).FirstOrDefault();
                if (t != null)
                {
                    lock (RemoveClientLock)
                    {
                        var x = new List <ClientData>();
                        while (Recv.TryTake(out var tmp))
                        {
                            if (!tmp.Equals(t))
                            {
                                x.Add(tmp);
                            }
                            else
                            {
                                if (tmp.Info.UserId != 0)
                                {
                                    UpdateMainPageState(
                                        $"{DateTime.Now:yyyy/MM/dd HH:mm:ss} 用户 {tmp.Info.UserName} 注销了");
                                }
                                break;
                            }
                        }
                        foreach (var i in x)
                        {
                            Recv.Add(i);
                        }
                    }
                }
                return(HandleResult.Ok);
            };
            HServer.OnReceive += HServerOnOnReceive;

            HServer.IpAddress = Configuration.Configurations.IpAddress;
            HServer.Port      = 23333;
            if (!HServer.Start())
            {
                MessageBox.Show("服务端网络初始化失败,请检查系统设置", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            new Thread(DealingBytes)
            {
                Priority = ThreadPriority.Highest
            }.Start();
            for (var i = 0; i < Environment.ProcessorCount; i++)
            {
                new Thread(DealingOperations)
                {
                    Priority = ThreadPriority.Highest
                }
            }