{"id":520,"date":"2020-03-11T09:00:10","date_gmt":"2020-03-11T16:00:10","guid":{"rendered":"http:\/\/devblogs.microsoft.com\/cosmosdb\/?p=520"},"modified":"2020-04-20T11:39:55","modified_gmt":"2020-04-20T18:39:55","slug":"cosmos-db-function-trigger-2-min","status":"publish","type":"post","link":"https:\/\/devblogs.microsoft.com\/cosmosdb\/cosmos-db-function-trigger-2-min\/","title":{"rendered":"Create a .NET Azure Cosmos DB Function Trigger using Visual Studio Code in 2 minutes!"},"content":{"rendered":"<p>&nbsp;<\/p>\n<p>Creating event sourcing solutions with Azure Cosmos DB is easy with <a href=\"https:\/\/docs.microsoft.com\/azure\/azure-functions\/functions-create-cosmos-db-triggered-function\">Azure Functions Triggers,<\/a> where you can leverage the <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/change-feed-processor\" data-linktype=\"relative-path\">Change Feed Processor<\/a>&#8216;s powerful scaling and reliable event detection functionality, without the need to maintain any <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/change-feed-processor\" data-linktype=\"relative-path\">worker infrastructure<\/a>. You can just focus on your Azure Function&#8217;s logic without worrying about the rest of the event-sourcing pipeline. In this blog, we have some quick how-to videos to get you up and running with .NET Azure Cosmos DB Functions Triggers!<\/p>\n<p>If you want to follow along, there are some pre-requisites you should have in place:<\/p>\n<ul>\n<li>Ideally a Windows 10 Machine.<\/li>\n<li>Access to an Azure subscription, and an Azure Cosmos DB account &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/create-cosmosdb-resources-portal\">here<\/a>.<\/li>\n<li>.NET Core installed &#8211; instructions <a href=\"https:\/\/dotnet.microsoft.com\/download\">here<\/a>.<\/li>\n<li>Visual Studio Code installed &#8211; instructions <a href=\"https:\/\/code.visualstudio.com\/download\">here<\/a>.<\/li>\n<li>Azure Storage Emulator installed (<strong>make sure this is running<\/strong> before trying to follow the demo) &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/azure\/storage\/common\/storage-use-emulator\">here.<\/a><\/li>\n<li>Azure Functions Core Tools installed &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/en-gb\/azure\/azure-functions\/functions-run-local?tabs=windows%2Ccsharp%2Cbash#install-the-azure-functions-core-tools\">here<\/a> (we recommend v3.x &#8211; note that this requires installing <a href=\"https:\/\/docs.npmjs.com\/downloading-and-installing-node-js-and-npm\">Node.js<\/a>).<\/li>\n<li>Azure Functions Extension installed &#8211; you should have Azure Functions Core Tools and VS code already installed, and access to an Azure subscription for sign-in, before attempting to install this extension) &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/azure\/azure-functions\/functions-develop-vs-code?tabs=csharp#install-the-azure-functions-extension\">here.<\/a><\/li>\n<\/ul>\n<p>Create an Azure Cosmos DB Functions Trigger in .NET with VS Code&#8230; in 2 minutes!<\/p>\n<p><iframe title=\"Create Azure Cosmos DB Functions Trigger (.NET) in 2 minutes!\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/VaAzqxutm34?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>&nbsp;<\/p>\n<p>Next, you can turn your function into a simple event sourcing solution, which streams updates and inserts from one collection into another, by replacing the boiler plate code with the below:<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true\">using System;\r\nusing System.Threading.Tasks;\r\nusing System.Collections.Generic;\r\nusing Microsoft.Azure.Documents;\r\nusing Microsoft.Azure.WebJobs;\r\nusing Microsoft.Azure.WebJobs.Host;\r\nusing Microsoft.Extensions.Logging;\r\n\r\nusing Microsoft.Azure.Cosmos;\r\n\r\nnamespace Company.Function\r\n{\r\n    public static class CosmosDBTriggerCSharp1\r\n    {\r\n        private static readonly string _endpointUrl = System.Environment.GetEnvironmentVariable(\"endpointUrl\");                \r\n        private static readonly string _primaryKey = System.Environment.GetEnvironmentVariable(\"primaryKey\");\r\n        private static readonly string _databaseId = \"database\";\r\n        private static readonly string _containerId = \"collection2\";\r\n        private static CosmosClient cosmosClient = new CosmosClient(_endpointUrl, _primaryKey);\r\n\r\n\r\n        [FunctionName(\"CosmosDBTriggerCSharp1\")]\r\n        public static async Task Run([CosmosDBTrigger(\r\n            databaseName: \"database\",\r\n            collectionName: \"collection1\",\r\n            ConnectionStringSetting = \"cosmosdbtvk_DOCUMENTDB\",\r\n            LeaseCollectionName = \"leases\",\r\n            CreateLeaseCollectionIfNotExists = true)]IReadOnlyList&lt;Document&gt; input, ILogger log)\r\n        {\r\n\r\n            var container2 = cosmosClient.GetContainer(_databaseId, _containerId);\r\n\r\n            foreach(Document doc in input){\r\n                log.LogInformation(\"pushed doc into container 2\");\r\n                log.LogInformation(\"doc: \"+doc);\r\n                try{\r\n                    await container2.CreateItemAsync&lt;Document&gt;(doc);\r\n                }\r\n                catch (Exception e) {\r\n                        log.LogInformation(\"Exception pushing doc into container 2: \"+e);\r\n                }\r\n                \r\n            }\r\n        }\r\n    }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>Make sure you install the latest Azure Cosmos DB .NET SDK. In terminal, run the following:<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"theme:powershell lang:default decode:true\">dotnet add package Microsoft.Azure.Cosmos<\/pre>\n<p>&nbsp;<\/p>\n<p>Your local.settings.json should also be updated to look something like this (note the &#8220;endpointUrl&#8221; and &#8220;primaryKey&#8221; added for the target collection):<\/p>\n<p>&nbsp;<\/p>\n<pre class=\"lang:default decode:true\">{\r\n  \"IsEncrypted\": false,\r\n  \"Values\": {\r\n    \"AzureWebJobsStorage\": \"UseDevelopmentStorage=true\",\r\n    \"FUNCTIONS_WORKER_RUNTIME\": \"dotnet\",\r\n    \"cosmosdbtvk_DOCUMENTDB\": \"&lt;PRIMARY CONNECTION STRING OF SOURCE COLLECTION&gt;\",\r\n    \"endpointUrl\":\"&lt;URI OF TARGET COLLECTION&gt;\",\r\n    \"primaryKey\": \"&lt;PRIMARY KEY OF TARGET COLLECTION&gt;\"\r\n  }\r\n}<\/pre>\n<p>&nbsp;<\/p>\n<p>Watch the video below to see how to deploy to Azure! To follow along with this video, you should have the pre-requisites from the above video already installed, plus the following:<\/p>\n<ul>\n<li>Azure CLI &#8211; instructions <a href=\"https:\/\/docs.microsoft.com\/cli\/azure\/install-azure-cli?view=azure-cli-latest\">here<\/a>.<\/li>\n<li>The Azure Cosmos DB<a href=\"https:\/\/www.nuget.org\/packages\/Microsoft.Azure.Cosmos\/\"> Core (SQL) API .NET SDK<\/a> at version 3.6.0 or higher<\/li>\n<li>NuGet Package Manager for VS code &#8211; instructions <a href=\"https:\/\/marketplace.visualstudio.com\/items?itemName=jmrog.vscode-nuget-package-manager\">here<\/a> (you would need this to install the latest version of the Azure Cosmos DB .NET SDK &#8211; this is illustrated but not installed during the video).<\/li>\n<\/ul>\n<p>&nbsp;<\/p>\n<p><iframe title=\"How to deploy event sourcing solution for Azure Cosmos DB with Azure Functions + .NET in 7 minutes\" width=\"500\" height=\"375\" src=\"https:\/\/www.youtube.com\/embed\/hfVXRsPYMuE?feature=oembed\" frameborder=\"0\" allow=\"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share\" referrerpolicy=\"strict-origin-when-cross-origin\" allowfullscreen><\/iframe><\/p>\n<p>For more information about Azure Cosmos DB&#8217;s change feed and it&#8217;s use cases, go <a href=\"https:\/\/docs.microsoft.com\/en-us\/azure\/cosmos-db\/change-feed\">here<\/a>!<\/p>\n<p>For the official documentation on creating an Azure Function triggered by Azure Cosmos DB, go <a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/change-feed-functions\">here<\/a>!<\/p>\n<p>For more depth on Azure Cosmos DB Change Feed, try our labs <a href=\"https:\/\/cosmosdb.github.io\/labs\/\">here<\/a>!<\/p>\n<h2><span style=\"font-size: 14pt;\"><strong>Get started<\/strong><\/span><\/h2>\n<p>Create a new account using the Azure Portal, ARM template or Azure CLI and connect to it using your favourite tools.\u00a0Stay up-to-date on the latest Azure\u202f<a href=\"https:\/\/twitter.com\/search?q=%23cosmosdb\">#CosmosDB<\/a>\u202fnews and features by following us on Twitter\u202f<a href=\"https:\/\/twitter.com\/azurecosmosdb\">@AzureCosmosDB<\/a>. We are really excited to see what you will build with Azure Cosmos DB!<\/p>\n<h2><span style=\"font-size: 14pt;\">About Azure Cosmos DB<\/span><\/h2>\n<p><a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/introduction\">Azure Cosmos DB<\/a> is a globally distributed, multi-model database service that enables you to read and write data from any Azure region. It offers <a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/distribute-data-globally\">turnkey global distribution<\/a>, guarantees\u00a0<a href=\"https:\/\/azure.microsoft.com\/support\/legal\/sla\/cosmos-db\/v1_3\/\">single-digit millisecond<\/a> latency at the 99<sup>th<\/sup>\u00a0percentile, 99.999 percent\u00a0<a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/high-availability\">high availability<\/a>, with <a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/scaling-throughput\">elastic scaling<\/a>\u00a0of\u00a0<a href=\"https:\/\/docs.microsoft.com\/azure\/cosmos-db\/request-units\">throughput and storage<\/a>.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>&nbsp; Creating event sourcing solutions with Azure Cosmos DB is easy with Azure Functions Triggers, where you can leverage the Change Feed Processor&#8216;s powerful scaling and reliable event detection functionality, without the need to maintain any worker infrastructure. You can just focus on your Azure Function&#8217;s logic without worrying about the rest of the event-sourcing [&hellip;]<\/p>\n","protected":false},"author":9387,"featured_media":551,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"video","meta":{"_acf_changed":false,"footnotes":""},"categories":[19],"tags":[539,499,536,500,497,498],"class_list":["post-520","post","type-post","status-publish","format-video","has-post-thumbnail","hentry","category-tips-and-tricks","tag-net","tag-azure-cosmos-db","tag-azure-functions-trigger","tag-change-feed","tag-event-sourcing","tag-visual-studio-code","post_format-post-format-video"],"acf":[],"blog_post_summary":"<p>&nbsp; Creating event sourcing solutions with Azure Cosmos DB is easy with Azure Functions Triggers, where you can leverage the Change Feed Processor&#8216;s powerful scaling and reliable event detection functionality, without the need to maintain any worker infrastructure. You can just focus on your Azure Function&#8217;s logic without worrying about the rest of the event-sourcing [&hellip;]<\/p>\n","_links":{"self":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/520","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/users\/9387"}],"replies":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/comments?post=520"}],"version-history":[{"count":0,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/posts\/520\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media\/551"}],"wp:attachment":[{"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/media?parent=520"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/categories?post=520"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/devblogs.microsoft.com\/cosmosdb\/wp-json\/wp\/v2\/tags?post=520"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}