Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Know Your Cloud Resource Costs on Azure
public async Task SaveResourceGroupCostsResultsAsync(Subscription subscription, IEnumerable<ResourceGroupCostResult> results)
{
var now = DateTimeOffset.UtcNow;
foreach (var result in results)
{
var totalSpendLimit = Convert.ToDecimal(result.TotalSpendLimit);
var dailySpendLimit = Convert.ToDecimal(result.DailySpendLimit);
var overspendAction = result.OverspendAction;
var record = await this._dbContext.ResourceGroupCostHistories
.SingleOrDefaultAsync(p => p.Subscription.Equals(subscription.DisplayName, StringComparison.CurrentCultureIgnoreCase) &&
p.ResourceGroupName.Equals(result.ResourceGroupName, StringComparison.CurrentCultureIgnoreCase) &&
p.Owners.Equals(result.OwnerEmails, StringComparison.CurrentCultureIgnoreCase) &&
p.DateStart == result.DateStart &&
p.DateEnd == result.DateEnd)
.ConfigureAwait(false);
if (record == null)
{
record = new ResourceGroupCostHistory()
{
ResourceGroupCostHistoryId = Guid.NewGuid(),
Subscription = subscription.DisplayName,
SubscriptionId = Guid.Parse(subscription.SubscriptionId),
ResourceGroupName = result.ResourceGroupName,
Owners = result.OwnerEmails,
DateStart = result.DateStart,
DateEnd = result.DateEnd,
DateCreated = now
};
}
record.Cost = Convert.ToDecimal(result.Cost);
record.TotalSpendLimit = totalSpendLimit;
record.DailySpendLimit = dailySpendLimit;
record.OverspendAction = overspendAction;
record.DateUpdated = now;
this._dbContext.ResourceGroupCostHistories.AddOrUpdate(record);
}
await this._dbContext.SaveChangesAsync().ConfigureAwait(false);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment