Cheat Sheet: Azure SDKs
azure
Series of short snippets of FUC. This one is for Azure SDKs.
August 21, 2018
I often find myself searching the internet for the same four lines of C# all over again, because of my inability to remember anything and the complexity of my filesystem structure... That's why I decided to start putting together quick snippets of frequently used code (FUC).
This one is about various Azure SDKs I work with.
It's a living document, I've been updating it over time.
Storage Tables
Update: There's an SDK specifically for Azure Tables now - Azure.Data.Tables
.
NuGet:
Install-Package Azure.Data.Tables
Create table client:
var tableClient = new TableClient("<connection string>", "<table name>");
tableClient.CreateIfNotExists();
Insert entity:
var entity = new TableEntity("<partition key>", "<row key>");
entity.Add("MyObject", System.Text.Json.JsonSerializer.Serialize(fullObject));
await tableClient.AddEntityAsync(entity);
Deprecated approach using the Cosmos.Table SDK:
There's new NuGet library for working with Storage Tables - coming from the effort to unify traditional Tables and Cosmos DB Table API.
NuGet:
Install-Package Microsoft.Azure.Cosmos.Table
Create table client:
var storageAccount = CloudStorageAccount.Parse("<connection string>");
var tableClient = storageAccount.CreateCloudTableClient();
var table = tableClient.GetTableReference("<table name>");
table.CreateIfNotExistsAsync();
List entities in partition:
var query = new TableQuery<MyEntity>().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, "<pk>"));
IEnumerable<MyEntity> res = table.ExecuteQuery(query);
Get single entity:
TableOperation retrieveOperation = TableOperation.Retrieve<MyEntity>(partitionKey, rowKey);
TableResult retrievedResult = table.Execute(retrieveOperation);
if (retrievedResult.Result != null)
{
// found
}
else
{
// not found
}
Insert entity:
TableOperation insertOperation = TableOperation.Insert(entity1);
table.Execute(insertOperation);
Replace entity:
TableOperation updateOperation = TableOperation.Replace(entity2);
table.Execute(updateOperation);
Storage Blobs
NuGet:
Microsoft.Azure.Storage.Blob
Upload file into blob:
static async Task UploadFileToBlob(string connectionString, string containerName, string fileName, string content)
{
if (!CloudStorageAccount.TryParse(connectionString, out CloudStorageAccount cloudStorageAccount))
{
Console.Error.WriteLine("Unable to parse storage connection string.");
return;
}
CloudBlobClient cloudBlobClient = cloudStorageAccount.CreateCloudBlobClient();
CloudBlobContainer blobContainer = cloudBlobClient.GetContainerReference(containerName);
await blobContainer.CreateIfNotExistsAsync();
CloudBlockBlob cloudBlockBlob = blobContainer.GetBlockBlobReference(fileName);
await cloudBlockBlob.UploadTextAsync(content); // upload text directly
// await cloudBlockBlob.UploadFromFileAsync(filePath); // upload file
}
Change content type when uploading block blob:
var blob = logsContainer.GetBlockBlobReference(blobName);
blob.Properties.ContentType = "text/plain";
await blob.UploadTextAsync(blobContent);
Azure Functions - HTTP
To change route for a particular function, edit host.json
:
{
"http": {
"routePrefix": "" // empty string removes the 'api' prefix
}
}
Then in function.json
set route
:
{
"bindings": [
{
"type": "httpTrigger",
"direction": "in",
"name": "req",
"methods": [
"get",
"post"
],
"authLevel": "anonymous",
"route": "myroute"
},
...
}
(Or do it in C# as the [HttpTrigger] attribute.)
Azure Resource Manager
A few quick and dirty snippets, since it's impossible to remember everything when working with ARM.
Possible uses of list* function in Docs
Application Insights Instrumentation Key
Azure Functions provide native support for Application Insights telemetry, you only need to define the APPINSIGHTS_INSTRUMENTATIONKEY
application setting and ARM provides the value:
"properties": {
"siteConfig": {
"appSettings": [
...
{
"name": "APPINSIGHTS_INSTRUMENTATIONKEY",
"value": "[reference(parameters('insights_name')).InstrumentationKey]"
}
...
]
}
},
Cognitive Services keys
Translator/Speech/Vision:
[listKeys(parameters('translator_name'), '2016-02-01-preview').key1]
As Output:
"speechServiceKey": {
"type": "string",
"value": "[listKeys(resourceId('Microsoft.CognitiveServices/accounts', variables('accounts_speech_service_name')), '2016-02-01-preview').key1]"
}
Event Grid
Key:
[listKeys(parameters('transcript_grid_name'), '2018-01-01').key1]
Storage
Key:
[concat('DefaultEndpointsProtocol=https;AccountName=', parameters('storage_account_name'),';AccountKey=',listKeys(resourceId('Microsoft.Storage/storageAccounts', parameters('storage_account_name')), providers('Microsoft.Storage', 'storageAccounts').apiVersions[0]).keys[0].value)]
Logic Apps
HTTP trigger URL:
[listCallbackURL(resourceId('Microsoft.Logic/workflows/triggers', parameters('logicAppName'), 'manual'), '2016-06-01').value]
[listCallbackURL(resourceId('Microsoft.Logic/workflows/triggers', parameters('logicAppName'), 'Request'), '2016-06-01').value]
Feedback
Found something inaccurate or plain wrong? Was this content helpful to you? Let me know!
š§ codez@deedx.cz