예제 #1
0
        private void HandleMessage(PasswordRequestMessage message)
        {
            var verifed = false;

            var args = new PasswordUserAuthArgs(_session, message.Username, message.Password);

            if (UserAuth != null)
            {
                UserAuth(this, args);
                verifed = args.Result;
            }

            if (verifed)
            {
                _session.RegisterService(message.ServiceName, args);

                Succeed?.Invoke(this, message.ServiceName);

                _session.SendMessage(new SuccessMessage());
                return;
            }
            else
            {
                _session.SendMessage(new FailureMessage());
                //  throw new SshConnectionException("Authentication fail.", DisconnectReason.NoMoreAuthMethodsAvailable);
            }
        }
예제 #2
0
        private void HandleMessage(PasswordRequestMessage message)
        {
            var verifed = false;

            var args = new UserauthArgs(_session, message.Username, message.Password);

            if (Userauth != null)
            {
                Userauth(this, args);
                verifed = args.Result;
            }

            if (verifed)
            {
                _session.RegisterService(message.ServiceName, args);

                Succeed?.Invoke(this, message.ServiceName);

                _session.SendMessage(new SuccessMessage());
                return;
            }
            else
            {
                _session.SendMessage(new FailureMessage());
            }
        }
예제 #3
0
        private void HandleMessage(PublicKeyRequestMessage message)
        {
            if (Session._publicKeyAlgorithms.ContainsKey(message.KeyAlgorithmName))
            {
                var verifed = false;

                var keyAlg = Session._publicKeyAlgorithms[message.KeyAlgorithmName](null);
                keyAlg.LoadKeyAndCertificatesData(message.PublicKey);

                var args = new PKUserAuthArgs(base._session, message.Username, message.KeyAlgorithmName, keyAlg.GetFingerprint(), message.PublicKey);
                UserAuth?.Invoke(this, args);
                verifed = args.Result;

                if (!verifed)
                {
                    _session.SendMessage(new FailureMessage());
                    return;
                }

                if (!message.HasSignature)
                {
                    _session.SendMessage(new PublicKeyOkMessage {
                        KeyAlgorithmName = message.KeyAlgorithmName, PublicKey = message.PublicKey
                    });
                    return;
                }

                var sig = keyAlg.GetSignature(message.Signature);

                using (var worker = new SshDataWorker())
                {
                    worker.WriteBinary(_session.SessionId);
                    worker.Write(message.PayloadWithoutSignature);

                    verifed = keyAlg.VerifyData(worker.ToByteArray(), sig);
                }

                if (verifed && UserAuth != null)
                {
                    UserAuth(this, args);
                    verifed = args.Result;
                }

                if (verifed)
                {
                    _session.RegisterService(message.ServiceName, args);
                    Succeed?.Invoke(this, message.ServiceName);
                    _session.SendMessage(new SuccessMessage());
                    return;
                }
                else
                {
                    _session.SendMessage(new FailureMessage());
                    //throw new SshConnectionException("Authentication fail.", DisconnectReason.NoMoreAuthMethodsAvailable);
                }
            }
        }
예제 #4
0
 public void StartWork()
 {
     IsWorking = true;
     while (IsWorking)
     {
         Y -= 10;
         if (Y <= 100)
         {
             Succeed?.Invoke(this);
             SignalizeAboutSuccess(TimeSpan.FromSeconds(3));
             return;
         }
         if (_rnd.NextDouble() <= _brokeChance && !IsBroken)
         {
             IsBroken = true;
             Broken?.Invoke(this);
             return;
         }
         Thread.Sleep(200);
     }
 }
예제 #5
0
        public RemoteScenarioView(RemoteScenario scenario)
        {
            InitializeComponent();
            Refresh(scenario);

            tbPort.Validation = (v) => EntryViewValidation.UShortValidation().Invoke(v);

            tbServiceName.TextChanged    += (o, e) => ApplyCurrent();
            tbSecretCode.PasswordChanged += (o, e) => ApplyCurrent();
            tbPort.TextChanged           += (o, e) => ApplyCurrent();
            tbPassword.PasswordChanged   += (o, e) => ApplyCurrent();
            tbLogin.TextChanged          += (o, e) => ApplyCurrent();
            tbHost.TextChanged           += (o, e) => ApplyCurrent();
            btExitingCredentials.Click   += (o, e) => {
                var credentialsSelect = new ExistingConnectionSelect(ClientFactory.ConnectionCredentials);
                var dialog            = new DialogView(credentialsSelect);
                credentialsSelect.SelectedCredentialsChanged += (o1, args) => {
                    tbHost.Text           = args.Value.Host;
                    tbLogin.Text          = args.Value.Login;
                    tbPassword.Password   = args.Value.Password;
                    tbPort.Text           = args.Value.Port.ToString();
                    tbSecretCode.Password = args.Value.SecretKey;
                    tbServiceName.Text    = args.Value.ServiceName;
                    Modified?.Invoke();
                    dialog.Close();
                };
                dialog.Show();
            };
            btScenariosList.Click += (o, e) =>
            {
                try
                {
                    var remoteScenarios = _scenario.GetServer().GetScenariosInfo().Decrypt(_scenario.Credentials.SecretKey).ToArray();
                    if (!remoteScenarios.Any())
                    {
                        throw new Exception("На удаленном сервере отсутсвуют сценарии.");
                    }
                    var selectScenarioControl = new RemoteScenarioSelect(remoteScenarios, _scenario.RemoteScenarioId);
                    var dialog = new DialogView(selectScenarioControl);
                    selectScenarioControl.ScenarioInfoSelected += (info) =>
                    {
                        dialog.Close();
                        _scenario.RemoteScenarioId   = info.ScenarioId;
                        _scenario.RemoteScenarioName = info.Name;
                        tbScenario.Text = _scenario.RemoteScenarioName;
                        var loadWindowCloseToken = MessageView.ShowLoad("Соединение с удаленным сервером...");
                        _scenario.InitializeAsync((result) =>
                        {
                            loadWindowCloseToken.Cancel();
                            Dispatcher.BeginInvoke(new Action(() => {
                                if (result)
                                {
                                    Modified?.Invoke();
                                    Succeed?.Invoke();
                                }
                                else
                                {
                                    WarningHandler.Error("Невозможно получить список сценариев.");
                                    Failed?.Invoke();
                                }
                            }));
                        });
                    };
                    dialog.Show();
                }
                catch (Exception exception)
                {
                    WarningHandler.Error("Невозможно получить список сценариев.", exception);
                    Failed?.Invoke();
                }
            };
            btTest.Click += (o, e) => {
                var loadWindowCloseToken = MessageView.ShowLoad("Соединение с удаленным сервером...");
                _scenario.InitializeAsync((result) => {
                    loadWindowCloseToken.Cancel();
                    if (result)
                    {
                        MessageView.ShowMessage("Соединение успешно!", "Тест удаленного сценария", Icons.Icon.Check);
                        Dispatcher.BeginInvoke(new Action(() => Succeed?.Invoke()));
                    }
                    else
                    {
                        MessageView.ShowMessage("Невозможно активировать удаленный сценарий!", "Тест удаленного сценария", Icons.Icon.Cancel);
                        Dispatcher.BeginInvoke(new Action(() => Failed?.Invoke()));
                    }
                });
            };
        }
예제 #6
0
 public void SignalizeAboutSuccess(TimeSpan time)
 {
     Thread.Sleep(time);
     Succeed?.Invoke(this);
     StopWork();
 }
예제 #7
0
            internal async void ProcessAsync(object sender, EventArgs e)
            {
                try
                {
                    if (!Enabled)
                    {
                        return;
                    }

                    Logger.Debug("{0}按钮触发", scaleOperator.Name);
                    if (IsBusy)
                    {
                        return;
                    }
                    IsBusy = true;

                    //Progress?.Invoke(this, new ProgressEventArgs("开始工作"));
                    Logger.Debug("开始工作");

                    Busy?.Invoke(this, new EventArgs());

                    if (!scaleOperator.IsGratingsOff())
                    {
                        var config = new LEDMessageShowConfig
                        {
                            FontSize  = 0,
                            ShowStyle = 3,
                            ShowSpeed = 8
                        };
                        scaleOperator.Display("调整车辆", config);
                        NeedAdjust?.Invoke(this, new EventArgs());
                        return;
                    }

                    //call remote service to get weight and plate number
                    //Progress?.Invoke(this, new ProgressEventArgs("正在请求重量"));
                    Logger.Debug("[{0}]请求重量", scaleOperator.Name);
                    GetWtResponse resp = await scaleOperator.RestClient.GetWtAsync(scaleOperator.ScaleIP, scaleOperator.InOrOut.ToString());

                    Logger.Debug("[{0}]返回重量{1}", scaleOperator.Name, resp.wt_num);

                    /*GetWtResponse resp = new GetWtResponse()
                     * {
                     *  status = 1,
                     *  tk_no = "辽A 88888888",
                     *  wt_num = 888.88
                     * };*/
                    if (resp.status == "0")
                    {
                        //Progress?.Invoke(this, new ProgressEventArgs("请求重量失败"));
                        Logger.Warn("称重失败");
                        return;
                    }

                    //Progress?.Invoke(this, new ProgressEventArgs("正在输出到显示屏"));
                    string text = String.Format(scaleOperator.LEDOptions.CPZLMessage.Template, resp.tk_no, resp.wt_num);
                    if (!scaleOperator.Display(text, scaleOperator.LEDOptions.CPZLMessage.ShowConfig))
                    {
                        //Progress?.Invoke(this, new ProgressEventArgs("输出到显示屏失败"));
                        Logger.Warn("LED显示失败");
                        //return;
                    }

                    //Progress?.Invoke(this, new ProgressEventArgs("正在抬杆"));
                    Logger.Debug("[{0}]请求抬杆", scaleOperator.Name);
                    GatePassResponse gpResp = await scaleOperator.RestClient.GatePassAsync(scaleOperator.ScaleIP, scaleOperator.InOrOut.ToString(), resp.tk_no, resp.wt_num);

                    Logger.Debug("[{0}]返回抬杆", scaleOperator.Name);

                    /*GatePassResponse gpResp = new GatePassResponse()
                     * {
                     *  status = 1
                     * };*/
                    if (gpResp.status == "0")//抬杆失败
                    {
                        //Progress?.Invoke(this, new ProgressEventArgs("抬杆失败"));
                        Logger.Warn("抬杆失败:" + gpResp.reason);
                        //SwitchRelay(false);//no need to call this, it's already red
                        return;
                    }

                    Logger.Info("抬杆成功:");
                    //Progress?.Invoke(this, new ProgressEventArgs("抬杆成功"));

                    Succeed?.Invoke(this, new EventArgs());
                }
                catch (Exception ex)
                {
                    //Progress?.Invoke(this, new ProgressEventArgs("发生错误:" + ex.Message));
                    Logger.Warn("{0}上的本次操作失败:{1}", scaleOperator.Name, ex.ToString());
                }
                finally
                {
                    IsBusy = false;
                }
            }