public override async void ViewAppeared() { log.Debug("CardTenderViewModel: View is appeared."); base.ViewAppeared(); try { SubscribeAllEvents(); amount = posManager.ActiveSale.Amount; IsTpsConnected = App.IsTpsConnected; IsFcsConnected = App.IsFcsConnected; if (!IsTpsConnected) { log.Error("CardTenderViewModel: TPS is not connected.Go to tender selection page."); await NavigateToTenderSelection(); } else { log.Debug("CardTenderViewModel: TPS is connected.Process sale."); await ProcessSaleResponse(); } } catch (Exception ex) { log.ErrorException(string.Format("CardTenderViewModel: Exception:{0}", ex.Message), ex); } }
private async Task RefreshPropertiesAsync() { try { IsBusy = true; var result = await _searchService.FindProperties(_navigationParams.location, _navigationParams.toLet); _currentPage = result.MetaData.PageNumber; _hasNextPage = result.MetaData.HasNextPage; _total = result.MetaData.TotalItemCount; PropertiesList.Clear(); foreach (var property in result.Properties) { PropertiesList.Add(property); } UpdateDisplyingDescription(); if (_isInitialised == false) { _isInitialised = true; } } catch (Exception exc) { _log.ErrorException("An error has occurred while trying to get search results", exc); await _useDialogs.AlertAsync("An error has occurred. Please try again."); } finally { IsBusy = false; } }
private async Task <ApiServiceResponse <TResult> > MakeApiCall <TResult>(string url, HttpMethod method, object data = null) { string targetUrl = $"{baseUrl}{url}"; using (var httpClient = httpClientFactory.CreateClient()) { using (var request = new HttpRequestMessage { RequestUri = new Uri(targetUrl), Method = method }) { if (method != HttpMethod.Get) { var json = JsonConvert.SerializeObject(data); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); } if (currentUserService.CurrentUser != null) { request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", currentUserService.CurrentUser.Token); } var result = new ApiServiceResponse <TResult>(); try { OnCallStart?.Invoke(); var response = await httpClient.SendAsync(request).ConfigureAwait(false); result.StatusCode = response.StatusCode; result.IsSuccessStatusCode = response.IsSuccessStatusCode; if (response.IsSuccessStatusCode) { var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false); result.Content = JsonConvert.DeserializeObject <TResult>(stringSerialized); } else { var content = await response.Content.ReadAsStringAsync(); string errorMessage = @$ "{GetStatusCodeErrorMessage(response.StatusCode)}/r/n{content}"; result.Error = errorMessage; } } catch (Exception ex) { mvxLog.ErrorException("MakeApiCall failed", ex); result.Error = ex.Message; } finally { OnCallEnd?.Invoke(); } return(result); } } }
public async Task SaveOrUpdateNews(NewsModel newsToSave) { try { await storage.SaveOrUpdate(newsToSave.ToRealmObject()); } catch (Exception ex) { _mvxLog.ErrorException("Save news failed", ex); } }
public async Task SetAccessToken(string accessToken) { try { Application.Current.Properties[_accessTokenKeyName] = accessToken; await Application.Current.SavePropertiesAsync(); //await SecureStorage.SetAsync(_accessTokenKeyName, accessToken); } catch (Exception ex) { _mvxLog.ErrorException("Cannot set access token", ex); } }
private async Task SearchPropertiesAsync() { if (string.IsNullOrWhiteSpace(Location)) { await _useDialogs.AlertAsync("Please specify location"); return; } try { IsBusy = true; var locationDetails = await _locationPromptService.GetLocationDetails(Location); if (locationDetails.Any() == false) { await _useDialogs.AlertAsync("No results found. Please try a different location"); return; } await _navigationService.Navigate <PropertiesViewModel, LocationPromptResult>(locationDetails.First()); } catch (Exception exc) { _log.ErrorException("An error has occurred while trying to get location prompt details", exc); await _useDialogs.AlertAsync("An error has occurred. Please try again."); } finally { IsBusy = false; } }
public string GetPassword() { string keyVaultName = Settings.Default.AzureKeyVaultName; string kvUri = $"https://{keyVaultName}.vault.azure.net"; Response <KeyVaultSecret> secret; try { SecretClient client = new(new Uri(kvUri), new DefaultAzureCredential()); secret = client.GetSecret(Settings.Default.AzureKeyVaultGitHubPassword); _log.Info("Got Azure secret!"); } catch (Exception e) { _log.ErrorException("Getting Azure secret failed", e); secret = null; } // async version- prob not a good idea //var secret = await client.GetSecretAsync(secretName); return(secret?.Value.Value); }
public async override void ViewAppearing() { base.ViewAppearing(); if (_isInitialised) { return; } try { IsBusy = true; await Task.Delay(500); _propertyDetails = await _propertyDetailsService.FetchPropertyDetails(_propertyId); _isInitialised = true; } catch (Exception exc) { _log.ErrorException("An error has occurred while trying to fetch property details", exc); await _useDialogs.AlertAsync("An error has occurred. Please try again."); } finally { IsBusy = false; } }
public async Task <TResult> MakeApiCall <TResult>(string url, HttpMethod method, object data = null) where TResult : class { url = url.Replace("http://", "https://"); using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = method }) { // add content if (method != HttpMethod.Get) { var json = _jsonConverter.SerializeObject(data); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); } HttpResponseMessage response = new HttpResponseMessage(); try { response = await httpClient.SendAsync(request).ConfigureAwait(false); } catch (Exception ex) { _mvxLog.ErrorException("MakeApiCall failed", ex); } var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // deserialize content return(_jsonConverter.DeserializeObject <TResult>(stringSerialized)); } } }
public HealthKitService( IMeasureService measureService, IMvxLogProvider logProvider ) { _log = logProvider.GetLogFor <HealthKitService>(); _measureService = measureService ?? throw new ArgumentNullException(nameof(measureService)); _healthStore = new HKHealthStore(); AddCommand = ReactiveCommand.CreateFromTask <Measure>( v => AddSamples(GetQuantitySamples(v))); AddCommand.ThrownExceptions .Subscribe(e => _log.ErrorException("While add measure to health kit", e)); EditCommand = ReactiveCommand.CreateFromTask <Measure>(EditMeasure); EditCommand.ThrownExceptions .Subscribe(e => _log.ErrorException("While edit measure to health kit", e)); DeleteCommand = ReactiveCommand.CreateFromTask <Measure>(DeleteSamples); DeleteCommand.ThrownExceptions .Subscribe(e => _log.ErrorException("While deleting measure", e)); MessageBus.Current .ListenIncludeLatest <MeasureAddedEvent>() .Select(v => v?.Value) .Where(v => v != null) .Where(v => GetStatus()) .InvokeCommand(this, v => v.AddCommand); MessageBus.Current .ListenIncludeLatest <MeasureChangedEvent>() .Select(v => v?.Value) .Where(v => v != null) .Where(v => GetStatus()) .InvokeCommand(this, v => v.EditCommand); MessageBus.Current .ListenIncludeLatest <MeasureDeletedEvent>() .Select(v => v?.Value) .Where(v => v != null) .Where(_ => GetStatus()) .InvokeCommand(this, v => v.DeleteCommand); }
public async Task <ResponseDTO <TResult> > MakeRequestAsync <TResult>(string url, HttpMethod method, object data = null) where TResult : class { using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = method }) { var result = new ResponseDTO <TResult>() { IsSuccess = true, Error = "", }; if (method != HttpMethod.Get) { var json = JsonConvert.SerializeObject(data); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); } var response = new HttpResponseMessage(); try { var ct = new CancellationTokenSource(); ct.CancelAfter(10000); response = await httpClient.SendAsync(request, ct.Token).ConfigureAwait(false); if (response?.StatusCode != null) { result.StatusCode = response.StatusCode; if (!response.IsSuccessStatusCode) { result.IsSuccess = false; return(result); } } var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false); result.Content = JsonConvert.DeserializeObject <List <TResult> >(stringSerialized); return(result); } catch (Exception ex) { result.Error = ex.GetLastMessage(); _mvxLog.ErrorException("Request failed", ex); return(result); } } } }
public void Add(TEntity obj) { lock (connectionDBClient) { try { connectionDBClient.Database.Insert(obj); } catch (Exception ex) { mvxLog.ErrorException($"Database exception. method: add.", ex); } } }
public Realm GetInstance() { try { return(Realm.GetInstance()); } catch (Exception e) { _log.ErrorException("Database initialization failed", e); throw; } }
protected override async Task <Boolean> ShowContentView(FrameworkElement element, MvxContentPresentationAttribute attribute, MvxViewModelRequest request) { try { // Everything that passes here should be a view IMvxView view = element as IMvxView; IMesManager manager = Mvx.IoCProvider.Resolve <IMesManager>(); // from which we can now get the view model. switch (view.ViewModel) { case IMesDocument document: // Try to set view, this is needed for DocumentManager IMesDocument docViewModel = (IMesDocument)view.ViewModel; docViewModel.View = view; // Needed for Binding with AvalonDock docViewModel.ViewAppearing(); docViewModel.ViewAppeared(); // Add to manager model manager.Documents.Add(docViewModel); _log.Trace($"Add {document.ToString()} to IManager.Documents"); return(true); case IMesTool tool: // Try to set view, this is needed for DocumentManager IMesTool toolViewModel = (IMesTool)view.ViewModel; toolViewModel.View = view; // Needed for Binding with AvalonDock toolViewModel.ViewAppearing(); toolViewModel.ViewAppeared(); // Add to manager model manager.Tools.Add(toolViewModel); _log.Trace($"Add {tool.ToString()} to IManager.Tools"); return(true); default: _log.Trace($"Passing to parent {view.ViewModel.ToString()}"); return(await base.ShowContentView(element, attribute, request)); } } catch (Exception exception) { if (_log == null) { _log = Mvx.IoCProvider.Resolve <IMvxLog>(); } _log.ErrorException("Error seen during navigation request to {0} - error {1}", exception, request.ViewModelType.Name, exception.ToLongString()); return(false); } }
public Realm GetInstance() { try { var config = new InMemoryConfiguration(Guid.NewGuid().ToString()); return(Realm.GetInstance(config)); } catch (Exception e) { _log.ErrorException("In-memory Database initialization failed", e); throw; } }
public async Task <TResult> MakeApiCall <TResult>(string url, HttpMethod method, object data = null, bool NeedAuth = false) where TResult : class { //url = url.Replace("http://", "https://"); using (var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = method }) { // add content if (method != HttpMethod.Get) { var json = _jsonConverter.SerializeObject(data); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); } HttpClient.DefaultRequestHeaders .Accept .Add(new MediaTypeWithQualityHeaderValue("application/json")); if (NeedAuth && TokenResponseModel != null) { HttpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", TokenResponseModel.Token); } HttpResponseMessage response = new HttpResponseMessage(); try { response = await HttpClient.SendAsync(request, HttpCompletionOption.ResponseContentRead).ConfigureAwait(false); } catch (WebException ex) { IsConnected = false; _mvxLog.ErrorException($"MakeApiCall failed ", ex); } catch (Exception e) { IsConnected = e.InnerException == null || !(e.InnerException is WebException); _mvxLog.ErrorException("MakeApiCall failed ", e); } var stringSerialized = await response.Content.ReadAsStringAsync().ConfigureAwait(false); // deserialize content var result = _jsonConverter.DeserializeObject <TResult>(stringSerialized); return(result); } }
private async Task NavigateToPrintReceipt() { try { if (App.IsFcsConnected && App.IsTpsConnected) { log.Debug("CardRefundViewModel: Navigate to print recipt page."); await this.navigationService.Navigate <PrintReceiptViewModel, int>(pumpId); } } catch (Exception ex) { log.ErrorException(string.Format("CardTenderViewModel: Exception: {0} ", ex.Message), ex); } }
private async Task ShowReceipts(string invoiceNo, ReceiptOrder receiptOrder) { try { DateToShow = SelectedDate.ToString("dddd MMM dd, yyyy"); log.Debug("ReprintReceiptViewModel: Trying to fetch receipt data."); ReceiptData = await GetReceipts(invoiceNo, receiptOrder); SetMaximumAndMinimumInvoiceNo(); } catch (Exception ex) { log.ErrorException(string.Format("ReprintReceiptViewModel: Exception:{0}", ex.Message), ex); } }
public override async void ViewAppeared() { log.Debug("PrintReceiptViewModel: View is appeared."); base.ViewAppeared(); App.CultureChange += OnCultureChangeAsync; try { log.Debug("PrintReceiptViewModel: Printing receipt."); Print(); await Navigate(); } catch (Exception ex) { log.ErrorException("PrintReceiptViewModel: ", ex); } }
public List <string> GetV4Ips() { try { log.Debug("IPAddressManager: Trying to fetch local ip addresses"); return(Dns.GetHostAddresses(Dns.GetHostName()) .Where(ip => ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) .ToList() .Select(ip => ip.ToString()) .ToList()); } catch (Exception ex) { log.ErrorException(string.Format("IPAddressManager: Exception: {0}.", ex.Message), ex); return(null); } }
public override async void ViewAppeared() { log.Debug("PrintReportViewModel: View is appeared."); base.ViewAppeared(); App.CultureChange += OnCultureChangeAsync; try { log.Debug("PrintReportViewModel: Printing report."); printer.PrintReportReceipt(report); await this.navigationService.Navigate <HomeViewModel>(); } catch (Exception ex) { log.ErrorException(string.Format("PrintReportViewModel: Exception:{0}. ", ex.Message), ex); } }
public async Task <TResult> MakeApiCall <TResult>(string url, HttpMethod method, object data = null, string token = null) where TResult : class { url = url.Replace("http://", "https://"); using (var httpClient = new HttpClient()) { using (var request = new HttpRequestMessage { RequestUri = new Uri(url), Method = method }) { request.Headers.Clear(); var accessToken = token ?? await _storageHelper.GetAccessToken(); request.Headers.Authorization = new AuthenticationHeaderValue(accessToken); // add content if (method != HttpMethod.Get) { var json = _jsonConverter.SerializeObject(data); request.Content = new StringContent(json, Encoding.UTF8, "application/json"); } HttpResponseMessage response = new HttpResponseMessage(); try { response = await httpClient.SendAsync(request).ConfigureAwait(false); if (response.StatusCode == System.Net.HttpStatusCode.Unauthorized) { throw new ApplicationException("The session was expired. Please, re-login."); } } catch (Exception ex) { _mvxLog.ErrorException("MakeApiCall failed", ex); throw; } var stringSerialized = await response.Content.ReadAsStringAsync(); return(_jsonConverter.DeserializeObject <TResult>(stringSerialized)); } } }
public async Task LoadAsync(string manifestPath) { try { // Ensure the directory exists if (!Directory.Exists(manifestPath)) { throw new DirectoryNotFoundException("The provided directory was not found"); } ReadMusicProvider(manifestPath, false); } catch (Exception ex) { _log.ErrorException("Could not load music provider", ex); Crashes.TrackError(ex); await _dialogService.ShowErrorMessageAsync("Error loading music provider", ex.Message); } }
private async Task <string> ProcessError(HttpResponseMessage result) { if (result.StatusCode != HttpStatusCode.BadRequest) { return(ErrorConst.UnknownErrorType); } try { var res = await result.Content.ReadFromJsonAsync <RegisterResultRequest>(); return(res.Type); } catch (Exception ex) { _log.ErrorException("Failed to parse JSON from error", ex); return(ErrorConst.UnknownErrorType); } }
public void AddUdpFrame(string frame) { try { string message = frame; _log.Info("Going to send a message over the UDP driver {message}", message); if (message.Contains("!0D!0A")) { message = message.Replace("!0D!0A", "\r\n"); byte[] inputBytes = Encoding.ASCII.GetBytes(message); // new byte array and feed it the input string _asyncUdpLink.SendMessage(inputBytes); _log.Info("Message contained <crlf>, replaced the hex with ASCII to be sent properly {message}", message); } else if (message.Contains("!0D")) { message = message.Replace("!0D", "\r"); byte[] inputBytes = Encoding.ASCII.GetBytes(message); // new byte array and feed it the input string _asyncUdpLink.SendMessage(inputBytes); _log.Info("Message contained <cr>, replaced the hex with ASCII to be sent properly {message}", message); } else if (message.Contains("!0A")) { message = message.Replace("!0A", "\n"); byte[] inputBytes = Encoding.ASCII.GetBytes(message); // new byte array and feed it the input string _asyncUdpLink.SendMessage(inputBytes); _log.Info("Message contained <lf>, replaced the hex with ASCII to be sent properly {message}", message); } else { byte[] inputBytes = Encoding.ASCII.GetBytes(message); // new byte array and feed it the input string _asyncUdpLink.SendMessage(inputBytes); _log.Info("Message did not contain any ending characters {message}", message); } } catch (Exception e) { _log.ErrorException("Parsing the FrameToSend has failed {e}", e); } WriteUDPDataToDataBase(frame, true); }
public int GetLogs(string numOfItems) { int numOfMsgs = 20; try { if (numOfItems is null) { numOfMsgs = 20; } else if (numOfItems.Contains("All")) { // All numOfMsgs = 100000000; } else if (numOfItems.Length == 40) { // 20, 50 string logComboBoxSelected = numOfItems.Substring(38, 2); numOfMsgs = int.Parse(logComboBoxSelected); } else if (numOfItems.Length == 41) { // hundred string logComboBoxSelected = numOfItems.Substring(38, 3); numOfMsgs = int.Parse(logComboBoxSelected); } else if (numOfItems.Length == 42) { // thousand string logComboBoxSelected = numOfItems.Substring(38, 4); numOfMsgs = int.Parse(logComboBoxSelected); } } catch (Exception e) { _log.ErrorException("Didn't parse the number in the ComboBox {e}", e); } return(numOfMsgs); }
private async void ConfigurePaymentServer() { log.Debug("App: Configuring Tps.."); try { var tpsService = Mvx.IoCProvider.Resolve <ITpsService>(); tpsService.TpsConnectionClosed += async() => { IsTpsConnected = false; log.Info("App: Attempting to re-establish connection to TPS..."); await tpsService.ConnectAsync(); }; tpsService.TpsConnectionEstablished += () => IsTpsConnected = true; log.Info("App: Establishing Connection to TPS..."); await tpsService.ConnectAsync(); } catch (Exception ex) { log.ErrorException("App: ", ex); } }
private async Task SetUserAndAuthorizationHeader(JwtToken jwtToken, bool save = false) { IsAuthenticated = true; _httpClient.DefaultRequestHeaders.Remove(AuthorizationHeader); _httpClient.DefaultRequestHeaders.Add(AuthorizationHeader, $"Bearer {jwtToken.IdToken}"); try { CurrentUser = await _httpClient.GetFromJsonAsync <UserModel>(AccountUrl); if (save) { await BlobCache.Secure.InvalidateAll(); await BlobCache.Secure.InsertObject <JwtToken>("token", jwtToken); } } catch (Exception ex) { _log.ErrorException("Failed to fetch user and login.", ex); IsAuthenticated = false; } }
private async Task GetReceiptData() { try { log.Debug("ReprintReceiptDataViewModel: Trying to get receipt data for invoice id:{0}.", invoiceId); var response = await this.fcsService?.GetReceiptData(ReceiptType.PayInStore, invoiceId); if (response.ResultOK) { log.Debug("ReprintReceiptDataViewModel: Successfully fetched receipt data."); Receipt = response.Receipt; log.Debug("ReprintReceiptDataViewModel: Receipt : {0}.", Receipt); } else { log.Error("ReprintReceiptDataViewModel: Error while fetching receipt data."); } } catch (Exception ex) { log.ErrorException(string.Format("ReprintReceiptDataViewModel: Exception:{0}", ex.Message), ex); } }
public async Task <IReadOnlyList <SimpleArtistModel> > GetTopAtists(int limit) { try { var url = $"{App.MainUrl}?method={MethodName}&format=json&api_key={App.ApiKey}&limit={limit}"; var response = await _httpClient.GetAsync(url); if (response.StatusCode == System.Net.HttpStatusCode.OK) { var content = await response.Content.ReadAsStringAsync(); var model = Newtonsoft.Json.JsonConvert.DeserializeObject <TopArtistsModel>(content); return(model?.Artists?.Artist ?? new List <SimpleArtistModel>()); } //TODO обработка других значений StatusCode } catch (Exception ex) { _logger.ErrorException("Get top atrists exception: ", ex); } return(new List <SimpleArtistModel>()); }