Пример #1
0
        public void WriteArchive(List <EntryData> EntryList, Stream BaseStream)
        {
            if (EntryList.Count == 0)
            {
                BaseStream.Close();
                DeleteArchive();
                return;
            }
            UserDataIOManager.GenerateNewCryptoRNGAndSave();
            Stream        CryptoStream = Crypto.AESStream.CtrEncryptionStreamCurrentSession(BaseStream);
            ArchiveWriter Writer       = new ArchiveWriter(CryptoStream, EntryList.Count);

            try
            {
                for (int i = 0; i < EntryList.Count; i++)
                {
                    Writer.WriteEntry(EntryList[i]);
                }
            }
            catch (Exception ex)
            {
                ExceptionThrownEvent?.Invoke(ex);
            }
            finally
            {
                Writer.Close();
                GC.Collect();
                ProgressCompletedEvent?.Invoke();
            }
        }
Пример #2
0
        public bool Write(byte[] data)
        {
            if (this.SerialPort == null)
            {
                ExceptionThrown?.Invoke(this, new Exception("Cannot send data to a null SerialPort (check to see if Connect was called)"));
                return(false);
            }

            if (!this.SerialPort.IsOpen)
            {
                ExceptionThrown?.Invoke(this, new Exception("The SerialPort is not opened"));
                return(false);
            }

            if (data == null)
            {
                return(false);
            }

            try
            {
                this.SerialPort.DiscardOutBuffer();
                this.SerialPort.DiscardInBuffer();
                this.SerialPort.Write(data, 0, data.Length);
                return(true);
            }
            catch (Exception ex)
            {
                ExceptionThrown?.Invoke(this, ex);
                return(false);
            }
        }
Пример #3
0
 protected void PublishUnhandledException(Task task)
 {
     if (task.IsFaulted)
     {
         ExceptionThrown?.Invoke(task.Exception);
     }
 }
Пример #4
0
        private string GetResponse()
        {
            string responseJson;

            try
            {
                var message = ReadString(_serverStream);
                if (string.IsNullOrEmpty(message))
                {
                    var ex = new Exception("Message is empty");
                    responseJson = GetErrorResponse(PipeName, ex);
                    ExceptionThrown?.Invoke(PipeName, ex);
                }
                else
                {
                    responseJson = _processMessageFunc.Invoke(message);
                }
            }
            catch (Exception ex)
            {
                ExceptionThrown?.Invoke(PipeName, ex);
                responseJson = GetErrorResponse(PipeName, ex);
            }

            return(responseJson);
        }
Пример #5
0
        public bool Open()
        {
            bool rtn = false;

            Close();
            try
            {
                this.SerialPort                = new SerialPort();
                this.SerialPort.PortName       = this.PortName;
                this.SerialPort.BaudRate       = (int)this.BaudRate;
                this.SerialPort.DataBits       = (int)this.DataBits;
                this.SerialPort.StopBits       = this.StopBits;
                this.SerialPort.Parity         = this.Parity;
                this.SerialPort.Encoding       = Encoding.UTF8;
                this.SerialPort.DtrEnable      = this.DTR;
                this.SerialPort.RtsEnable      = this.RTS;
                this.SerialPort.DataReceived  += SerialPort_DataReceived;
                this.SerialPort.ErrorReceived += SerialPort_ErrorReceived;
                this.SerialPort.Open();
                rtn = true;
            }
            catch (Exception ex)
            {
                ExceptionThrown?.Invoke(this, ex);
            }

            if (this.SerialPort != null && this.SerialPort.IsOpen)
            {
                OpenStatusChanged?.Invoke(this, true);
            }

            return(rtn);
        }
Пример #6
0
        private void DoConnect()
        {
            try
            {
                irc    = new TcpClient(serverName, port);
                stream = irc.GetStream();
                if (sslEnabled)
                {
                    ssl = new SslStream(stream, false);
                    ssl.AuthenticateAsClient(serverName);
                    reader = new StreamReader(ssl);
                    writer = new StreamWriter(ssl);
                }
                else
                {
                    reader = new StreamReader(stream);
                    writer = new StreamWriter(stream);
                }

                if (!string.IsNullOrEmpty(serverPassword))
                {
                    Send("PASS " + serverPassword);
                }

                Send("NICK " + nick);
                Send("USER " + nick + " 0 * :" + nick);

                Listen();
            }
            catch (Exception ex)
            {
                ExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
            }
        }
Пример #7
0
 /// <summary>
 /// Raises the event
 /// </summary>
 /// <param name="caller">The caller of the event</param>
 /// <param name="e">The exception that caused the event</param>
 internal void RaiseAsyncException(object caller, Exception e)
 {
     // TODO: This line should be brought back. It has been outcommented to test that
     // our .Clone() hack works
     //if (ExceptionThrown != null)
     ExceptionThrown.Invoke(caller, e);
 }
Пример #8
0
        private void ProcessEvents()
        {
            var ct = _cts.Token;

            while (!ct.IsCancellationRequested)
            {
                var data = _tdJsonClient.Receive(0.1);

                if (!string.IsNullOrEmpty(data))
                {
                    try
                    {
                        var structure = JsonConvert.DeserializeObject <TdApi.Object>(data, _converter);

                        Received?.Invoke(this, structure);

                        if (structure is TdApi.Update.UpdateAuthorizationState update)
                        {
                            AuthorizationStateChanged?.Invoke(this, update.AuthorizationState);
                        }
                    }
                    catch (Exception e)
                    {
                        ExceptionThrown?.Invoke(this, e);
                    }
                }
            }
        }
Пример #9
0
        /// <summary>
        ///     Listens for messages from the server
        /// </summary>
        private void Listen()
        {
            string inputLine = null;

            while ((inputLine = reader.ReadLine()) != null)
            {
                try
                {
                    if (inputLine[0] != '@')
                    {
                        ProcessData(inputLine, new Badge());
                    }
                    else
                    {
                        ParseBagedData(inputLine);
                    }
                }
                catch (Exception ex)
                {
                    ExceptionThrown?.Invoke(this, new ExceptionEventArgs(ex));
                }
            }

            ConnectionClosed?.Invoke(this, new EventArgs());
        }
Пример #10
0
 /// <summary>
 /// Raises the event
 /// </summary>
 /// <param name="caller">The caller of the event</param>
 /// <param name="e">The exception that caused the event</param>
 internal void RaiseAsyncException(object caller, Exception e)
 {
     if (ExceptionThrown != null)
     {
         ExceptionThrown.Invoke(caller, e);
     }
 }
Пример #11
0
        public void RegisterUploadMonitor(int channelSeq, int count, TimeSpan timeSpan)
        {
            ValidateStrictlyPostiveInteger(channelSeq, nameof(channelSeq));
            ValidateStrictlyPostiveInteger(count, nameof(count));

            count = Math.Min(count, 50);

            lock (_lock)
            {
                UploadMonitorTask task = new UploadMonitorTask(channelSeq, count, timeSpan, _service);
                if (!_uploadTasks.ContainsKey(task.ChannelSeq))
                {
                    task.ExceptionThrown += ExceptionThrownRepeater;
                    task.NewUpload       += NewUploadRepeater;
                    bool success = _uploadTasks.TryAdd(task.ChannelSeq, task);
                    if (!success)
                    {
                        ExceptionThrown.Invoke(null, new FailedToRegisterUploadMonitorException(channelSeq, Monitor.Upload, "Failed to register a task with the monitor service."));
                    }
                    else
                    {
                        task.StartTask();
                    }
                }
            }
        }
Пример #12
0
 protected virtual void Dispose(bool disposing)
 {
     if (_disposed)
     {
         return;
     }
     if (disposing)
     {
         try
         {
             if (_ipcListener != null)
             {
                 _ipcListener.StopListen();
                 _ipcListener.ExceptionThrown -= OnIpcListenerExceptionThrown;
                 _ipcListener.Dispose();
             }
         }
         catch (Exception ex)
         {
             var outerEx = new Exception($"{_engineName}IPC engine Dispose() error", ex);
             ExceptionThrown?.Invoke(this, outerEx);
         }
     }
     _disposed = true;
 }
Пример #13
0
 /// <summary>
 /// Raises the event
 /// </summary>
 /// <param name="caller">The caller of the event</param>
 /// <param name="e">The exception that caused the event</param>
 public static void Raise(object caller, Exception e)
 {
     if (ExceptionThrown != null)
     {
         ExceptionThrown.Invoke(caller, e);
     }
 }
Пример #14
0
 public override void OnError(Exception error)
 {
     try
     {
         ExceptionThrown?.Invoke(this, error);
     }
     catch { }
 }
Пример #15
0
 /// <summary>
 /// Callback for exceptions from the communications layer
 /// </summary>
 /// <param name="caller">The caller</param>
 /// <param name="ex"></param>
 private void EmailTransportExceptionEvent_ExceptionThrown(object caller, Exception ex)
 {
     ChangeState(ListenerState.faulted);
     if (ExceptionThrown != null)
     {
         ExceptionThrown.Invoke(this, ex);
     }
 }
Пример #16
0
 public override void OnError(Exception error)
 {
     try
     {
         ExceptionThrown?.Invoke(this, new ExceptionThrownArgs(new TelloException("FlightController Error", error)));
     }
     catch { }
 }
Пример #17
0
        /// <summary>
        /// Starts the session receiving loop. This exits when closed explicitly or by remote end point.
        /// </summary>
        public void Loop()
        {
            if (IsClosing || IsDisposing)
            {
                return;
            }
            var token = Cancellation.Token;

            WorkerThreadId = Thread.CurrentThread.ManagedThreadId;
            IsActive       = true;
            if (Owner.IsServer)
            {
                Owner.IsListening = true;
            }
            else
            {
                Owner.IsConnected = true;
            }
            while (!token.IsCancellationRequested && Stream.WaitDataAvailable(token))
            {
                try {
                    var received = Transceiver.Receive(Stream);
                    if (token.IsCancellationRequested)
                    {
                        break;
                    }
                    switch (received.Key)
                    {
                    case ReceiveStatus.Over: continue;

                    case ReceiveStatus.OverAndOut:
                        Message = received.Value;
                        MessageReceived?.Invoke(this, EventArgs.Empty);
                        if (((object)Message is X690.Message m) && m.IsEndSession)
                        {
                            break;
                        }
                        continue;
                    }
                    break;
                }
                catch (Exception x) {
                    var source = $"{GetType().Name}.{MethodBase.GetCurrentMethod().Name}";
                    if (String.IsNullOrEmpty(x.Source))
                    {
                        x.Source = source;
                    }
                    else
                    {
                        x.Source += $"; {source}";
                    }
                    ExceptionThrown?.Invoke(this, new ExceptionEventArgs(x));
                    break;
                }
            }
            IsActive = false;
            End?.Invoke(this, EventArgs.Empty);
        }
Пример #18
0
        /// <summary>
        ///     Prints an exception
        /// </summary>
        public static void Error(Exception e)
        {
#if DEBUG
            Error(e.ToString());
#else
            Error(e.Message);
#endif
            ExceptionThrown?.Invoke(e);
        }
        public void ProcessEvent(EventWrittenEventArgs e)
        {
            const int EventIdExceptionThrown = 80;

            if (e.EventId == EventIdExceptionThrown)
            {
                ExceptionThrown?.Invoke(Events.ExceptionThrownEvent.ParseFrom(e));
            }
        }
Пример #20
0
 public SoundPreviewManager(Control syncObj)
 {
     SyncObject  = syncObj;
     Timer.Tick += Tick;
     SoundManager.ExceptionThrown += (s, e) =>
     {
         Stop();
         ExceptionThrown?.Invoke(this, EventArgs.Empty);
     };
 }
Пример #21
0
 public SoundPreviewManager(Control syncControl)
 {
     SyncControl = syncControl;
     Timer.Tick += Tick;
     SoundManager.ExceptionThrown += (s, e) => SyncControl.InvokeIfRequired(() =>
     {
         Stop();
         ExceptionThrown?.Invoke(this, EventArgs.Empty);
     });
 }
Пример #22
0
        private void SerialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            List <byte> bytesReceived = new List <byte>();

            while (this.SerialPort.BytesToRead > 0 && this.SerialPort.IsOpen && !isDelimiter)
            {
                try
                {
                    int count = this.SerialPort.BytesToRead;
                    if (this.SerialPort.BytesToRead > this.SerialPort.ReadBufferSize)
                    {
                        count = this.SerialPort.ReadBufferSize;
                    }
                    byte[] message = new byte[count];
                    this.SerialPort.Read(message, 0, count);
                    bytesReceived.AddRange(message);
                }
                catch (Exception ex)
                {
                    ExceptionThrown?.Invoke(this, ex);
                }
            }
            if (isDelimiter && this.SerialPort.IsOpen)
            {
                try
                {
                    string message2 = this.SerialPort.ReadTo(this.Delimiter.ToString());
                    bytesReceived.AddRange(System.Text.Encoding.Default.GetBytes(message2));
                }
                catch (Exception ex)
                {
                    ExceptionThrown?.Invoke(this, ex);
                }
            }

            if (bytesReceived.Count > 0)
            {
                DataReceived?.Invoke(sender, new ByteData(bytesReceived.ToArray(), this.SerialPort.Encoding));
            }
            List <byte> bytelist = new List <byte>();

            foreach (var item in bytesReceived)
            {
                if (item == BitConverter.GetBytes(this.Delimiter)[0])
                {
                    DelimiterDataReceived?.Invoke(sender, new ByteData(bytelist.ToArray(), this.SerialPort.Encoding));
                    bytelist.Clear();
                }
                else
                {
                    bytelist.Add(item);
                }
            }
        }
Пример #23
0
 public SoundPreviewManager(Control syncControl)
 {
     SyncControl = syncControl;
     ClapSource  = new SoundSource("guide.mp3", 0.036);
     Timer.Tick += Tick;
     SoundManager.ExceptionThrown += (s, e) => SyncControl.InvokeIfRequired(() =>
     {
         Stop();
         ExceptionThrown?.Invoke(this, EventArgs.Empty);
     });
 }
 private async Task RunTaskSafeAsync(Task task)
 {
     try
     {
         await task.ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         ExceptionThrown?.Invoke(this, new AsyncVoidExceptionEventArgs(task, new AggregateException("An exception was thrown by an async void function", ex)));
     }
 }
Пример #25
0
 public SoundPreviewManager(NoteView noteView)
 {
     ClapSource  = new SoundSource("guide.mp3", 0.036);
     NoteView    = noteView;
     Timer.Tick += Tick;
     SoundManager.ExceptionThrown += (s, e) => noteView.InvokeIfRequired(() =>
     {
         Stop();
         ExceptionThrown?.Invoke(this, EventArgs.Empty);
     });
 }
Пример #26
0
 public void StartListen()
 {
     try
     {
         _serverStream.BeginWaitForConnection(WaitForConnectionCallBack, null);
     }
     catch (Exception ex)
     {
         ExceptionThrown?.Invoke(this, ex);
     }
 }
Пример #27
0
 public void Play(string path, TimeSpan offset)
 {
     CheckSupported();
     Task.Run(() => PlayInternal(path, offset))
     .ContinueWith(p =>
     {
         if (p.Exception != null)
         {
             Program.DumpExceptionTo(p.Exception, "sound_exception.json");
             ExceptionThrown?.Invoke(this, EventArgs.Empty);
         }
     });
 }
Пример #28
0
        protected IpcResponse GetErrorResponse(string message, string methodName, string suffix = null)
        {
            var prefix = string.IsNullOrEmpty(suffix)
                ? $"{_engineName}{methodName}() error"
                : $"{_engineName}{methodName}() {suffix} error";
            var ex = new Exception($"{prefix}. {message}");

            ExceptionThrown?.Invoke(this, ex);
            var response = new IpcResponse(false);

            response.SetData(message);
            return(response);
        }
Пример #29
0
        protected IpcResponse GetErrorResponse(Exception ex, string methodName, string suffix = null)
        {
            var message = string.IsNullOrEmpty(suffix)
                ? $"{_engineName}{methodName}() error"
                : $"{_engineName}{methodName}() {suffix} error";
            var outerEx = new Exception(message, ex);

            ExceptionThrown?.Invoke(this, outerEx);
            var response = new IpcResponse(false);

            response.SetData(ex.Message);
            return(response);
        }
Пример #30
0
 /// <summary>
 /// Will try to accept connections one more time.
 /// </summary>
 /// <exception cref="Exception">If any exceptions is thrown.</exception>
 private void RetryBeginAccept()
 {
     try
     {
         m_logWriter.Write(this, LogPrio.Error, "Trying to accept connections again.");
         m_listener.BeginAcceptSocket(OnAccept, null);
     }
     catch (Exception err)
     {
         m_logWriter.Write(this, LogPrio.Fatal, err.Message);
         ExceptionThrown?.Invoke(this, err);
     }
 }