public async Task ExecuteAsync_InsertAllMessagesAfter50ms_Ok() { var sqlServerMock = new Mock <ISqlServerBulk>(); sqlServerMock.Setup( v => v.ExecuteAsync(It.IsAny <ICollection <YadlMessage> >(), It.IsAny <CancellationToken>())) .Returns(() => Task.CompletedTask); var options = new YadlLoggerOptions { BatchSize = 100, BatchPeriod = 50 }; var yadlProcessor = new YadlProcessor(options); var hostedService = new TimedHostedService(yadlProcessor, options, sqlServerMock.Object); await hostedService.StartAsync(CancellationToken.None); for (int i = 1; i <= 15; i++) { _ = yadlProcessor !.ChannelWriter.TryWrite(new YadlMessage { Message = $"MSG: {i}", Level = 1, LevelDescription = "Debug", TimeStamp = DateTimeOffset.Now }); } await hostedService.StopAsync(CancellationToken.None); yadlProcessor.Messages.Should().BeEmpty(); }
public async Task DoWorkAsync_Gets_Game_Status_Then_Evolve_And_Then_Set_New_Game_Status() { //assert _serviceProviderMock .Setup(x => x.GetService(typeof(IGamestatusService))) .Returns(_gamestatusServiceMock.Object); _serviceProviderMock .Setup(x => x.GetService(typeof(IGameEvolutionService))) .Returns(_gameEvolutionService.Object); var serviceScope = new Mock <IServiceScope>(); serviceScope.Setup(x => x.ServiceProvider).Returns(_serviceProviderMock.Object); var serviceScopeFactory = new Mock <IServiceScopeFactory>(); serviceScopeFactory .Setup(x => x.CreateScope()) .Returns(serviceScope.Object); _serviceProviderMock .Setup(x => x.GetService(typeof(IServiceScopeFactory))) .Returns(serviceScopeFactory.Object); _timedHostedService = new TimedHostedService( _loggerMock.Object, _hubContextMock.Object, _serviceProviderMock.Object ); await _timedHostedService.DoWorkAsync(); _gamestatusServiceMock.Verify(gamestatusService => gamestatusService.GetGameStatusAsync(), Times.Once); _gameEvolutionService.Verify(gameEvolutionService => gameEvolutionService.Evolve(It.IsAny <GameStatusDto>()), Times.Once); _gamestatusServiceMock.Verify(gamestatusService => gamestatusService.SetGameStatusAsync(It.IsAny <GameStatusDto>()), Times.Once); }
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, TimedHostedService timedHostedService, IServiceProvider serviceProvider) { var defaultCulture = new CultureInfo("es-ec"); defaultCulture.NumberFormat.NumberDecimalSeparator = "."; defaultCulture.NumberFormat.CurrencyDecimalSeparator = "."; app.UseRequestLocalization(new RequestLocalizationOptions { DefaultRequestCulture = new RequestCulture(defaultCulture), SupportedCultures = new List <CultureInfo> { defaultCulture }, SupportedUICultures = new List <CultureInfo> { defaultCulture }, FallBackToParentCultures = false, FallBackToParentUICultures = false, RequestCultureProviders = new List <IRequestCultureProvider> { } }); loggerFactory.AddConsole(Configuration.GetSection("Logging")); loggerFactory.AddDebug(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); app.UseDatabaseErrorPage(); app.UseBrowserLink(); } else { app.UseExceptionHandler("/Principal/Error"); } app.UseStaticFiles(); app.UseIdentity(); app.UseSession(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Account}/{action=Login}/{id?}"); }); CreateRoles(serviceProvider); //CreateUsers(serviceProvider); app.UseHangfireDashboard(); app.UseHangfireServer(); BackgroundJob.Enqueue(() => timedHostedService.EnviarNotificacionRequisitos()); RecurringJob.AddOrUpdate(() => timedHostedService.EnviarNotificacionRequisitos(), $"{ConstantesTimerEnvioNotificacion.Minutos} {ConstantesTimerEnvioNotificacion.Hora} * * *"); BackgroundJob.Enqueue(() => timedHostedService.EnviarNotificacionRequisitosCincoDias()); RecurringJob.AddOrUpdate(() => timedHostedService.EnviarNotificacionRequisitosCincoDias(), $"{ConstantesTimerEnvioNotificacion.Minutos} {ConstantesTimerEnvioNotificacion.Hora} * * *"); }
public async Task <ActionResult <EFTTransactionResponse> > PostTransactionAsync([FromBody] float amount) { var sessionId = Guid.NewGuid(); var url = appSettings.Server + $"sessions/{sessionId}/transaction"; var request = new ApiRequest <EFTTransactionRequest>() { Request = new EFTTransactionRequest() { TxnType = "P", TxnRef = RandomStr.RandomString(TRX_RND_STR_LENGTH), AmtPurchase = Convert.ToInt32(amount * DOLLAR_TO_CENT), Merchant = appSettings.Merchant, Application = appSettings.Application }, Notification = new Notification { Uri = appSettings.NotificationUri } }; if (string.IsNullOrEmpty(token)) { token = (await GetTokenAsync())?.Token; } apiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); apiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpContent content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); try { var response = await apiClient.PostAsync(url, content); if (response != null && response.IsSuccessStatusCode) { var apiResponse = await response.Content.ReadAsAsync <ApiResponse <EFTTransactionResponse> >(); if (apiResponse != null && apiResponse.Response != null) { return(apiResponse.Response); } } } catch { using (var s = new TimedHostedService(sessionId, apiClient, token)) { using (var cts = new CancellationTokenSource(TRX_EXPIRATION_MINS)) { await s.StartAsync(cts.Token); EFTTransactionResponse txn = null; while (txn == null) { txn = s.GetTransaction(); await Task.Delay(WAIT_PERIOD_SEC); if (cts.IsCancellationRequested) { await s.StopAsync(cts.Token); } } await s.StopAsync(cts.Token); if (txn == null || !txn.Success) { return(BadRequest()); } return(txn); } } } return(BadRequest()); }
public async Task <ActionResult <EFTTransactionResponse> > PostTransactionAsync([FromBody] TransactionRequest transaction) { if (transaction == null || transaction.Amount <= 0 || string.IsNullOrEmpty(transaction.TxnType)) { return(BadRequest()); } var sessionId = Guid.NewGuid(); var url = appSettings.Server + $"sessions/{sessionId}/transaction"; var request = new ApiRequest <EFTTransactionRequest>(); var application = "00"; if (!string.IsNullOrEmpty(transaction.Merchant) && transaction.Merchant != "00") { application = "02"; } request.Request = new EFTTransactionRequest() { TxnType = string.IsNullOrEmpty(transaction.TxnType) ? "P" : transaction.TxnType, ReceiptAutoPrint = "0", TxnRef = RandomStr.RandomString(TRX_RND_STR_LENGTH), AmtPurchase = Convert.ToInt32(transaction.Amount * DOLLAR_TO_CENT), Merchant = string.IsNullOrEmpty(transaction.Merchant) ? appSettings.Merchant : transaction.Merchant, Application = application }; request.Notification = new Notification { Uri = appSettings.NotificationUri }; // if refund if (string.Equals(transaction.TxnType, "R")) { int.TryParse(transaction.Merchant, out int merchant); if (merchant > 0) // Means the refund is going through TPP extension { if (!string.IsNullOrEmpty(transaction.RefundReference)) { dynamic purchaseData = new Newtonsoft.Json.Linq.JObject(); purchaseData.REF = transaction.RefundReference; request.Request.PurchaseAnalysisData = purchaseData; } else { return(BadRequest()); } } } if (string.IsNullOrEmpty(token)) { token = (await GetTokenAsync())?.Token; } if (string.IsNullOrEmpty(token)) { return(Unauthorized()); } apiClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json")); apiClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token); HttpContent content = new StringContent(JsonConvert.SerializeObject(request), Encoding.UTF8, "application/json"); try { var response = await apiClient.PostAsync(url, content); if (response.IsSuccessStatusCode) { var apiResponse = await response.Content.ReadAsAsync <ApiResponse <EFTTransactionResponse> >(); if (apiResponse?.Response != null) { return(apiResponse.Response); } } } catch { //Start timer for background service using (var s = new TimedHostedService(sessionId, apiClient, token)) { using (var cts = new CancellationTokenSource(TimeSpan.FromMinutes(3))) { await s.StartAsync(cts.Token); EFTTransactionResponse txn = null; while (txn == null) { txn = s.GetTransaction(); await Task.Delay(TimeSpan.FromSeconds(WAIT_PERIOD_SEC)); if (cts.IsCancellationRequested) { await s.StopAsync(cts.Token); } } await s.StopAsync(cts.Token); if (txn == null || !txn.Success) { return(BadRequest()); } return(txn); } } } return(BadRequest()); }