Beispiel #1
0
        private void HandleCloseHandshake(WebSocketPackage receivedClosePackage)
        {
            var reader = new SequenceReader <byte>(receivedClosePackage.Data);

            reader.TryReadBigEndian(out ushort closeReason);
            var reasonText = reader.ReadString(_utf8Encoding);

            var closeStatus = CloseStatus;

            if (closeStatus == null)
            {
                CloseStatus = new CloseStatus
                {
                    Reason     = (CloseReason)closeReason,
                    ReasonText = reasonText
                };

                return;
            }

            if (closeStatus.Reason != (CloseReason)closeReason)
            {
                OnError("Unmatched CloseReason");
                return;
            }

            if (closeStatus.ReasonText != reasonText)
            {
                OnError("Unmatched CloseReasonText");
                return;
            }
        }
Beispiel #2
0
        private CloseStatus GetCloseStatusFromPackage(WebSocketPackage package)
        {
            if (package.Data.Length < 2)
            {
                _logger.LogWarning($"This close handshake (data length: {package.Data.Length}) doesn't include any close reason or reason text, so default it to normal closure.");

                return(new CloseStatus
                {
                    Reason = CloseReason.NormalClosure
                });
            }

            var reader = new SequenceReader <byte>(package.Data);

            reader.TryReadBigEndian(out short closeReason);

            var closeStatus = new CloseStatus
            {
                Reason = (CloseReason)closeReason
            };

            if (reader.Remaining > 0)
            {
                closeStatus.ReasonText = package.Data.Slice(2).GetString(Encoding.UTF8);
            }

            return(closeStatus);
        }
Beispiel #3
0
        /// <summary>
        /// 向客户端发送关闭指令
        /// 断开客户端的连接并回收利用client对象
        /// </summary>
        /// <param name="client">客户端</param>
        /// <param name="reason">关闭原因</param>
        public void CloseClient(SocketAsync <Hybi13Packet> client, CloseStatus reason)
        {
            var reasonByes = ByteConverter.ToBytes((ushort)(reason), Endians.Big);

            this.Send(client, FrameTypes.Close, reasonByes);
            this.CloseClient(client);
        }
Beispiel #4
0
        private static bool SaveToPDF(string name, out string fileName)
        {
            string           destinationFile = String.Empty;
            ManualResetEvent endUIThread     = new ManualResetEvent(false);
            CloseStatus      returnValue     = CloseStatus.CANCEL;
            Form             mainForm        = Form.ActiveForm;

            mainForm.Invoke((Action)(() =>
            {
                try
                {
                    string ext = "*.pdf";
                    SaveFileDialog fileChooser = new SaveFileDialog();
                    fileChooser.FileName = name;
                    fileChooser.Filter = String.Format("PDF document|{0}", ext);
                    fileChooser.Title = "Save";
                    fileChooser.AddExtension = true;

                    fileChooser.FileOk += delegate
                    {
                        destinationFile = fileChooser.FileName;
                        returnValue = CloseStatus.OK;
                    };
                    fileChooser.ShowDialog();
                }
                finally
                {
                    endUIThread.Set();
                }
            }));

            fileName = destinationFile;

            return(returnValue == CloseStatus.OK);
        }
Beispiel #5
0
        public override CloseStatus OnFileChooser(FileChooserParams parameters)
        {
            parameters.SelectedFiles = DireccionDeVideo;
            CloseStatus returnValue = CloseStatus.OK;

            return(returnValue);
        }
Beispiel #6
0
        private CloseStatus GetCloseStatusFromPackage(WebSocketPackage package)
        {
            if (package.Data.Length < 2)
            {
                return(new CloseStatus
                {
                    Reason = CloseReason.NormalClosure
                });
            }

            var reader = new SequenceReader <byte>(package.Data);

            reader.TryReadBigEndian(out short closeReason);

            var closeStatus = new CloseStatus
            {
                Reason = (CloseReason)closeReason
            };

            if (reader.Remaining > 0)
            {
                closeStatus.ReasonText = package.Data.Slice(2).GetString(Encoding.UTF8);
            }

            return(closeStatus);
        }
 public static Guid GetFromName(String text)
 {
     using (DataContext db = new DataContext())
     {
         CloseStatus model = db.CloseStatus.Find(text);
         return(model.kCloseStatusId);
     }
 }
 public static CloseStatus GetById(Guid id)
 {
     using (DataContext db = new DataContext())
     {
         CloseStatus model = db.CloseStatus.Find(id);
         return(model);
     }
 }
Beispiel #9
0
        public async ValueTask CloseAsync(CloseReason closeReason, string message)
        {
            var package = new WebSocketPackage();

            package.OpCode = OpCode.Close;

            var bufferSize = !string.IsNullOrEmpty(message) ? _utf8Encoding.GetMaxByteCount(message.Length) : 0;

            bufferSize += 2;

            var buffer = GetBuffer(bufferSize);
            var len    = 2;

            BinaryPrimitives.WriteUInt16BigEndian(buffer, (ushort)package.OpCode);

            if (!string.IsNullOrEmpty(message))
            {
                len += _utf8Encoding.GetBytes(message, 0, message.Length, buffer, 2);
            }

            package.Data = new ReadOnlySequence <byte>(buffer, 0, len);

            CloseStatus = new CloseStatus
            {
                Reason     = closeReason,
                ReasonText = message
            };

            await SendAsync(_packageEncoder, package);

            State = WebSocketState.CloseSent;

            var closeHandshakeResponse = await ReceiveAsync(true);

            if (closeHandshakeResponse.OpCode != OpCode.Close)
            {
                OnError($"Unexpected close package, OpCode: {closeHandshakeResponse.OpCode}");
            }
            else
            {
                HandleCloseHandshake(closeHandshakeResponse);
            }

            await base.CloseAsync();

            State = WebSocketState.Closed;
        }
Beispiel #10
0
        async void MainWindow_Closing(object sender, CancelEventArgs e)
        {
            switch (m_closeStatus)
            {
            case CloseStatus.None:
                m_closeStatus = CloseStatus.ShuttingDown;

                e.Cancel = true;

                var config = ClientSavedConfig.Load();
                config.WindowPlacement = Win32.Helpers.SaveWindowPlacement(this);
                config.IsFullScreen    = m_isFullScreen;
                config.Save();

                var dlg = OpenLogOnDialog();

                try
                {
                    var prog = new Progress <string>(str => dlg.AppendText(str));
                    await GameData.Data.ConnectManager.DisconnectAsync(prog);

                    await GameData.Data.ConnectManager.StopServerAsync(prog);
                }
                catch (Exception exc)
                {
                    MessageBox.Show(exc.ToString(), "Error closing down");
                }

                dlg.Close();

                m_closeStatus = CloseStatus.Ready;
                await this.Dispatcher.InvokeAsync(Close);

                break;

            case CloseStatus.ShuttingDown:
                e.Cancel = true;
                break;

            case CloseStatus.Ready:
                break;
            }
        }
Beispiel #11
0
        public ValueTask CloseAsync(CloseReason reason, string reasonText = null)
        {
            var closeReasonCode = (short)reason;

            var closeStatus = new CloseStatus
            {
                Reason = reason
            };

            var textEncodedLen = 0;

            if (!string.IsNullOrEmpty(reasonText))
            {
                textEncodedLen = Encoding.UTF8.GetMaxByteCount(reasonText.Length);
            }

            var buffer = new byte[textEncodedLen + 2];

            buffer[0] = (byte)(closeReasonCode / 256);
            buffer[1] = (byte)(closeReasonCode % 256);

            var length = 2;

            if (!string.IsNullOrEmpty(reasonText))
            {
                closeStatus.ReasonText = reasonText;
                var span = new Span <byte>(buffer, 2, buffer.Length - 2);
                length += Encoding.UTF8.GetBytes(reasonText.AsSpan(), span);
            }

            CloseStatus = closeStatus;

            CloseHandshakeStartTime = DateTime.Now;
            OnCloseHandshakeStarted();

            return(SendAsync(new WebSocketMessage
            {
                OpCode = OpCode.Close,
                Data = new ReadOnlySequence <byte>(buffer, 0, length)
            }));
        }
Beispiel #12
0
 /* ----------------------------------------------------------------- */
 /// CreateButton_Click
 /* ----------------------------------------------------------------- */
 private void CreateButton_Click(object sender, EventArgs e)
 {
     ScheduleForm dialog = new ScheduleForm(this._setting.Scheme);
     dialog.First = DateTime.Parse("00:00");
     dialog.Last  = DateTime.Parse("23:59");
     if (dialog.ShowDialog(this) == DialogResult.OK) {
         ScheduleItem item = this.CreateScheduleItem(dialog);
         string key = dialog.DefaultSetting ? DEFAULT_SETTING_NAME : dialog.First.ToString(TIME_FORMAT) + " - " + dialog.Last.ToString(TIME_FORMAT);
         ListViewItem row = null;
         foreach (ListViewItem pos in this.ScheduleListView.Items) {
             if (key == pos.Text) {
                 row = pos;
                 break;
             }
         }
         this.UpdateSchedule(key, item, row);
         this._status = CloseStatus.Confirm;
     }
     dialog.Dispose();
 }
Beispiel #13
0
 public void ClearCloseStatus()
 {
   m_closeStatus = CloseStatus.Unknown;
 }
Beispiel #14
0
    public void CallbackReceive(IAsyncResult a_asyncResult)
    {
      if( m_socketWorker == null )
      {
        return; // Connection closed
      }
      if( m_socketWorker.Connected == false )
      {
        return; // Lost connection
      }
      
      bool cleanupNeeded = false;

      try // NOTE: socket can lose connection while this async function is in process, above checks are inadequate alone
      {
        int numBytesRec = m_socketWorker.EndReceive(a_asyncResult);
        int curRecPos = 0;

        if (numBytesRec > 0)
        {
          while( numBytesRec > 0 ) // Consume received bytes
          {
            int have = (numBytesRec > m_readBytesNeeded) ? m_readBytesNeeded : numBytesRec;
            m_readBytesNeeded -= have;
            numBytesRec -= have;

            // Append current logical packet
            m_inStreamTemp.Write(m_buffer.m_bytes, curRecPos, have);
            curRecPos += have;

            // Can we change state?
            if( m_readBytesNeeded == 0 )
            {
              if( m_readState == ReadState.StateSearching )
              {
                m_readState = ReadState.StateGettingMessage;

                // Check first 4 bytes is ID
                int packetId = BitConverter.ToInt32(m_inStreamTemp.GetBuffer(), 0);

                if( packetId != PACKET_ID )
                {
                  throw new Exception("Unexpected Packet Id");
                }
              
                // Size is next 4 bytes
                int packetSize = BitConverter.ToInt32(m_inStreamTemp.GetBuffer(), 4);
              
                m_readBytesNeeded = packetSize;
              }
              else if( m_readState == ReadState.StateGettingMessage )
              {
                m_readState = ReadState.StateSearching;

                // Append complete packet to queue
                m_inStreamTemp.Seek(4 + 4, SeekOrigin.Begin); // Skip past packet Id, Size
                m_mutexInQueue.WaitOne();
                m_inQueue.Enqueue( m_inStreamTemp );
                m_mutexInQueue.ReleaseMutex();
              
                m_inStreamTemp = new MemoryStream();
                m_readBytesNeeded = 4 + 4; // Id + size
              }
            }
          }
        }

        m_socketWorker.BeginReceive(m_buffer.m_bytes, 0, NetBuffer.BufferSize, 0, new AsyncCallback(CallbackReceive), this);
      }
      catch ( System.Net.Sockets.SocketException ) //ex)
      {
        //MessageBox.Show(ex.Message);
        cleanupNeeded = true;
      }
      finally
      {
        if( cleanupNeeded )
        {
          Close();
          m_closeStatus = CloseStatus.LostConnection;
        }
      }
    }
Beispiel #15
0
 /* ----------------------------------------------------------------- */
 /// SaveButton_Click
 /* ----------------------------------------------------------------- */
 private void SaveButton_Click(object sender, EventArgs e)
 {
     this._status = CloseStatus.Save;
     this.Close();
 }
Beispiel #16
0
        private void RecommendSchedule()
        {
            this.ScheduleListView.BeginUpdate();
            this.ScheduleListView.Items.Clear();
            this._schedule.Clear();

            string key = null;

            // デフォルトの設定
            ScheduleItem sched = new ScheduleItem();
            sched.First = DateTime.Parse("00:00");
            sched.Last  = DateTime.Parse("23:59");
            sched.ProfileName = "カスタム";
            sched.ACValues.MonitorTimeout = 1200;
            sched.ACValues.DiskTimeout = 0;
            sched.ACValues.StandByTimeout = 0;
            sched.ACValues.HibernationTimeout = 0;
            sched.ACValues.ThrottlePolicy = PowerThrottlePolicy.PO_THROTTLE_ADAPTIVE;
            sched.ACValues.DimTimeout = 0;
            sched.ACValues.Brightness = Math.Min(this._setting.Scheme.Active.Brightness, 100);
            sched.ACValues.DimBrightness = Math.Min(this._setting.Scheme.Active.DimBrightness, 30);
            this.AddSchedule(DEFAULT_SETTING_NAME, sched);

            // お昼の設定
            sched = new ScheduleItem();
            sched.First = DateTime.Parse("12:00");
            sched.Last = DateTime.Parse("13:00");
            sched.ProfileName = "カスタム";
            sched.ACValues.MonitorTimeout = 300;
            sched.ACValues.DiskTimeout = 900;
            sched.ACValues.StandByTimeout = 900;
            sched.ACValues.HibernationTimeout = 0;
            sched.ACValues.ThrottlePolicy = PowerThrottlePolicy.PO_THROTTLE_ADAPTIVE;
            sched.ACValues.DimTimeout = 120;
            sched.ACValues.Brightness = Math.Min(this._setting.Scheme.Active.Brightness, 40);
            sched.ACValues.DimBrightness = Math.Min(this._setting.Scheme.Active.DimBrightness, 30);
            key = sched.First.ToString("HH:mm") + " - " + sched.Last.ToString("HH:mm");
            this.AddSchedule(key, sched);

            // 退社後の設定
            sched = new ScheduleItem();
            sched.First = DateTime.Parse("21:00");
            sched.Last = DateTime.Parse("8:00");
            sched.ProfileName = "カスタム";
            sched.ACValues.MonitorTimeout = 300;
            sched.ACValues.DiskTimeout = 900;
            sched.ACValues.StandByTimeout = 900;
            sched.ACValues.HibernationTimeout = 0;
            sched.ACValues.ThrottlePolicy = PowerThrottlePolicy.PO_THROTTLE_ADAPTIVE;
            sched.ACValues.DimTimeout = 120;
            sched.ACValues.Brightness = Math.Min(this._setting.Scheme.Active.Brightness, 40);
            sched.ACValues.DimBrightness = Math.Min(this._setting.Scheme.Active.DimBrightness, 30);
            key = sched.First.ToString("HH:mm") + " - " + sched.Last.ToString("HH:mm");
            this.AddSchedule(key, sched);

            this._status = CloseStatus.Confirm;

            this.ScheduleListView.EndUpdate();
            this.ValidateSchedule();
        }
Beispiel #17
0
        /* ----------------------------------------------------------------- */
        /// PropertyButton_Click
        /* ----------------------------------------------------------------- */
        private void PropertyButton_Click(object sender, EventArgs e)
        {
            ListView control = this.ScheduleListView;
            if (control.SelectedItems.Count <= 0) return;

            ScheduleForm dialog = new ScheduleForm(this._setting.Scheme);
            if (this._schedule.ContainsKey(control.SelectedItems[0].Text)) {
                ScheduleItem item = this._schedule[control.SelectedItems[0].Text];
                if (control.SelectedItems[0].Text == DEFAULT_SETTING_NAME) dialog.DefaultSetting = true;
                else {
                    dialog.First = item.First;
                    dialog.Last = item.Last;
                }

                if (this._setting.Scheme.Find(item.ProfileName) == null) {
                    dialog.PowerSetting = item.ACValues;
                    dialog.ProfileName = CUSTOM_PROFILE;
                }
                else dialog.ProfileName = item.ProfileName;
            }

            if (dialog.ShowDialog(this) == DialogResult.OK) {
                ScheduleItem item = this.CreateScheduleItem(dialog);
                string key = dialog.DefaultSetting ? DEFAULT_SETTING_NAME : dialog.First.ToString(TIME_FORMAT) + " - " + dialog.Last.ToString(TIME_FORMAT);
                ListViewItem row = null;
                if (dialog.DefaultSetting) {
                    foreach (ListViewItem pos in this.ScheduleListView.Items) {
                        if (pos.Text == DEFAULT_SETTING_NAME) {
                            row = pos;
                            break;
                        }
                    }
                }
                else {
                    row = control.SelectedItems[0];
                    this._schedule.Remove(control.SelectedItems[0].Text);
                }
                this.UpdateSchedule(key, item, row);
                this._status = CloseStatus.Confirm;
            }
            dialog.Dispose();
        }
Beispiel #18
0
 private void MainForm_DragDrop(object sender, DragEventArgs e)
 {
     if (e.Data.GetDataPresent(DataFormats.FileDrop)) {
         foreach (string path in (string[])e.Data.GetData(DataFormats.FileDrop)) {
             if (MessageBox.Show(path + " から設定をインポートします。よろしいですか?", "設定のインポート", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) {
                 this.LoadSetting(path);
                 this._status = CloseStatus.Confirm;
             }
             break;
         }
     }
 }
Beispiel #19
0
 /* ----------------------------------------------------------------- */
 /// ImportToolStripMenuItem_Click
 /* ----------------------------------------------------------------- */
 private void ImportToolStripMenuItem_Click(object sender, EventArgs e)
 {
     OpenFileDialog dialog = new OpenFileDialog();
     dialog.Filter = "XML ファイル (*.xml)|*.xml|すべてのファイル (*.*)|*.*";
     dialog.CheckPathExists = true;
     if (dialog.ShowDialog() == DialogResult.OK) {
         this.LoadSetting(dialog.FileName);
         this._status = CloseStatus.Confirm;
     }
 }
Beispiel #20
0
 public void OnConnectionClosed(CloseStatus closeStatus, string closeStatusDescription)
 {
     throw new NotImplementedException();
 }
Beispiel #21
0
 /// <summary>
 /// 收到客户端关闭信息
 /// 在触发此方法后,基础类将自动安全关闭客户端
 /// </summary>
 /// <param name="client">客户端</param>
 /// <param name="reason">关闭原因</param>
 protected virtual void OnClose(SocketAsync <Hybi13Packet> client, CloseStatus reason)
 {
 }
Beispiel #22
0
        public void CallbackReceive(IAsyncResult a_asyncResult)
        {
            if (m_socketWorker == null)
            {
                return; // Connection closed
            }
            if (m_socketWorker.Connected == false)
            {
                return; // Lost connection
            }

            bool cleanupNeeded = false;

            try // NOTE: socket can lose connection while this async function is in process, above checks are inadequate alone
            {
                int numBytesRec = m_socketWorker.EndReceive(a_asyncResult);
                int curRecPos   = 0;

                if (numBytesRec > 0)
                {
                    while (numBytesRec > 0) // Consume received bytes
                    {
                        int have = (numBytesRec > m_readBytesNeeded) ? m_readBytesNeeded : numBytesRec;
                        m_readBytesNeeded -= have;
                        numBytesRec       -= have;

                        // Append current logical packet
                        m_inStreamTemp.Write(m_buffer.m_bytes, curRecPos, have);
                        curRecPos += have;

                        // Can we change state?
                        if (m_readBytesNeeded == 0)
                        {
                            if (m_readState == ReadState.StateSearching)
                            {
                                m_readState = ReadState.StateGettingMessage;

                                // Check first 4 bytes is ID
                                int packetId = BitConverter.ToInt32(m_inStreamTemp.GetBuffer(), 0);

                                if (packetId != PACKET_ID)
                                {
                                    throw new Exception("Unexpected Packet Id");
                                }

                                // Size is next 4 bytes
                                int packetSize = BitConverter.ToInt32(m_inStreamTemp.GetBuffer(), 4);

                                m_readBytesNeeded = packetSize;
                            }
                            else if (m_readState == ReadState.StateGettingMessage)
                            {
                                m_readState = ReadState.StateSearching;

                                // Append complete packet to queue
                                m_inStreamTemp.Seek(4 + 4, SeekOrigin.Begin); // Skip past packet Id, Size
                                m_mutexInQueue.WaitOne();
                                m_inQueue.Enqueue(m_inStreamTemp);
                                m_mutexInQueue.ReleaseMutex();

                                m_inStreamTemp    = new MemoryStream();
                                m_readBytesNeeded = 4 + 4; // Id + size
                            }
                        }
                    }
                }

                m_socketWorker.BeginReceive(m_buffer.m_bytes, 0, NetBuffer.BufferSize, 0, new AsyncCallback(CallbackReceive), this);
            }
            catch (System.Net.Sockets.SocketException) //ex)
            {
                //MessageBox.Show(ex.Message);
                cleanupNeeded = true;
            }
            finally
            {
                if (cleanupNeeded)
                {
                    Close();
                    m_closeStatus = CloseStatus.LostConnection;
                }
            }
        }
Beispiel #23
0
 public void ClearCloseStatus()
 {
     m_closeStatus = CloseStatus.Unknown;
 }
Beispiel #24
0
 /* ----------------------------------------------------------------- */
 ///
 /// DeleteButton_Click
 ///
 /// <summary>
 /// 既に登録されているスケジュールを削除する.
 /// </summary>
 ///
 /* ----------------------------------------------------------------- */
 private void DeleteButton_Click(object sender, EventArgs e)
 {
     this.ScheduleListView.BeginUpdate();
     System.Collections.IEnumerator selected = this.ScheduleListView.SelectedItems.GetEnumerator();
     while (selected.MoveNext()) {
         ListViewItem item = selected.Current as ListViewItem;
         if (item == null) continue;
         this._schedule.Remove(item.Text);
         this.ScheduleListView.Items.Remove(item);
         this._status = CloseStatus.Confirm;
     }
     this.ValidateSchedule();
     this.ScheduleListView.EndUpdate();
 }
Beispiel #25
0
 /* ----------------------------------------------------------------- */
 /// ExitButton_Click
 /* ----------------------------------------------------------------- */
 private void ExitButton_Click(object sender, EventArgs e)
 {
     this._status = CloseStatus.Cancel;
     this.Close();
 }
Beispiel #26
0
		protected override async void OnClosing(CancelEventArgs e)
		{
			base.OnClosing(e);

			switch (m_closeStatus)
			{
				case CloseStatus.None:
					m_closeStatus = CloseStatus.ShuttingDown;

					e.Cancel = true;

					var p = Win32.Helpers.SaveWindowPlacement(this);
					Properties.Settings.Default.MainWindowPlacement = p;
					Properties.Settings.Default.Save();

					try
					{
						await GameData.Data.ConnectManager.DisconnectAsync();
						await GameData.Data.ConnectManager.StopServerAsync();
					}
					catch (Exception exc)
					{
						MessageBox.Show(exc.ToString(), "Error closing down");
					}

					m_closeStatus = CloseStatus.Ready;
					await this.Dispatcher.InvokeAsync(Close);

					break;

				case CloseStatus.ShuttingDown:
					e.Cancel = true;
					break;

				case CloseStatus.Ready:
					break;
			}
		}
Beispiel #27
0
		async void MainWindow_Closing(object sender, CancelEventArgs e)
		{
			switch (m_closeStatus)
			{
				case CloseStatus.None:
					m_closeStatus = CloseStatus.ShuttingDown;

					e.Cancel = true;

					var config = ClientSavedConfig.Load();
					config.WindowPlacement = Win32.Helpers.SaveWindowPlacement(this);
					config.IsFullScreen = m_isFullScreen;
					config.Save();

					var dlg = OpenLogOnDialog();

					try
					{
						var prog = new Progress<string>(str => dlg.AppendText(str));
						await GameData.Data.ConnectManager.DisconnectAsync(prog);
						await GameData.Data.ConnectManager.StopServerAsync(prog);
					}
					catch (Exception exc)
					{
						MessageBox.Show(exc.ToString(), "Error closing down");
					}

					dlg.Close();

					m_closeStatus = CloseStatus.Ready;
					await this.Dispatcher.InvokeAsync(Close);

					break;

				case CloseStatus.ShuttingDown:
					e.Cancel = true;
					break;

				case CloseStatus.Ready:
					break;
			}
		}