public List <LastTransactions> LoadLastTransactions(AuthenticateResponse user, SummaryResponse accounts, int count = 2, string type = "") { var transactions = new List <LastTransactions>(); if (accounts != null && accounts.Summaries.Count > 0) { foreach (var summary in accounts.Summaries) { var request = new LastTransactionRequest { MembershipNumber = user.MembershipKey, ProductCode = summary.ProductCode, Count = count }; var code = summary.ProductCode; var response = _clientService.GetLastTransactions(request); if (response.LastTransactions != null && response.LastTransactions.Count > 0) { transactions = response.LastTransactions; } } } return(transactions); }
/// <summary> /// Download all orders from specific endpoint /// </summary> /// <param name="endPoint">API endpoint</param> /// <param name="currentPage">page index</param> /// <param name="currentPageSize">page size</param> /// <param name="token">cancellation token</param> /// <returns></returns> public async Task DownloadOrdersAsync(SummaryResponse <ShipStationOrder> summary, string endPoint, int currentPage, int currentPageSize, CancellationToken token) { while (true) { var ordersPage = await DownloadOrdersPageAsync(endPoint, currentPage, currentPageSize, token).ConfigureAwait(false); if (ordersPage.HasInternalError) { if (currentPageSize == 1) { summary.ReadErrors.Add(new ReadError() { Url = endPoint, Page = currentPage, PageSize = currentPageSize }); summary.TotalEntitiesHandled += 1; currentPage++; ShipStationLogger.Log.Warn("Skipped order on pos {orderPos} of request {request} due to internal error on ShipStation's side", summary.TotalEntitiesHandled - 1, endPoint); continue; } currentPageSize = PageSizeAdjuster.GetHalfPageSize(currentPageSize); currentPage = PageSizeAdjuster.GetNextPageIndex(summary.TotalEntitiesHandled, currentPageSize); summary.TotalEntitiesHandled -= summary.TotalEntitiesHandled % currentPageSize; ShipStationLogger.Log.Warn("Trying to decrease orders page size twice due to internal error on ShipStation's side. Current page size: {ordersPageSize}, orders downloaded {ordersDownloaded}", currentPageSize, summary.TotalEntitiesHandled); await DownloadOrdersAsync(summary, endPoint, currentPage, currentPageSize, token).ConfigureAwait(false); return; } if (!ordersPage.Data.Any()) { return; } summary.TotalEntitiesExpected = ordersPage.TotalEntities; summary.TotalEntitiesHandled += ordersPage.Data.Count; summary.Data.AddRange(ordersPage.Data); currentPage++; if (currentPageSize != RequestMaxLimit) { var newPageSize = PageSizeAdjuster.DoublePageSize(currentPageSize, RequestMaxLimit); var newCurrentPage = PageSizeAdjuster.GetNextPageIndex(summary.TotalEntitiesHandled, newPageSize); if (!PageSizeAdjuster.AreEntitiesWillBeDownloadedAgainAfterChangingThePageSize(newCurrentPage, newPageSize, summary.TotalEntitiesHandled)) { await DownloadOrdersAsync(summary, endPoint, newCurrentPage, newPageSize, token).ConfigureAwait(false); return; } } } }
public async Task GetSummaryTest() { ArachniApi api = new ArachniApi(Address); SummaryResponse result = await api.GetSummary(id); Assert.IsNotNull(result); string j = JsonConvert.SerializeObject(result); await File.WriteAllTextAsync("d:\\result_summary.json", j); }
public SummaryResponse GetAccountSummary(int membershipkey) { var accountsResponse = new SummaryResponse(); var accountsRequest = new SummaryRequest { MembershipNumber = membershipkey }; accountsResponse = _clientService.GetAccountSummary(accountsRequest); return(accountsResponse); }
public Summaries GetProductInAccount(string productcode, SummaryResponse accounts) { if (accounts.Summaries != null) { foreach (var item in accounts.Summaries) { if (item.ProductCode == productcode) { return(item); } } } return(null); }
public async Task Get_Sensors() { var client = _webApplicationFactory.CreateClient(); var response = await client.GetAsync("https://localhost:44338/api/summary"); var expectedResult = new SummaryResponse("Success", await _sensorService.GetSummaryAsync()); response.EnsureSuccessStatusCode(); Expect.Equal("application/json; charset=utf-8", response.Content.Headers.ContentType.ToString()); var responseString = await response.Content.ReadAsStringAsync(); Expect.DeepEqualLowerCaseFields(expectedResult, responseString); }
public async Task <IActionResult> GetSummary() { try { SummaryResponse response; var sensors = await _sensorService.GetSummaryAsync(); response = new SummaryResponse("Success", sensors); return(Ok(response)); } catch (Exception) { //TODO log exception return(StatusCode(500, "Internal server error")); } }
public IActionResult ListAll() { RestRequest request = new RestRequest("/summary", Method.GET); request.AddHeader("Content-Type", "application/json; charset=utf-8"); IRestResponse response = new RestClient("https://api.covid19api.com/").Execute(request); if (response.StatusCode == System.Net.HttpStatusCode.OK) { SummaryResponse countryStats = JsonConvert.DeserializeObject <SummaryResponse>(Encoding.UTF8.GetString(response.RawBytes)); return(View(countryStats)); } else { return(View("Error")); } }
public async Task <HttpResponseMessage> TriggerOnDeviceSynce(string triggerState, [Metadata("Timezone Offset", "Timezone offset for desired return time (e.g. -7 for Pacific Daylight Time)", VisibilityType.Default)] int offset = 0) { timezoneOffset = new TimeSpan(offset, 0, 0); if (string.IsNullOrEmpty(triggerState)) { triggerState = DateTime.UtcNow.AddDays(-1).ToString("o"); } else { var triggerDate = DateTime.Parse(triggerState); triggerState = triggerDate.ToUniversalTime().ToString("o"); } await tokenHandler.CheckToken(); if (authorization == null || authorization.access_token == null) { return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "You are not authorized. Please go to https://{url}/authorize to authorize against Microsoft Health Service. Ensure your client ID, client Secret, and redirect are all correct. See the GitHub repo for details.")); } using (var client = new HttpClient()) { client.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", authorization.access_token); var profileResult = await client.GetAsync("https://api.microsofthealth.net/v1/me/Profile"); var lastSyncedBand = (DateTime)JObject.Parse((await profileResult.Content.ReadAsStringAsync()))["lastUpdateTime"]; if (lastSyncedBand == null || lastSyncedBand < DateTime.Parse(triggerState).ToUniversalTime()) { return(Request.EventWaitPoll(null, triggerState)); } var result = await client.GetAsync(string.Format("https://api.microsofthealth.net/v1/me/Summaries/{0}?startTime={1}&endTime={2}", "Hourly", DateTime.Parse(triggerState).ToUniversalTime().ToString("o"), lastSyncedBand.ToUniversalTime().ToString("o"))); var sumResponse = new SummaryResponse(JsonConvert.DeserializeObject <Summaries>((await result.Content.ReadAsStringAsync())), 1, lastSyncedBand); if (sumResponse.rows == null || sumResponse.rows.FirstOrDefault() == null) { return(Request.EventWaitPoll(null, triggerState)); } return(Request.EventTriggered(sumResponse, triggerState = sumResponse.rows.First().endTime.ToUniversalTime().ToString("o"))); } }
public async Task <SummaryResponse <ShipStationOrder> > GetModifiedOrdersAsync(DateTime dateFrom, DateTime dateTo, CancellationToken token) { var modifiedOrdersEndpoint = ParamsBuilder.CreateModifiedOrdersParams(dateFrom, dateTo); var modifiedOrdersResponse = new SummaryResponse <ShipStationOrder>(); await this.DownloadOrdersAsync(modifiedOrdersResponse, modifiedOrdersEndpoint, 1, RequestMaxLimit, token).ConfigureAwait(false); if (modifiedOrdersResponse.Data.Any()) { ShipStationLogger.Log.Info("Modified orders downloaded using tenant's API key '{apiKey}' - {orders}/{expectedOrders} orders from {endpoint}", _webRequestServices.GetApiKey(), modifiedOrdersResponse.Data.Count(), modifiedOrdersResponse.TotalEntitiesExpected ?? 0, modifiedOrdersResponse); } return(modifiedOrdersResponse); }
public async Task <IActionResult> GetSummaryAsync() { var activeDates = this.dateCalculator.GetActiveDates(); var requests = await this.requestRepository.GetRequests( this.GetCognitoUserId(), activeDates.First(), activeDates.Last()); var data = activeDates.ToDictionary( d => d, d => CreateDailyData(d, requests)); var calendar = CreateCalendar(data); var response = new SummaryResponse(calendar); return(this.Ok(response)); }
protected override async Task <object> Run_Internal(IObserver observer, string asset, IScanRepository repository, object args) { ReportResponse ret = null; if (!String.IsNullOrEmpty(asset) && args is IDictionary <string, object> dic) { string arachniRestApiAddress = dic[nameof(arachniRestApiAddress)]?.ToString(); if (!String.IsNullOrEmpty(arachniRestApiAddress)) { ArachniApi api = new ArachniApi(arachniRestApiAddress); string id = await api.NewScan(PostRequest.Create(asset)); if (!String.IsNullOrEmpty(id)) { while (true) { await Task.Delay(1000); SummaryResponse summary = await api.GetSummary(id); if (null != summary && null != summary.Status) { observer?.Notify("Arachni_" + asset, $"Status: {summary.Status}, request: {summary.Statistics?.Http?["request_count"]}, runtime: {summary.Statistics?.Runtime}", null); if (summary.Status == "done") { ret = await api.GetReport(id); observer?.Notify("Arachni_" + asset, $"{asset} scan has been completed", null); break; } } else { break; } } } } } return(ret); }
internal override void MapResponse(Element response) { base.MapResponse(response); string category = response.GetValue <string>("TableCategory") ?? ""; if (category == null) { category = LastCategory; } var fieldValues = new Dictionary <string, string>(); foreach (Element field in response.GetAll("Field")) { fieldValues.Add(field.GetValue <string>("Key"), field.GetValue <string>("Value")); } if (category.EndsWith("SUMMARY", StringComparison.OrdinalIgnoreCase)) { var summary = new SummaryResponse { SummaryType = MapSummaryType(category), Count = fieldValues.GetValue <int>("Count"), Amount = fieldValues.GetAmount("Amount"), TotalAmount = fieldValues.GetAmount("Total Amount"), AuthorizedAmount = fieldValues.GetAmount("Authorized Amount"), AmountDue = fieldValues.GetAmount("Balance Due Amount"), }; if (category.Contains("APPROVED")) { if (Approved == null) { Approved = new Dictionary <SummaryType, SummaryResponse>(); } Approved.Add(summary.SummaryType, summary); } else if (category.StartsWith("PENDING")) { if (Pending == null) { Pending = new Dictionary <SummaryType, SummaryResponse>(); } Pending.Add(summary.SummaryType, summary); } else if (category.StartsWith("DECLINED")) { if (Declined == null) { Declined = new Dictionary <SummaryType, SummaryResponse>(); } Declined.Add(summary.SummaryType, summary); } } else if (category.EndsWith("RECORD", StringComparison.OrdinalIgnoreCase)) { TransactionSummary trans; if (category.Equals(LastCategory, StringComparison.OrdinalIgnoreCase)) { trans = LastTransactionSummary; } else { trans = new TransactionSummary { TransactionId = fieldValues.GetValue <string>("TransactionId"), OriginalTransactionId = fieldValues.GetValue <string>("OriginalTransactionId"), TransactionDate = fieldValues.GetValue <string>("TransactionTime").ToDateTime(), TransactionType = fieldValues.GetValue <string>("TransactionType"), MaskedCardNumber = fieldValues.GetValue <string>("MaskedPAN"), CardType = fieldValues.GetValue <string>("CardType"), CardEntryMethod = fieldValues.GetValue <string>("CardAcquisition"), AuthCode = fieldValues.GetValue <string>("ApprovalCode"), IssuerResponseCode = fieldValues.GetValue <string>("ResponseCode"), IssuerResponseMessage = fieldValues.GetValue <string>("ResponseText"), HostTimeout = (bool)fieldValues.GetBoolean("HostTimeOut"), // BaseAmount - Not doing this one TaxAmount = fieldValues.GetAmount("TaxAmount"), GratuityAmount = fieldValues.GetAmount("TipAmount"), Amount = fieldValues.GetAmount("RequestAmount"), AuthorizedAmount = fieldValues.GetAmount("Authorized Amount"), AmountDue = fieldValues.GetAmount("Balance Due Amount") }; } if (!(category.Equals(LastCategory))) { if (category.StartsWith("APPROVED")) { var summary = Approved[SummaryType.Approved]; summary.Transactions.Add(trans); } else if (category.StartsWith("PENDING")) { var summary = Pending[SummaryType.Pending]; summary.Transactions.Add(trans); } else if (category.StartsWith("DECLINED")) { var summary = Declined[SummaryType.Declined]; summary.Transactions.Add(trans); } } LastTransactionSummary = trans; } LastCategory = category; }
public SafReportResponse(JsonDoc root) { var firstDataNode = root.Get("data"); if (firstDataNode == null) { throw new MessageException(INVALID_RESPONSE_FORMAT); } var cmdResult = firstDataNode.Get("cmdResult"); if (cmdResult == null) { throw new MessageException(INVALID_RESPONSE_FORMAT); } Status = cmdResult.GetValue <string>("result"); if (string.IsNullOrEmpty(Status)) { var errorCode = cmdResult.GetValue <string>("errorCode"); var errorMsg = cmdResult.GetValue <string>("errorMessage"); DeviceResponseText = $"Error: {errorCode} - {errorMsg}"; } else { // If the Status is not "Success", there is either nothing to process, or something else went wrong. // Skip the processing of the rest of the message, as we'll likely hit null reference exceptions if (Status == "Success") { ReportResult = new SafReport(); var secondDataNode = firstDataNode.Get("data"); if (secondDataNode == null) { throw new MessageException(INVALID_RESPONSE_FORMAT); } Multiplemessage = secondDataNode.GetValue <string>("multipleMessage"); var safDetailsList = secondDataNode.GetEnumerator("SafDetails"); foreach (var detail in safDetailsList) { var safRecords = detail.GetEnumerator("SafRecords"); if (ReportResult.TotalAmount == null) { ReportResult.TotalAmount = 0.00m; } ReportResult.TotalAmount += detail.GetValue <decimal>("SafTotal"); ReportResult.TotalCount += detail.GetValue <int>("SafCount"); SummaryResponse summaryResponse = new SummaryResponse() { TotalAmount = detail.GetValue <decimal>("SafTotal"), Count = detail.GetValue <int>("SafCount"), SummaryType = MapSummaryType(detail.GetValue <string>("SafType")), Transactions = new List <TransactionSummary>() }; if (detail.Has("SafRecords")) { foreach (var record in detail.GetEnumerator("SafRecords")) { TransactionSummary transactionSummary = new TransactionSummary() { TransactionType = record.GetValue <string>("transactionType"), TerminalRefNumber = record.GetValue <string>("transId"), // The sample XML says tranNo? ReferenceNumber = record.GetValue <string>("referenceNumber"), GratuityAmount = record.GetValue <decimal>("tipAmount"), TaxAmount = record.GetValue <decimal>("taxAmount"), Amount = record.GetValue <decimal>("baseAmount"), AuthorizedAmount = record.GetValue <decimal>("authorizedAmount"), //AmountDue = record.GetValue<decimal>("totalAmount"), CardType = record.GetValue <string>("cardType"), MaskedCardNumber = record.GetValue <string>("maskedPan"), TransactionDate = record.GetValue <DateTime>("transactionTime"), AuthCode = record.GetValue <string>("approvalCode"), HostTimeout = record.GetValue <bool>("hostTimeOut"), CardEntryMethod = record.GetValue <string>("cardAcquisition"), Status = record.GetValue <string>("responseCode"), //record.GetValue<decimal>("requestAmount") }; summaryResponse.Transactions.Add(transactionSummary); } } if (summaryResponse.SummaryType == SummaryType.Approved) { if (ReportResult.Approved == null) { ReportResult.Approved = new Dictionary <SummaryType, SummaryResponse>(); } ReportResult.Approved.Add(summaryResponse.SummaryType, summaryResponse); } else if (summaryResponse.SummaryType == SummaryType.Pending) { if (ReportResult.Pending == null) { ReportResult.Pending = new Dictionary <SummaryType, SummaryResponse>(); } ReportResult.Pending.Add(summaryResponse.SummaryType, summaryResponse); } else if (summaryResponse.SummaryType == SummaryType.Declined) { if (ReportResult.Declined == null) { ReportResult.Declined = new Dictionary <SummaryType, SummaryResponse>(); } ReportResult.Declined.Add(summaryResponse.SummaryType, summaryResponse); } } } else // the only other option is "Failed" { var errorCode = cmdResult.GetValue <string>("errorCode"); var errorMsg = cmdResult.GetValue <string>("errorMessage"); DeviceResponseText = $"Error: {errorCode} - {errorMsg}"; } } }