Sunday, November 11, 2018

Functions binding Cosmos DB, C# -- 1

I was trying Cosmos DB binding for Azure Functions, and want to share what I learned. This is a basic skill for Azure users because it uses Cosmos DB that can handle Json files easily, and Azure Functions that manages http requests. Below is the system configuration.


Environment setup
Visual Studio 2017
  Azure Functions and Web Jobs Tools
  Microsoft.NET.Sdk.Functions
  Microsoft.Azure.WebJobs.Extensions.ComosDB

Cosmos DB
  Database Name: "VehicleSpec"
  Collection Name: "Vehicles"
  Connection String: <CosmosDBConnectionString>

The Cosmos DB has 10 documents below.

"id": "d7b70f4a-6cb0-e56d-2c41-1698a5a2bb0b"


"id": "c4b2088f-85c1-c616-02c9-0f6f69e47a08"


"id": "2ea20ecf-9087-3327-01ee-71a724954e3b"


"id": "1af97a2a-3a53-96ec-c470-dc13622f1dc0"


"id": "a273e3ad-058f-d456-2256-ff10baabcf5d"


"id": "343d27e7-261f-3a6f-3981-35610f2c7671"


"id": "f91cd57d-e45f-7cc7-8dcd-5f2d8099c47a"


"id": "d01aacba-2eeb-5c4a-6578-1852a2b4f0fe"


"id": "ef47cfc3-0639-cf06-904a-8db1ebf95cef"


Sample Code
1. Read a single document, looking up "id" from query string
2. local.settings.json
3. Read a single document, looking up "id" from route data
4. Extract specific json properties
5. Read multiple documents

1. Read a single document, looking up "id" from query string

VehicleList.cs


local.settings.json


GetDocument.cs





Sample request query and return


Point 1
Query string should be exact match

Point 2
When you set a wrong name of Cosmos DB database or collection, it returns "status": 400

Poitnt 3
For VehicleList class, type Guid is used, but string also works

2. local.settings.json
It is recommended that you develop Azure Functions locally using Visual Studio or Visual Studio Code. I do not find clarification in the official document, but you do not need to edit function.json by yourself, but it is automatically generated when you set up local.setting.json.
One thing I learned here is, if you do not want to describe the Cosmos DB setup parameters such as Database Name or Collection Name on Main method, you can pass it to local.settings.json. You can use Attribute property in between %, for example, databaseName: "%DatabaseName%" like below.
GetDocument.cs


local.settings.json


3. Read a single document, looking up "id" from route data

GetDocumentRoute.cs




Sample request query and return