public async Task <bool> DeleteAccount(Guid accountId, Guid businessId) { HttpResponseMessage response = null; try { response = await _client.IdentityClient.PostAsync("admin/remove", JsonMessage.CreateJsonMessage(new { BusinessId = businessId, Id = accountId }));; } catch (HttpRequestException) { _toastService.ShowError(ServiceError.Standard.Reason); return(false); } if (response.IsSuccessStatusCode) { _toastService.ShowSuccess($"admin removed successfully."); return(true); } else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { var error = await ServiceError.Deserialize(response); _toastService.ShowError(error.Reason); return(false); } return(false); }
public override async Task <Unit> Handle(LoginAction action, CancellationToken cancellationToken) { try { State.StartLoading(); await Login(action.Data, cancellationToken); State.User = await GetUserData(cancellationToken); State.Succeed(); _navigationManager.NavigateTo("/"); } catch (UnauthorizedAccessException uae) { State.Fail(uae.Message); _toastService.ShowError(uae.Message, "Login"); } catch (Exception ex) { _logger.LogError(ex, ex.Message); State.Fail(ex.Message); _toastService.ShowError(ex.Message, "Login"); } return(await Unit.Task); }
/// <inheritdoc /> public async Task <(bool isAuthorized, IEnumerable <StoredFile> files)> GetFilesAsync(ClaimsPrincipal user) { try { var result = await graphServiceClient.Me.Drive.Root.Children.Request() .Select("Id,Name,File") .GetAsync(); return(true, result.Where(i => i.File != null) .Select(i => new StoredFile { Id = i.Id, Name = i.Name })); } catch (ServiceException ex) { // We expect this, if the user isn't a OneDrive user. logger.LogError($"Failed to get OneDrive files for {user?.Identity?.Name} : {ex.Message}"); return(false, null); } catch (Exception ex) { logger.LogError(ex, $"Failed to get OneDrive files for {user?.Identity?.Name} : {ex.Message}"); toastService.ShowError(ex.Message); return(true, null); } }
public async Task SubmitAsync() { HttpResponseMessage response = null; try { response = await _client.IdentityClient.PostAsync("admin/create-business-admin", JsonMessage.CreateJsonMessage(new { BusinessId = Id, Email })); } catch (HttpRequestException) { _toastService.ShowError(ServiceError.Standard.Reason); return; } if (response.IsSuccessStatusCode) { _modalService.Close(ModalResult.Cancel()); _toastService.ShowSuccess($"Email sent to user {Email} to confirm their account"); Email = string.Empty; Id = Guid.Empty; return; } else if (response.StatusCode == System.Net.HttpStatusCode.BadRequest) { var error = await ServiceError.Deserialize(response); _toastService.ShowError(error.Reason); } }
public async Task AddPortfolioTransaction(Transaction transaction) { var result = await _http.PostAsJsonAsync <Transaction>("api/portfoliotransaction/", transaction); if (result.StatusCode != System.Net.HttpStatusCode.OK) { _toastService.ShowError(await result.Content.ReadAsStringAsync()); } else { _toastService.ShowSuccess("The transaction was added to your account!", "Transaction added!"); } }
public async Task AddPortfolioCoin(Coin c) { var result = await _http.PostAsJsonAsync <Coin>("api/portfoliocoin", c); if (result.StatusCode != System.Net.HttpStatusCode.OK) { _toastService.ShowError(await result.Content.ReadAsStringAsync()); } else { _toastService.ShowSuccess($"{c.name} was added to your portfolio!", "Coin added!"); } }
public async Task UpdatePortfolio(UserPortfolio portfolio) { var result = await _http.PostAsJsonAsync <UserPortfolio>("api/userportfolio/updateportfolio", portfolio); if (result.StatusCode != System.Net.HttpStatusCode.OK) { _toastService.ShowError(await result.Content.ReadAsStringAsync()); } else { _toastService.ShowSuccess($"{portfolio.Name} was updated successfully.", "Update successful"); } }
public override async Task Save(ProductDto saveDto) { try { await base.Save(saveDto); _toastService.ShowSuccess("Successfully saved " + saveDto.Name); } catch (Exception e) { Console.WriteLine("Error while saving " + saveDto.Id + ", " + saveDto.Name); Console.WriteLine(e); _toastService.ShowError("Error while saving " + saveDto.Name); } }
public async Task <Activity> GetActivity(string id) { var response = await Get($"/activities/{id}"); var content = await response.Content.ReadAsStringAsync(); // TODO: handle Network Error if (response.StatusCode == HttpStatusCode.NotFound || response.StatusCode == HttpStatusCode.BadRequest) { _navigationManager.NavigateTo("error"); } else if (response.StatusCode == HttpStatusCode.InternalServerError) { _toastService.ShowError(response.ReasonPhrase); return(null); } else { return(JsonSerializer.Deserialize <Activity>(content, _jsonSerializerOptions)); } return(null); }
public override async Task <Unit> Handle(AnswerQuestionAction action, CancellationToken cancellationToken) { try { State.StartLoading(); await PostQuestionAnswer(action.Answer, cancellationToken); await GetRemainingQuestions(action.TrackId, cancellationToken); if (State.RemainingQuestions == State.TotalQuestions) { State.Succeed(); _navigationManager.NavigateTo($"/track-result/{action.TrackId}"); return(await Unit.Task); } State.Question = await GetNextQuestion(action.TrackId, cancellationToken); State.RemainingQuestions = await GetRemainingQuestions(action.TrackId, cancellationToken); State.Succeed(); } catch (UnauthorizedAccessException uae) { State.Fail(uae.Message); _navigationManager.NavigateTo("/login"); } catch (Exception ex) { _logger.LogError(ex, ex.Message); State.Fail(ex.Message); _toastService.ShowError(ex.Message, "Trilha"); } return(await Unit.Task); }
protected async Task HandleValidSubmit() { Mapper.Map(InvoiceViewModel, Invoice); InvoiceServiceResponse response = null; if (Invoice.InvoiceNumber != new Guid()) { Invoice result = null; result = await InvoiceService.UpdateInvoice(Invoice); ToastService.ShowSuccess(Invoice.Description + " was updated successfully"); NavigationManager.NavigateTo("/"); } else { response = await InvoiceService.CreateInvoice(Invoice); if (response.ResponseCode == StatusCodes.Status422UnprocessableEntity || response.ResponseCode == StatusCodes.Status409Conflict) { ToastService.ShowError(response.ResponseMessage); } if (response.ResponseCode == StatusCodes.Status201Created) { ToastService.ShowSuccess(response.ResponseMessage); NavigationManager.NavigateTo("/"); } } }
public async Task AddUnit(int unitId) { Unit unit = Units.First(unit => unit.Id == unitId); var result = await _http.PostAsJsonAsync <int>("api/UserUnit", unitId); if (result.StatusCode != System.Net.HttpStatusCode.OK) { _toastService.ShowError(await result.Content.ReadAsStringAsync()); } else { await _bananaService.GetBananas(); _toastService.ShowSuccess($"Your {unit.Title} has been built!", "Unit built!"); } }
public async Task <bool> _transact(Guid streamId, Tuple <FSharpResult <Unit, string>, FSharpList <Deck.Events.Event> > x) { var(r, events) = x; if (r.IsOk) { await events .Select(e => new ClientEvent <Deck.Events.Event>(streamId, e)) .Pipe(_dexie.Append); return(true); } else { _toastService.ShowError(r.ErrorValue); return(false); } }
public async Task BookWorkTask(int workTaskId) { var result = await _httpClient.PutAsJsonAsync("api/WorkTask", workTaskId); var response = await result.Content.ReadFromJsonAsync <ServiceResponse <string> >(); if (response.Success) { _toastService.ShowSuccess(response.Message, "Succès"); } else { _toastService.ShowError(response.Message, "Erreur."); } await GetWorkTaskAsync(); await GetNumberOfRemainingWorkTasks(); }
public static void HandleError(IToastService toastService, ApiException apiException) { if (!CanHandleErrorWithErrorDetails(toastService, apiException)) { var(message, title) = HandleErrorsWithoutProblemDetails(apiException); toastService.ShowError(message, title); } }
public static async Task Match(this Task <FSharpResult <Unit, string> > tr, IToastService toastService) { var r = await tr; if (r.IsError) { toastService.ShowError(r.ErrorValue); } }
public static void ShowSuccessOrFailure(this IToastService me, IStringLocalizer localizer, int count, string message) { if (count > 0) me.ShowSuccess(localizer[message], localizer["Success"].ToString()); else if (count < 0) me.ShowInfo(localizer[message], localizer["Info"].ToString()); else me.ShowError(localizer[message], localizer["Fault"].ToString()); }
public async Task JoinAsync(string gameCode, string userName) { await EnsureStartedAsync(); GameStateDto gameStateDto; try { gameStateDto = await _hubConnection.InvokeAsync <GameStateDto>(nameof(IGameHub.JoinAsync), gameCode, userName); } catch (HubException e) { _toastService.ShowError(e.GetErrorMessage(), "Error joining game"); return; } var gameState = new GameState(SynchronisationState.Connected, gameStateDto.Code, gameStateDto.Players, gameStateDto.FirstName, gameStateDto.LastName, gameStateDto.Objectives, gameStateDto.EvidenceStates, gameStateDto.EvidencePossibilities, gameStateDto.GhostPossibilities); Dispatcher.Dispatch(new JoinGameResultAction(gameState)); }
public void Login(string userId, string password) { User user; user = _db.Users.SingleOrDefault(u => u.UserId == userId && u.Password == Md5.GetMd5(userId + password)); if (userId == password && user == null) { user = _db.Users.SingleOrDefault(u => u.UserId == userId && string.IsNullOrEmpty(u.Password)); } if (user != null) { ClaimsIdentity identity; if (string.IsNullOrEmpty(user.Password)) { identity = new ClaimsIdentity(new[] { new Claim("UserId", user.UserId), new Claim(ClaimTypes.Role, "NewUser"), new Claim(ClaimTypes.Name, user.Name), }, "NewUser"); _storage.SetAsync("UserId", user.UserId); _storage.SetAsync("Name", user.Name); _storage.SetAsync("Role", "NewUser"); _storage.SetAsync("ExpireTime", DateTime.Now.AddHours(5)); } else { identity = new ClaimsIdentity(new[] { new Claim("UserId", user.UserId), new Claim(ClaimTypes.Role, user.Role.ToString()), new Claim(ClaimTypes.Name, user.Name), }, "Login Page"); _storage.SetAsync("UserId", user.UserId); _storage.SetAsync("Name", user.Name); _storage.SetAsync("Role", user.Role.ToString()); _storage.SetAsync("ExpireTime", DateTime.Now.AddHours(5)); } var claims = new ClaimsPrincipal(identity); if (identity.FindFirst(ClaimTypes.Role).Value == "NewUser") { _navigation.NavigateTo("/initpasswd", true); } NotifyAuthenticationStateChanged(Task.FromResult(new AuthenticationState(claims))); } else { _toastService.ShowError("Incorrect username or password", "Login failed"); } }
public async Task <T?> HandleJsonResponse <T>(HttpResponseMessage responseMessage) { string?content = null; if (responseMessage.Content != null) { content = await responseMessage.Content.ReadAsStringAsync(); } if (responseMessage.IsSuccessStatusCode && content != null) { return(content.DeserializeJson <T>(DefaulJsonSerializertOptions)); } else { switch (responseMessage.StatusCode) { case System.Net.HttpStatusCode.BadRequest: if (content == null) { content = "Bad data"; } break; case System.Net.HttpStatusCode.Conflict: if (content == null) { content = "Conflict"; } break; case System.Net.HttpStatusCode.Forbidden: if (content == null) { content = "Forbidden"; } break; case System.Net.HttpStatusCode.InternalServerError: content = "An error occurred loading data."; break; case System.Net.HttpStatusCode.Unauthorized: if (content == null) { content = "Unauthorized"; } break; default: break; } _toastService.ShowError(content ?? "Error occurred"); } return(default);
public async Task <Summary.User> ForceSummary() { var summary = await GetSummary(); if (summary.IsSome()) { return(summary.Value); } _toastService.ShowError("You aren't logged in."); throw new Exception("You aren't logged in"); }
public async Task AddUnit(int unitId) { var unit = Units.FirstOrDefault(x => x.Id == unitId); if (unit == null) { return; } var res = await _http.PostAsJsonAsync <int>("api/UserUnit", unitId); if (res.StatusCode != HttpStatusCode.OK) { _toastService.ShowError(await res.Content.ReadAsStringAsync()); } else { await _bananaService.GetBananas(); _toastService.ShowSuccess($"Your {unit.Title} has been built!", "Unit built!"); } }
public void Toast(Bread bread) { switch (bread.Level) { case Bread.Hawtness.Success: toaster.ShowSuccess(bread.Banner, bread.Message); return; case Bread.Hawtness.Error: toaster.ShowError(bread.Banner, bread.Message); return; } }
public override async Task <Unit> Handle(RemoveAccountAction aAction, CancellationToken aCancellationToken) { try { State.StartLoading(); await RemoveAccount(); State.Succeed(); } catch (UnauthorizedAccessException uae) { State.Fail(uae.Message); _toastService.ShowError(uae.Message, "Remover Conta"); } catch (Exception ex) { _logger.LogError(ex, ex.Message); State.Fail(ex.Message); _toastService.ShowError(ex.Message, "Remover Conta"); } return(await Unit.Task); }
public static async Task Match <TOk>(this Task <FSharpResult <TOk, string> > tr, IToastService toastService, Action <TOk> onOk) { var r = await tr; if (r.IsOk) { onOk(r.ResultValue); } else { toastService.ShowError(r.ErrorValue); } }
public override async Task <Unit> Handle(LogoutAction action, CancellationToken cancellationToken) { try { State.StartLoading(); State.User = null; await((ApiAuthenticationStateProvider)_authenticationStateProvider).MarkUserAsLoggedOut(); State.Succeed(); _navigationManager.NavigateTo("/login"); } catch (UnauthorizedAccessException uae) { State.Fail(uae.Message); _toastService.ShowError(uae.Message, "Logout"); } catch (Exception ex) { _logger.LogError(ex, ex.Message); State.Fail(ex.Message); _toastService.ShowError(ex.Message, "Logout"); } return(await Unit.Task); }
public static void Handle <TOk>(this FSharpResult <TOk, string> r, IToastService toastService, ref TOk ok, ref string error) { if (r.IsOk) { ok = r.ResultValue; } else { error = string.IsNullOrWhiteSpace(error) ? r.ErrorValue : $"{error} {r.ErrorValue}"; toastService.ShowError(error); } }
public override async Task <Unit> Handle(TAction aAction, CancellationToken aCancellationToken) { try { return(await InnerHandleAsync(aAction, aCancellationToken)); } catch (RpcException rpcException) { _toastService.ShowError((RenderFragment)CreateErrorMessage, "Server-Error"); throw; void CreateErrorMessage(RenderTreeBuilder builder) { builder.AddMarkupContent(0, "There was an error while communicating with the server<br/>"); builder.AddMarkupContent(1, $"Status-Code: {rpcException.Status}"); } } catch (Exception exc) { _toastService.ShowError($"Unknown Error: {exc.Message}"); throw; } }
public virtual bool?Reload() { if (mConfigXml == null) { throw new InvalidOperationException($"{nameof(Load)} must be called before {nameof(Reload)}."); } XmlNodeList log4NetNodes = mConfigXml.SelectNodes("//log4net"); if (log4NetNodes == null || log4NetNodes.Count == 0) { mToastService.ShowError("Could not find log4net configuration."); return(null); } if (log4NetNodes.Count > 1) { mToastService.ShowWarning("More than one 'log4net' element was found in the specified file. Using the first occurrence."); } Log4NetNode = log4NetNodes[0]; mMutableChildren.Clear(); bool unrecognized = false; foreach (XmlNode node in Log4NetNode.ChildNodes) { ModelCreateResult result = ModelFactory.TryCreate(node, Log4NetNode, out ModelBase model); if (result == ModelCreateResult.Success) { mMutableChildren.Add(model); } else if (result == ModelCreateResult.UnknownAppender) { unrecognized = true; } } LoadRootAttributes(); return(unrecognized); }
public static void ShowSuccessOrFailure(this IToastService me, IStringLocalizer localizer, int count, string?message) { if (string.IsNullOrWhiteSpace(message)) { message = string.Empty; } if (count > 0) { me.ShowSuccess(localizer[message], localizer["Success"].ToString()); } else if (count < 0) { me.ShowInfo(localizer[message], localizer["Info"].ToString()); } else { me.ShowError(localizer[message], localizer["Fault"].ToString()); } }