예제 #1
0
파일: Client.cs 프로젝트: Dids/SharpMUD
        public string RequestToken(string password)
        {
            if (string.IsNullOrEmpty(password))
            {
                throw new InvalidOperationException("Cannot request a token without a password provided.");
            }

            if (IsAuthenticated)
            {
                throw new InvalidOperationException("Already authenticated.");
            }

            var jObject = new JObject();

            jObject["pass"] = password ?? Password;

            try
            {
                var response = Requester.PostRequest(Methods.GetToken, jObject);
                var obj      = JsonConvert.DeserializeObject(response) as JObject;

                var token     = obj["chat_token"].ToString();
                var eventArgs = new AuthenticationEventArgs(token);

                Token = token;
                Authenticated?.Invoke(this, eventArgs);
                return(token);
            }
            catch (RequestException e)
            {
                ErrorOccured?.Invoke(this, new ErrorEventArgs(e));
                return(string.Empty);
            }
        }
예제 #2
0
 private void OnErrorOccured(string message, string reason)
 {
     ErrorOccured?.Invoke(this, new NpMessageEventArgs()
     {
         Message = message, Error = true, Reason = reason
     });
 }
예제 #3
0
        private void OnConnect(IAsyncResult ar)
        {
            try
            {
                // Retrieve the socket from the state object.
                var client = (TcpClient)ar.AsyncState;

                // Complete the connection.
                client.EndConnect(ar);

                _tcpStream = _tcpClient.GetStream();

                if (Connected != null)
                {
                    Connected.Invoke(this);
                }

                _reader.StartReceiving(_tcpStream, Process);
            }
            catch (Exception ex)
            {
                if (ErrorOccured != null)
                {
                    ErrorOccured.Invoke(this, ex);
                }
            }
        }
예제 #4
0
        public void Send(T message)
        {
            if (_tcpClient != null && _tcpClient.Connected && _tcpStream != null)
            {
                var msgBuff = _serializer.Serialize(message);
                var msgLen  = (short)msgBuff.Length;

                var buff = new byte[2 + msgBuff.Length];
                System.Buffer.BlockCopy(BitConverter.GetBytes(msgLen), 0, buff, 0, 2);
                System.Buffer.BlockCopy(msgBuff, 0, buff, 2, msgBuff.Length);
                _tcpStream.BeginWrite(buff, 0, buff.Length, (ar) =>
                {
                    try
                    {
                        _tcpStream.EndWrite(ar);
                    }
                    catch (Exception ex)
                    {
                        if (ErrorOccured != null)
                        {
                            ErrorOccured.Invoke(this, ex);
                        }
                    }
                }, null);
            }
        }
예제 #5
0
        void Record()
        {
            try
            {
                var lastFrameWriteTime = DateTime.MinValue;

                while (!_stopCapturing.WaitOne(0) && _continueCapturing.WaitOne())
                {
                    var frame = _imageProvider.Capture();

                    var delay = lastFrameWriteTime == DateTime.MinValue ? 0
                        : (int)(DateTime.Now - lastFrameWriteTime).TotalMilliseconds;

                    lastFrameWriteTime = DateTime.Now;

                    _videoEncoder.WriteFrame(frame, delay);
                }
            }
            catch (Exception E)
            {
                ErrorOccured?.Invoke(E);

                Dispose(true);
            }
        }
예제 #6
0
파일: Recorder.cs 프로젝트: yazici/Screna
        void DoRecord()
        {
            try
            {
                var frameInterval = TimeSpan.FromSeconds(1.0 / _frameRate);

                while (_continueCapturing.WaitOne() && !_frames.IsAddingCompleted)
                {
                    var timestamp = DateTime.Now;

                    try { _frames.Add(_imageProvider.Capture()); }
                    catch { }

                    var timeTillNextFrame = timestamp + frameInterval - DateTime.Now;

                    if (timeTillNextFrame > TimeSpan.Zero)
                    {
                        Thread.Sleep(timeTillNextFrame);
                    }
                }
            }
            catch (Exception E)
            {
                ErrorOccured?.Invoke(E);

                Dispose(false, true);
            }
        }
예제 #7
0
        public void Initialize()
        {
            if (isInitialized)
            {
                return;
            }

            if (config == null)
            {
                throw new InvalidOperationException("Robot configuration is not set.");
            }

            Task.Run(() => {
                Task communicationTask = Connect();

                communicationTask.ContinueWith(task => {
                    string robotAdress = ToString();
                    rsiAdapter.Disconnect();

                    if (task.IsFaulted)
                    {
                        var args = new ErrorOccuredEventArgs {
                            RobotIp   = robotAdress,
                            Exception = task.Exception.GetBaseException()
                        };

                        ErrorOccured?.Invoke(this, args);
                    }

                    isInitialized = false;
                    Uninitialized?.Invoke(this, EventArgs.Empty);
                });
            });
        }
예제 #8
0
        private async Task ProcessMessages()
        {
            try
            {
                while (Connected || _messagesQueue.Count > 0)
                {
                    if (_messagesQueue.Count > 0)
                    {
                        if (_messagesQueue.TryDequeue(out JObject obj))
                        {
                            MessageReceived?.Invoke(this, obj);
                        }
                    }
                    else if (_waitingToBeClosed)
                    {
                        _waitingToBeClosed = false;
                        Connected          = false;
                    }

                    // Friendly Infinite Loop
                    await Task.Delay(10);
                }
            }
            catch (Exception ex)
            {
                ErrorOccured?.Invoke(this, ex);
            }

            Closed?.Invoke(this);
        }
예제 #9
0
        public ProjectProvider(IConfiguration configuration, IPluginRepository pluginRepository)
        {
            _configuration = configuration;

            _projectFactory = new ProjectFactory(pluginRepository, configuration);
            _projectFactory.ErrorOccured += (sender, args) => ErrorOccured?.Invoke(this, args);
        }
예제 #10
0
 protected void RaiseError(BaseResponseInfo error)
 {
     if (error is BaseErrorResponseInfo)
     {
         ErrorOccured?.Invoke(this, error as BaseErrorResponseInfo);
     }
 }
예제 #11
0
 private void FireErrorOccured(string text, Exception exception)
 {
     ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs()
     {
         ErrorMessage = text, Exception = exception
     });
 }
 public async Task LoadModules(string path, string filter)
 {
     await Task.Run(() =>
     {
         try
         {
             var curplug     = 0;
             var pluginFiles = System.IO.Directory.GetFiles(path, filter, System.IO.SearchOption.TopDirectoryOnly);
             foreach (var filename in pluginFiles)
             {
                 ReportProgress?.Invoke(this, new ReportProgressEventArgs(++curplug, pluginFiles.Length, "Loading plugins...", OperationTag.Active));
                 var types = AssemblyLoader.LoadClassesFromFile <IInstallerModule>(System.IO.Path.GetFullPath(filename)).Where(t => t != null);
                 if (types.Any())
                 {
                     PluginLoaded?.Invoke(this, new PluginLoadedEventArgs(types));
                 }
             }
         }
         catch (Exception ex)
         {
             ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(ex, "Error loading modules"));
         }
         finally
         {
             ReportProgress?.Invoke(this, new ReportProgressEventArgs(0, StatusName.Idle, OperationTag.None));
             LoadingFinished?.Invoke(this, EventArgs.Empty);
         }
     });
 }
예제 #13
0
        private void TcpListener_AcceptCallback(IAsyncResult ar)
        {
            if (!Listening)
            {
                return;
            }

            try
            {
                var newClient     = (ar.AsyncState as TcpListener).EndAcceptSocket(ar);
                var clientWrapper = new ClientWrapper(newClient);

                clientWrapper.Disconnected += Client_Disconnected;

                Clients.Add(clientWrapper);
                clientWrapper.Start();
                ClientConnected?.Invoke(clientWrapper);

                // Re-call BeginAcceptSocket
                _tcpListener.BeginAcceptSocket(TcpListener_AcceptCallback, _tcpListener);
            }
            catch (Exception ex)
            {
                ErrorOccured?.Invoke(ex);
            }
        }
예제 #14
0
        void Record()
        {
            try
            {
                Bitmap lastFrame = null;

                while (!_stopCapturing.WaitOne(0) && _continueCapturing.WaitOne())
                {
                    var frame = _imageProvider.Capture();

                    var delay = (int)_timing.Elapsed.TotalMilliseconds;

                    _timing.Stop();
                    _timing.Start();

                    // delay is the time between this and next frame
                    if (lastFrame != null)
                    {
                        _videoEncoder.WriteFrame(lastFrame, delay);
                    }

                    lastFrame = frame;
                }
            }
            catch (Exception E)
            {
                ErrorOccured?.Invoke(E);

                Dispose(true);
            }
        }
예제 #15
0
        private void ReadLoop(StreamReader reader, CancellationToken token, Action <string> action)
        {
            try
            {
                while (!token.IsCancellationRequested)
                {
                    char[]        buffer = new char[BUFMAX];
                    Task <string> task   = reader.ReadLineAsync();
                    task.Wait(token);

                    if (task.Result == null)
                    {
                        lock (_lock)
                        {
                            if (!_hasExited && _localProcess.HasExited)
                            {
                                _hasExited = true;
                                Closed?.Invoke(this, _localProcess.ExitCode);
                            }
                        }
                        return; // end of stream
                    }

                    action(task.Result);
                }
            }
            catch (Exception e)
            {
                ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(e));
                Dispose();
            }
        }
예제 #16
0
 private void Fight()
 {
     if (WinBoxState)
     {
         FFMovieValue = "";
         FSMovieValue = "";
         MFMovieValue = "";
         MSMovieValue = "";
         WinBoxState  = false;
         ButtonState  = "Fight";
         return;
     }
     try
     {
         List <String> movies = new List <string>();
         if (_ffMovieValue == "" || _fsMovieValue == "" || _mfMovieValue == "" || _msMovieValue == "")
         {
             throw new NullReferenceException();
         }
         movies.Add(_ffMovieValue);
         movies.Add(_fsMovieValue);
         movies.Add(_mfMovieValue);
         movies.Add(_msMovieValue);
         _model.Fight(movies);
     }
     catch (NullReferenceException)
     {
         ErrorOccured?.Invoke(this, EventArgs.Empty);
     }
 }
예제 #17
0
 private void OnServerErrorRaised(object sender, SocketError e)
 {
     ErrorOccured?.Invoke(this, new ConnectionMessageEventArgs()
     {
         Source = UniqueId, Message = $"udp socket error, error code = {e}", Type = MessageType.Text
     });
 }
예제 #18
0
        public void Simulate()
        {
            var failObj  = DataAccessor.DeserializeData();
            var duration = Decimal.Divide(new Decimal(SecondsDuration), new Decimal(TimeFrame));

            _thread = new Thread(() =>
            {
                for (int i = 0; i < TimeFrame; i++)
                {
                    Thread.Sleep(TimeSpan.FromSeconds((int)Math.Round(duration)));
                    int index   = new Random().Next(0, FailureXes.Count);
                    int boolean = new Random().Next(0, 2);
                    if (boolean == 1)
                    {
                        int numberOfErrors = new Random().Next();
                        for (int j = 0; j == MAXERRORCOUNT; j++)
                        {
                            var idF    = FailureXes[index];
                            var idComp = failObj.IdComponentFailureX[new Random().Next(0, failObj.IdComponentFailureX.Length)];
                            ErrorOccured?.Invoke(Plane, idF, PlaneType, idComp);
                        }
                    }
                    var idFailure          = FailureXes[index];
                    var idComponentFailure = failObj.IdComponentFailureX[new Random().Next(0, failObj.IdComponentFailureX.Length)];
                    ErrorOccured?.Invoke(Plane, idFailure, PlaneType, idComponentFailure);
                }
                SimulationFinished?.Invoke();
            });

            _thread.Start();
        }
 protected virtual void OnErrorOccured(string s)
 {
     if (ErrorOccured != null)
     {
         ErrorOccured.Invoke(s);
     }
 }
예제 #20
0
 private void OnErrorOutput(object sender, DataReceivedEventArgs e)
 {
     if (!string.IsNullOrWhiteSpace(e.Data))
     {
         ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(new Exception(e.Data)));
     }
 }
예제 #21
0
 protected void OnErrorOccured(HttpStatusCode?httpStatus)
 {
     ErrorOccured?.Invoke(this, new ConnectionMessageEventArgs()
     {
         Source = UniqueId, Message = $"http status = {httpStatus}", Type = MessageType.Text
     });
 }
예제 #22
0
        public async Task WriteAsync(string value)
        {
            try
            {
                // 保证指令间同步发送
                await _writeSlim.WaitAsync();

                var data = Encoding.UTF8.GetBytes($"{value}\r\n");
                // 大于20字节需要分包
                var count  = data.Length / 20;
                var length = data.Length % 20;
                for (int i = 0; i < count; i++)
                {
                    var large = new byte[20];
                    Array.Copy(data, i * 20, large, 0, 20);
                    await _characteristic.WriteAsync(large);
                }
                if (length > 0)
                {
                    var small = new byte[length];
                    Array.Copy(data, count * 20, small, 0, length);
                    await _characteristic.WriteAsync(small);
                }
            }
            catch (Exception ex)
            {
                ErrorOccured?.Invoke(this, $"发送失败 - {ex.Message}");
            }
            finally
            {
                _writeSlim?.Release();
            }
        }
예제 #23
0
        internal async Task MessageLoop()
        {
            while (true)
            {
                IIOTMessage message = null;

                try
                {
                    message = await ParseRequestAsync();
                }
                catch (Exception ex)
                {
                    if (ex is AlarmServerException)
                    {
                        ErrorOccured?.Invoke(this, ex);
                    }
                    else
                    {
                        Disconnected?.Invoke(this, ex);
                        break;
                    }
                }

                if (message != null)
                {
                    MessageReceived?.Invoke(this, message);
                }
            }
        }
예제 #24
0
파일: Client.cs 프로젝트: Dids/SharpMUD
        public void TellMessage(string user, string message)
        {
            if (!IsAuthenticated)
            {
                throw new InvalidOperationException("Not authenticated. Request/set token first.");
            }

            if (AccountData == null)
            {
                throw new InvalidOperationException("No account data requested. Request account data first.");
            }

            try
            {
                var jObject = new JObject();
                jObject["chat_token"] = Token;
                jObject["username"]   = SelectedUser;
                jObject["tell"]       = user;
                jObject["msg"]        = message;

                Requester.PostRequest(Methods.MessageOutlet, jObject);
                MessageSent?.Invoke(this, new MessageEventArgs(new Message(string.Empty, Utilities.GetTime(), user, SelectedUser, string.Empty, message)));
            }
            catch (RequestException e)
            {
                ErrorOccured?.Invoke(this, new ErrorEventArgs(e));
            }
        }
예제 #25
0
        /// <summary>
        /// Invoke the ErrorOccured event; called whenever there is an error
        /// </summary>
        /// <param name="Error">The Error message wrapped in a Exception object</param>
        protected virtual void OnErrorOccured(Exception Error)
        {
            m_exceptions.Add(Error);

            if (ErrorOccured != null)
            {
                ErrorOccured.Invoke(this, new EventArgs <Exception>(Error));
            }
        }
예제 #26
0
        protected virtual void OnErrorOccured(ApiErrorArgs e)
        {
            if (e.StatusCode == HttpStatusCode.Unauthorized)
            {
                throw new ApiUnauthorizedException(Status = e.Message);
            }

            ErrorOccured?.Invoke(this, e);
        }
예제 #27
0
 private void process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
 {
     if (string.IsNullOrWhiteSpace(e.Data))
     {
         return;
     }
     ErrorOccured?.Invoke(sender, new Exception(e.Data));
     // throw new NotImplementedException();
 }
 public IEnumerable <string> GetLines()
 {
     if (!string.IsNullOrEmpty(ErrorMessage))
     {
         ErrorOccured?.Invoke(this, ErrorMessage);
         return(Enumerable.Empty <string>());
     }
     return(Lines);
 }
예제 #29
0
        void DoRecord()
        {
            try
            {
                var frameInterval = TimeSpan.FromSeconds(1.0 / _frameRate);
                var frameCount    = 0;

                while (_continueCapturing.WaitOne() && !_frames.IsAddingCompleted)
                {
                    var timestamp = DateTime.Now;

                    var frame = _imageProvider.Capture();

                    try
                    {
                        _frames.Add(frame);

                        ++frameCount;
                    }
                    catch (InvalidOperationException)
                    {
                        return;
                    }

                    var requiredFrames = _sw.Elapsed.TotalSeconds * _frameRate;
                    var diff           = requiredFrames - frameCount;

                    for (var i = 0; i < diff; ++i)
                    {
                        try
                        {
                            _frames.Add(frame);

                            ++frameCount;
                        }
                        catch (InvalidOperationException)
                        {
                            return;
                        }
                    }

                    var timeTillNextFrame = timestamp + frameInterval - DateTime.Now;

                    if (timeTillNextFrame > TimeSpan.Zero)
                    {
                        Thread.Sleep(timeTillNextFrame);
                    }
                }
            }
            catch (Exception E)
            {
                ErrorOccured?.Invoke(E);

                Dispose(false, true);
            }
        }
예제 #30
0
        private void RunRoboCopyProcess()
        {
            try
            {
                ErrorOccured?.Invoke(this, new Exception("Robocopy Agent has been started"));
                IsRunning = true;
                LastRunOn = DateTime.Now;
                if (fromPath.IsUNC)
                {
                    fromPath.ConnectToUNC(false);
                }

                if (toPath.IsUNC)
                {
                    toPath.ConnectToUNC(false);
                }

                process = new Process();
                process.StartInfo.WorkingDirectory       = AppDomain.CurrentDomain.BaseDirectory;
                process.StartInfo.UseShellExecute        = false;
                process.StartInfo.LoadUserProfile        = true;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.RedirectStandardError  = true;
                process.StartInfo.WindowStyle            = ProcessWindowStyle.Hidden;
                process.StartInfo.CreateNoWindow         = true;
                process.StartInfo.FileName  = "ROBOCOPY.exe";
                process.StartInfo.Arguments = GenerateParameters();
                process.OutputDataReceived += process_OutputDataReceived;
                process.ErrorDataReceived  += process_ErrorDataReceived;

                if (fromPath.IsPathHasUserName && !fromPath.IsUNC && !toPath.IsUNC)
                {
                    process.StartInfo.UserName = fromPath.UserName;
                    process.StartInfo.Password = fromPath.Password.ToSecureString();
                    if (!string.IsNullOrWhiteSpace(fromPath.Domain))
                    {
                        process.StartInfo.Domain = fromPath.Domain;
                    }
                }
                process.Start();
                process.BeginOutputReadLine();
                process.BeginErrorReadLine();
                process.WaitForExit();
                IsRunning = process.ExitCode == 0;
            }
            catch (Exception er)
            {
                IsRunning = false;
                LastRunOn = null;
                ErrorOccured?.Invoke(this, er);
            }
            finally
            {
                Stop();
            }
        }