Esempio n. 1
0
        // EndInvokeJSFromDotNet is used in a fire-and-forget context, so it's responsible for its own
        // error handling.
        public async Task EndInvokeJSFromDotNet(long asyncCall, bool succeeded, string arguments)
        {
            AssertInitialized();
            AssertNotDisposed();

            try
            {
                await Renderer.Dispatcher.InvokeAsync(() =>
                {
                    if (!succeeded)
                    {
                        // We can log the arguments here because it is simply the JS error with the call stack.
                        Log.EndInvokeJSFailed(_logger, asyncCall, arguments);
                    }
                    else
                    {
                        Log.EndInvokeJSSucceeded(_logger, asyncCall);
                    }

                    DotNetDispatcher.EndInvokeJS(JSRuntime, arguments);
                });
            }
            catch (Exception ex)
            {
                // An error completing JS interop means that the user sent invalid data, a well-behaved
                // client won't do this.
                Log.EndInvokeDispatchException(_logger, ex);
                await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Invalid interop arguments."));

                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
            }
        }
Esempio n. 2
0
        public static void Invoke(Action action, bool ignoreCurrentThread = true)
        {
            if (action == null)
            {
                return;
            }

            if (_context == null || (!ignoreCurrentThread && IsUIThread))
            {
                action();
                return;
            }

            _context.Post
            (
                s =>
            {
                try
                {
                    ((Action)s)();
                }
                catch (Exception ex)
                {
                    UnhandledException?.Invoke(ex);
                }
            },
                action
            );
        }
    protected override void NavigateToCore(string uri, NavigationOptions options)
    {
        Log.RequestingNavigation(_logger, uri, options);

        if (_jsRuntime == null)
        {
            var absoluteUriString = ToAbsoluteUri(uri).ToString();
            throw new NavigationException(absoluteUriString);
        }

        _ = PerformNavigationAsync();

        async Task PerformNavigationAsync()
        {
            try
            {
                var shouldContinueNavigation = await NotifyLocationChangingAsync(uri, options.HistoryEntryState, false);

                if (!shouldContinueNavigation)
                {
                    Log.NavigationCanceled(_logger, uri);
                    return;
                }

                await _jsRuntime.InvokeVoidAsync(Interop.NavigateTo, uri, options);
            }
            catch (Exception ex)
            {
                // We shouldn't ever reach this since exceptions thrown from handlers are handled in HandleLocationChangingHandlerException.
                // But if some other exception gets thrown, we still want to know about it.
                Log.NavigationFailed(_logger, uri, ex);
                UnhandledException?.Invoke(this, ex);
            }
        }
    }
Esempio n. 4
0
        // BeginInvokeDotNetFromJS is used in a fire-and-forget context, so it's responsible for its own
        // error handling.
        public async Task BeginInvokeDotNetFromJS(string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson)
        {
            AssertInitialized();
            AssertNotDisposed();

            try
            {
                await Renderer.Dispatcher.InvokeAsync(() =>
                {
                    SetCurrentCircuitHost(this);
                    Log.BeginInvokeDotNet(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId);
                    DotNetDispatcher.BeginInvoke(callId, assemblyName, methodIdentifier, dotNetObjectId, argsJson);
                });
            }
            catch (Exception ex)
            {
                // We don't expect any of this code to actually throw, because DotNetDispatcher.BeginInvoke doesn't throw
                // however, we still want this to get logged if we do.
                Log.BeginInvokeDotNetFailed(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId, ex);
                if (Client.Connected)
                {
                    await NotifyClientError(Client, "Interop call failed.");
                }
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
            }
        }
Esempio n. 5
0
        public Subscription Subscribe <T>(string name, Func <T, Message, CancellationToken, Task> callback, Volume minimumVolume = Volume.Normal)
        {
            var subscription = new Subscription(name, async(o, m, t) => {
                if (o is T variable)
                {
                    await callback.Invoke(variable, m, t);
                }
            }, minimumVolume, Unsubscribe);

            if (!_handlers.TryAdd(subscription, Handler))
            {
                throw new Exception("Unable to subscribe");
            }

            var sub = _connection.GetSubscriber();

            sub.Subscribe(name, Handler);

            return(subscription);

            void Handler(RedisChannel c, RedisValue v)
            {
                try
                {
                    var msg = JsonConvert.DeserializeObject <Message>(v);
                    msg.Object = JsonConvert.DeserializeObject <T>(msg.Object as string);
                    subscription.Invoke(msg.Object, msg, CancellationToken.None);
                }
                catch (Exception ex)
                {
                    UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex));
                }
            }
        }
Esempio n. 6
0
        public async Task DispatchEvent(string eventDescriptorJson, string eventArgs)
        {
            RendererRegistryEventDispatcher.BrowserEventDescriptor eventDescriptor = null;
            try
            {
                AssertInitialized();
                eventDescriptor = ParseEventDescriptor(eventDescriptorJson);
                if (eventDescriptor == null)
                {
                    return;
                }


                await Renderer.Dispatcher.InvokeAsync(() =>
                {
                    SetCurrentCircuitHost(this);
                    return(RendererRegistryEventDispatcher.DispatchEvent(eventDescriptor, eventArgs));
                });
            }
            catch (Exception ex)
            {
                Log.DispatchEventFailedToDispatchEvent(_logger, eventDescriptor != null ? eventDescriptor.EventHandlerId.ToString() : null, ex);
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
            }
        }
Esempio n. 7
0
 public async Task OnLocationChangedAsync(string uri, bool intercepted)
 {
     try
     {
         AssertInitialized();
         await Renderer.Dispatcher.InvokeAsync(() =>
         {
             SetCurrentCircuitHost(this);
             Log.LocationChange(_logger, CircuitId, uri);
             var navigationManager = (RemoteNavigationManager)Services.GetRequiredService <NavigationManager>();
             navigationManager.NotifyLocationChanged(uri, intercepted);
             Log.LocationChangeSucceeded(_logger, CircuitId, uri);
         });
     }
     catch (Exception ex)
     {
         // It's up to the NavigationManager implementation to validate the URI.
         //
         // Note that it's also possible that setting the URI could cause a failure in code that listens
         // to NavigationManager.LocationChanged.
         //
         // In either case, a well-behaved client will not send invalid URIs, and we don't really
         // want to continue processing with the circuit if setting the URI failed inside application
         // code. The safest thing to do is consider it a critical failure since URI is global state,
         // and a failure means that an update to global state was partially applied.
         Log.LocationChangeFailed(_logger, CircuitId, uri, ex);
         UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
     }
 }
Esempio n. 8
0
        public async Task BeginInvokeDotNetFromJS(string callId, string assemblyName, string methodIdentifier, long dotNetObjectId, string argsJson)
        {
            try
            {
                AssertInitialized();
                if (assemblyName == "Microsoft.AspNetCore.Components.Web" && methodIdentifier == "DispatchEvent")
                {
                    Log.DispatchEventTroughJSInterop(_logger);
                    return;
                }

                await Renderer.Dispatcher.InvokeAsync(() =>
                {
                    SetCurrentCircuitHost(this);
                    Log.BeginInvokeDotNet(_logger, callId, assemblyName, methodIdentifier, dotNetObjectId);
                    DotNetDispatcher.BeginInvoke(callId, assemblyName, methodIdentifier, dotNetObjectId, argsJson);
                });
            }
            catch (Exception ex)
            {
                // We don't expect any of this code to actually throw, because DotNetDispatcher.BeginInvoke doesn't throw
                // however, we still want this to get logged if we do.
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
            }
        }
Esempio n. 9
0
        public async Task DispatchEvent(string eventDescriptorJson, string eventArgsJson)
        {
            WebEventData webEventData;

            try
            {
                AssertInitialized();
                webEventData = WebEventData.Parse(eventDescriptorJson, eventArgsJson);
            }
            catch (Exception ex)
            {
                Log.DispatchEventFailedToParseEventData(_logger, ex);
                return;
            }

            try
            {
                await Renderer.Dispatcher.InvokeAsync(() =>
                {
                    SetCurrentCircuitHost(this);
                    return(Renderer.DispatchEventAsync(
                               webEventData.EventHandlerId,
                               webEventData.EventFieldInfo,
                               webEventData.EventArgs));
                });
            }
            catch (Exception ex)
            {
                Log.DispatchEventFailedToDispatchEvent(_logger, webEventData.EventHandlerId.ToString(), ex);
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
            }
        }
Esempio n. 10
0
        public AsyncTimer()
        {
            Tick += (sender, e) => ServiceFactory.MessageService.Debug($"AsyncTimer.Tick {Guid}");

            Timer          = new Timer(16);
            Timer.Elapsed += (sender, e) =>
            {
                try
                {
                    if (IsCompleted && NextExecuteDate <= DateTime.Now)
                    {
                        IsCompleted = false;
                        Timer?.Stop();
                        SetNextExecuteDate(NextExecuteDate);

                        Tick.Invoke(sender, e);
                    }
                }
                catch (Exception ex)
                {
                    ServiceFactory.MessageService.Exception(ex);

                    if (UnhandledException != null)
                    {
                        UnhandledException.Invoke(this, new UnhandledExceptionEventArgs(ex, false));
                    }
                    else
                    {
                        throw;
                    }
                }
            };
        }
Esempio n. 11
0
    public async Task <DotNetStreamReference> TryClaimPendingStream(long streamId)
    {
        AssertInitialized();
        AssertNotDisposed();

        DotNetStreamReference dotNetStreamReference = null;

        try
        {
            return(await Renderer.Dispatcher.InvokeAsync <DotNetStreamReference>(() =>
            {
                if (!JSRuntime.TryClaimPendingStreamForSending(streamId, out dotNetStreamReference))
                {
                    throw new InvalidOperationException($"The stream with ID {streamId} is not available. It may have timed out.");
                }

                return dotNetStreamReference;
            }));
        }
        catch (Exception ex)
        {
            // An error completing stream interop means that the user sent invalid data, a well-behaved
            // client won't do this.
            Log.SendDotNetStreamException(_logger, streamId, ex);
            await TryNotifyClientErrorAsync(Client, GetClientErrorMessage(ex, "Unable to locate .NET stream."));

            UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, isTerminating: false));
            return(default);
Esempio n. 12
0
        /// <summary>
        /// Asynchronously handles an individual incoming HTTP request, or aborts if the server was
        /// stopped.
        /// </summary>
        /// <returns>True if a request was handled, or false if the server was stopped.</returns>
        public async Task <HandleRequestResult> HandleRequestAsync()
        {
            var contextTask = _listener.GetContextAsync();

            try
            {
                await Task.WhenAny(contextTask, _stopEvent.Task);
            }
            catch (Exception e)
            {
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ReduceException(e), false));
                return(HandleRequestResult.UnhandledException);
            }

            if (!contextTask.IsCompleted)
            {
                return(HandleRequestResult.Stopped);
            }

            try
            {
                OnGetContext(contextTask.Result);
            }
            catch (Exception e)
            {
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ReduceException(e), false));
                return(HandleRequestResult.UnhandledException);
            }

            return(HandleRequestResult.Success);
        }
Esempio n. 13
0
        private void HandleResponseMessage(ResponseMessage responseMessage, string debugData)
        {
            if (!PendingMessages.TryRemove(responseMessage.Id, out var pm))
            {
                // got the unknown answer message
                // cannot throw here because we're on the worker thread
                var ex    = new InternalErrorException($"Got a response for the unknown message #{responseMessage.Id}: {debugData}");
                var eargs = new ThreadExceptionEventArgs(ex);
                UnhandledException?.Invoke(this, eargs);
                return;
            }

            var tcs = pm.CompletionSource;

            // signal the remote exception
            if (responseMessage.Error != null)
            {
                var exception = JsonServicesException.Create(responseMessage.Error);
                tcs.TrySetException(exception);
                return;
            }

            // signal the result
            tcs.TrySetResult(responseMessage.Result);
        }
Esempio n. 14
0
        private void ProcessTask()
        {
            this._taskLock.WaitOne();
            while (!this._stop)
            {
                Task task = null;
                lock (this._syncRoot) {
                    if (this._taskQueue.Count > 0)
                    {
                        try {
                            task = this._taskQueue.Dequeue();
                        } catch { }
                    }
                }
                if (task == null)
                {
                    this._taskLock.WaitOne();
                    continue;
                }

                try {
                    task.Execute();
                } catch (Exception ex) {
                    try {
                        UnhandledException?.Invoke(typeof(Taskscheduler), new UnhandledExceptionEventArgs(ex, false));
                    } catch { }
                }
            }
        }
Esempio n. 15
0
 internal static void OnUnhandledException(Exception e, bool fatal)
 {
     UnhandledException?.Invoke(e, new UnhandledExceptionEventArgs(e, fatal));
     if (fatal)
     {
         Environment.FailFast("Unhandled exception in native callback", e);
     }
 }
Esempio n. 16
0
        /// <inheritdoc />
        public async Task Publish <T>(string name, T obj, Volume volume = Volume.Normal, CancellationToken token = default(CancellationToken))
        {
            var message = new Message(name, obj, volume);
            // Process subscriptions and unsubscriptions
            Subscription sub;

            while (_pendingUnsubscriptions.TryDequeue(out sub))
            {
                _subscriptions.TryRemove(sub, out _);
            }
            while (_pendingSubscriptions.TryDequeue(out sub))
            {
                _subscriptions.TryAdd(sub, true);
            }

            var done = Task.FromResult(0);
            var list = new List <Task> {
                done
            };

            foreach (var subscription in _subscriptions.Keys.ToList())
            {
                if (token.IsCancellationRequested)
                {
                    break;
                }

                if (!subscription.ShouldPost(message))
                {
                    continue;
                }

                try
                {
                    list.Add(subscription.Invoke(obj, message, token));
                }
                catch (Exception ex)
                {
                    UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex));
                }
            }

            try
            {
                await Task.WhenAll(list);
            }
            catch (AggregateException ex)
            {
                foreach (var aex in ex.InnerExceptions)
                {
                    UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(aex));
                }
            }
            catch (Exception ex)
            {
                UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex));
            }
        }
Esempio n. 17
0
    /// <summary>
    /// Called to notify listeners of an unhandled exception.
    /// </summary>
    /// <param name="e">The <see cref="UnhandledExceptionEventArgs"/>.</param>
    protected void OnUnhandledException(UnhandledExceptionEventArgs e)
    {
        if (e is null)
        {
            throw new ArgumentNullException(nameof(e));
        }

        UnhandledException?.Invoke(this, e);
    }
Esempio n. 18
0
        private void TriggerEffects(object action)
        {
            var recordedExceptions = new List <Exception>();
            var effectsToExecute   = Effects
                                     .Where(x => x.ShouldReactToAction(action))
                                     .ToArray();
            var executedEffects = new List <Task>();

            Action <Exception> collectExceptions = e =>
            {
                if (e is AggregateException aggregateException)
                {
                    recordedExceptions.AddRange(aggregateException.Flatten().InnerExceptions);
                }
                else
                {
                    recordedExceptions.Add(e);
                }
            };

            // Execute all tasks. Some will execute synchronously and complete immediately,
            // so we need to catch their exceptions in the loop so they don't prevent
            // other effects from executing.
            // It's then up to the UI to decide if any of those exceptions should cause
            // the app to terminate or not.
            foreach (IEffect effect in effectsToExecute)
            {
                try
                {
                    executedEffects.Add(effect.HandleAsync(action, this));
                }
                catch (Exception e)
                {
                    collectExceptions(e);
                }
            }

            Task.Run(async() =>
            {
                try
                {
                    await Task.WhenAll(executedEffects);
                }
                catch (Exception e)
                {
                    collectExceptions(e);
                }

                // Let the UI decide if it wishes to deal with any unhandled exceptions.
                // By default it should throw the exception if it is not handled.
                foreach (Exception exception in recordedExceptions)
                {
                    UnhandledException?.Invoke(this, new Exceptions.UnhandledExceptionEventArgs(exception));
                }
            });
        }
Esempio n. 19
0
        /// <summary>
        /// Handles unhandled exceptions.
        /// </summary>
        /// <param name="e">The exception event args.</param>
        /// <returns>If the exception was handled.</returns>
        private bool OnUnhandledException(ServiceExceptionEventArgs e)
        {
            if (UnhandledException == null)
            {
                return(false);
            }

            UnhandledException.Invoke(this, e);
            return(true);
        }
 public void Invoke(Action action)
 {
     try
     {
         _dispatcher.Invoke(action);
     }
     catch (Exception e)
     {
         UnhandledException?.Invoke(this, e);
     }
 }
Esempio n. 21
0
        public static bool HandleException(Exception ex, WindowCore window)
        {
            var windowException = new WindowException(ex, window);

            window?.Exception?.Invoke(windowException);
            if (!windowException.IsHandled)
            {
                UnhandledException?.Invoke(windowException);
            }
            return(windowException.IsHandled);
        }
Esempio n. 22
0
 public void HandleInboundPoolException(
     string engineURI,
     Exception exception,
     object @event)
 {
     UnhandledException?.Invoke(
         this,
         new ExceptionHandlerEventArgs {
         InboundPoolContext = new ExceptionHandlerContextUnassociated(engineURI, exception, @event)
     });
 }
Esempio n. 23
0
 private void OnUnhandledException(Exception e)
 {
     try
     {
         UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(e));
     }
     catch (Exception)
     {
         // ignore exceptions during event handling for unhandled exceptions
     }
 }
 public void ProcessWorkitemInline(SendOrPostCallback callback, object state)
 {
     try
     {
         callback(state);
     }
     catch (Exception e)
     {
         UnhandledException?.Invoke(this, e);
     }
 }
Esempio n. 25
0
        /// <summary>
        /// Starts the task
        /// </summary>
        public void Start()
        {
            if (!IsRunning)
            {
                IsRunning = true;

                timerThread = new Thread(() =>
                {
                    if (Stopwatch == null)
                    {
                        Stopwatch = Stopwatch.StartNew();
                    }
                    else if (!Stopwatch.IsRunning)
                    {
                        Stopwatch.Restart();
                    }

                    long startTime     = Stopwatch.ElapsedMilliseconds;
                    double nextRunTime = StartDelay + Interval;

                    while (IsRunning)
                    {
                        long elapsedTime = Stopwatch.ElapsedMilliseconds;
                        double waitTime  = nextRunTime - (elapsedTime - startTime);
                        if (waitTime > 0)
                        {
                            if (resetEvent.WaitOne((int)(waitTime)))
                            {
                                break;
                            }
                        }

                        runWatch.Restart();
                        try
                        {
                            Run();
                        }
                        catch (Exception ex)
                        {
                            UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, false));
                        }

                        long runTime  = runWatch.ElapsedMilliseconds;
                        TotalLagTime += runTime - Interval;
                        TotalRunTime += runTime;
                        RunCount++;
                        nextRunTime += Interval;
                    }
                });

                timerThread.Priority = Priorty;
                timerThread.Start();
            }
        }
 /// <summary>
 /// Wrap Run method in Try/Catch
 /// </summary>
 private void SafeRun()
 {
     try
     {
         this.Run();
     }
     catch (Exception ex)
     {
         UnhandledException?.Invoke(this, new UnhandledExceptionEventArgs(ex, false));
     }
 }
Esempio n. 27
0
        /// <summary>
        /// Keeps a <see cref="IRunnable"/> running.
        /// </summary>
        /// <param name="registration"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        async Task RunAsync(ServiceRegistration registration, CancellationToken cancellationToken)
        {
            if (registration == null)
            {
                throw new ArgumentNullException(nameof(registration));
            }

            while (cancellationToken.IsCancellationRequested == false)
            {
                // each invocation gets it's own instance and lifetime scope
                using (var scope = parent.BeginLifetimeScope(RunnableScope))
                {
                    // instantiate runnable
                    var runnable = (IRunnable)scope.ResolveComponent(new ResolveRequest(new TypedService(typeof(IRunnable)), registration, Enumerable.Empty <Parameter>()));

                    try
                    {
                        logger.LogInformation("{Runnable} starting.", runnable.GetType());

                        // enter into runnable
                        await runnable.RunAsync(cancellationToken);

                        // delay for a second to prevent storms
                        if (cancellationToken.IsCancellationRequested == false)
                        {
                            try
                            {
                                await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
                            }
                            catch (OperationCanceledException)
                            {
                                // ignore
                            }
                        }

                        logger.LogInformation("{Runnable} stopped.", runnable.GetType());
                    }
                    catch (OperationCanceledException)
                    {
                        // ignore
                    }
                    catch (Exception e)
                    {
                        logger.LogError(e, "{Runnable} threw an unexpected exception. Restarting...", runnable.GetType());

                        // signal any interested parties about the exception
                        UnhandledException?.Invoke(e, new UnhandledExceptionEventArgs(e, false));

                        // delay to prevent storms
                        await Task.Delay(TimeSpan.FromSeconds(2));
                    }
                }
            }
        }
Esempio n. 28
0
 private async void TimerCallback(object _)
 {
     try
     {
         await this.callback().ConfigureAwait(false);
     }
     catch (Exception ex)
     {
         UnhandledException?.Invoke(this, new ThreadExceptionEventArgs(ex));
     }
 }
Esempio n. 29
0
        void OnChange(Range target)
        {
            try
            {
                _children.OnChange(target);
            }
            catch (Exception ex)
            {
                UnhandledException?.Invoke(ex);
            }

            Paint();
        }
Esempio n. 30
0
        //private void DataReceived(object o)
        private void DataSocket_MessageReceived(DatagramSocket sender, DatagramSocketMessageReceivedEventArgs args)
        {
            try
            {
                var reader = args.GetDataReader();

                byte[] data = new byte[reader.UnconsumedBufferLength];
                args.GetDataReader().ReadBytes(data);

                this.Socket = sender;

                var dhcpRequest = new DhcpRequest(data, Socket, this);
                //ccDHCP = new clsDHCP();


                //data is now in the structure
                //get the msg type
                OnDataReceived(this, dhcpRequest);
                var msgType = dhcpRequest.GetMsgType();
                switch (msgType)
                {
                case DhcpMsgType.DHCPDISCOVER:
                    OnDiscover(this, dhcpRequest);
                    break;

                case DhcpMsgType.DHCPREQUEST:
                    OnRequest(this, dhcpRequest);
                    break;

                case DhcpMsgType.DHCPDECLINE:
                    OnDecline(this, dhcpRequest);
                    break;

                case DhcpMsgType.DHCPRELEASE:
                    OnReleased(this, dhcpRequest);
                    break;

                case DhcpMsgType.DHCPINFORM:
                    OnInform(this, dhcpRequest);
                    break;
                    //default:
                    //    Console.WriteLine("Unknown DHCP message: " + (int)MsgTyp + " (" + MsgTyp.ToString() + ")");
                    //    break;
                }
            }
            catch (Exception ex)
            {
                UnhandledException?.Invoke(this, ex);   // EDITED:: invoke viene eseguito se e soltanto se UnhandledException non è null
            }
        }