BraintreePayments API Query Transactions for a given date - c#

I am trying to query transactions in Braintree Gateway using BraintreePayments API .NET SDK.
There is a note in the documentation which says:
https://developers.braintreepayments.com/reference/request/transaction/search/dotnet
"Time zones specified in the time value will be respected in the search; if you do not specify a time zone, the search will default to the time zone associated with your gateway account. Results will always be returned with time values in UTC"
How can this be specified in the search request API call?
var searchRequest = new TransactionSearchRequest().
CreatedAt.GreaterThanOrEqualTo(DateTime.Now.AddDays(-1));
ResourceCollection<Transaction> results = gateway.Transaction.Search(searchRequest);

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact
support.
According to Microsoft .NET docs, you can use the ConvertTime(DateTime, TimeZoneInfo) method to convert your DateTime object from your time zone to a different time zone.
You could proceed as follows:
// Retrieve the time zone for Eastern Standard Time (U.S. and Canada).
TimeZoneInfo est;
try {
est = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
}
catch (TimeZoneNotFoundException) {
Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
return;
}
catch (InvalidTimeZoneException) {
Console.WriteLine("Unable to retrieve the Eastern Standard time zone.");
return;
}
//Create a converted time zone DateTime object
DateTime targetTime = TimeZoneInfo.ConvertTime(timeToConvert, est);
//Run search request
var searchRequest = new TransactionSearchRequest().
CreatedAt.GreaterThanOrEqualTo(targetTime.AddDays(-1));

Related

Can't retrieve forecast cost using Azure Cost Management API for Month range (start date to last date) if the request happen in 1st date of month

I'm using Azure Forecast Cost Management API to try to retrieve the forecast cost shown in the azure portal like below.
This is the API I'm using -> https://learn.microsoft.com/en-us/rest/api/cost-management/forecast/usage?tabs=HTTP
This is my request body looks like
{
"Dataset": {
"Aggregation": {
"TotalCost": {
"Function": "Sum",
"Name": "Cost"
}
},
"Granularity": "Monthly"
},
"TimePeriod": {
"From": "2023-02-01",
"To": "2023-02-28"
},
"Timeframe": "Custom",
"Type": "Usage"
}
Everything is working if i did the request not in the 1st day of month. But when i make a request to API in 1st day of month, the request is success and the API give me a response, but i can't find any information related to forecast cost amount.
I can see the forecast cost from the Azure portal, so i believe there must be a way to retrieve the data. Help me please?
Thanks.
I have try to modify the timeframe, granularity, and others in the request body. But still can't get the data.
Check the datetime you are using is the same as what is being used on Azure for the service/plan/account or whatever, these can differ on both sides.It could also be that Azure requires the datetime in GMT or a US format.
So it may be that your request is being read as last month, but azure is only providing data for this in the upcoming month.
To test this try switching to prior dates and see if any dates in the past give you the same data as what you are getting on the 1st. If so I would say that is what is happening.
The fact it only occurs on the first but the data is available in the portal would indicate to me it is definitely something to do with the timezone, but I could be wrong.
Personally I use Azure Cost Management connector in Power BI Desktop to retrieve the data. I scheduled a daily refresh and I never had problems.
I know for sure that there are problems with calculation in the early days of the month and I have a colleague that withdraw the last month after the first week.
I suggest you to open a ticket with the Azure Billing support.

Get local datetime instead of server DateTime in server side code C#

I am using ASP MVC 4.5. I have view to input payment details. I use C# to get current time when user input payment. But after hosting it on server, i found a hot error. It gets another dateTime (may be my server's time) instead of my user's local time!
I want to get user's current time using C#. Should i use C# or javascript?
I think it is easy to get user's time using javascript. But i want to use C# for this. Can you help me?
My web API:
// POST api/PaymentApi
public HttpResponseMessage PostPayment(Payment payment)
{
if (ModelState.IsValid)
{
var mem= db.Members.Where(m => m.MemberID.Equals(payment.MemberID)).FirstOrDefault();
if (mem ==null)
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
payment.Date = DateTime.Now;
db.Payments.Add(payment);
db.SaveChanges();
HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.Created, payment);
response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = payment.PaymentID }));
return response;
}
else
{
return Request.CreateErrorResponse(HttpStatusCode.BadRequest, ModelState);
}
}
I used payment.Date = DateTime.Now.ToLocalTime(); also but not worked!
Many of here answered to use javascript date. That's why i used it. But javascript sends a datetime and my WebApi makes it slightly different.
Javascript: Date:Tue Dec 27 2016 11:04:12 GMT+0600 (Local Standard Time)
C#: Date:{27/12/2016 05:04:12}
It's impossible to get client DateTime at server-side if client is not sending it by itself.
You'll need to get the local date time in javascript and pass it to the server. I recommend you to use ISO8601 format.
DateTime works with local host's clock, e.g. the server. Most payments systems save the dates as relative to UTC, to avoid client/server time differences.
payment.Date = DateTime.UtcNow;
There isn't any way to know the user Local time from the server. What you need to do is send the local time from the client to the server inside the request in UTC format.
Javascript(requires Jquery):
var UTC = new Date().getTime();

How to correctly set expiration datetime for cookies on ASP.NET Core MVC

I'm trying to set a Cookie to the browser from back-end (Asp.Net core) which should expire on the next day same time minus 5 minutes. Here is the C# code from controller
HttpContext.Response.Cookies.Append("MyCookie",
"test cookie value",
new Microsoft.AspNetCore.Http.CookieOptions
{
Expires = DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
});
But to the browser it is coming with wrong expiration DateTime.
For example if cookie expiration date was set to 2016-09-28 19:15, on the browser it will expire at 2016-09-29T17:15, and it is 2 hours less, which is weird because my time zone is +1.
DateTimeOffset.UtcNow is DateTimeOffset.Now + yourTimezone.
So
DateTimeOffset.UtcNow.AddDays(1).AddMinutes(-5)
Will return the same as
DateTimeOffset.Now.AddDays(1).AddMinutes(-5).AddHours(-2 /*your Timezone*/)
Browser showed everything right.
Change your code to
HttpContext.Response.Cookies.Append("MyCookie",
"test cookie value",
new Microsoft.AspNetCore.Http.CookieOptions
{
Expires = DateTimeOffset.Now.AddDays(1).AddMinutes(-5)
});
//if you want to have the same expiration date as your server's
or use UtcNow + client's timezone

The specified time zone isn't valid - using EWS from server

I set appointment in MS Exchange from ASP.NET MVC application.
When i run code from my computer in Ukraine - everyghing is ok,
but when I deploy my code on server in Russia - it shows:
The specified time zone isn't valid.
I tried a lot of things but can't fix that. Please help me with this issue.
I use:
Appointment appointment = new Appointment(service);
appointmet.Start;
If some people just come accross the same issue, it has been reported as an issue in EWS api (cf https://github.com/OfficeDev/ews-managed-api/issues/13) but seems most likely an issue in .NET's TimeZoneInfo parsing logic. An update of your .Net version might fix it.
This worked for me:
static TimeZoneInfo getCorrectTimeZone()
{
return TimeZoneInfo.CreateCustomTimeZone("Time zone to workaround a bug", TimeZoneInfo.Local.BaseUtcOffset, "Time zone to workaround a bug", "Time zone to workaround a bug");
}
static ExchangeService getExchangeService()
{
var service = new ExchangeService(ExchangeVersion.Exchange2010_SP2, getCorrectTimeZone());
return service;
}

Does Decrypting a cookie convert it to local time?

I have my own asp.net cookie created like this:
var authTicket = new FormsAuthenticationTicket(
version,
userName,
DateTime.UtcNow,
DateTime.UtcNow.AddMinutes(30),
createPersistentCookie,
userData,
"/");
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
As you can see everything is in UTC time.
When I decrypt it:
var cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);
if (cookie != null)
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
return ticket.Expiration.Ticks;
}
else
{
return 0;
}
It returns local time. So, does it get converted automatically or is it something else? If so how can I get it back to UTC time?
From MSDN:
FormsAuthenticationTicket.Expiration Property
Gets the local date and time at which the forms-authentication ticket expires.
You can use the DateTime.ToUniversalTime method to convert a DateTime to UTC:
return ticket.Expiration.ToUniversalTime().Ticks;
As you've seen, once the FormsAuthenticationTicket has been serialized to a cookie and deserialized, the Expiration and Issue times will always be local.
The Remarks section in MSDN says "If the FormsAuthenticationTicket was created using a constructor that takes an expiration parameter, the Expiration property returns the value supplied to the expiration parameter.". Hence if you pass UTC, you will get back UTC until the ticket has been serialized/deserialized, after which it will be converted to local.
If you supply issueDate and expiration to the constructor, they should normally be in local time. However no attempt is made to convert them to local time - probably the reason for this is for backwards compatibility with .NET 1.x.
With .NET 1.x the DateTime struct did not have a "Kind" property, so there was no way to tell it the caller supplied UTC or local time - it was just assumed to be local.
Therefore I suggest you change your code to pass local time to the FormsAuthenticationTicket constructor, though it does expose you to this bug recorded on Microsoft Connect.

Categories