private async Task <TransitionResult> ViewModelOnPageTransitionRequested(object sender, [NotNull] TransitionRequest transitionRequest) { if (transitionRequest == null) { throw new ArgumentNullException(nameof(transitionRequest)); } var tcs = new TaskCompletionSource <TransitionResult>(); await Invoker.InvokeAsync(async() => { try { if (!(sender is IStoryboardPageViewModel viewModel)) { throw new InvalidOperationException("Incorrect request of transition"); } var result = await GoToPageAsync( transitionRequest.DestinationPageId, viewModel.StoryboardId, transitionRequest.DestinationPageContext) .ConfigureAwait(true); tcs.SetResult(result); } catch (Exception e) { ExceptionOccured?.Invoke(this, e); tcs.SetResult(TransitionResult.Failed); } }).ConfigureAwait(false); return(await tcs.Task.ConfigureAwait(true)); }
protected void OnExceptionOccured(Exception e) { ExceptionOccured?.Invoke(this, new ExceptionEventArgs() { Exception = e }); }
private void ProviderOnClassListLoaded(object sender, ClassesListLoadedEventArgs args) { if (args.Cancelled) { IsClassListLoading = false; return; } if (args.Error != null) { ExceptionOccured?.Invoke(args.Error, Method.LoadClass); IsClassListLoading = false; return; } var classDict = new Dictionary <string, List <string> >(); foreach (var @class in args.Classes) { var match = _regex.Match(@class); var number = match.Groups[1].ToString(); var liter = match.Groups[2].ToString().ToUpper(); if (!classDict.ContainsKey(number)) { classDict[number] = new List <string>(); } classDict[number].Add(liter); } Classes = classDict; IsClassListLoading = false; }
private void Listen(ReceiveMode receiveMode) { var mr = _messagingFactory.CreateMessageReceiver(_subscription.FullPath, receiveMode); while (_isListening) { BrokeredMessage message = null; try { message = mr.Receive(); } catch (TimeoutException) { ListeningTimedOut?.Invoke(); continue; } catch (OperationCanceledException) //When Cancel() is called on client or factory { return; } catch (Exception ex) { ExceptionOccured?.Invoke(message, ex); return; } if (message == null) { continue; } try { var isMessageHandled = HandleMessage(message); if (receiveMode == ReceiveMode.PeekLock) { if (isMessageHandled) { message.Complete(); } else { message.Abandon(); } } } catch (Exception ex) { if (receiveMode == ReceiveMode.PeekLock) { message.Abandon(); } ExceptionOccured?.Invoke(message, ex); } Thread.Sleep(50); } }
public void FireExceptionOccured(Exception ex) { if (null == ExceptionOccured) { return; } ExceptionOccured.Invoke(this, ex); }
private void OnExceptionOccured(Exception e) { cardQProcessor.StopServiceQProcess(); ExceptionOccured?.Invoke(this, new ExceptionEventArgs() { Exception = e }); }
protected virtual async Task <TransitionResult> HandleViewModelTransitionsAsync( object sender, PageTransitionTrigger trigger, IStoryboardPageContext context = null) { var tcs = new TaskCompletionSource <TransitionResult>(); await Invoker.InvokeAsync(async() => { try { if (!(sender is IStoryboardPageViewModel viewModel)) { throw new InvalidOperationException("Incorrect request of transition"); } // todo is it correct? different behaviour of transition var removingResult = await RemoveOpennedPageAsync() .ConfigureAwait(true); if (removingResult == null) { tcs.SetResult(TransitionResult.Unavailable); return; } if (removingResult.Item2 != TransitionResult.Completed) { tcs.SetResult(removingResult.Item2); return; } var storyboard = Storyboards.Values.FirstOrDefault(x => x.StoryboardId == viewModel.StoryboardId); if (storyboard == null) { throw new InvalidOperationException("Storyboard not found"); } var destinationPageId = storyboard.GetDestinationPage(viewModel.PageId, trigger); var result = await GoToPageAsync(destinationPageId, storyboard.StoryboardId, context) .ConfigureAwait(true); tcs.SetResult(result); } catch (Exception e) { ExceptionOccured?.Invoke(this, e); tcs.SetResult(TransitionResult.Failed); } }).ConfigureAwait(false); return(await tcs.Task.ConfigureAwait(false)); }
/// <summary> /// Starts the server /// </summary> public void Start() { IsRunning = true; try { hl.Start(); ServerStarted?.Invoke(); hl.BeginGetContext(new AsyncCallback(ServerProc), hl); } catch (HttpListenerException ex) { ExceptionOccured?.Invoke(ex); } }
private async void SenderWorkerLoop(object _ctx) { SynchronizationContext context = (SynchronizationContext)_ctx; foreach (var message in messageQueue.GetConsumingEnumerable()) { try { await SendMessage(message); } catch { context.Post(exc => ExceptionOccured?.Invoke(this, new ExceptionEventArgs((Exception)exc)), this); } await Task.Delay(50); } }
private void ProviderOnWeekScheduleForClassLoaded(object sender, WeekScheduleForClassLoadedEventArgs args) { IsWeekClassSchduleLoading = false; IsRefreshing = false; if (args.Cancelled) { return; } if (args.Error != null) { ExceptionOccured?.Invoke(args.Error, Method.LoadTimetable); return; } var @class = args.Schedule.First().Key; AppendSchedule(@class, args.Schedule[@class]); CurrentClass = @class; }
public virtual async Task <TransitionResult> GoBackAsync() { if (!CanGoBack()) { return(TransitionResult.Unavailable); } if (ActiveInnerStoryboardPageInfo == null) { return(TransitionResult.Unavailable); } var tcs = new TaskCompletionSource <TransitionResult>(); await Invoker.InvokeAsync(async() => { try { var lastPageFromStoryboard = await RemoveOpennedPageAsync().ConfigureAwait(true); if (lastPageFromStoryboard == null) { tcs.SetResult(TransitionResult.Unavailable); return; } if (lastPageFromStoryboard.Item2 != TransitionResult.Completed) { tcs.SetResult(lastPageFromStoryboard.Item2); return; } // already have been added var result = await OpenPageAsync(lastPageFromStoryboard.Item1, addToJournal: false) .ConfigureAwait(true); tcs.SetResult(result); } catch (Exception e) { ExceptionOccured?.Invoke(this, e); tcs.SetResult(TransitionResult.Failed); } }).ConfigureAwait(false); return(await tcs.Task); }
public virtual async Task <TransitionResult> GoToPageAsync( Guid pageId, Guid?storyboardId = null, IStoryboardPageContext pageContext = null) { var tcs = new TaskCompletionSource <TransitionResult>(); await Invoker.InvokeAsync(async() => { try { var storyBoard = storyboardId.HasValue ? Storyboards.FirstOrDefault(x => x.Key == storyboardId.Value).Value : ActiveStoryboard; //first try to find desired page in current storyboard, then look up at all registered pages var pageInfo = storyBoard != null ? RegisteredPages.Keys.FirstOrDefault(x => x.PageId == pageId && x.StoryboardId == storyBoard.StoryboardId) : RegisteredPages.Keys.FirstOrDefault(x => x.PageId == pageId); if (pageInfo == null) { pageInfo = RegisteredPages.Keys.FirstOrDefault(x => x.PageId == pageId); if (pageInfo == null) { throw new InvalidOperationException("Page not found"); } } var result = await OpenPageAsync(pageInfo, pageContext) .ConfigureAwait(true); tcs.SetResult(result); } catch (Exception e) { ExceptionOccured?.Invoke(this, e); tcs.SetResult(TransitionResult.Failed); } }).ConfigureAwait(false); return(await tcs.Task .ConfigureAwait(false)); }
private async void AttemptConnectionAsync() { HubConnection = new HubConnectionBuilder() .WithUrl(_baseUrl) .Build(); try { await HubConnection.StartAsync(); Connected?.Invoke(); _connectionRetryTimer.Dispose(); HubConnection.On("Ping", async() => { _previousDelayBetweenPings = DateTimeOffset.UtcNow - _lastPingTime; _lastPingTime = DateTimeOffset.UtcNow; await Task.Delay(_pingPongFrequency); try { await HubConnection.SendAsync("Pong"); } catch (Exception e) { ExceptionOccured?.Invoke(new SignalRClientException( $"Pong to {_baseUrl} failed. Will try to reconnect in {_connectionRetryDelay.TotalMilliseconds}ms. Reason :", e)); } }); _connectionRefreshTimer = new Timer((e) => RefreshConnectionStatus(), null, TimeSpan.FromMilliseconds(0), _connectionRefreshFrequency); } catch (Exception e) { ExceptionOccured?.Invoke(new SignalRClientException( $"Connection to {_baseUrl} failed. Will retry in {_connectionRetryDelay.TotalMilliseconds}ms. Reason :", e)); } }
protected virtual void CardInterface_ExceptionOccured(object sender, EventArgs e) { //StopServiceQProcess(); ExceptionOccured?.Invoke(this, e); }
void OnExceptionOccured(string msg) { ExceptionOccured?.Invoke(this, new ExceptionEventArgs(new SourceException(msg))); }
/// <summary> /// Raises the <see cref="ExceptionOccured"/> event. /// </summary> /// <param name="e">The event arguments.</param> protected virtual void OnExceptionOccured(ExceptionEventArgs e) => ExceptionOccured?.Invoke(this, e);
/// <summary> /// Spin off a thread that will constantly try to get new events from the SbListener. /// </summary> public void Start() { if (IsRunning) { return; } _tokenSource = new CancellationTokenSource(); var task = Task.Run(() => { try { while (!_tokenSource.IsCancellationRequested) { if (!_lldbListener.WaitForEvent(_listenerIntervalInSeconds, out SbEvent lldbEvent)) { continue; } if (lldbEvent == null) { return; } var eventType = lldbEvent.GetEventType(); if (lldbEvent.IsBreakpointEvent) { BreakpointChanged?.Invoke( null, new BreakpointChangedEventArgs(lldbEvent)); } else if ((eventType & EventType.STATE_CHANGED) != 0) { StateChanged?.Invoke(null, new StateChangedEventArgs(lldbEvent)); } else if ((eventType & EventType.STRUCTURED_DATA) != 0) { var update = _descriptionParser.Parse <FileProcessingUpdate>( lldbEvent.GetDescription()); if (update != null) { FileUpdateReceived ?.Invoke(null, new FileUpdateReceivedEventArgs(update)); } } } } catch (TaskCanceledException) { Trace.WriteLine($"Listener was stopped"); } catch (Exception exception) { Trace.WriteLine( "Internal error: Failed to receive event from listener due to " + exception.Message); ExceptionOccured?.Invoke(null, new ExceptionOccuredEventArgs(exception)); } }, _tokenSource.Token); IsRunning = true; }
protected void OnExceptionOccured(Exception exception) { ExceptionOccured?.Invoke(this, new ExceptionOccuredEventArgs(exception)); }
protected void SubscribeExceptionHandling() => exceptionOccuredToken = eventAggregator.GetEvent <ExceptionOccuredEvent>() .Subscribe(ex => ExceptionOccured?.Invoke(ex));
public virtual async Task <TransitionResult> GoToStoryboardStartPage(Guid storyboardId) { if (!Storyboards.ContainsKey(storyboardId)) { throw new ArgumentException($"Storyboard with Id {storyboardId} not registered"); } var tcs = new TaskCompletionSource <TransitionResult>(); await Invoker.InvokeAsync(async() => { var previousActiveStoryboard = ActiveStoryboard; try { if (ActiveStoryboard?.ActivePage != null) { var previousPage = ActiveStoryboard.ActivePage; var viewModel = previousPage.ViewModel; var canLeave = await viewModel.CanLeaveAsync().ConfigureAwait(true); if (!canLeave) { tcs.SetResult(TransitionResult.CanceledByUser); return; } await viewModel .LeaveAsync().ConfigureAwait(true); } var pagesToClose = Journal .Where(x => x.StoryboardId == storyboardId) .ToList(); ActiveStoryboard = null; switch (pagesToClose.Count) { case 0: { var startPage = RegisteredPages.Keys.FirstOrDefault( x => x.StoryboardId == storyboardId && x.IsStartPage); if (startPage == null) { throw new InvalidOperationException("Pages for storyboard does not registered"); } var result = await OpenPageAsync(startPage).ConfigureAwait(true); tcs.SetResult(result); return; } case 1: { var result = await OpenPageAsync( pagesToClose[0], addToJournal: false) .ConfigureAwait(true); tcs.SetResult(result); return; } default: { var orderedPagesToClose = new Stack <InnerStoryboardPageInfo>(pagesToClose); var storyboard = Storyboards[storyboardId]; var pageInfo = orderedPagesToClose.Pop(); while (!pageInfo.IsStartPage && orderedPagesToClose.Count > 0) { if (!CachedPages.ContainsKey(pageInfo.PageUniqueId)) { throw new InvalidOperationException($"Page with Id {pageInfo.PageUniqueId} not cached"); } var page = CachedPages[pageInfo.PageUniqueId]; var canClose = await page.ViewModel .CanCloseAsync() .ConfigureAwait(false); if (!canClose) { // open page that user don't want to close var openningResult = await OpenPageAsync( pageInfo, addToJournal: false) .ConfigureAwait(true); tcs.SetResult(openningResult == TransitionResult.Completed ? TransitionResult.CanceledByUser // because user canceled transition to start page : openningResult); return; } await RemovePageAsync( pageInfo, storyboard) .ConfigureAwait(true); pageInfo = orderedPagesToClose.Pop(); } var result = await OpenPageAsync( pageInfo, addToJournal: false) .ConfigureAwait(true); tcs.SetResult(result); return; } } } catch (Exception e) { tcs.SetResult(TransitionResult.Failed); ExceptionOccured?.Invoke(tcs, e); ActiveStoryboard = previousActiveStoryboard; } }) .ConfigureAwait(false); return(await tcs.Task.ConfigureAwait(false)); }
private void ServerProc(IAsyncResult ar) { HttpListenerContext context = null; HttpListener listener = (HttpListener)ar.AsyncState; listener.BeginGetContext(new AsyncCallback(ServerProc), listener); //Make new async request try { context = listener.EndGetContext(ar); //TODO clone request maybe? error An operation was attempted on a nonexistent network connection is thrown when too many reloads are occuring pls fix context.Response.Headers["Server"] = "FastHTTPServer/1.0"; //logger.Log("Raw URL is " + context.Request.Url); string pageUrl = context.Request.RawUrl.ToString(); //TODO fix relative (../.) paths, they do not work for some reason if ((pageUrl != "/") && pageUrl.EndsWith("/")) { pageUrl = pageUrl.Substring(0, pageUrl.Length - 1); } //Check if REST API is available if (restAPIs.ContainsKey(pageUrl)) { logger.Log(LogLevel.INFORMATION, "Invoking REST API {0}", pageUrl); restAPIs[pageUrl].InvokeResponseReceived(context.Request, context.Response, logger); return; } logger.Log(LogLevel.INFORMATION, "Got request from host {0} for URL {1}", context.Request.RemoteEndPoint, pageUrl); //TODO check for malformed paths //TODO fix url system string pathInFS = Path.Combine(htmlFolder, Uri.UnescapeDataString(pageUrl.Substring(1)).Replace('/', Path.DirectorySeparatorChar)); logger.Log(LogLevel.INFORMATION, "Serving file " + pathInFS); //Check if specified path is a directory. If it is, check if any indexes exist and if not, display dir listing if its enabled if (Directory.Exists(pathInFS)) { bool foundIndexPage = false; foreach (var indexPageName in config.IndexPages) { string indexPath = Path.Combine(pathInFS, indexPageName); if (File.Exists(indexPath)) { logger.Log(LogLevel.INFORMATION, "Not showing dir listing for URL, found index file " + indexPath); ServeFile(context, indexPath, 200); foundIndexPage = true; break; } } if (foundIndexPage) { return; } //TODO allow user to customize the style of the dir listing like apache web server //TODO check if cookies specify listing format //Set location header context.Response.Headers["Location"] = context.Request.RawUrl; #region Simple file listing - pls remove when better implementation is added if (!config.DisableDirListing) { var html = @"<meta charset='utf-8'><style>a { text-decoration: none; }</style><h2>Directory listing of " + Uri.UnescapeDataString(pageUrl) + "</h2><hr>"; if (pageUrl != "/") { html += "<a href=\"" + pageUrl + "/..\">🔼 Up..</a><br>"; } foreach (var d in Directory.GetDirectories(pathInFS)) { if (context.Request.RawUrl != "/") { html += string.Format("<a href=\"{1}/{0}\">📁 {0}</a><br>", Path.GetFileName(d), pageUrl); } else { html += string.Format("<a href=\"/{0}\">📁 {0}</a><br>", Path.GetFileName(d)); } } foreach (var f in Directory.GetFiles(pathInFS)) { if (context.Request.RawUrl != "/") { html += string.Format("<a href=\"{1}/{0}\">📄 {0}</a><br>", Path.GetFileName(f), pageUrl); } else { html += string.Format("<a href=\"/{0}\">📄 {0}</a><br>", Path.GetFileName(f)); } } ServeHtml(context, html); } else { ServeHtml(context, ConstructErrorPage("404 Not Found", "The requested resource has not been found."), 404); } #endregion } else { ServeFile(context, pathInFS); } } catch (HttpListenerException hlex) { ExceptionOccured?.Invoke(hlex); } catch (Exception ex) { ExceptionOccured?.Invoke(ex); if (context != null) { //Send 500 ISE logger.Log(LogLevel.WARNING, "Internal server error caught! Message: " + ex.Message); ServeHtml(context, "500 Internal Server Error<hr><i>FastHTTP Server v1.0</i>", 500); } } //TODO revert if it doesnt work //listener.BeginGetContext(new AsyncCallback(ServerProc), listener); }
protected virtual async Task <TransitionResult> OpenPageAsync( [NotNull] InnerStoryboardPageInfo pageInfo, [CanBeNull] IStoryboardPageContext pageContext = null, bool addToJournal = true) { if (!Storyboards.ContainsKey(pageInfo.StoryboardId)) { throw new InvalidOperationException($"Storyboard {pageInfo.StoryboardId} does not registered"); } var tcs = new TaskCompletionSource <TransitionResult>(); await Invoker.InvokeAsync(async() => { try { var storyboard = Storyboards[pageInfo.StoryboardId]; if (ActiveStoryboard?.ActivePage != null) { var previousPage = ActiveStoryboard.ActivePage; var viewModel = previousPage.ViewModel; var canLeave = await viewModel.CanLeaveAsync().ConfigureAwait(true); if (!canLeave) { tcs.SetResult(TransitionResult.CanceledByUser); return; } await viewModel.LeaveAsync().ConfigureAwait(true); } var storyboardsWasChanged = ActiveStoryboard == null || ActiveStoryboard.StoryboardId != storyboard.StoryboardId; ActiveInnerStoryboardPageInfo = pageInfo; ActiveStoryboard = storyboard; if (storyboardsWasChanged) { ActiveStoryboardChanged?.Invoke(this, pageInfo.StoryboardId); } if (CachedPages.ContainsKey(pageInfo.PageUniqueId)) { var page = CachedPages[pageInfo.PageUniqueId]; storyboard.ActivePage = page; PageContexts.TryGetValue(pageInfo.PageUniqueId, out var restoredPageContext); StartPagesOpenningStat.TryGetValue(pageInfo.PageUniqueId, out var wasPageOpenned); if (wasPageOpenned) { await page.ViewModel.ReturnAsync(pageContext ?? restoredPageContext).ConfigureAwait(true); } else { await page.ViewModel.OpenAsync(pageContext ?? restoredPageContext).ConfigureAwait(true); StartPagesOpenningStat[pageInfo.PageUniqueId] = true; } } else { var view = CreatePageView(pageInfo); storyboard.ActivePage = view; await view.ViewModel.OpenAsync(pageContext).ConfigureAwait(true); PageContexts[pageInfo.PageUniqueId] = pageContext; } if (addToJournal) { Journal.AddLast(pageInfo); } tcs.SetResult(TransitionResult.Completed); CanBackChanged?.Invoke(this, EventArgs.Empty); } catch (Exception e) { ExceptionOccured?.Invoke(this, e); tcs.SetResult(TransitionResult.Failed); } }).ConfigureAwait(false); return(await tcs.Task.ConfigureAwait(false)); }
private void OnExceptionOccured(Exception ex) { ExceptionOccured?.Invoke(this, ex); }
private void OnExceptionOccured(ExceptionEventArgs e) { ExceptionOccured?.Invoke(this, e); }
protected virtual void Kernel_ExceptionOccured(object sender, EventArgs e) { cardQProcessor.StopServiceQProcess(); StopServiceQProcess(); ExceptionOccured?.Invoke(this, e); }