Cheat Sheet: Azure SDKs

Series of short snippets of FUC. This one is for Azure SDKs.
August 21, 2018
azure

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

There’s new NuGet library for working with Storage Tables - coming from the effort to unify traditional Tables and Cosmos DB Table API.

Do NOT use .NET Core - as of today (June 2nd) there’s no support with this newer library.

NuGet:

Install-Package Microsoft.Azure.DocumentDB
Install-Package Microsoft.Azure.Storage.Common –IncludePrerelease -Version 9.0.0.1-preview
Install-Package Microsoft.Azure.CosmosDB.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

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]
comments powered by Disqus