using System.Net.Http.Headers;
using System.Threading.Tasks;
using Microsoft.Azure.Cosmos;
using Microsoft.Azure.Services.AppAuthentication;
using Microsoft.Azure.WebJobs;
using Microsoft.Extensions.Logging;
public static class FishTankTemperatureService
private static string subscriptionId =
"<azure subscription id>";
private static string resourceGroupName =
"<name of your azure resource group>";
private static string accountName =
"<Azure Cosmos DB account name>";
private static string cosmosDbEndpoint =
"<Azure Cosmos DB endpoint>";
private static string databaseName =
"<Azure Cosmos DB name>";
private static string containerName =
"<container to store the temperature in>";
[FunctionName("FishTankTemperatureService")]
public static async Task Run([TimerTrigger("0 * * * * *")]TimerInfo myTimer, ILogger log)
log.LogInformation($"Starting temperature monitoring: {DateTime.Now}");
var azureServiceTokenProvider = new AzureServiceTokenProvider();
string accessToken = await azureServiceTokenProvider.GetAccessTokenAsync("https://management.azure.com/");
string endpoint = $"https://management.azure.com/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DocumentDB/databaseAccounts/{accountName}/listKeys?api-version=2019-12-12";
HttpClient httpClient = new HttpClient();
httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
var result = await httpClient.PostAsync(endpoint, new StringContent(""));
DatabaseAccountListKeysResult keys = await result.Content.ReadAsAsync<DatabaseAccountListKeysResult>();
log.LogInformation("Starting to create the client");
CosmosClient client = new CosmosClient(cosmosDbEndpoint, keys.primaryMasterKey);
log.LogInformation("Client created");
var database = client.GetDatabase(databaseName);
var container = database.GetContainer(containerName);
log.LogInformation("Get the temperature.");
var tempRecord = new TemperatureRecord() { RecordTime = DateTime.UtcNow, Temperature = GetTemperature() };
log.LogInformation("Store temperature");
await container.CreateItemAsync<TemperatureRecord>(tempRecord);
log.LogInformation($"Ending temperature monitor: {DateTime.Now}");
private static int GetTemperature()
Random r = new Random(DateTime.UtcNow.Second);
public class DatabaseAccountListKeysResult
public string primaryMasterKey {get;set;}
public string primaryReadonlyMasterKey {get; set;}
public string secondaryMasterKey {get; set;}
public string secondaryReadonlyMasterKey {get;set;}
public class TemperatureRecord
public string id { get; set; } = Guid.NewGuid().ToString();
public DateTime RecordTime { get; set; }
public int Temperature { get; set; }