Пример #1
0
        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();
        }
Пример #2
0
        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());
        }
Пример #3
0
        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());
        }