// ReSharper restore InconsistentNaming /// <summary> /// Register a global callback that will be notified when exceptions occur /// during UnitOfWork calls to <c>InnerExecute()</c> or /// <c>ITransaction.Commit()</c>. This handler will be called for the /// remainder of the application lifetime, and cannot be un-registered. /// </summary> /// <para> /// The exception will still bubble up from the original call, so this is NOT /// a substitute for normal exception handling. /// </para> public static void AddGlobalExecuteOrCommitExceptionHandler( OnException handler) { if (null == handler) throw new ArgumentNullException("handler"); _onExecuteOrCommitException += handler; }
/// <summary> /// <para> /// Register a global callback that will be notified when exceptions occur /// during UnitOfWork calls to <c>ITransaction.Rollback()</c>. This handler /// will be called for the remainder of the application lifetime, and cannot /// be un-registered. /// </para> /// <para> /// The exception will still bubble up from the original call, so this is NOT /// a substitute for normal exception handling. /// </para> /// </summary> public static void AddGlobalRollbackExceptionHandler( OnException handler) { if (null == handler) throw new ArgumentNullException("handler"); _onRollbackException += handler; }
private void FireOnException(Exception exception) => OnException?.Invoke(exception);
void ITcpListener.handleException(IChannel channel, Exception ex) { OnException?.Invoke(channel, ex); }
private void Config(CancellationToken ct) { while (_wordlist.HasNext && !_theEnd) { int retry = 0; string data = _wordlist.GetData(); Retry: if (ct.IsCancellationRequested) { break; } try { Proxy proxy = null; if (!_proxylist.Less) { proxy = _proxylist.Get(); if (proxy == null) { goto Retry; } } Status?status = Status.OK; status = OnConfig?.Invoke(this, new DataEventArgs() { Retry = retry, Data = data, Proxy = proxy, Save = _save, Log = _log }); switch (status) { case Status.OK: _datapool.Add(); break; case Status.Retry: retry++; goto Retry; case Status.TheEnd: _theEnd = true; break; default: _datapool.Add(); break; } } catch (Exception ex) { OnException?.Invoke(this, new ExceptionEventArgs() { Location = "OnConfig", Exception = ex, Log = _log }); } } }
/// <summary> /// This method is used to fire the event when an exception occurs. /// </summary> /// <param name="sender">The sender.</param> /// <param name="payload">The payload.</param> /// <param name="ex">The exception raised.</param> protected void OnExceptionInvoke(object sender, TransmissionPayload payload, Exception ex) { var e = new CommunicationBridgeAgentEventArgs(payload, ex); OnException?.Invoke(sender, e); }
/// <summary> /// 新开线程,连接 /// </summary> /// <param name="host"></param> /// <param name="port"></param> /// <param name="onConnected"></param> /// <param name="onException"></param> public static void Connect(string host, int port, OnConnected onConnected, OnException onException = null) { Connect(ParseToIPAddress(host), port, onConnected, onException); }
/// <summary> /// 处理业务逻辑 /// </summary> /// <param name="userToken"></param> public override void HttpHandle(IUserToken userToken) { IHttpResult result = null; try { this.InitSession(userToken); switch (this.Request.Method) { case ConstHelper.GET: case ConstHelper.POST: case ConstHelper.PUT: case ConstHelper.DELETE: if (this.Request.Query.Count > 0) { foreach (var item in this.Request.Query) { this.Request.Parmas[item.Key] = item.Value; } } if (this.Request.Forms.Count > 0) { foreach (var item in this.Request.Forms) { this.Request.Parmas[item.Key] = item.Value; } } if (OnRequestDelegate != null) { OnRequestDelegate.Invoke(this); } else { result = GetActionResult(); } break; case ConstHelper.OPTIONS: result = new EmptyResult(); break; default: result = new ContentResult("不支持的请求方式", System.Net.HttpStatusCode.NotImplemented); break; } } catch (Exception ex) { result = OnException.Invoke(this, ex); if (result == null) { result = new ContentResult("请求发生异常:" + ex.Message, System.Net.HttpStatusCode.InternalServerError); } } if (result != null && !(result is IBigDataResult || result is IEventStream)) { Response.SetCached(result, this.Session.CacheCalcString); Response.End(); } }
void IPeerListener.OnPeerException(Peer peer, Exception exception) { OnException?.Invoke(peer, exception); }
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e) { OnException?.Invoke(this, e); }
//THis is the method called by Blazor public override void WriteLine(string value) { OnException?.Invoke(this, value); _decorated.WriteLine(value); }
private void logNvrSdkExceprtion(NvrSdkException ex) { Console.WriteLine($"[Debug] LiveViewService: Exception: {ex.Message}\n{ex.StackTrace}\n\n"); OnException?.Invoke(this, $"NvrException Code[{ex.SdkErrorCode}]: {ex.Message}\n\n"); }
private void logException(Exception ex) { Console.WriteLine($"[Debug] LiveViewService: Exception: {ex.Message}\n{ex.StackTrace}\n\n"); OnException?.Invoke(this, $"Exception: {ex.Message}\n\n{ex.StackTrace}\n\n"); }
private void onPreviewError(object sender, Tuple <uint, string> args) { Console.WriteLine($"[Debug] LiveViewService: PreviewError: Code[{args.Item1}]: {args.Item2}\n\n"); OnException?.Invoke(this, $"PreviewError: Code[{args.Item1}]: {args.Item2}\n\n"); }
private async Task Listen() { try { while (webSocket.State != WebSocketState.Closed && webSocket.State != WebSocketState.Aborted && !cancellationTokenSource.Token.IsCancellationRequested) { var messageType = await webSocket.GetWebsocketBuffer(readerBuffer, cancellationTokenSource.Token); if (cancellationTokenSource.Token.IsCancellationRequested) { break; } //the client send close message if (messageType == WebSocketMessageType.Close) { if (webSocket.State != WebSocketState.CloseReceived) { continue; } await sendMessageSemaphore.WaitAsync(); try { await webSocket.CloseOutputAsync(WebSocketCloseStatus.NormalClosure, "Close", CancellationToken.None); } finally { sendMessageSemaphore.Release(); cancellationTokenSource.Cancel(); } continue; } try { var envelope = XdrConverter.Deserialize <MessageEnvelope>(new XdrBufferReader(readerBuffer.Buffer)); OnMessage.Invoke(envelope); } catch { OnException?.Invoke(new UnexpectedMessageException("Failed to deserialize a response message received from the server.")); } } } catch (OperationCanceledException) { } catch (Exception e) { var status = WebSocketCloseStatus.InternalServerError; //connection has been already closed by the other side if ((e as WebSocketException)?.WebSocketErrorCode == WebSocketError.ConnectionClosedPrematurely) { return; } string errorDescription = null; if (e is ConnectionCloseException closeException) { status = closeException.Status; errorDescription = closeException.Description; } else if (e is FormatException) { status = WebSocketCloseStatus.ProtocolError; } else { logger.Error(e); } await CloseConnection(status, errorDescription); } finally { _ = Task.Factory.StartNew(() => OnClose?.Invoke()); } }
public async Task SendWeatherDataAsync(Packet packet, DateTime receivedTime) { if (packet.type != PacketTypes.Weather) { throw new InvalidOperationException(); } var now = new DateTimeOffset(receivedTime).ToUniversalTime(); var subPackets = packet.packetData as IList <SingleWeatherData>; var groupedPackets = subPackets.GroupBy(p => p.sendingStation); foreach (var grp in groupedPackets.Where(grp => grp.Count() > 1)) { byte spaceAfter(SingleWeatherData d) { if (grp.Count() == 1) { return(255); } var otherPackets = grp.Where(p => p != d); var nextId = otherPackets.Where(p => p.uniqueID > d.uniqueID) .Min(p => (byte?)p.uniqueID); if (nextId != null) { return((byte)(nextId - d.uniqueID)); } var firstId = otherPackets.Min(p => p.uniqueID); return((byte)(firstId + (255 - d.uniqueID))); } var lastId = grp.OrderBy(p => spaceAfter(p)).Last().uniqueID; TimeSpan timeBetweenPackets = TimeSpan.FromSeconds(4); foreach (var subPacket in grp) { byte idSpace = (byte)(lastId - subPacket.uniqueID); var packetTime = now - idSpace * timeBetweenPackets; subPacket.calculatedTime = packetTime; } } foreach (var subPacket in subPackets.OrderBy(p => p.calculatedTime ?? now)) { var identifier = new PacketIdentifier() { packetType = 'W', stationID = subPacket.sendingStation, uniqueID = subPacket.uniqueID }; if (IsPacketDoubleReceived(identifier, now)) { continue; } receivedPacketTimes[identifier] = now; var toSerialize = new { timestamp = (subPacket.calculatedTime ?? now).ToUnixTimeSeconds(), wind_speed = subPacket.windSpeed, wind_direction = subPacket.windDirection, battery = subPacket.batteryLevelH, external_temp = subPacket.externalTemp, internal_temp = subPacket.internalTemp, wind_gust = subPacket.gust, pwm = subPacket.pwmValue, current = subPacket.current, }; var json = JsonConvert.SerializeObject(toSerialize); var content = new StringContent(json, Encoding.UTF8, "application/json"); var url = _url + $"/api/station/{subPacket.sendingStation + Offset}/data"; var uri = new Uri(url); try { var response = await _client.PostAsync(uri, content); if (response.IsSuccessStatusCode) { OutputWriter.WriteLine($"Succesfully posted {subPacket.sendingStation}/{(char)packet.type}{subPacket.uniqueID} to {url}."); } else { OutputWriter.WriteLine($"Post of {packet.sendingStation}/{(char)packet.type}{packet.uniqueID} to {url} failed ({response.StatusCode}): {response.ReasonPhrase}"); OutputWriter.WriteLine($"Content: {response.Content.ReadAsStringAsync().Result}"); OutputWriter.WriteLine($"JSON: {json}"); } } catch (Exception ex) { OnException?.Invoke(this, ex); } } }
public override void ExceptionCaught(IChannelHandlerContext ctx, Exception exception) { OnException?.Invoke(exception); completionSource.TrySetException(exception); ctx.CloseAsync(); }
/// <summary> /// 处理业务逻辑 /// </summary> /// <param name="userToken"></param> public override void HttpHandle(IUserToken userToken) { IHttpResult result = null; try { this.InitSession(userToken); switch (Request.Method) { case ConstHelper.GET: case ConstHelper.POST: case ConstHelper.PUT: case ConstHelper.DELETE: if (Request.Query.Count > 0) { foreach (var item in Request.Query) { Request.Parmas[item.Key] = item.Value; } } if (Request.Forms.Count > 0) { foreach (var item in Request.Forms) { Request.Parmas[item.Key] = item.Value; } } if (OnRequestDelegate != null) { OnRequestDelegate.Invoke(this); } else { result = GetActionResult(); } break; case ConstHelper.OPTIONS: result = new HttpEmptyResult(); break; default: result = new HttpContentResult("不支持的请求方式", System.Net.HttpStatusCode.HttpVersionNotSupported); break; } } catch (Exception ex) { result = OnException?.Invoke(this, ex); } if (result != null) { if (!(result is IBigDataResult)) { if (result is IFileResult && _webHost.WebConfig.IsStaticsCached) { Response.SetCached(result, "60,60"); } else { Response.SetCached(result, this.Session.CacheCalcString); } Response.End(); } } }
/// <summary> /// 新开线程,监听。 /// 外部负责关闭返回的TcpListener /// </summary> /// <param name="port"></param> /// <param name="onConnected"></param> /// <returns></returns> public static TcpListener Listening(int port, OnConnected onConnected, OnException onException = null) { if (null == onException) { onException = (e) => { }; } var listener = new TcpListener(new System.Net.IPEndPoint(0, port)); listener.Start(); try { new Task(() => { try { while (true) { var client = listener.AcceptTcpClient(); new Task(() => { try { onConnected(client); } catch (Exception e) { try { onException(e); } catch { } } }).Start(); } } catch (Exception e) { try { onException(e); } catch { } } }).Start(); } catch (Exception e) { try { listener.Stop(); } catch { } try { onException(e); } catch { } } return(listener); }
public SimConnectInterface(OnConnect connectHandler, OnDisconnect disconnectHandler, OnException exceptionHandler) { this.clientConnectHandler = new OnConnect(connectHandler); this.clientDisconnectHandler = new OnDisconnect(disconnectHandler); this.clientExceptionHandler = new OnException(exceptionHandler); }
public static void Connect(IPAddress ipAddress, int port, OnConnected onConnected, OnException onException = null) { if (null == onException) { onException = (e) => { }; } new Task(() => { try { var client = new TcpClient(); client.Connect(ipAddress, port); //var stream = client.GetStream(); onConnected(client); } catch (Exception e) { try { onException(e); } catch { } } }).Start(); }
protected virtual void HandleEx(ItemEventArgs <Exception> e) { OnException?.Invoke(this, e); }
public void Replay(Stream stream, Progress progress) { var gzipStream = new GZipStream(stream, CompressionMode.Decompress, leaveOpen: true); var bufferedStream = new BufferedStream(gzipStream, 32768); var binaryReader = new BinaryReader(bufferedStream); int fileFormatVersion = binaryReader.ReadInt32(); OnFileFormatVersionRead?.Invoke(fileFormatVersion); // the log file is written using a newer version of file format // that we don't know how to read if (fileFormatVersion > BinaryLogger.FileFormatVersion) { var text = $"Unsupported log file format. Latest supported version is {BinaryLogger.FileFormatVersion}, the log file has version {fileFormatVersion}."; throw new NotSupportedException(text); } // Use a producer-consumer queue so that IO can happen on one thread // while processing can happen on another thread decoupled. The speed // up is from 4.65 to 4.15 seconds. var queue = new BlockingCollection <BuildEventArgs>(boundedCapacity: 5000); var processingTask = System.Threading.Tasks.Task.Run(() => { foreach (var args in queue.GetConsumingEnumerable()) { Dispatch(args); } }); int recordsRead = 0; using var reader = new BuildEventArgsReader(binaryReader, fileFormatVersion); reader.OnBlobRead += OnBlobRead; Stopwatch stopwatch = Stopwatch.StartNew(); var streamLength = stream.Length; while (true) { BuildEventArgs instance = null; try { instance = reader.Read(); } catch (Exception ex) { OnException?.Invoke(ex); } recordsRead++; if (instance == null) { queue.CompleteAdding(); break; } queue.Add(instance); if (progress != null && stopwatch.ElapsedMilliseconds > 200) { stopwatch.Restart(); var streamPosition = stream.Position; double ratio = (double)streamPosition / streamLength; progress.Report(ratio); } } processingTask.Wait(); if (fileFormatVersion >= 10) { var strings = reader.GetStrings(); if (strings != null && strings.Any()) { OnStringDictionaryComplete?.Invoke(strings); } } if (progress != null) { progress.Report(1.0); } }
private IHttpResult HttpContext_OnException(IHttpContext httpContext, Exception ex) { return(OnException?.Invoke(httpContext, ex)); }
private void CompletedTask() { while (_run) { try { var activeThread = Active; if (activeThread == 0 && _runnerStatus == RunnerStatus.Stopped) { _run = false; _stopwatch.Stop(); _datapool.Clear(); _cts.Dispose(); try { OnStopped?.Invoke(this, new StopEventArgs() { WordList = _wordlist, Save = _save, Log = _log }); } catch (Exception ex) { OnException?.Invoke(this, new ExceptionEventArgs() { Location = "OnStopped", Exception = ex, Log = _log }); } } else if (activeThread == 0) { _run = false; _stopwatch.Stop(); _datapool.Clear(); _cts.Dispose(); _runnerStatus = RunnerStatus.Completed; try { OnCompleted?.Invoke(this, new EventArgs()); } catch (Exception ex) { OnException?.Invoke(this, new ExceptionEventArgs() { Location = "OnCompleted", Exception = ex, Log = _log }); } } } catch { } Thread.Sleep(100); } }
/// <summary> /// Executes the <paramref name="correlatedTask"/> with its own <see cref="CorrelationContext"/>. /// </summary> /// <typeparam name="T">The return type of the awaitable task.</typeparam> /// <param name="asyncCorrelationManager">The async correlation manager.</param> /// <param name="correlatedTask">The task to execute.</param> /// <param name="onException">A delegate to handle the exception inside the correlation scope, before it is disposed. Returns <see langword="true" /> to consider the exception handled, or <see langword="false" /> to throw.</param> /// <returns>An awaitable that completes with a result <typeparamref name="T"/> once the <paramref name="correlatedTask"/> has executed and the correlation context has disposed.</returns> /// <remarks> /// When logging and tracing are both disabled, no correlation context is created and the task simply executed as it normally would. /// </remarks> public static Task <T> CorrelateAsync <T>(this IAsyncCorrelationManager asyncCorrelationManager, Func <Task <T> > correlatedTask, OnException <T> onException) { return(asyncCorrelationManager.CorrelateAsync(null, correlatedTask, onException)); }
public void Parse() { try { reader.MoveToContent(); while (reader.Read()) { var arg = new ParseEventArg { NodeType = reader.NodeType, Depth = reader.Depth, Name = reader.Name, EmptyElement = reader.IsEmptyElement }; if (reader.HasValue) { arg.Value = reader.Value; } else { arg.Value = null; } if (reader.HasAttributes) { var arr = new Attribute[reader.AttributeCount]; for (var i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); arr[i] = new Attribute { Name = reader.Name, Value = reader.Value, Index = i }; } reader.MoveToElement(); arg.Attributes = new ReadOnlyCollection <Attribute>(arr); } else { arg.Attributes = new ReadOnlyCollection <Attribute>(empty); } OnNode?.Invoke(this, arg); switch (reader.NodeType) { case XmlNodeType.Element: OnElement?.Invoke(this, arg); break; case XmlNodeType.CDATA: OnCData?.Invoke(this, arg); break; case XmlNodeType.Comment: OnComment?.Invoke(this, arg); break; case XmlNodeType.DocumentType: OnDocType?.Invoke(this, arg); break; case XmlNodeType.EndElement: OnEndElement?.Invoke(this, arg); break; case XmlNodeType.EntityReference: OnEntityReferenceUnresolved?.Invoke(this, arg); reader.ResolveEntity(); reader.Read(); arg.Name = reader.Name; arg.Value = reader.Value; arg.Depth = reader.Depth; arg.NodeType = reader.NodeType; OnEntityReference?.Invoke(this, arg); break; case XmlNodeType.ProcessingInstruction: OnProcessingInstruction?.Invoke(this, arg); break; case XmlNodeType.Text: OnText?.Invoke(this, arg); break; } } } catch (XmlException e) { OnException?.Invoke(this, e); } }
protected virtual void DoOnException(Exception e) { OnException?.Invoke(this, e); }
public static void Exception(string message, Exception exception, [CallerFilePath] string file = "", [CallerLineNumber] int line = 0) => OnException?.Invoke(message, exception, file, line);
protected void Handle(string msg, Exception ex) => OnException?.Invoke(msg, ex);
protected virtual void InvokeOnException(ConnectionErrorArgs errorArgs) { OnException?.Invoke(this, errorArgs); }
/// <summary> /// Executes the <paramref name="correlatedFunc"/> with its own <see cref="CorrelationContext"/>. /// </summary> /// <typeparam name="T">The return type.</typeparam> /// <param name="correlationManager">The correlation manager.</param> /// <param name="correlatedFunc">The func to execute.</param> /// <param name="onException">A delegate to handle the exception inside the correlation scope, before it is disposed. Returns <see langword="true" /> to consider the exception handled, or <see langword="false" /> to throw.</param> /// <returns>Returns the result of the <paramref name="correlatedFunc"/>.</returns> /// <remarks> /// When logging and tracing are both disabled, no correlation context is created and the action simply executed as it normally would. /// </remarks> public static T Correlate <T>(this ICorrelationManager correlationManager, Func <T> correlatedFunc, OnException <T> onException) { return(correlationManager.Correlate(null, correlatedFunc, onException)); }