<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mohamed Mohsen on Medium]]></title>
        <description><![CDATA[Stories by Mohamed Mohsen on Medium]]></description>
        <link>https://medium.com/@mohamed.ebrahim.mohsen?source=rss-abd0cf67189c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*9Hvmom3-OHaACOhIIrD0fQ.jpeg</url>
            <title>Stories by Mohamed Mohsen on Medium</title>
            <link>https://medium.com/@mohamed.ebrahim.mohsen?source=rss-abd0cf67189c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 12:10:21 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mohamed.ebrahim.mohsen/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Azure Resource Manager ARM Templates (Azure IaaC)]]></title>
            <link>https://levelup.gitconnected.com/azure-resource-manager-arm-templates-azure-iaac-5d50034f374f?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d50034f374f</guid>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cloud-computing]]></category>
            <category><![CDATA[cloud]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[infrastructure-as-code]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Thu, 27 Jun 2024 13:06:40 GMT</pubDate>
            <atom:updated>2024-06-27T13:06:40.828Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04vIx2fDXo4I_pPS-ikM0g.jpeg" /></figure><h3>What &amp; Why?</h3><p>When dealing with cloud infrastructure, as your application starts to utilize more cloud resources and you begin to have multiple environments such as Development, Testing, and Production, you will find the need for a consistent way to deploy the same infrastructure across all environments without modifications.</p><p>This is where Azure Resource Manager (ARM) comes into play. ARM allows you to configure your infrastructure once and then use parameterization to deploy it across multiple environments seamlessly, regardless of their number.</p><h3>Our Goal</h3><p>Our goal is to learn how to create ARM templates, understand any ARM templates you come across, and explore the various methods of deploying ARM templates. Additionally, we will learn how to organize your templates by leveraging the use of template parameter files.</p><h3>ARM Development Tools</h3><p>To make your development process easier with features like autocomplete and IntelliSense, we can start by installing the following Visual Studio Code extensions:</p><ul><li><a href="https://code.visualstudio.com/docs/azure/extensions">Azure Tools</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=msazurermtools.azurerm-vscode-tools#:~:text=The%20Azure%20Resource%20Manager%20(ARM,validate%20Azure%20Resource%20Manager%20templates.">Azure Resource Manager (ARM) Tools</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=bencoleman.armview">ARM Template Viewer</a></li></ul><h3>ARM Template Scheme</h3><p>Every ARM template follows a specific scheme, which can be quickly generated by typing arm and pressing tab for autocomplete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*3JOguF8acV9D8fFWj5PUWA.png" /></figure><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {},<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {},<br>    &quot;resources&quot;: [],<br>    &quot;outputs&quot;: {}<br>}</pre><p>Let’s break down the components of the scheme.</p><h4><strong>$schema</strong></h4><p>This defines the version of the ARM template itself, determining the properties to be used and how the template will be compiled and deployed with the Azure engine.</p><p>The version is date-based, for example, the version used above here is 2019–04–01 .</p><h4><strong>contentVersion</strong></h4><p>This is your version of the template, so feel free to change or update it as needed.</p><h4><strong>parameters</strong></h4><p>Parameters define the acceptable inputs for the template, similar to function parameters. You specify the name, type, and optionally other attributes like default values.</p><pre>// here a &amp; b are paremeters for MyFunction<br>MyFunction(string a, string b = &quot;hello&quot;)</pre><p>Here is an example of how to define parameters in an ARM template:</p><pre>&quot;parameters&quot;: {<br>        &quot;a&quot;: {<br>            &quot;type&quot;: &quot;string&quot; //required<br>        },<br>        &quot;b&quot;: {<br>            &quot;type&quot;: &quot;string&quot;, //required<br>            &quot;defaultValue&quot;: &quot;hello&quot;<br>        }<br>    }</pre><p>As shown in the above JSON, it is similar to defining function parameters. Like in functions, a parameter type is required and cannot be omitted.</p><h4><strong>variables</strong></h4><p>Variables hold computed values that you may want to reuse multiple times. This allows you to update the value in one place and have it propagate throughout the template.</p><p>For example, if you want to use the resource group location multiple times, you can compute it once like this</p><pre>&quot;variables&quot;: {<br>    &quot;location&quot;: &quot;[resourceGroup().location]&quot;<br>}</pre><p>[resourceGroup().location] is an ARM built-in function returns the resource group location.</p><p>You might wonder why not use this in the default value of parameters. While you can, later in this article you will see how you can extract the parameters in a separate file, and in this parameters file you can’t use any functions. <em>it’s better to keep them separate because parameters in an external file cannot use functions.</em></p><p>You can also create composite values using parameters in variables, such as naming your service with the format AppName-Location-Environment</p><pre>&quot;parameters&quot;: {<br>    &quot;app&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;defaultValue&quot;: &quot;myapp&quot;<br>    },<br>    &quot;env&quot;: {<br>        &quot;type&quot;: &quot;string&quot;,<br>        &quot;defaultValue&quot;: &quot;dev&quot;<br>    }<br>},<br>&quot;variables&quot;: {<br>    &quot;name&quot;: &quot;[concat(parameters(&#39;app&#39;), &#39;-&#39;, resourceGroup().location, &#39;-&#39; , parameters(&#39;env&#39;))]&quot;<br>}</pre><h4><strong>resources</strong></h4><p>This section is where you configure all your Azure resources. We will focus on this part in the article to demonstrate resource configuration.</p><h4><strong>output</strong></h4><p>This section returns variables from the template execution as output.</p><h4><strong>functions (advanced)</strong></h4><p>In ARM templates, you can declare functions to use within the template, but there are some restrictions:</p><ul><li>Functions can’t access variables.</li><li>Functions can only use parameters defined within them. When using parameters within a user-defined function, you are restricted to the parameters for that function.</li><li>Functions can’t call other user-defined functions.</li><li>Functions can’t use the reference function.</li><li>Parameters for the function can’t have default values.</li></ul><p>Below is a <a href="https://learn.microsoft.com/en-us/azure/azure-resource-manager/templates/user-defined-functions">Microsoft example</a> of creating a user-defined function, and a link to a useful <a href="https://dev.to/omiossec/infra-as-code-user-defined-functions-in-arm-templates-987">post</a> about user-defined functions.</p><pre>{<br> &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br> &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br> &quot;parameters&quot;: {<br>   &quot;storageNamePrefix&quot;: {<br>     &quot;type&quot;: &quot;string&quot;,<br>     &quot;maxLength&quot;: 11<br>   }<br> },<br> &quot;functions&quot;: [<br>  {<br>    &quot;namespace&quot;: &quot;contoso&quot;,<br>    &quot;members&quot;: {<br>      &quot;uniqueName&quot;: {<br>        &quot;parameters&quot;: [<br>          {<br>            &quot;name&quot;: &quot;namePrefix&quot;,<br>            &quot;type&quot;: &quot;string&quot;<br>          }<br>        ],<br>        &quot;output&quot;: {<br>          &quot;type&quot;: &quot;string&quot;,<br>          &quot;value&quot;: &quot;[concat(toLower(parameters(&#39;namePrefix&#39;)), uniqueString(resourceGroup().id))]&quot;<br>        }<br>      }<br>    }<br>  }<br>],<br> &quot;resources&quot;: [<br>   {<br>     &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>     &quot;apiVersion&quot;: &quot;2022-09-01&quot;,<br>     &quot;name&quot;: &quot;[contoso.uniqueName(parameters(&#39;storageNamePrefix&#39;))]&quot;,<br>     &quot;location&quot;: &quot;South Central US&quot;,<br>     &quot;sku&quot;: {<br>       &quot;name&quot;: &quot;Standard_LRS&quot;<br>     },<br>     &quot;kind&quot;: &quot;StorageV2&quot;,<br>     &quot;properties&quot;: {<br>       &quot;supportsHttpsTrafficOnly&quot;: true<br>     }<br>   }<br> ]<br>}</pre><h3>First ARM Template</h3><p>Let’s create an ARM template with a single resource, a storage account, and give it a unique random name with a prefix of our application name and a suffix for the environment.</p><p>First, create an empty ARM template named myapp.dev.template.json.</p><p>You have several options to start:</p><ul><li>Generate an ARM template from the Azure Portal.</li><li>Create it from scratch with the help of IntelliSense.</li><li>Use a quick start template from a popular GitHub repository.</li><li>Combine a generated ARM template from the Azure Portal with an empty template created from scratch with IntelliSense.</li></ul><p>Let’s discuss these options one by one.</p><h4>1. Generated ARM Template from the Azure Portal</h4><p>Go to the Azure Portal and create a new storage account. Fill in all the configurations and go to the final tab, “Review and Create.” You should see a link to View automation template</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*9vf36BWpPRv1vnS6VfuKjg.png" /></figure><p>Clicking this link will show you the generated ARM template for the resource with all the configurations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5ASes4r73Mx4PbmBt6Yhw.png" /></figure><p><strong>Pros:</strong></p><ul><li>Automatically generated and includes all configurations, making it easy to copy and paste into your template.</li></ul><p><strong>Cons:</strong></p><ul><li>Generates everything, making it hard to maintain.</li><li>When adding multiple resources to the same template, each copied from the generated Azure Portal template, it becomes difficult to read and manage.</li></ul><h4>2. From Scratch with the Help of IntelliSense</h4><p>To instruct IntelliSense to help create a template for a storage account, follow these steps:</p><ul><li>Create an ARM template by typing arm and pressing tab to auto-generate the ARM template scheme.</li><li>In the resources section, add a new resource of type storage account.</li><li>IntelliSense will now guide you based on the resource type.</li><li>Press Ctrl + Space to automatically suggest the next required property and list all available options.</li><li>Deploy the template, and if any required property is missing, an error will be shown.</li></ul><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {},<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {},<br>    &quot;resources&quot;: [],<br>    &quot;outputs&quot;: {}<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ikTZ7pwC5ZYcVsO7uGARaw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*sQIFmx8txfbRY8oDdkg4mw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*97KKV3ZAwN2SfdlRCeTIdw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vFJlDzCrq4aucy40SYitjg.png" /></figure><p>Your resource will typically have the following information:</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {},<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {},<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[resourceGroup().location]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;myapprandomhashdev&quot;,<br>            &quot;sku&quot;: {<br>                &quot;name&quot;: &quot;Standard_LRS&quot;<br>            },<br>            &quot;properties&quot;: {<br>                &quot;accessTier&quot;: &quot;Cool&quot;<br>            }<br>        }<br>    ],<br>    &quot;outputs&quot;: {}<br>}</pre><p>where the [resourceGroup().location] is a function that gets the resource group location.</p><p><strong>Pros:</strong></p><ul><li>Summarized and easy to understand and maintain, with fewer lines of JSON configuration.</li></ul><p><strong>Cons:</strong></p><ul><li>Requires a learning curve to become familiar with necessary values to avoid errors from incorrect or missing properties.</li></ul><blockquote><strong>Be aware that any optional property not set will take the default value.</strong></blockquote><h4>3. A Quick Start Template from GitHub</h4><p>This <a href="https://github.com/Azure/azure-quickstart-templates">GitHub repository</a> has many useful quick start templates. You can use it as a reference to see if the template you need is available.</p><h4>4. Mixed Approach</h4><p>This is the preferred method for most software engineers. You build the template from scratch and generate an ARM template from the Azure Portal for any values you need as a reference.</p><p>For example, if you need to create a storage account that allows public access, you can create a storage account with this option in the Azure Portal, view the generated template, and find how to set it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*cdXoK6qTxc3dOPUBm54hmQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dOl409CqtSdn3EfCqhCkGg.png" /></figure><p>To get the value, go to the parameters and search for the used parameter, such as allowBlobPublicAccess. We will learn more about these parameters later in this article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*jhlizoYn19SBV6G7LluY1g.png" /></figure><p>Now our ARM template for creating a storage account should look like this:</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {},<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {},<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[resourceGroup().location]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;myapprandomhashdev&quot;,<br>            &quot;sku&quot;: {<br>                &quot;name&quot;: &quot;Standard_LRS&quot;<br>            },<br>            &quot;properties&quot;: {<br>                &quot;accessTier&quot;: &quot;Cool&quot;,<br>                &quot;allowBlobPublicAccess&quot;: true<br>            }<br>        }<br>    ],<br>    &quot;outputs&quot;: {}<br>}</pre><p>Let’s utilize the parameters section to dynamically assign our prefix and suffix at runtime rather than hardcoding them like myapprandomhashdev.</p><p>In-order to do this, we need to:</p><ul><li>Create two parameters: app and env.</li><li>Declare the name property in the variables section.</li><li>Assign the name property with the concatenation of app + randomhash + env.</li><li>Use the built-in functions concat(), uniqueString(), and resourceGroup().</li></ul><p>concat(): Concatenates any number of values.</p><p>uniqueString(): Generates a unique string based on the input, <em>producing the same string for the same input each time.</em></p><p>resourceGroup(): Returns many properties of the used resource group such as id, name, location, etc.</p><p>Now, the ARM template should look like this:</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;app&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;defaultValue&quot;: &quot;myapp&quot;<br>        },<br>        &quot;env&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;defaultValue&quot;: &quot;dev&quot;<br>        }<br>    },<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {<br>        &quot;name&quot;: &quot;[concat(parameters(&#39;app&#39;) , uniqueString(resourceGroup().location) , parameters(&#39;env&#39;))]&quot;<br>    },<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[resourceGroup().location]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;name&#39;)]&quot;,<br>            &quot;sku&quot;: {<br>                &quot;name&quot;: &quot;Standard_LRS&quot;<br>            },<br>            &quot;properties&quot;: {<br>                &quot;accessTier&quot;: &quot;Cool&quot;,<br>                &quot;allowBlobPublicAccess&quot;: true<br>            }<br>        }<br>    ],<br>    &quot;outputs&quot;: {}<br>}</pre><h3>Multiple Environments (Separate Parameters File)</h3><p>Now that you know the exact resources you need and have successfully created and tested the right ARM template in the Dev environment, you need to deploy the same template in other environments such as Test, QC, Pre-Prod, and Prod.</p><p>To do this, you need to parameterize your template so it can run in multiple environments with a configuration file for each environment containing only the values related to that environment.</p><p>Well, This can be easily achieved by separating all your parameters into separate files, which then become inputs to the ARM template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JxpzZbFVHt8Dm-wdn2DqJg.png" /></figure><p>In the previous example, we created a template with two parameters and assigned their values using default values.</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;app&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;defaultValue&quot;: &quot;myapp&quot;<br>        },<br>        &quot;env&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;defaultValue&quot;: &quot;dev&quot;<br>        }<br>    },<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {<br>        &quot;name&quot;: &quot;[concat(parameters(&#39;app&#39;) , uniqueString(resourceGroup().location) , parameters(&#39;env&#39;))]&quot;<br>    },<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[resourceGroup().location]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;name&#39;)]&quot;,<br>            &quot;sku&quot;: {<br>                &quot;name&quot;: &quot;Standard_LRS&quot;<br>            },<br>            &quot;properties&quot;: {<br>                &quot;accessTier&quot;: &quot;Cool&quot;,<br>                &quot;allowBlobPublicAccess&quot;: true<br>            }<br>        }<br>    ],<br>    &quot;outputs&quot;: {}<br>}</pre><p>Now, let’s see how to take these parameter values from a parameters file.</p><p>Create a new file called myapp.dev.parameters.json and type armp then press tab to generate the parameters scheme.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/724/1*cF0qiYjD-PLeWrtg_GEKOw.png" /></figure><p>It should generate the following scheme:</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>    }<br>}</pre><p>Next, define the parameters and assign values for them in this parameters file.</p><p>If you follow a consistent naming convention, such as myapp.template.json and myapp.dev.parameters.json, Visual Studio Code (VSCode) will link them for you and show the parameters in the autocomplete IntelliSense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08Qh15g9brDMXxdwXiOenw.png" /></figure><p>You can also manually link the files in VSCode by going to the template file, clicking “Select or create a parameter file…” and choosing the appropriate parameters file. This can be changed at any time in the future.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V6JftG4oaRPGTsmKwP0SPg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/899/1*JXyh0IpoWDmGGWo-J5945g.png" /></figure><p>Define your parameters in the parameters file to look like this:</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;app&quot;: {<br>            &quot;value&quot;: &quot;myapp&quot;<br>        },<br>        &quot;env&quot;: {<br>            &quot;value&quot;: &quot;dev&quot;<br>        }<br>    }<br>}</pre><p>Back in the ARM template file, you can remove the default values, or keep them as a fallback.</p><blockquote>Note that the parameters file has the highest precedence, so if a value is found there, it will override the default value.</blockquote><h3>Deploy Your First ARM Template</h3><p>Let’s deploy the ARM template we created. There are several deployment options available:</p><ul><li>Azure Portal Custom Template</li><li>PowerShell</li><li>Azure CLI</li><li>CI/CD Pipeline</li></ul><p>To master ARM template deployment, I will guide you through most of these methods in detail.</p><h4>Azure Portal Custom Template Deployment</h4><p>This is the simplest method, making it easy to apply and very effective for verifying that your ARM template will behave as expected.</p><p>It doesn’t require any machine environment setup or scripting skills.</p><p><em>However, it is recommended to configure deployment using a CI/CD Pipeline for your main deployment.</em></p><p>Go to the Azure Portal, search for “Custom Template,” and click it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*O-rnfX6Bf54RKiJG3hwV3g.png" /></figure><p>Select “Build your own template in the editor.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*08gC3Qhv3wxoTmKYzdY92A.png" /></figure><p>Copy the created ARM template and replace the content in the editor. Click the Save button.</p><p>Remove the default value for the env property to see how it appears with and without default values.</p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;app&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;defaultValue&quot;: &quot;myapp&quot;<br>        },<br>        &quot;env&quot;: {<br>            &quot;type&quot;: &quot;string&quot;<br>        }<br>    },<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {<br>        &quot;name&quot;: &quot;[concat(parameters(&#39;app&#39;) , uniqueString(resourceGroup().location) , parameters(&#39;env&#39;))]&quot;<br>    },<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[resourceGroup().location]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;name&#39;)]&quot;,<br>            &quot;sku&quot;: {<br>                &quot;name&quot;: &quot;Standard_LRS&quot;<br>            },<br>            &quot;properties&quot;: {<br>                &quot;accessTier&quot;: &quot;Cool&quot;,<br>                &quot;allowBlobPublicAccess&quot;: true<br>            }<br>        }<br>    ],<br>    &quot;outputs&quot;: {}<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i8LqKqWUhNN-hEEdFepJ7A.png" /></figure><p>After saving, you will see your parameters. with required entering, but also the parameter which has default values will have the default value as the initial value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*4OG0JLE7kjcJDWj1UlD84A.png" /></figure><p>Now you have two options</p><ol><li>Enter the data manually.</li><li>Attach a parameters file.</li></ol><p>let’s attach parameters file, by choosing “Edit parameters” and replacing the content with your parameters file.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/737/1*C8efbA6siFytmxfq8xzX8w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/861/1*c7VGTTnXP3GrJ2Cof5xkGA.png" /></figure><p>Click Save. You should now see the values replaced.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*l2SxvYVGGX-CkX-KI0GX1Q.png" /></figure><p>Choose the Resource Group and click “Review + create”.</p><p>Finally, click the “Create” button to start the deployment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QumojIqM7_rLNSI5tMvMYg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qHVRDiTazi2aQ5TpUW_5jQ.png" /></figure><p>Congratulations on your first ARM template deployment!</p><h4>Azure CLI — PowerShell Deployment</h4><p>First, download and install the Azure CLI SDK on your local machine.</p><p>Follow the instructions in this <a href="https://learn.microsoft.com/en-us/cli/azure/install-azure-cli">Microsoft document</a> to download and install it.</p><p>Then, open PowerShell and run the following command to ensure it’s installed properly:</p><pre>az --version</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*RpL2jFI4aNzwRFjtWJlGuA.png" /><figcaption>az — version Output</figcaption></figure><p>Next, connect and authenticate the Azure CLI by opening PowerShell in administrator mode and running:</p><pre>Install-Module -Name Az -AllowClobber -Scope CurrentUser<br><br># run this one.<br>Connect-AzAccount<br><br># or this if the above not working.<br>Connect-AzAccount -DeviceCode</pre><p>If you encounter an error like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/1*gSKtvw_gZvEtgUsCh_Lzew.png" /></figure><p>Copy the tenant ID from the error message and run:</p><pre>Connect-AzAccount -TenantId ***********6df67e7</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/864/1*1okx8xySgE45bcVWhWnsYQ.png" /></figure><p>To deploy the ARM template using PowerShell:</p><p>Assume the resource group is named rg-myapp-useast-dev, the ARM template is named myapp.template.json, and the parameters file is named myapp.parameters.dev.json.</p><p>Open VSCode PowerShell or the PowerShell where the ARM template is located.</p><p>The PowerShell command typically like the following:</p><pre>New-AzResourceGroupDeployment <br>-Name &#39;Your-Deployment-Name&#39; #Overwrite the previous deployments with the same name<br>-ResourceGroupName &#39;resource-group-name&#39; <br>-TemplateFile &#39;arm.template.file.json&#39; <br>-TemplateParameterFile &#39;arm.template.parameters.file.json&#39;</pre><p>Regarding the above command our command should looks like this:</p><pre>New-AzResourceGroupDeployment <br>-Name &#39;Powershell-Manual-Deployment-01&#39; <br>-ResourceGroupName &#39;rg-myapp-useast-dev&#39; <br>-TemplateFile &#39;myapp.template.json&#39; <br>-TemplateParameterFile &#39;myapp.dev.parameters.json&#39;</pre><p>Running the command should show the status as “Succeeded”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xs1zqKjJLm4guUgiQ-2AuQ.png" /></figure><blockquote>You can also write the commands in a PowerShell file with .ps extension and call it, will show the same output.</blockquote><p>By navigating to the Azure Portal, you should find the created deployment with the same name of the deployment name which here was Powershell-Manual-Deployment-01, also you should find the created resource created successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2eIjbWEOU1gUkq8UktVFyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*VThweD5F1O-PNWFdM_jY7w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bHvkJrMxoPf44YU9x7rHIA.png" /></figure><h4>Azure CLI — Cloud Shell Deployment</h4><p>Open the Azure Portal and click the Shell icon in the top right corner, then choose PowerShell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wLIxCMWExT8kTyyw2d7IbQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*TsU-4x1vmnOuH7GkO1dj3A.png" /></figure><p>A Shell screen will appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ojq6HqluGl0hki3gfI35Ow.png" /></figure><p>In Cloud Shell, you have two options to upload your template and parameters files:</p><ul><li>Upload files directly.</li><li>Use the classic editor, which opens a VSCode view for creating and editing your files.</li></ul><p><strong>Upload files directly</strong></p><p>Before uploading the files, let’s introduce a new parameter in your template to ensure a different name is generated each time. For example, add a platform parameter.</p><p>Add a value for it, such as csu for CloudShellUpload. The template and parameters should look like the following:</p><p><em>Make it short as possible as the name has max length of 24 characters.</em></p><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;app&quot;: {<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        &quot;env&quot;: {<br>            &quot;type&quot;: &quot;string&quot;<br>        },<br>        &quot;platform&quot;: {<br>            &quot;type&quot;: &quot;string&quot;<br>        }<br>    },<br>    &quot;functions&quot;: [],<br>    &quot;variables&quot;: {<br>        &quot;name&quot;: &quot;[concat(parameters(&#39;app&#39;) , uniqueString(resourceGroup().location) , parameters(&#39;env&#39;), parameters(&#39;platform&#39;) )]&quot;<br>    },<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[resourceGroup().location]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;name&#39;)]&quot;,<br>            &quot;sku&quot;: {<br>                &quot;name&quot;: &quot;Standard_LRS&quot;<br>            },<br>            &quot;properties&quot;: {<br>                &quot;accessTier&quot;: &quot;Cool&quot;,<br>                &quot;allowBlobPublicAccess&quot;: true<br>            }<br>        }<br>    ],<br>    &quot;outputs&quot;: {}<br>}</pre><pre>{<br>    &quot;$schema&quot;: &quot;https://schema.management.azure.com/schemas/2019-04-01/deploymentParameters.json#&quot;,<br>    &quot;contentVersion&quot;: &quot;1.0.0.0&quot;,<br>    &quot;parameters&quot;: {<br>        &quot;app&quot;: {<br>            &quot;value&quot;: &quot;myapp&quot;<br>        },<br>        &quot;env&quot;: {<br>            &quot;value&quot;: &quot;dev&quot;<br>        },<br>        &quot;platform&quot;: {<br>            &quot;value&quot;: &quot;csu&quot;<br>        }<br>    }<br>}</pre><p>Click “Manage files,” then choose “Upload” and select the template and parameters files. Click “Open.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/885/1*DEJovZAOW_2l9er5p1QAug.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/827/1*W-prmKC_pEt4_VHesKL4_w.png" /></figure><p>A success message should appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*eISxWAmCGu8cbeiTvifPvg.png" /></figure><p>You can check the uploaded files by running ls in the Shell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*-AfBAO7lY8Os3glgcf9Pqg.png" /></figure><p>Next, run the same PowerShell command used previously:</p><pre>New-AzResourceGroupDeployment <br>-Name &#39;CloudShell-Upload-Manual-Deployment-01&#39; <br>-ResourceGroupName &#39;rg-myapp-useast-dev&#39; <br>-TemplateFile &#39;myapp.template.json&#39; <br>-TemplateParameterFile &#39;myapp.dev.parameters.json&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jgjBeZchvBDpEEUD-X7xnQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/811/1*p6jTPVQYp4WPgn04ardj1g.png" /></figure><p><strong>Classic Editor</strong></p><p>The easiest way to deal with Cloud Shell is to write the command code . or click the Editor option, which will open a VSCode view for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*gn6MbB0-F5_VtAH9PFFCPA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*8ssG4jqLy3HfBcAf9YGPKw.png" /></figure><p>Click “Confirm” to switch to the classic editor, then write the command code . or click the {} option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/1*noeJoUiDxynbmgBEmqd4zw.png" /></figure><p>A VSCode editor should appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/870/1*HyY9PcpbjWwoyr5ndFmBBQ.png" /></figure><p>Paste the template file and click Ctrl + S to save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wKzlOdeMuI_udGdXui302A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*j5wIjj4KVq252d5BngK-Zg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NfZrh_VbFdK9XjrMMIhIhg.png" /></figure><p>To add the parameters file, use the Shell command <br>code myapp.parameters.dev.json</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWEmkjQwUAxSN-DDQsKPTg.png" /></figure><p>Update the platform parameter in the parameters file to be cse for CloudShellEditor, then paste the content and press Ctrl + S to save it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRiXT8iyy-hgeuC5h-R5UQ.png" /></figure><p>You can also press F1 for the command palette.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*Zr5_r4sM7f9YFaKb068Caw.png" /></figure><p>Finally, click Ctrl + Q or press the X button to close the editor, and then run the same PowerShell command as before.</p><pre>New-AzResourceGroupDeployment <br>-Name &#39;CloudShell-Editor-Manual-Deployment-01&#39; <br>-ResourceGroupName &#39;rg-myapp-useast-dev&#39; <br>-TemplateFile &#39;myapp.template.json&#39; <br>-TemplateParameterFile &#39;myapp.parameters.dev.json&#39;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xHCrtTKOUKV22RsYJq1Xkg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*ADYjUnRG9x3L-BY-9o1xHA.png" /></figure><h4>CI/CD Pipeline Deployment</h4><p>This type of deployment will be discussed in the next article, which will cover Azure DevOps Pipelines, including ARM Template Pipelines, Deploy Azure Application Pipelines, Deploy Azure Functions Pipeline, and more.</p><p>Make sure you follow and subscribe to get notified once it’s published.</p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><h3>More about ARM templates</h3><h4>Restrict Value to Be One from a List</h4><p>To enforce users to choose a valid value from a predefined list, you can use the allowedValues property.</p><p>Let’s say we need to have two parameters: clusterNumber, which should be one of [c1, c2, c3, c4, c5, c6, c7], and env, which should be one of [dev, test, prod]. Based on these inputs, we generate a unique storage account name.</p><p>Here’s how your parameters should look:</p><pre>{<br>    ...<br>    &quot;parameters&quot;: {<br>        &quot;clusterNumber&quot;: {<br>            &quot;type&quot;: &quot;array&quot;,<br>            &quot;allowedValues&quot;: [&quot;c1&quot;, &quot;c2&quot;, &quot;c3&quot;, &quot;c4&quot;, &quot;c5&quot;, &quot;c6&quot;, &quot;c7&quot;]<br>        },<br>        &quot;env&quot;: {<br>            &quot;type&quot;: &quot;array&quot;,<br>            &quot;allowedValues&quot;: [&quot;dev&quot;, &quot;test&quot;, &quot;prod&quot;]<br>        }<br>    }<br>    ...<br>}</pre><p><strong>Result:</strong></p><p>Allowed values turn into a dropdown list in the custom deployment editor. An error is thrown in PowerShell if a value not in the allowed list is provided.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*Zq0teW4GU-vIQIJ_7vISlg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fUyqoxGpfqoetAnIRHP1aQ.png" /></figure><h4>Add Parameter Description</h4><p>To add a parameter description that appears in the deployment editor, use the description property.</p><pre>{<br>    ...<br>    &quot;parameters&quot;: {<br>        &quot;tenantId&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;metadata&quot;: {<br>                &quot;description&quot;: &quot;How to get? In Azure Portal search for Azure Active Directory, On the &#39;Overview&#39; page, look for the &#39;Tenant ID&#39; field and copy the value.&quot;<br>            }<br>        }<br>    }<br>    ...<br>}</pre><p><strong>Results:</strong></p><p>The metadata appears as a description when the i icon is hovered over.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*CFcNVc8fsqpQgC58VgaJhQ.png" /></figure><h4>Parameter Validations</h4><p>To add parameter validations, use the following properties:</p><ul><li>minValue</li><li>maxValue</li><li>minLength</li><li>maxLength</li></ul><pre>{<br>    ...<br>    &quot;parameters&quot;: {<br>        &quot;kvPrefix&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;maxLength&quot;: 4,<br>            &quot;minLength&quot;: 1<br>        },<br>        &quot;kvId&quot;: {<br>            &quot;type&quot;: &quot;int&quot;,<br>            &quot;maxValue&quot;: 100,<br>            &quot;minValue&quot;: 1<br>        },<br>        ...<br>    }<br>    ...<br>}</pre><p><strong>Result:</strong></p><p>Validation errors will be displayed if the criteria are not met.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*FsXQyfIm2KAFrggGpAFntg.png" /></figure><h4>Create Multiple Resources of the Same Type</h4><p>In an ARM template, you can create multiple resources of the same type with similar or different configurations.</p><p><strong>Example:</strong></p><p>Let’s say you want to create multiple load balancers, each handling a single VMSS (Virtual Machine Scale Set).</p><p>First, add a array VMSS parameter that looks like this:</p><pre>// template.json<br>{<br>    ...<br>    &quot;parameters&quot;: {<br>        &quot;vmss&quot;: {<br>            &quot;type&quot;: &quot;array&quot;<br>        }<br>        ...<br>    }<br>    ...<br>}</pre><p>Your parameters file should look like this:</p><pre>// parameters.json<br>{<br>    ...<br>    &quot;parameters&quot;: {<br>        &quot;vmss&quot;: {<br>            &quot;value&quot;: [<br>                {<br>                    &quot;name&quot;: &quot;vmss-01&quot;                    <br>                },<br>                {<br>                    &quot;name&quot;: &quot;vmss-02&quot;                    <br>                },<br>                {<br>                    &quot;name&quot;: &quot;vmss-03&quot;                    <br>                }<br>            ]<br>        }<br>        ...<br>    }<br>    ...<br>}</pre><p>To create a load balancer for each VMSS, use the copy command as follows:</p><pre>{<br>    ...<br>    &quot;resources&quot;: [<br>        {<br>            &quot;apiVersion&quot;: &quot;2018-08-01&quot;,<br>            &quot;type&quot;: &quot;Microsoft.Network/loadBalancers&quot;,<br>            &quot;copy&quot;: {<br>                &quot;name&quot;: &quot;loadBalancerDeploy&quot;,<br>                &quot;count&quot;: &quot;[length(parameters(&#39;vmss&#39;))]&quot;<br>            },<br>            &quot;name&quot;: &quot;[concat(&#39;lb-&#39;, parameters(&#39;vmss&#39;)[copyIndex()].name)]&quot;<br>            ...<br>        }<br>        ...<br>    ],<br>    ...<br>}</pre><p>name is the copy operation name not the resource name.</p><h4>Create Resource Only After Another Resource is Created</h4><p>To ensure that a resource is created only after another resource, use the dependsOn property.</p><blockquote>Remember to concatenate the name of the resource with its type.</blockquote><pre>{<br>    ...<br>    &quot;resources&quot;: [<br>        {<br>            &quot;type&quot;: &quot;Microsoft.Storage/storageAccounts&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-01-01&quot;,<br>            &quot;location&quot;: &quot;[variables(&#39;location&#39;)]&quot;,<br>            &quot;kind&quot;: &quot;StorageV2&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;storageAccountName&#39;)]&quot;,<br>            ...<br>        },<br>        {<br>            &quot;type&quot;: &quot;Microsoft.KeyVault/vaults&quot;,<br>            &quot;apiVersion&quot;: &quot;2023-02-01&quot;,<br>            &quot;location&quot;: &quot;[variables(&#39;location&#39;)]&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;kvName&#39;)]&quot;,<br>            &quot;dependsOn&quot;: [<br>                &quot;[concat(&#39;Microsoft.Storage/storageAccounts/&#39;, variables(&#39;storageAccountName&#39;))]&quot;<br>            ]<br>            ...<br>        }<br>    ]<br>    ...<br>}</pre><h4>Use KeyVault Secret in the ARM Template</h4><p>You can use secrets from KeyVault to add sensitive information to your template, such as usernames and passwords.</p><pre>// template.json<br>{<br>    &quot;parameters&quot;: {<br>        &quot;userName&quot;: {<br>            &quot;type&quot;: &quot;string&quot;,<br>            &quot;defaultValue&quot;: &quot;defaultusername&quot;<br>        },<br>        &quot;password&quot;: {<br>            &quot;type&quot;: &quot;securestring&quot;<br>        }<br>        ...<br>    },<br>    &quot;resources&quot;: [<br>        {<br>            &quot;apiVersion&quot;: &quot;[variables(&#39;sfApiVersion&#39;)]&quot;,<br>            &quot;type&quot;: &quot;Microsoft.ServiceFabric/managedClusters&quot;,<br>            &quot;name&quot;: &quot;[variables(&#39;clusterName&#39;)]&quot;,<br>            &quot;location&quot;: &quot;[resourcegroup().location]&quot;,<br>            &quot;properties&quot;: {<br>                &quot;adminUserName&quot;: &quot;[parameters(&#39;userName&#39;)]&quot;,<br>                &quot;adminPassword&quot;: &quot;[parameters(&#39;password&#39;)]&quot;,<br>                ...<br>            }<br>        }<br>    ],<br>    ...<br>}</pre><pre>// parameters.json<br>{<br>    ...<br>    &quot;parameters&quot;: {<br>        &quot;password&quot;: {<br>            &quot;reference&quot;: {<br>                &quot;keyVault&quot;: {<br>                &quot;id&quot;: &quot;/subscriptions/your-subscription/resourceGroups/your-resource-group-name/providers/Microsoft.KeyVault/vaults/your-keyvault-name&quot;<br>                },<br>                &quot;secretName&quot;: &quot;your-secrent-name&quot;<br>            }<br>        },<br>        ...<br>    }<br>}</pre><blockquote>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d50034f374f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/azure-resource-manager-arm-templates-azure-iaac-5d50034f374f">Azure Resource Manager ARM Templates (Azure IaaC)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Top 7 Use Cases of Azure Functions with .NET]]></title>
            <link>https://levelup.gitconnected.com/top-7-use-cases-of-azure-functions-with-net-c156266a81d9?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c156266a81d9</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Mon, 03 Jun 2024 15:55:42 GMT</pubDate>
            <atom:updated>2024-06-03T15:55:42.300Z</atom:updated>
            <content:encoded><![CDATA[<h3>Top 7 Use Cases of Azure Functions with .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*sghU7TH_z1eEE_UfB7e1yg.jpeg" /></figure><p>Continuing our series on <a href="https://medium.com/@mohamed.ebrahim.mohsen">Azure integration with .NET 9</a>, you can delve into previous articles covering various aspects of integrating Azure services with .NET 9. A new article is published weekly to keep you updated.</p><p>In this article, I will guide you through leveraging Azure Functions in a .NET 9 Web API application.</p><h3>Our goal is to create:</h3><ol><li>Multi Handler Azure Function [GET, POST, PUT,…etc] (HTTP Trigger).</li><li>Cron Jobs (Timer Trigger).</li><li>Event Processing for Service Bus Queues (Service Bus Queue Trigger).</li><li>Event Processing for Service Bus Topics (Service Bus Topic Trigger).</li><li>File Upload Processing (Blob Trigger).</li><li>Functions triggered by Azure Cosmos DB (Cosmos DB Trigger).</li><li>Functions triggered by Azure SQL DB (SQL Trigger).</li></ol><h4>Before we go</h4><p>Please note that this article will not cover the deployment of Azure Functions, as that topic is comprehensively addressed in another article, “<a href="https://medium.com/gitconnected/azure-functions-deployments-with-net-bf925da5cc37">Azure Functions Deployments with .NET</a>” which details various methods for creating and deploying Azure Functions.</p><p>Instead, this article will focus on the other essential aspects such as the code implementation, Azure Portal configurations, and other relevant details to get you started.</p><h3>Multi Handler Azure Function [GET, POST, PUT,…etc] (HTTP Trigger)</h3><p>Azure Functions are particularly useful when you need to handle multiple HTTP methods for the same endpoint. For instance, imagine you are developing a task management application and need to create an API that allows users to manage their tasks. This API should support operations to:</p><ul><li>Retrieve a list of tasks (GET)</li><li>Create a new task (POST)</li><li>Update an existing task (PUT)</li><li>Partially update an existing task (PATCH)</li><li>Delete a task (DELETE)</li></ul><p>Instead of creating a separate Azure Function for each operation, you can manage all of them within a single Azure Function.</p><p>To create a multi-handler Azure Function, select the HTTP Trigger option when setting up the Azure Function project in Visual Studio or any other development tool.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*1HOJpOlPlsCGUZa_1-Aqrw.png" /></figure><p>As shown below, you can either define separate methods for each HTTP method or handle all of them within the same method, depending on your preferences and the complexity of your code.</p><pre>public class MultiRequestHandlerFunction(ILogger&lt;MultiRequestHandlerFunction&gt; logger)<br>{<br>    private readonly ILogger&lt;MultiRequestHandlerFunction&gt; _logger = logger;<br><br>    [Function(&quot;MultiRequestHandlerFunction&quot;)]<br>    public IActionResult Run([HttpTrigger(AuthorizationLevel.Function, &quot;GET&quot;, &quot;POST&quot;, &quot;PUT&quot;, &quot;PATCH&quot;, &quot;DELETE&quot;)] HttpRequest req)<br>    {<br>        return req.Method switch<br>        {<br>            &quot;GET&quot; =&gt; HandleGet(req),<br>            &quot;POST&quot; =&gt; HandlePost(req),<br>            &quot;PUT&quot; =&gt; HandlePut(req),<br>            &quot;PATCH&quot; =&gt; HandlePatch(req),<br>            &quot;DELETE&quot; =&gt; HandleDelete(req),<br>            _ =&gt; new OkObjectResult(&quot;Welcome to Azure Functions!&quot;),<br>        };<br>    }<br><br>    private IActionResult HandleGet(HttpRequest req) =&gt; new OkObjectResult(&quot;Function triggered from GET request.&quot;);<br>    private IActionResult HandlePost(HttpRequest req) =&gt; new OkObjectResult(&quot;Function triggered from POST request.&quot;);<br>    private IActionResult HandlePut(HttpRequest req) =&gt; new OkObjectResult(&quot;Function triggered from PUT request.&quot;);<br>    private IActionResult HandlePatch(HttpRequest req) =&gt; new OkObjectResult(&quot;Function triggered from PATCH request.&quot;);<br>    private IActionResult HandleDelete(HttpRequest req) =&gt; new OkObjectResult(&quot;Function triggered from DELETE request.&quot;);<br>}</pre><h3>Cron Jobs (Timer Trigger)</h3><p>Cron jobs are invaluable for automating repetitive tasks. For instance, to prevent data loss, a website can use a cron job to schedule daily database backups at midnight. This ensures consistent and reliable backups without manual effort, saving time and reducing errors.</p><p>Create a new Azure Function project with a Timer Trigger and set your desired schedule. For guidance on cron expressions, refer to this <a href="https://crontab.cronhub.io/">website</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*h2yjDydNIKS4OQUo03edAw.png" /></figure><p>Your project should generate an Azure Function class similar to the following:</p><pre>public class CronJobFunction<br>{<br>    private readonly ILogger _logger;<br><br>    public CronJobFunction(ILoggerFactory loggerFactory)<br>    {<br>        _logger = loggerFactory.CreateLogger&lt;CronJobFunction&gt;();<br>    }<br><br>    [Function(&quot;CronJobFunction&quot;)]<br>    public void Run([TimerTrigger(&quot;0 */1 * * * *&quot;)] TimerInfo myTimer)<br>    {<br>        _logger.LogInformation($&quot;C# Timer trigger function executed at: {DateTime.Now}&quot;);<br>        <br>        if (myTimer.ScheduleStatus is not null)<br>        {<br>            _logger.LogInformation($&quot;Next timer schedule at: {myTimer.ScheduleStatus.Next}&quot;);<br>        }<br>    }<br>}</pre><p>After deploying your function, navigate to the Log Stream in the Azure Portal. You should observe logs indicating the function is executed every minute, as specified by the cron expression 0 */1 * * * *.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cg32uzAvQpXFD8-pW8z3Iw.png" /></figure><h3>Event Processing for Service Bus Queues (Service Bus Queue Trigger)</h3><p>When you’re dealing with Service Bus Queues and there is a need to process incoming messages on arrival, Azure Functions offer an optimal solution. By triggering a designated function upon the arrival of new messages in the queue, you can efficiently handle the processing of these messages.</p><p>To begin, create a new Azure Function project with the type of Service Bus Queue Trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*mD8CDbHmHr6osz1WswuBFQ.png" /></figure><p>MyQueueConnectionString: represents the connection string of your Service Bus, configured either in the appsettings.json or secrets.json file.</p><p>my-queue: represents the created queue name.</p><blockquote>For enhanced security, it’s advisable to store sensitive information like connection strings in Azure Key Vault. For comprehensive instructions on configuring and leveraging Azure Key Vault, you can refer to my Medium article titled “<a href="https://medium.com/@mohamed.ebrahim.mohsen/mastering-azure-key-vault-integration-for-net-web-apis-405b12edaf4a"><strong>Mastering Azure Key Vault Integration for .NET Web APIs</strong></a>”.</blockquote><p>Your function should be structured as follows:</p><pre>public class QueueTrigger<br>{<br>    private readonly ILogger&lt;QueueTrigger&gt; _logger;<br><br>    public QueueTrigger(ILogger&lt;QueueTrigger&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    [Function(nameof(QueueTrigger))]<br>    public async Task Run(<br>        [ServiceBusTrigger(&quot;my-queue&quot;, Connection = &quot;MyQueueConnectionString&quot;)]<br>        ServiceBusReceivedMessage message,<br>        ServiceBusMessageActions messageActions)<br>    {<br>        _logger.LogInformation(&quot;Message ID: {id}&quot;, message.MessageId);<br>        _logger.LogInformation(&quot;Message Body: {body}&quot;, message.Body);<br>        _logger.LogInformation(&quot;Message Content-Type: {contentType}&quot;, message.ContentType);<br><br>        // Complete the message<br>        await messageActions.CompleteMessageAsync(message);<br>    }<br>}</pre><p>Now, deploy your function. Once deployed, send a message to the queue and observe its processing through the Log Stream of the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*GaUaT0tc_LOI_R2QAk32ng.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/907/1*tOe2ioRO37kGDMjq3eXPzQ.png" /></figure><p>In case you encounter the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/609/1*O7HrY6qDb2tW4j0351OOUg.png" /></figure><p>Simply navigate to the environment variables and add the connection string, MyQueueConnectionString. This should resolve the issue of your Azure Function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCrJ68dmgKbwmt8m60x3Ew.png" /></figure><h3>Event Processing for Service Bus Topics (Service Bus Topic Trigger)</h3><p>When setting up a Function for Event Processing for Topics, it‘s’ identically as the previous one for the Queues except when creating the Azure function project it should be of type Service Bus Topic Trigger, and add the Subscription name and Topic name</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*TOXAJ3ZxptCW5FO9NQVNWA.png" /></figure><h3>File Upload Processing (Blob Trigger)</h3><p>In case you require post-processing actions following the addition of files to a specific blob container, Azure Functions offers an efficient solution. To achieve this.</p><p>Create a new Azure Function project with the Blob Trigger type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*v5gJ2O8GHcv37yAW0VOHkw.png" /></figure><p>MyStorageAccConnectionString: represents the connection string of your Storage Account, configured either in the appsettings.json or secrets.json file.</p><p>Path: representing the directory path where the files will be uploaded. In this example, let’s consider it as root/files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hOpjjkFfOOxLQTj1rvVe_A.png" /></figure><p>Your function code should resemble the following structure:</p><pre>public class FileUploadProcessing<br>{<br>    private readonly ILogger&lt;FileUploadProcessing&gt; _logger;<br><br>    public FileUploadProcessing(ILogger&lt;FileUploadProcessing&gt; logger)<br>    {<br>        _logger = logger;<br>    }<br><br>    [Function(nameof(FileUploadProcessing))]<br>    public async Task Run([BlobTrigger(&quot;root/files/{name}&quot;, Connection = &quot;MyStorageAccConnectionString&quot;)] Stream stream, string name)<br>    {<br>        using var blobStreamReader = new StreamReader(stream);<br>        var content = await blobStreamReader.ReadToEndAsync();<br>        _logger.LogInformation($&quot;C# Blob trigger function Processed blob\n Name: {name} \n Data: {content}&quot;);<br>    }<br>}</pre><p>{name}: serves as a wildcard placeholder for any upcoming file names.</p><p>You can customize it further, for instance, to only process PDF files use the pattern {name}.pdf.</p><p>Now, deploy your function, and upload files to the specified directory within the path. You should observe these files appearing in the Log Stream of the function, triggering the specified post-processing actions accordingly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/836/1*q0bIpGK3AQkckIvCUdcSWQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*pYZLlcxqimjHAmgfquvX5Q.png" /></figure><h3>Functions triggered by Azure Cosmos DB (Cosmos DB Trigger)</h3><p>In certain scenarios, performing post-actions after a new record is added to a specific container or table becomes necessary. For instance, sending a welcome email upon the addition of a new user to the users container/table is a common use case.</p><p>To begin, create a new Azure Function project with the Cosmos DB Trigger function type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*u-mU1v3_rVDSn5dOAQ9sBQ.png" /></figure><p>storedb: represents the database ID.</p><p>products: denotes the container name within the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*LqUKo-EgL1bvQwnf4mpwDw.png" /></figure><p>Here, I’ll be connecting to Cosmos DB NoSQL. For further insights into the types of Cosmos databases available, you can refer to my article “<a href="https://medium.com/@mohamed.ebrahim.mohsen/azure-cosmosdb-types-of-accounts-explained-77d6114bb6ec">Azure CosmosDB: Types of Accounts Explained</a>”. Additionally, for a detailed guide on integrating Cosmos DB with your .NET application, you can explore my article “<a href="https://medium.com/@mohamed.ebrahim.mohsen/how-to-integrate-azure-cosmosdb-with-net9-5acbe635f489">How to integrate Azure CosmosDB with .NET9</a>”.</p><p>Upon creation, the function project generates sample code.</p><pre><br>  public class Function1<br>  {<br>      private readonly ILogger _logger;<br><br>      public Function1(ILoggerFactory loggerFactory)<br>      {<br>          _logger = loggerFactory.CreateLogger&lt;Function1&gt;();<br>      }<br><br>      [Function(&quot;Function1&quot;)]<br>      public void Run([CosmosDBTrigger(<br>          databaseName: &quot;storedb&quot;,<br>          containerName: &quot;products&quot;,<br>          Connection = &quot;MyCosmosDBConnectionString&quot;,<br>          LeaseContainerName = &quot;leases&quot;,<br>          CreateLeaseContainerIfNotExists = true)] IReadOnlyList&lt;MyDocument&gt; input)<br>      {<br>          if (input != null &amp;&amp; input.Count &gt; 0)<br>          {<br>              _logger.LogInformation(&quot;Documents modified: &quot; + input.Count);<br>              _logger.LogInformation(&quot;First document Id: &quot; + input[0].id);<br>          }<br>      }<br>  }<br><br>  public class MyDocument<br>  {<br>      public string id { get; set; }<br>      public string Text { get; set; }<br>      public int Number { get; set; }<br>      public bool Boolean { get; set; }<br>  }<br></pre><p>Let’s modify it to accept our Product instance and log all added or modified products. The modified code should resemble the following:</p><pre>public class CosmosDBTrigger<br>{<br>    private readonly ILogger _logger;<br><br>    public CosmosDBTrigger(ILoggerFactory loggerFactory)<br>    {<br>        _logger = loggerFactory.CreateLogger&lt;CosmosDBTrigger&gt;();<br>    }<br><br>    [Function(&quot;Function1&quot;)]<br>    public void Run([CosmosDBTrigger(<br>        databaseName: &quot;storedb&quot;,<br>        containerName: &quot;products&quot;,<br>        Connection = &quot;MyCosmosDBConnectionString&quot;,<br>        LeaseContainerName = &quot;leases&quot;,<br>        CreateLeaseContainerIfNotExists = true)] IReadOnlyList&lt;Product&gt; products)<br>    {<br>        if (products is null || products.Count == 0)<br>        {<br>            _logger.LogInformation(&quot;No products added or modified&quot;);<br>            return;<br>        }<br><br>        _logger.LogInformation($&quot;{products.Count} products added or modified&quot;);<br>        foreach (var product in products)<br>        {<br>            _logger.LogInformation($&quot;Product =&gt; name: {product.Name}, price: {product.Price}, quantity: {product.Quantity}&quot;);<br>        }<br>    }<br>}<br><br>public class Product<br>{<br>    public int ProductId { get; set; }<br>    public string Name { get; set; }<br>    public double Price { get; set; }<br>    public double Quantity { get; set; }<br>}</pre><p>Once deployed, add a new document to our storedb in the products container, and observe the Log Stream of our function for logging details.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8k2N_fnbCODYO3kxLINehQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*fvTxyC8WQMc_LGR-IhqmMA.png" /></figure><h3>Functions triggered by Azure SQL DB (SQL Trigger)</h3><p>Similarly to the usage scenarios with Cosmos DB, let’s begin by creating an Azure Function project with the SQL Trigger function type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*GKd5Y-x8wk8vjpNztior0w.png" /></figure><p>MySQLConnectionString: represents the SQL database connection string.</p><p>[dbo].[products]: denotes the table name that triggers the function when a new record is added or updated.</p><p>After creation, the project generates sample code like the following:</p><pre>public class SQLTrigger<br>{<br>    private readonly ILogger _logger;<br><br>    public SQLTrigger(ILoggerFactory loggerFactory)<br>    {<br>        _logger = loggerFactory.CreateLogger&lt;SQLTrigger&gt;();<br>    }<br><br>    // Visit https://aka.ms/sqltrigger to learn how to use this trigger binding<br>    [Function(&quot;Function1&quot;)]<br>    public void Run(<br>        [SqlTrigger(&quot;[dbo].[table1]&quot;, &quot;MySQLConnectionString&quot;)] IReadOnlyList&lt;SqlChange&lt;ToDoItem&gt;&gt; changes,<br>            FunctionContext context)<br>    {<br>        _logger.LogInformation(&quot;SQL Changes: &quot; + JsonSerializer.Serialize(changes));<br><br>    }<br>}<br><br>public class ToDoItem<br>{<br>    public string Id { get; set; }<br>    public int Priority { get; set; }<br>    public string Description { get; set; }<br>}</pre><p>Let’s customize it to work with our products table.</p><pre>public class SQLTrigger<br>{<br>    private readonly ILogger _logger;<br><br>    public SQLTrigger(ILoggerFactory loggerFactory)<br>    {<br>        _logger = loggerFactory.CreateLogger&lt;SQLTrigger&gt;();<br>    }<br><br>    [Function(&quot;SQLTrigger&quot;)]<br>    public void Run(<br>        [SqlTrigger(&quot;[dbo].[products]&quot;, &quot;MySQLConnectionString&quot;)] IReadOnlyList&lt;SqlChange&lt;Product&gt;&gt; changes,<br>            FunctionContext context)<br>    {<br>        _logger.LogInformation(&quot;SQL Changes: &quot; + JsonSerializer.Serialize(changes));<br><br>    }<br>}<br><br>public class Product<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public double Price { get; set; }<br>    public double Quantity { get; set; }<br>}</pre><p>After deployment, access the created database and ensure the products table exists. If not, you can create it from the query editor as below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_esFydImccnV3D45KjWYcA.png" /></figure><p>Then, add a new record to the products table. This action should trigger the appearance of the record in the function Log Stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*KdgVTWXbS5O_BACIq_kB0Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w5L60guyGhh-EHtXDUldZg.png" /></figure><p>If you encountered the following error:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YzjE3fTvqWLWyjq3f9xOYA.png" /></figure><p>Execute the following two commands to enable the change tracker for your database and table.</p><pre>ALTER DATABASE storedb  <br>SET CHANGE_TRACKING = ON  <br>(CHANGE_RETENTION = 2 DAYS, AUTO_CLEANUP = ON)  <br><br><br>ALTER TABLE [dbo].[products]<br>ENABLE CHANGE_TRACKING<br>WITH (TRACK_COLUMNS_UPDATED = ON);</pre><h3>GitHub repository</h3><p>You can find all the code used in this <a href="https://github.com/dotnet-azure/AzureFunctions"><strong>GitHub repository</strong></a>.</p><blockquote><em>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</em></blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c156266a81d9" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/top-7-use-cases-of-azure-functions-with-net-c156266a81d9">Top 7 Use Cases of Azure Functions with .NET</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure Functions Deployments with .NET]]></title>
            <link>https://levelup.gitconnected.com/azure-functions-deployments-with-net-bf925da5cc37?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf925da5cc37</guid>
            <category><![CDATA[azure-functions]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[azure-devops]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Tue, 28 May 2024 22:28:44 GMT</pubDate>
            <atom:updated>2024-05-28T22:28:44.298Z</atom:updated>
            <content:encoded><![CDATA[<h3>Azure Functions Deployments with .NET</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Phrif4t5ES5QO5YXF9byzw.jpeg" /></figure><p>Deploying Azure Functions offers multiple methods to suit different development environments and workflows. This article will explore three primary scenarios for deploying your Azure Functions. Specifically, I will demonstrate how to deploy using:</p><ol><li>Visual Studio</li><li>Visual Studio Code</li><li>Azure DevOps Pipeline</li></ol><p>In this article, I will follow the same steps for each new deployment, as outlined below.</p><ol><li>Create a Function Project (Code)</li><li>Create an Azure Function (Azure)</li><li>Deploy the Function Project to Azure</li><li>Test the Deployed Azure Function</li></ol><h3>Deploy Azure Function from Visual Studio.</h3><h4>Create a Function Project (Code)</h4><p>Let’s begin by creating a new project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*K378fOjZHSMHMDysD7MB3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/996/1*d1xhuRvAwd_1aKLXGyvp7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/860/1*i_vnaeeTjD7xyQGj97F45A.png" /></figure><p>Most HTTP trigger templates use the Authorization level Function, which requires an API key in the request. Consequently, your HTTP request typically resembles the following URL format:</p><pre>https://&lt;APP_NAME&gt;.azurewebsites.net/api/&lt;FUNCTION_NAME&gt;?code=&lt;API_KEY&gt;</pre><p>You can obtain or create this API_KEY by navigating to your Azure Function, then to the “Functions” section, and selecting “App Keys”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kr9OjTgKwuWbg7Vm_LCR0A.png" /></figure><p>For simplicity, I will use the ‘Anonymous’ authorization level.</p><p>After creating the function, you will find a file named Function1.cs containing sample code.</p><p>To deploy it, right-click on the project and select ‘Publish’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*cDDYclMgILf-eG-cbKrrPw.png" /></figure><p>Choose ‘Azure’ as the deployment target, since we are deploying code rather than a Docker container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*9zk60vqZ2L5mkMXkQ3bAcA.png" /></figure><p>Select ‘Linux’ for a lower-cost option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*FN01vswL6-d2ULh9_FId2w.png" /></figure><p>Sign in with the same account used to create the Azure Function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*FWzZFkpxaKREdAGhx99SJA.png" /></figure><h4>Create an Azure Function (Azure)</h4><p>Next, let’s create a new Azure Function from Visual Studio.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*fwRULAej7_HEPdiFLsip7g.png" /></figure><p>Fill in the required fields, and ensure you select the Consumption plan type. The Consumption plan is generally a good choice for most scenarios unless your application requires very low latency or other premium features.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/582/1*-5LgZ-XdwYLS6oWt8LIKPQ.png" /></figure><p>Select the created function and click “Next”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/783/1*dxej3syxMQUYcKa5NSEBrg.png" /></figure><p>Finally, choose the publish option and click “Finish”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/793/1*xlFvSxZFG4-UuKpmCfeMVw.png" /></figure><p>At this point, your function should be ready to publish.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*ypLPf1zEViAubdjbdnL_5g.png" /></figure><h4>Deploy the Function Project to Azure</h4><p>Let’s publish the function by clicking the “Publish” button.</p><p>You should now see a green notification indicating that your function has been successfully deployed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*Ekw5qIYgJYG6zpKmAITuQQ.png" /></figure><h4>Test the Deployed Azure Function</h4><p>Next, open the Azure Portal and navigate to your resources. You should see the new Azure Function listed. Open the function and copy the URL</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RWMuBYpFKz4j5oSXZplQtg.png" /></figure><p>Append /api/FUNCTION_NAME to the copied URL, where FUNCTION_NAME is the name of your function, as annotated in the below image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*2CudSG6sVuNMtwzeljJ74Q.png" /></figure><p>Open a new browser tab, paste the modified URL, and you should see the message “<em>Welcome to Azure Functions!</em>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/512/1*cJQJD-kvWAsZ_NbFp2fojw.png" /></figure><h3>Deploy Azure Function from Visual Studio Code.</h3><p>Let’s begin by installing the necessary extensions:</p><ul><li><a href="https://marketplace.visualstudio.com/items?itemName=ms-vscode.vscode-node-azure-pack">Azure Tools</a></li><li><a href="https://marketplace.visualstudio.com/items?itemName=ms-azuretools.vscode-azurefunctions">Azure Functions</a></li></ul><p>Once the extensions are installed, select the Azure icon and sign in to your Azure account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*LtqKLEl2USqi0vJPeeu3sg.png" /></figure><h4>Create a Function Project (Code)</h4><p>Next, create a new Azure Function Project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*KvU2W5m2AfNMHte4WYUwmw.png" /></figure><p>Select C#</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*_R3TbeFokVEIZtXLJ5W3IQ.png" /></figure><p>Choose .NET 8 Isolated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*Lik91YyViQucOAu5ro265A.png" /></figure><p>For the trigger type, select HTTP Trigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*iodYXwxdy7xB3jOochjIcQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*tcMTqsfjzFEGaPKwrDLIVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*Yjx4ovWoqF9n9Hl3GAz5OA.png" /></figure><p>Set the authorization level to Anonymous, as in the previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*i1OipWDWb8ZQ4dAI6nzYMw.png" /></figure><p>Choose to Add to Workspace to display the project in the current VS Code workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*5bYxV4_n7hIo6wm0oYgyQw.png" /></figure><p>A new Azure Function Project should now be created and visible in your workspace.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c-gv-fu969x73roJSisY5w.png" /></figure><h4>Create an Azure Function (Azure)</h4><p>Now, let’s create our Azure Function by opening the Command Palette.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*TVG-COfypubwUQwH1F2qCg.png" /></figure><p>Type Azure Functions: Create function app in Azure…(Advanced) and select it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/623/1*0qgPL3NPeEcyNX3ZRcyzBQ.png" /></figure><p>Provide a unique name for your function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*fRD-MyCjAsMGesJJ05qmdQ.png" /></figure><p>Select the Consumption plan, as in the previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/619/1*xusXdCRpCZHlKtYUCok9Cw.png" /></figure><p>Choose your preferred region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*4o8lpzFxNiNkTzJCa2fQPw.png" /></figure><p>Select .NET 8 Isolated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*x5S8z01k3DbWhRTxkcJ_ZQ.png" /></figure><p>Choose Linux as the operating system, as in the previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*EU-FcqajPsQezQ43zYa2ug.png" /></figure><p>Select your resource group.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*w8-RzFJW2KBuScHNzH5nWg.png" /></figure><p>Finally, choose a storage account in the same region.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*pXMangnwtVPlXTg0RNG9cg.png" /></figure><p>You should now see the created Azure Function under the “Function App” section in your subscription.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/433/1*_w6W7Xqwagt25EGX614T8A.png" /></figure><h4>Deploy the Function Project to Azure</h4><p>Next, let’s publish our code to the Azure Function. Right-click on the created Azure Function and select “Deploy to Function App”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*alO-0ptqwVyDFk7COEJCSQ.png" /></figure><p>Then, select “Deploy” to overwrite any previous code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/573/1*q4qvBCztAu1nJrD5T9z0bA.png" /></figure><p>You should see a success message in the output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*AKDygz5bLvDrj8P0pkjHrQ.png" /></figure><h4>Test the Deployed Azure Function</h4><p>Now, test the function the same way as in the previous example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*WtBSfoCVBK82aUnFKFHcTQ.png" /></figure><h3>Deploy Azure Function from Azure DevOps Pipeline</h3><h4>Create a Function Project (Code)</h4><p>You can create your project as we did in the previous examples using either Visual Studio or VSCode.</p><p>This time, we will push our code into an Azure DevOps Git project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s33n0FP5ahFnZM0M1OYaow.png" /></figure><h4>Create an Azure Function (Azure)</h4><p>Now, let’s create our Azure Function. You can create it using Visual Studio or VSCode as shown previously, but here I will demonstrate how to create it from the Azure Portal.</p><p>Go to the Azure Portal and search for “Function App”, and create a new function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*C67r8acbDc19QroUf33zkA.png" /></figure><p>Select Consumption as we did in the previous examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XtVJDR-1uH4tKiwderQCDw.png" /></figure><p>Fill in the required fields, then proceed to create the function.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/1*lGK3EXVTTNI89aka-SXB8Q.png" /></figure><h4>Deploy the Function Project to Azure</h4><p>To deploy our .NET code to the created Azure Function, we need to follow these steps:</p><ul><li>Build the .NET code.</li><li>Publish the .NET code.</li><li>Zip the published .dll files.</li><li>Deploy the zipped folder to the Azure Function.</li></ul><p>Usually, DevOps splits the deployment into two segments, the build pipeline and the release pipeline. These segments will be implemented as follows.</p><p><strong>Build Pipeline</strong></p><p>Let’s start by creating a new classic pipeline in Azure DevOps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pd0PLwXBCtZPAwi_yjomNg.png" /></figure><p>Choose your Azure repository.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*x5GQXewOCg_dOvrOZ5W7wQ.png" /></figure><p>Select the ASP.NET Core template.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*X4tyk_mo-YOFb1UKn2QxPw.png" /></figure><p>You should now see the pipeline configurations for a .NET application.</p><p>First, remove the Test stage, as we don’t have any tests.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HofTz2va0SQjHymWdSLrCQ.png" /></figure><p>Then, make sure to uncheck “Publish web projects.” If you created your project as an Azure Function Project, leaving this checked will cause an error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tEzqiwGERYD2wHYukOBZsw.png" /></figure><p>Choose ubuntu-latest if your function is Linux-based, otherwise, select the appropriate agent for your platform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UfHobTSguYEkGovuprmjxw.png" /></figure><p>Enable continuous integration on the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7_W_K6zww11Ri6rDUh4hgA.png" /></figure><p>Next, save the configuration and queue the pipeline to run.</p><p>If you encountered the below error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CbD34ljJGkFNVGPi4UKfEw.png" /></figure><p>follow the steps in this <a href="https://www.youtube.com/watch?v=i9qrXuilNVM">Youtube video</a> on how to configure a self-hosted agent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/746/1*yojFdVXYi35PWglMjnkZSQ.png" /></figure><p><strong>Release Pipeline</strong></p><p>Let’s create a new release and search for “functions”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PckyC1uksoco75ra9UPY4A.png" /></figure><p>Open the task jobs configurations and select your subscription. Choose the Azure Function OS and select the function created earlier in this request (in my case, it was named my-devops-function).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XIzkMp5pI-cEsThEWpTLbw.png" /></figure><ul><li>Note: Change the agent to default if you are working with a Self-Hosted agent, otherwise, ignore this step.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1Rbq_9fV-GLW0fOQWV6Eag.png" /></figure><p>Now save it and let’s create an artifact to link this release with our previously created build pipeline.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TPApqa08y3jMN_tDp_dD2g.png" /></figure><p>Enable continuous deployment by clicking on the hazard symbol. You can also add a filter so the release pipeline runs only on the main branch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Vls_aCEQ26YxK-PGitOpmg.png" /></figure><p>Lastly, Save the pipeline configuration and click “Create Release,” select the stage, and click “Run.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kbr6iUnzUJmKZiZS_Gjt6Q.png" /></figure><p>Now, let’s run our CI/CD by committing anything in the README file. You should see this reflected in the commits.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fqvJ-FZnFP4jo9vDc-b9Zg.png" /></figure><p>Navigate to Pipelines to see that the build pipeline has run successfully.</p><p>Additionally, in the Release section, you should find a new release that has been created and run successfully.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vpNvYKk6yEAD3NKH9E1jyg.png" /></figure><p>if you encountered the following error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*dG0DR4uPo19-Y_VPTeDhLA.png" /></figure><p>Then navigate to the created Azure function in the Azure Portal. Go to environment variables and select a storage account in the same region.</p><p>Create AzureWebJobsStorage as the key and its value as your storage account App Key.</p><p>To read more about this issue, refer to this <a href="https://learn.microsoft.com/en-us/answers/questions/76485/change-storage-account-of-azure-function">Microsoft thread</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ncXgCt4lc_uScq-a3D4eg.png" /></figure><p>Re-deploy your release again, it should succeed now.</p><h4>Test the Deployed Azure Function</h4><p>Finally, let’s test our function again as in the previous examples.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/638/1*xXloB593pv3DWK5wuQQx_Q.png" /></figure><blockquote><em>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</em></blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf925da5cc37" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/azure-functions-deployments-with-net-bf925da5cc37">Azure Functions Deployments with .NET</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Integrating Azure Blob Storage with .NET9 and Utilizing Azure CDN]]></title>
            <link>https://levelup.gitconnected.com/integrating-azure-blob-storage-with-net9-and-utilizing-azure-cdn-3910b70b44ae?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3910b70b44ae</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Tue, 21 May 2024 22:22:24 GMT</pubDate>
            <atom:updated>2024-05-21T22:22:24.408Z</atom:updated>
            <content:encoded><![CDATA[<h3>Integrating Azure Blob Storage with .NET9 and Utilizing Azure CDN</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*6xprvIBLeHqyvmhZsRiAiA.jpeg" /></figure><p>In continuation of the Azure integration series with .NET 9, you can explore all the previous <a href="https://medium.com/@mohamed.ebrahim.mohsen">articles on integrating Azure services with .NET 9</a> Every week, a new article is published.</p><p>In this article, I will demonstrate how to integrate Azure Blob Storage with .NET 9.</p><h3>Our Goal</h3><p>Create an account to store your application’s files, including images and JSON data. Then, following simple steps to set up a .NET 9 Web API app for uploading files to Blob Storage and leveraging the power of Azure CDN integration for enhanced content delivery.</p><h3>Set up Azure Blob Storage</h3><p>Let’s start by outlining the structure of Azure Blob storage, which has has three types of resources:</p><ol><li>Storage Account</li><li>Container in the storage account</li><li>Blob file</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/329/0*AuL_lx9RnQvj9j-d.png" /><figcaption>Reserved image (<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fcloud.telestream.net%2Ftutorials%2Fhow-to-setting-up-azure-blob-storage%2F&amp;psig=AOvVaw2VBHrtxaAA-LPbmk7ljUgg&amp;ust=1716143700622000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBAQjRxqFwoTCOD5o9Drl4YDFQAAAAAdAAAAABAU">link</a>)</figcaption></figure><p>As shown in the above image, it’s essential to note that you can’t create a blob file without having a container to host it. Similarly, you can’t have a container without a storage account to contain it.</p><p>Now, let’s create the storage account, by opening the azure portal and searching for the “storage account”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/529/1*YS_r6GJV3nwLp95X_vNnrA.png" /></figure><p>Next, create a new storage account, ensuring the name is unique across all existing storage account names in Azure.</p><p>Also, specify the replication strategy, which ensures data in your Azure storage account is replicated for durability and high availability.</p><blockquote>If you’re comfortable with no duplications for your storage and can tolerate some downtime if the storage account encounters any issues, you can choose the LRS (Locally Redundant Storage) option which offers no replication with the lowest price compared to other strategies.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*VSlPXbR4P6FNRc02wyn0cg.png" /></figure><p>Next, go to the “Advanced” tab. Then, choose the “Access tier”. Here is a table showing the differences between all the access tiers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*p_9ppeBwf8mymqwLJwUV_w.png" /></figure><p>For more details about the pricing comparison, please refer to this <a href="https://azure.microsoft.com/en-us/pricing/details/storage/blobs/">Microsoft comparison link</a>.</p><p>Here, I will choose the “cool” tier as the application is simple and there is no data need to be accessed frequently.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*oq_JdqkKN9gbekwQJYCsCg.png" /></figure><p>Then, proceed to create the storage account.</p><p>To create a blob container, navigate to the created storage account, select “Storage browser” from the left-side menu, then go to “Blob containers”, and create a blob container by clicking the “Add container” button.</p><p>I will not create it from the portal and alternatively, I’ll demonstrate how to create it from the code if it doesn’t already exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*wTkf99895h6PcQQlcLRL2A.png" /></figure><p>In order to access the blob container from the .NET 9 application, we need to do two steps:</p><p>1- Modify the storage account accessibility to be public. Navigate to the “Settings” section, then the “Configuration” tab, and enable “Allow Blob anonymous access”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*plcdxfPTZd-yusOSFY6dkg.png" /></figure><p>2- Save the “Connection string”, which is essential for connecting with our .NET application. Go to the “Security + networking” section, then select “Access keys”, and save the “Connection string”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*Cy-RzXenvOHh-Z84afBulA.png" /></figure><p>Fantastic! We’ve configured our storage account and prepared it to connect with our .NET application.</p><h3>Create a .NET 9 application and establish a connection with Blob Storage</h3><p>Let’s begin by initiating a new .NET9 Web API project. You can do this through Visual Studio or the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/0*38LltNzCLSAiq9S0.png" /></figure><pre># CLI<br>dotnet new webapi --framework net9.0 --output AzureBlobStorage</pre><p>Next, add the necessary NuGet packages.</p><pre>dotnet add package Azure.Storage.Blobs<br>dotnet add package Microsoft.Extensions.Azure</pre><p>Next, Insert the Blob Storage connection string into either the appsettings.json, secrets.json or in Azure Key Vault.</p><blockquote><em>Storing it in Azure Key Vault is advised for the highest security in managing secrets. For further guidance on configuring and utilizing Azure Key Vault, you can refer to my Medium article titled “</em><a href="https://medium.com/@mohamed.ebrahim.mohsen/mastering-azure-key-vault-integration-for-net-web-apis-405b12edaf4a"><strong><em>Mastering Azure Key Vault Integration for .NET Web APIs</em></strong></a><em>”.</em></blockquote><p>Now, configure Blob Storage dependency injection in the Program.cs file.</p><pre>builder.Services.AddAzureClients(azureBuilder =&gt;<br>{<br>    azureBuilder.AddBlobServiceClient(builder.Configuration[&quot;ConnectionStrings:BlobStorage&quot;]);<br>});</pre><p>Excellent!, we connected our application to our azure storage account.</p><p>Now, let’s explore how to upload a single blob file or multiple blob files.</p><p>Following the structure of blob storage, we first need to obtain the blob container and create one if it doesn’t exist. Then, we can proceed to upload the blob files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*AuL_lx9RnQvj9j-d.png" /><figcaption>Reserved image (<a href="https://www.google.com/url?sa=i&amp;url=https%3A%2F%2Fcloud.telestream.net%2Ftutorials%2Fhow-to-setting-up-azure-blob-storage%2F&amp;psig=AOvVaw2VBHrtxaAA-LPbmk7ljUgg&amp;ust=1716143700622000&amp;source=images&amp;cd=vfe&amp;opi=89978449&amp;ved=0CBAQjRxqFwoTCOD5o9Drl4YDFQAAAAAdAAAAABAU">link</a>)</figcaption></figure><p>Why might we need to create a blob container instead of having a pre-existing one with a constant name for all file operations?</p><p>Think of the blob container as a folder. Just like we typically have multiple folders to organize our media, having different blob containers serves a similar purpose. One valid use case is creating a new blob container for each user in your application. This ensures that all media files for each user are centralized in one place.</p><p>Let’s create a MediaController responsible for uploading media images for a specific user and returning a full URL for the uploaded image.</p><p>In this example, I’ll separate the logic of uploading media files into a new service called MediaUploader. I’ll demonstrate how to upload a single blob file and handle multiple blob files. Additionally, a new blob container will be created for users who don’t have an existing one.</p><pre>public interface IMediaUploader<br>{<br>    Task&lt;string&gt; UploadBlobFileAsync(string filePath, string blobContainerName, CancellationToken cancellationToken = default);<br>    Task&lt;List&lt;string&gt;&gt; UploadBlobFilesAsync(List&lt;string&gt; filePaths, string blobContainerName, CancellationToken cancellationToken = default);<br>}</pre><p>The IMediaUploader interface has two main methods UploadBlobFileAsync for uploading a single blob file and UploadBlobFilesAsync for handling multiple blob files.</p><p>Here’s the implementation of the IMediaUploader.</p><pre>public class MediaUploader(BlobServiceClient blobServiceClient) : IMediaUploader<br>{<br>    private readonly BlobServiceClient _blobServiceClient = blobServiceClient;<br><br>    public async Task&lt;List&lt;string&gt;&gt; UploadBlobFilesAsync(List&lt;string&gt; filePaths, string blobContainerName, CancellationToken cancellationToken = default)<br>    {<br>        var uploadTasks = new List&lt;Task&lt;string&gt;&gt;();<br><br>        foreach (var filePath in filePaths)<br>        {<br>            uploadTasks.Add(UploadBlobFileAsync(filePath, blobContainerName, cancellationToken));<br>        }<br><br>        var fileNames = await Task.WhenAll(uploadTasks);<br>        return fileNames.ToList();<br>    }<br><br>    public async Task&lt;string&gt; UploadBlobFileAsync(string filePath, string blobContainerName, CancellationToken cancellationToken = default)<br>    {<br>        var fileName = GenerateUniqueFileName(Path.GetExtension(filePath), Path.GetFileNameWithoutExtension(filePath));<br>        var containerClient = await GetBlobContainerClientAsync(blobContainerName, cancellationToken);<br>        var blobClient = containerClient.GetBlobClient(fileName);<br>        <br>        await blobClient.UploadAsync(path: filePath, overwrite: true, cancellationToken: cancellationToken);<br>        await blobClient.SetHttpHeadersAsync(new BlobHttpHeaders { ContentType = fileName.GetContentType() });<br>        <br>        return blobClient.Uri.AbsoluteUri;<br>    }<br><br>    private async Task&lt;BlobContainerClient&gt; GetBlobContainerClientAsync(string blobContainerName, CancellationToken cancellationToken)<br>    {<br>        var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName) ?? throw new Exception($&quot;could not connect to azure blob container: {blobContainerName}&quot;);<br>        <br>        await containerClient.CreateIfNotExistsAsync(PublicAccessType.BlobContainer, cancellationToken: cancellationToken);<br><br>        return containerClient;<br>    }<br><br>    public static string GenerateUniqueFileName(string extension, string prefix = &quot;&quot;)<br>    {<br>        DateTime timestamp = DateTime.UtcNow;<br>        return $&quot;{prefix}{timestamp:yyyyMMddHHmmssfff}{extension}&quot;;<br>    }<br>}</pre><p>Additionally, I’ve utilized an extension method for retrieving the media content type. Here’s how it’s implemented:</p><pre>public static class FileExtensions<br>{<br>    private static readonly FileExtensionContentTypeProvider provider = new FileExtensionContentTypeProvider();<br><br>    public static string GetContentType(this string fileName)<br>    {<br>        if (!provider.TryGetContentType(fileName, out var contentType))<br>        {<br>            contentType = &quot;application/octet-stream&quot;;<br>        }<br>        return contentType;<br>    }<br>}</pre><p>Before diving into explaining each method, remember to inject the IMediaUploader in the Program.cs.</p><pre>builder.Services.AddScoped&lt;IMediaUploader, MediaUploader&gt;();</pre><p>Let’s begin with GenerateUniqueFileName, as the name suggests, it’s a straightforward method for generating unique file names by appending the current timestamp to the file name. This helps avoid accidental overwriting of files in the future.</p><pre>public static string GenerateUniqueFileName(string extension, string prefix = &quot;&quot;)<br>{<br>    DateTime timestamp = DateTime.UtcNow;<br>    return $&quot;{prefix}{timestamp:yyyyMMddHHmmssfff}{extension}&quot;;<br>}</pre><p>Next, we have GetBlobContainerClientAsync, which attempts to retrieve the desired blob container by its name. If it doesn’t exist, it creates one. It will also throw an exception if it’s unable to connect with the Azure storage account.</p><pre>private async Task&lt;BlobContainerClient&gt; GetBlobContainerClientAsync(string blobContainerName, CancellationToken cancellationToken)<br>{<br>    var containerClient = _blobServiceClient.GetBlobContainerClient(blobContainerName) ?? throw new Exception($&quot;could not connect to azure blob container: {blobContainerName}&quot;);<br>    await containerClient.CreateIfNotExistsAsync(PublicAccessType.BlobContainer, cancellationToken: cancellationToken);<br><br>    return containerClient;<br>}</pre><p>Moving on to the UploadBlobFileAsync method, it’s responsible for uploading a single blob file to the desired blob container. Here’s how it works:</p><ol><li>Generate a new unique file name.</li><li>Retrieve the blob container client, which is essentially a connection to the blob container where the blob file will be uploaded.</li><li>Get the blob file client. Although it might seem ambiguous to get a blob client for a non-existent blob, in the blob storage SDK, the ‘get’ method is also used for creation. If a blob file with the specified name is found, it returns its blob client; otherwise, it creates a new one.</li><li>Upload the blob file using its blob client. This upload process works for both updates and initial uploads. If the blob client returned from the previous step corresponds to an existing blob, it will overwrite and update it. Otherwise, if a new blob client is created, the file will be uploaded for the first time.</li><li>Set the HttpHeaders, This step resolves a mystery issue where attempting to open a blob image in the browser and find it downloaded instead of opening in a new tab. This issue can be fixed by setting the correct content-type of the uploaded blob file.</li><li>Return the URL of the uploaded file.</li></ol><pre>public async Task&lt;string&gt; UploadBlobFileAsync(string filePath, string blobContainerName, CancellationToken cancellationToken = default)<br>{<br>    // Step #1<br>    var fileName = GenerateUniqueFileName(Path.GetExtension(filePath), Path.GetFileNameWithoutExtension(filePath));<br><br>    // Step #2<br>    var containerClient = await GetBlobContainerClientAsync(blobContainerName, cancellationToken);<br>    <br>    // Step #3<br>    var blobClient = containerClient.GetBlobClient(fileName);<br><br>    // Step #4<br>    await blobClient.UploadAsync(path: filePath, overwrite: true, cancellationToken: cancellationToken);<br>    <br>    // Step #5<br>    await blobClient.SetHttpHeadersAsync(new BlobHttpHeaders { ContentType = fileName.GetContentType() <br>    <br>    // Step #6<br>    return blobClient.Uri.AbsoluteUri;<br>}</pre><p>Next, we have the UploadBlobFilesAsync method, responsible for asynchronously uploading multiple files simultaneously. It also utilizes the GetBlobContainerClientAsync method.</p><pre>public async Task&lt;List&lt;string&gt;&gt; UploadBlobFilesAsync(List&lt;string&gt; filePaths, string blobContainerName, CancellationToken cancellationToken = default)<br>{<br>    var uploadTasks = new List&lt;Task&lt;string&gt;&gt;();<br><br>    foreach (var filePath in filePaths)<br>    {<br>        uploadTasks.Add(UploadBlobFileAsync(filePath, blobContainerName, cancellationToken));<br>    }<br><br>    var fileNames = await Task.WhenAll(uploadTasks);<br>    return fileNames.ToList();<br>}</pre><p>Following that, we have the GetContentType extension method, which simply utilizes the FileExtensionContentTypeProvider to determine the correct content type of the uploaded file. If it’s not recognized, it adds the default Azure content type for unrecognized blob files.</p><pre>public static string GetContentType(this string fileName)<br>{<br>    if (!provider.TryGetContentType(fileName, out var contentType))<br>    {<br>        contentType = &quot;application/octet-stream&quot;;<br>    }<br>    return contentType;<br>}</pre><p>Now, let’s return to our controller and begin using our MediaUploader service for uploading media files.</p><p>The controller will have two endpoints: one for uploading a single media file and another for uploading multiple media files.</p><p>The MediaController should look like this:</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class MediaController(IMediaUploader mediaUploader) : ControllerBase<br>{<br>    private readonly IMediaUploader _mediaUploader = mediaUploader;<br><br>    [HttpPost]<br>    [Route(&quot;single&quot;)]<br>    public async Task&lt;IActionResult&gt; UploadSingleMediaFileAsync([FromBody] UploadSingleFileRequest request, CancellationToken cancellationToken)<br>    {<br>        var result = await _mediaUploader.UploadBlobFileAsync(request.FilePath, request.Username, cancellationToken);<br>        return Ok(result);<br>    }<br><br>    [HttpPost]<br>    [Route(&quot;multiple&quot;)]<br>    public async Task&lt;IActionResult&gt; UploadMultipleMediaFilesAsync([FromBody] UploadMultipleFilesRequest request, CancellationToken cancellationToken)<br>    {<br>        var result = await _mediaUploader.UploadBlobFilesAsync(request.FilePaths, request.Username, cancellationToken);<br>        return Ok(result);<br>    }<br>}<br><br>public record UploadSingleFileRequest(string FilePath, string Username);<br>public record UploadMultipleFilesRequest(List&lt;string&gt; FilePaths, string Username);</pre><h3>Testing File Uploads</h3><p>Let’s run the application and test it using “Postman”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4_YfoRnsppPibHFXmUbyvA.png" /></figure><p>By copying the returned URL and pasting it in the browser, it should display the uploaded image in the browser.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5VNxkjmX_rennpthuXRHCA.png" /></figure><p>Also, by opening the Azure portal and navigating to the blob containers, you should find a new blob container created for the user “<em>mohamedmohsen</em>”. Inside it, you should find the uploaded image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3w8xJ0I-Pk5Cs37IRO-Jdg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZX93hVXBRTLF0FK-eflkxg.png" /></figure><p>Remember, you can view the image in the browser by copying the image URL and pasting it in the browser. because we have set the Content-Type of the blob file, allowing it to be viewed directly in the browser. You can verify this by clicking on the image, navigating to the CONTENT-TYPE in the properties. If it’s not set, the image will be downloaded rather than displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qrRe2antp-c93dHtmddjQ.png" /></figure><p>Additionally, you can upload other types of files such as JSON files, not only images.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cdJNj8HuTwyCU00YPIu38g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I5zHuVj9qPdiPPy_sXDEKQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v2c6zWExNB_x_ux6Pl7Uiw.png" /></figure><h3>Configure blob storage CDN</h3><p>When working with Azure Blob Storage, you can enhance performance by utilizing the Azure Content Delivery Network (CDN) to serve your static files or frequently accessed files with low latency.</p><p>To configure the CDN, navigate to the storage account and select “Front Door and CDN” from the “Security + networking” section in the left side menu.</p><p>First, create a new CDN Endpoint, which will be used to serve your application files instead of retrieving them directly from the blob containers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CEZdHXUpc-1tIrbNRNcBUQ.png" /></figure><p><strong>Service type</strong></p><p>Azure Front Door is suitable for delivering sites, services, and APIs, while Azure CDN is ideal for delivering static content such as videos, images, and PDFs.</p><p>For further insights into the difference between Front Door and CDN, I recommend reading this <a href="https://kishoregopalan.medium.com/azure-front-door-or-azure-cdn-what-solution-will-you-use-for-your-high-availability-sites-be26bb34aee7"><strong>article</strong></a>.</p><p><strong>Query string caching behavior</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/851/1*k6sXfb2M48tZQjSl3KVfDQ.png" /><figcaption>Microsoft Reserved Docs (<a href="https://learn.microsoft.com/en-us/azure/cdn/cdn-query-string">link</a>)</figcaption></figure><p>For comprehensive information, please refer to <a href="https://learn.microsoft.com/en-us/azure/cdn/cdn-query-string"><strong>Microsoft Docs</strong></a>.</p><p>Now, proceed to create the Azure CDN Endpoint.</p><p>Now, go to the created CDN resource and navigate to the created Endpoint by clicking on its name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*P1yXXwkOadsfwIGbVXaoIA.png" /></figure><p>Save the “Endpoint hostname” for later use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UYGBxR4qXNucFklb06y3w.png" /></figure><p>Great! We have configured our CDN, so any media files uploaded to the selected blob storage can now be automatically retrieved from the CDN.</p><p>Let’s run our application again and upload a new image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xvsM3r_IrwvNCW_tgAQ_iA.png" /></figure><p>Now, as before, use the returned URL to browse the uploaded image.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IS2GTGp4jAd6yKZJDFx5aA.png" /></figure><p>Let’s also attempt to retrieve the image from the CDN by replacing the URL with the created “Endpoint hostname”.</p><p>So, this URL:</p><p><em>https://mystorageaccount12457.blob.core.windows.net/</em><strong><em>mohamedmohsen/books20240519153014669.jpeg</em></strong></p><p>Should be converted to this:</p><p><em>https://myblobscdn.azureedge.net/</em><strong><em>mohamedmohsen/books20240519153014669.jpeg</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CORKc2X4eRpyZVW3CLt-Zg.png" /></figure><p>Then, let’s compare the latency performance between retrieving the image from the blob container and the CDN.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VqHssV9PBxkL1limODl1qw.png" /><figcaption>Retrieve image from Blob Container</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OIiU86LlNJXxcT1mqR9zMw.png" /><figcaption>Retrieve image from CDN</figcaption></figure><p>From the two images above, you can observe that for this lightweight image, the latency is enhanced by around <strong>750%</strong>.</p><h3>GitHub repository</h3><p>You can find all the code used in this <a href="https://github.com/dotnet-azure/AzureBlobStorage"><strong>GitHub repository</strong></a>.</p><blockquote><em>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</em></blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3910b70b44ae" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/integrating-azure-blob-storage-with-net9-and-utilizing-azure-cdn-3910b70b44ae">Integrating Azure Blob Storage with .NET9 and Utilizing Azure CDN</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate Azure Cache for Redis with .NET9]]></title>
            <link>https://medium.com/@mohamed.ebrahim.mohsen/how-to-integrate-azure-cache-for-redis-with-net9-a22306947f82?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a22306947f82</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[redis]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Sat, 18 May 2024 14:23:24 GMT</pubDate>
            <atom:updated>2024-05-18T14:23:24.462Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to integrate Azure for Redis with .NET9</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*vKEb__dz1_b_IPt1G1eDdg.jpeg" /></figure><p>In continuation of the Azure integration series with .NET 9, you can explore all the previous <a href="https://medium.com/@mohamed.ebrahim.mohsen">articles on integrating Azure services with .NET 9</a> Every week, a new article is published.</p><p>In this article, I will demonstrate how to integrate Azure Cache for Redis with .NET 9.</p><h3>Our Goal</h3><p>Our goal is to set up Azure for Redis. Then, we’ll integrate it with a .NET9 web API application to fetch data from the cache. If the data isn’t found, we’ll add it to the cache. We’ll also implement caching strategies and eviction policies. Finally, we’ll view our cached keys and values in VSCode.</p><h3>Set up Azure Cache for Redis</h3><p>Let’s begin by searching for “azure caching for redis” in the Azure portal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*zwfZVgyS9_b2JjYhLaWGmA.png" /></figure><p>After that, create a new Redis cache by entering a unique DNS name. Then, choose the Cache SKU and Cache size.</p><p>Be careful of selecting the most suitable plan since it can be expensive. For this simple application, I opted for the smallest and cheapest one.</p><blockquote>If you’re unsure about your needs, start with the minimum and upgrade as necessary. Sometimes, caching strategies and eviction policies can address issues, which we’ll explore later in this article.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*5rYFy7dREDmeWQMMRkzEgQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*NQ9Se57_h5cu21v1L6pDCg.png" /></figure><p>Now, let’s create it. After that, go to the Azure Cache for Redis resource you just created and select “Authentication” from the menu on the left side.</p><p>Save the “Primary connection string” as you’ll need it shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JJIzfFDjwM9U5moGqvkfZg.png" /></figure><p>Now, our Redis caching is created and ready to connect with applications and be used.</p><h3>Create a .NET 9 application and establish a connection with Redis.</h3><p>Let’s begin by initiating a new .NET9 Web API project. You can do this through Visual Studio or the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/931/1*TCgnssWQucHhptf4tMWskA.png" /></figure><pre># CLI<br>dotnet new webapi --framework net9.0 --output AzureCachingForRedis</pre><p>Next, add the necessary NuGet packages.</p><pre>dotnet add package Microsoft.Extensions.Caching.StackExchangeRedis</pre><p>Next, Insert the Redis connection string into either the appsettings.json or secrets.json file.</p><blockquote>Storing it in Azure Key Vault is advised for the utmost security in managing secrets. For further guidance on configuring and utilizing Azure Key Vault, you can refer to my Medium article titled “<a href="https://medium.com/@mohamed.ebrahim.mohsen/mastering-azure-key-vault-integration-for-net-web-apis-405b12edaf4a"><strong>Mastering Azure Key Vault Integration for .NET Web APIs</strong></a>”.</blockquote><p>Now, inject Redis into the Program.cs file.</p><pre>builder.Services.AddStackExchangeRedisCache(option =&gt;<br>{<br>    option.Configuration = builder.Configuration[&quot;ConnectionStrings:RedisCache&quot;];<br>});</pre><p>Excellent, the connection between Redis and the .NET application is now configured. Let’s proceed by creating a test controller to validate our connection.</p><p>We’ll design a Products controller responsible for retrieving product information from the cache. If the information isn’t found in the cache, it will fetch it from the database and then store it in the cache for subsequent retrievals.</p><p>Below is how the ProductsController will be structured.</p><pre><br>[ApiController]<br>[Route(&quot;{controller}&quot;)]<br>public class ProductsController : ControllerBase<br>{<br>    private readonly IDistributedCache _cache;<br><br>    public ProductsController(IDistributedCache cache)<br>    {<br>        _cache = cache;<br>    }<br><br>    [HttpGet]<br>    public async Task&lt;ActionResult&lt;Product&gt;&gt; Get(int id, CancellationToken cancellationToken)<br>    {<br>        var cachedProduct = await _cache.GetStringAsync(id.ToString(), cancellationToken);<br>        <br>        if (cachedProduct != null)<br>        {<br>            return Ok(JsonSerializer.Deserialize&lt;Product&gt;(cachedProduct));<br>        }<br><br>        var dbProduct = Product.DbProducts.Where(p =&gt; p.Id == id).FirstOrDefault();<br><br>        if (dbProduct is null)<br>        {<br>            return NotFound();<br>        }<br><br>        await _cache.SetStringAsync(dbProduct.Id.ToString(), JsonSerializer.Serialize(dbProduct), cancellationToken);<br>        return Ok(dbProduct);<br>    }<br>}<br><br>public class Product<br>{<br>    public int Id { get; set; }<br>    public string Name { get; set; }<br>    public double Price { get; set; }<br><br>    // Simulates the database products.<br>    public static List&lt;Product&gt; DbProducts = <br>        [<br>            new(){ Id = 1, Name = &quot;T-Shirt&quot;, Price = 30 },<br>            new(){ Id = 2, Name = &quot;Jeans&quot;, Price = 70 },<br>            new(){ Id = 3, Name = &quot;Dress&quot;, Price = 95 },<br>            new(){ Id = 4, Name = &quot;Ball&quot;, Price = 6 },<br>            new(){ Id = 5, Name = &quot;Laptop&quot;, Price = 400 },<br>        ];<br>}</pre><p>Next, let’s run the application and attempt to retrieve a value for a key that hasn’t been inserted yet. It should fetch the product from the database and cache it for future use.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPf8nmXPV57OJgiNYg7PaQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1tmdT0jP1Sahbxt2GNAt-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g1wq1yu6Y13pi8MC1mWcqA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*APmMdjKd8aaU2sKOJCJVAw.png" /></figure><p>Now, let’s attempt to retrieve the same product once more. This time, it should be served from the cache rather than from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tkcy47fUqNWbsT_rFF-aFw.png" /></figure><p>The product will now always be served from the cache until it expires.</p><h3>Configure an expiration of a key</h3><p>Configuring key expiration is crucial for efficient caching, preventing stale data from occupying storage that could be utilized for other purposes or necessitating an upgrade to the current caching plan.</p><p>You have three options for expiration: AbsoluteExpiration, AbsoluteExpirationRelativeToNow, and SlidingExpiration, which can also be combined.</p><ul><li><strong>AbsoluteExpiration:</strong> Set a fixed date for expiration, like June 1st, 2024.</li><li><strong>AbsoluteExpirationRelativeToNow:</strong> Specify a time span from the present moment, for instance, expire after 15 minutes from now, similar to how cookies work.</li><li><strong>SlidingExpiration:</strong> Determine that if the key hasn’t been accessed within a particular timeframe, it should be removed. For instance, if the value is set to one minute, every time the key is requested, the timer resets and starts counting anew. If the key remains untouched for a minute, it expires, gets removed from the cache, and will subsequently be fetched from the database. A new timer is then set.</li></ul><p>You can implement these expiration methods by including a new parameter, DistributedCacheEntryOptions</p><p>Here’s how to configure each one of them:</p><pre>var options = new DistributedCacheEntryOptions()<br>{<br>    AbsoluteExpirationRelativeToNow = TimeSpan.FromMinutes(15)<br>};<br><br>await _cache.SetStringAsync(dbProduct.Id.ToString(), JsonSerializer.Serialize(dbProduct), options, cancellationToken);</pre><pre>var options = new DistributedCacheEntryOptions()<br>{<br>    // Expire at 1st of June 2024 at 7:00AM<br>    AbsoluteExpiration = new DateTime(2024, 6, 1, 7, 0, 0)<br>};<br><br>await _cache.SetStringAsync(dbProduct.Id.ToString(), JsonSerializer.Serialize(dbProduct), options, cancellationToken);</pre><pre>var options = new DistributedCacheEntryOptions()<br>{<br>    SlidingExpiration = TimeSpan.FromMinutes(1)<br>};<br><br>await _cache.SetStringAsync(dbProduct.Id.ToString(), JsonSerializer.Serialize(dbProduct), options, cancellationToken);</pre><p>Additionally, you have the option to combine these expiration methods to achieve specific behaviors. For instance, if you want a key to have a relative expiration of a maximum of 30 days, but also to be removed if it hasn’t been accessed for 6 hours, you can combine AbsoluteExpirationRelativeToNow with SlidingExpiration.</p><pre>var options = new DistributedCacheEntryOptions()<br>{<br>    SlidingExpiration = TimeSpan.FromHours(6),<br>AbsoluteExpirationRelativeToNow = TimeSpan.FromDays(30)<br>};<br><br>await _cache.SetStringAsync(dbProduct.Id.ToString(), JsonSerializer.Serialize(dbProduct), options, cancellationToken);</pre><h3>View your Azure Cache for Redis data in VSCode</h3><p>Open VSCode and search for “Azure Cache” plugin, then install it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oyMd6puIs3BQ7GUojDWrCQ.png" /></figure><p>Next, move to the Azure tab, and sign in with your azure account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/431/1*Ndwc1OH7IK4sd-TIkw0DJg.png" /></figure><p>Now, you can easily access your cached data by selecting your caching resource and navigating to the data section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/825/1*9LFvjaRuFjpbU3FKkp69IQ.png" /></figure><h3>GitHub repository</h3><p>You can find all the code used in this <a href="https://github.com/dotnet-azure/AzureCachingForRedis"><strong>GitHub repository</strong></a>.</p><blockquote><em>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</em></blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a22306947f82" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ERROR: Could not find a version that satisfies the requirement [FIXED]]]></title>
            <link>https://python.plainenglish.io/error-could-not-find-a-version-that-satisfies-the-requirement-fixed-146e270fe877?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/146e270fe877</guid>
            <category><![CDATA[fastapi]]></category>
            <category><![CDATA[python3]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[python-programming]]></category>
            <category><![CDATA[python-web-developer]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Mon, 13 May 2024 00:13:03 GMT</pubDate>
            <atom:updated>2024-05-20T02:34:38.545Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*45ccipSextRNdo_tkNNCKA.jpeg" /></figure><p>Hello! Recently, while deploying my company’s Python FastAPI application, I encountered a challenge. The company mad a decision to maintain all cloud EC2 instances offline, disconnected from the internet. This posed a problem as I couldn’t use the standard pip install command.</p><p>After some research, I discovered a way of downloading the dependencies offline.</p><h3>Story</h3><p>Let’s say our dependencies are listed in a requirements.txt file as the following:</p><pre>aiocache==0.12.2<br>fastapi==0.111.0<br>uvicorn==0.29.0<br>requests==2.31.0</pre><p>Here’s how you can install the requirements offline:</p><ul><li>Create a folder named offline-packages</li><li>Within this folder, create a subfolder for each dependency, without specifying any versions for simplicity.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/124/1*0e_y9ihWWFs9BcHwRvROZg.png" /></figure><ul><li>Now, execute the following command to download each dependency. Alternatively, you can create a .bat file to automate this process.</li></ul><pre>pip download aiocache -d &quot;your path\offline-packages\aiocache&quot;<br>pip download fastapi  -d &quot;your path\offline-packages\fastapi&quot;<br>pip download requests -d &quot;your path\offline-packages\requests&quot;<br>pip download uvicorn  -d &quot;your path\offline-packages\uvicorn&quot;</pre><ul><li>Once all the required packages are downloaded, zip the folder and upload it to the server. This way, you can ensure seamless installation of dependencies even in an offline environment.</li></ul><p>Now, let’s open our EC2 instance, unzip the offline-packages.zip and list all the files</p><p>Next, let’s navigate to the offline-packages/aiocache folder and start installing it offline by running this command</p><pre>cd your-path/aiocache<br>pip install aiocache --no-index -f &quot;./&quot;</pre><p>The installation was successful, as evidenced below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BaiSNhVNevIK4BcJ-oucig.png" /></figure><p>Now, let’s attempt to install a dependency that encounters an issue, so we can address it accordingly.</p><pre>cd your-path/fastapi<br>pip install fastapi--no-index -f &quot;./&quot;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HmcnqhXT8s_wklDsg5YReQ.png" /></figure><p>As demonstrated, the installation failed.</p><p>After numerous attempts, I discovered that the EC2 instance is running Python version 3.9, whereas our local environment utilizes Python version 3.11. Despite attempts to downgrade all packages to align with Python 3.9, this effort proved useless after investing considerable time in the process.</p><h3>Solution</h3><p>Install the same Python version on your machine (Python 3.9 in my case).</p><p>Then, install the virtualenvlibrary.</p><pre>pip install virtualenv</pre><p>Create a virtual environment using the installed Python version.</p><pre>virtualenv -p &quot;C:\Users\your-user\AppData\Local\Programs\Python\Python39\python.exe&quot; &quot;your-path\myenv&quot;</pre><p>Activate the myenv virtual environment by running the appropriate activation command.</p><pre>cd your-path\myenv\Scripts\activate</pre><p>Once activated, you’ll notice that the prompt in your terminal changes to indicate that you are now working within the virtual environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*z1ioziEGSc-9RDMyh-qjXg.png" /></figure><p>Navigate to the same dependency in the offline-packages directory that is causing the issue. For example, let’s navigate to fastapi.</p><p>Run the installation command for the dependency. This will likely result in the same error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bstdfzxVaUJEwa8-ePCtg.png" /></figure><p>Ensure you take careful note of the error message, especially the part that pinpoints the problematic dependency, like exceptiongroup.</p><p>Now, since the virtual environment is connected to the internet, try running this installation command again. This time, the command should execute successfully.</p><pre>pip install fastapi -f &quot;./&quot;</pre><p>This command works like magic, instructing the pip installer to install whatever it can find in the folder. If it encounters any missing packages, it simply fetches them from the internet. Additionally, as it installs, it provides a list of all the correct dependencies required for the library to function properly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*N8jzRw9QM7H1BLfJ0Y9wQw.png" /></figure><p>Here’s an example of the log when downloading new libraries:</p><pre>Collecting ujson!=4.0.2,!=4.1.0,!=4.2.0,!=4.3.0,!=5.0.0,!=5.1.0,&gt;=4.0.1 (from fastapi)<br>  Downloading ujson-5.9.0-cp39-cp39-win_amd64.whl.metadata (8.9 kB)<br>Collecting orjson&gt;=3.2.1 (from fastapi)<br>  Downloading orjson-3.10.3-cp39-none-win_amd64.whl.metadata (50 kB)<br>     ---------------------------------------- 50.9/50.9 kB 369.9 kB/s eta 0:00:00<br>Collecting MarkupSafe&gt;=2.0 (from jinja2&gt;=2.11.2-&gt;fastapi)<br>  Downloading MarkupSafe-2.1.5-cp39-cp39-win_amd64.whl.metadata (3.1 kB)<br>Collecting annotated-types&gt;=0.4.0 (from pydantic!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,&lt;3.0.0,&gt;=1.7.4-&gt;fastapi)<br>  Using cached annotated_types-0.6.0-py3-none-any.whl.metadata (12 kB)<br>Collecting pydantic-core==2.18.2 (from pydantic!=1.8,!=1.8.1,!=2.0.0,!=2.0.1,!=2.1.0,&lt;3.0.0,&gt;=1.7.4-&gt;fastapi)<br>  Using cached pydantic_core-2.18.2-cp39-none-win_amd64.whl.metadata (6.7 kB)<br>Requirement already satisfied: click&gt;=7.0 in c:\workspace\git_projects\virtualenvs\myenv-01\lib\site-packages (from uvicorn&gt;=0.12.0-&gt;uvicorn[standard]&gt;=0.12.0-&gt;fastapi) (8.1.7)<br>Requirement already satisfied: colorama&gt;=0.4 in c:\workspace\git_projects\virtualenvs\myenv-01\lib\site-packages (from uvicorn[standard]&gt;=0.12.0-&gt;fastapi) (0.4.6)<br>Collecting httptools&gt;=0.5.0 (from uvicorn[standard]&gt;=0.12.0-&gt;fastapi)<br>  Downloading httptools-0.6.1-cp39-cp39-win_amd64.whl.metadata (3.7 kB)<br>Collecting python-dotenv&gt;=0.13 (from uvicorn[standard]&gt;=0.12.0-&gt;fastapi)<br>  Using cached python_dotenv-1.0.1-py3-none-any.whl.metadata (23 kB)<br>Collecting pyyaml&gt;=5.1 (from uvicorn[standard]&gt;=0.12.0-&gt;fastapi)<br>  Downloading PyYAML-6.0.1-cp39-cp39-win_amd64.whl.metadata (2.1 kB)<br>Collecting watchfiles&gt;=0.13 (from uvicorn[standard]&gt;=0.12.0-&gt;fastapi)<br>  Downloading watchfiles-0.21.0-cp39-none-win_amd64.whl.metadata (5.0 kB)<br>Collecting websockets&gt;=10.4 (from uvicorn[standard]&gt;=0.12.0-&gt;fastapi)<br>  Downloading websockets-12.0-cp39-cp39-win_amd64.whl.metadata (6.8 kB)<br>Collecting exceptiongroup&gt;=1.0.2 (from anyio-&gt;httpx&gt;=0.23.0-&gt;fastapi)<br>  Using cached exceptiongroup-1.2.1-py3-none-any.whl.metadata (6.6 kB)</pre><p>To troubleshoot dependency issues while installing in offline mode, follow these steps:</p><ol><li>Save all the logs output from the console during installation.</li><li>Identify the library causing the errors (shown as red lines).</li><li>Search for the problematic library in the logs.</li><li>Copy its full name until the .whl extension.</li><li>Search for the library’s full name in a search engine.</li><li>Choose the first PYPI link.</li><li>Navigate to the Downloaded files section.</li><li>Search for the downloaded .whl file.</li><li>Download the file.</li><li>Copy the downloaded file to your dependency folder.</li><li>Run the offline installation command again.</li><li>Repeat the process if another library causes dependency issues.</li></ol><p>It’s important to understand that .whl files come in three types: Windows, Linux, macOS and .whl file can support any of these operating systems. You can differentiate between them by looking at their names.</p><ul><li>charset_normalizer-3.3.2-py3-none-<strong>any</strong>.whl</li><li>charset_normalizer-3.3.2-cp312-cp312-<strong>win</strong>_amd64.whl</li><li>charset_normalizer-3.3.2-cp312-cp312-many<strong>linux</strong>_2_17_s390x.manylinux2014_s390x.whl</li><li>charset_normalizer-3.3.2-cp37-cp37m-<strong>macosx</strong>_10_9_x86_64.whl</li></ul><h3>Example of applying the same steps to the dependency &quot;exceptiongroup&quot;</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9bstdfzxVaUJEwa8-ePCtg.png" /><figcaption>Find the library that cause the error</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*f5dkb097nN3MhH4Oee4Xbw.png" /><figcaption>Find the needed exact .whl version to be installed</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu-YdwRhIDvkpgudjuMHwg.png" /><figcaption>Searching for the .whl file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cd0Uhr7HCiq15V39omHIOQ.png" /><figcaption>Download the .whl file</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/341/1*f67d0CbC_HEuQT9Bo8sS5w.png" /><figcaption>Copied the downloaded .whl file to the fastapi folder</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pv_gzNhLccbRuKRv4UDtlw.png" /><figcaption>Issue fixed and fastapi installed successfully</figcaption></figure><h3>Other Options</h3><ol><li>Upgrading the server’s Python version to match the local environment might resolve the problem.</li><li>Temporary internet connectivity for the server could resolve the issue by enabling access to required dependencies.</li></ol><h3>Optimal Solution</h3><p>For such issues, Containers like Docker Containers offer the most effective solution. However, constraints such as policies may prevent their use, as was the case in my situation.</p><blockquote>I hope this article was able to address your concern and provide a solution to resolve the issue you encountered.</blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><h3>In Plain English 🚀</h3><p><em>Thank you for being a part of the </em><a href="https://plainenglish.io/"><strong><em>In Plain English</em></strong></a><em> community! Before you go:</em></p><ul><li>Be sure to <strong>clap</strong> and <strong>follow</strong> the writer ️👏<strong>️️</strong></li><li>Follow us: <a href="https://twitter.com/inPlainEngHQ"><strong>X</strong></a><strong> | </strong><a href="https://www.linkedin.com/company/inplainenglish/"><strong>LinkedIn</strong></a><strong> | </strong><a href="https://www.youtube.com/channel/UCtipWUghju290NWcn8jhyAw"><strong>YouTube</strong></a><strong> | </strong><a href="https://discord.gg/in-plain-english-709094664682340443"><strong>Discord</strong></a><strong> | </strong><a href="https://newsletter.plainenglish.io/"><strong>Newsletter</strong></a></li><li>Visit our other platforms: <a href="https://stackademic.com/"><strong>Stackademic</strong></a><strong> | </strong><a href="https://cofeed.app/"><strong>CoFeed</strong></a><strong> | </strong><a href="https://venturemagazine.net/"><strong>Venture</strong></a><strong> | </strong><a href="https://blog.cubed.run/"><strong>Cubed</strong></a></li><li>Tired of blogging platforms that force you to deal with algorithmic content? Try <a href="https://differ.blog/"><strong>Differ</strong></a></li><li>More content at <a href="https://plainenglish.io/"><strong>PlainEnglish.io</strong></a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=146e270fe877" width="1" height="1" alt=""><hr><p><a href="https://python.plainenglish.io/error-could-not-find-a-version-that-satisfies-the-requirement-fixed-146e270fe877">ERROR: Could not find a version that satisfies the requirement [FIXED]</a> was originally published in <a href="https://python.plainenglish.io/">Python in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to integrate Azure CosmosDB with .NET9]]></title>
            <link>https://medium.com/@mohamed.ebrahim.mohsen/how-to-integrate-azure-cosmosdb-with-net9-5acbe635f489?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/5acbe635f489</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[azure]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[nosql]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Sun, 12 May 2024 18:57:59 GMT</pubDate>
            <atom:updated>2024-05-12T18:57:59.127Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to integrate Azure CosmosDB with .NET9</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*H8zOrtJqNmzXGudvCbASOQ.jpeg" /></figure><p>In continuation of the Azure integration series with .NET 9, you can explore all the previous <a href="https://medium.com/@mohamed.ebrahim.mohsen">articles on integrating Azure services with .NET 9</a> Every week, a new article is published. In this article, I’ll demonstrate how to integrate Azure Cosmos DB NoSQL with .NET 9.</p><h3>Our Goal</h3><p>We aim to establish a CosmosDB NoSQL database named store-db and set up a table within it named orders. Subsequently, we will utilize a .NET9 web API application to establish a connection with the database and execute all CRUD operations on the orders table.</p><h3>Create CosmosDB NoSQL database</h3><p>Let’s begin by opening the Azure Portal and searching for CosmosDB.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*mCFgRsUjnE_2mEuLhi9KAQ.png" /><figcaption><a href="https://portal.azure.com/#home">Azure portal</a></figcaption></figure><p>Create a new Azure Cosmos DB account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1017/1*maWVmnygQqPjVuWHx6nHfw.png" /></figure><p>Multiple options will appear. Select “Azure Cosmos DB for NoSQL.”</p><p>To learn more about the differences between each Cosmos DB account, you can read my Medium article “<a href="https://medium.com/@mohamed.ebrahim.mohsen/azure-cosmosdb-types-of-accounts-explained-77d6114bb6ec"><strong>Azure CosmosDB: Types of Accounts Explained</strong></a>”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Nz4Nl9p66P2zSIx5I2U0XQ.png" /></figure><p>Enter your desired name and select the capacity mode.</p><p>Azure Cosmos DB offers two capacity modes: <strong>provisioned throughput</strong> and <strong>serverless</strong>. While both modes allow you to execute the same database operations, they differ significantly in billing methods.</p><p>For a comprehensive overview of the differences between these modes, watch this <a href="https://www.microsoft.com/en-us/videoplayer/embed/RE4S1ML"><strong>video</strong></a> from the Microsoft Cosmos DB team.</p><p>I’ve chosen “Provisioned throughput” since it aligns with the free-tier subscription I’m currently using.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ih7OvXV9Yjdr2ZT954pWTQ.png" /></figure><p>Keep the other defaults and proceed to create it.</p><p>After the database is successfully created, go to the created resource, then navigate to the “Data Explorer” and create a new container.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZMD_81hYr21VCfmm3R_4NQ.png" /></figure><p>You can think of the container as the database table. Usually, when creating a new container, you need to select the database to which it belongs. Since this is the first time, you’ll find a section for creating a new database.</p><p>Let’s create an orders table and name our database store-db</p><p>Then, we need to set the most important thing, which is the “<strong>Partition key</strong>”. The partition key is used to automatically distribute data across partitions for scalability. Choose a property in your JSON document that has a wide range of values and evenly distributes request volume.</p><p>For small read-heavy or write-heavy workloads of any size, id is often a good choice.</p><p>Take your time to choose the right partition key for read-heavy or write-heavy workloads to avoid falling into the trap of hot partition issues.</p><blockquote>A hot partition refers to a situation where one partition in a database receives significantly more traffic or requests than other partitions. This can cause performance bottlenecks, reduce system efficiency, and lead to delays in accessing data.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/732/1*vk6Cg-gE6kSUlAcmRu722A.png" /></figure><p>Next, set the unique ID, which is optional. Unique keys add a layer of data integrity to your database by ensuring the uniqueness of one or more values per partition key.</p><p>For demonstration purposes, I’m using the UserId as the partition key and OrderId as the unique ID. However, this setup may not be suitable for read-heavy or write-heavy applications.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/407/1*jmKku5-04rBvyhWp3xDsoA.png" /></figure><p>Now our Azure CosmosDB NoSQL is configured and ready to be connected with the .NET application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*oLJN5CtFpkjbHuBJTSsplw.png" /></figure><p>Before proceeding to connect to the .NET app, let’s prepare the CosmosDB database connection string, which will be needed for the integration. You can find it by navigating to “<strong>Keys</strong>” and copying the primary connection string.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7FJuYo30Nq1xTVBNVkLEyg.png" /></figure><h3>Creating a .NET9 Web API and connecting it with CosmosDB</h3><p>Let’s begin by initiating a new .NET9 Web API project. You can do this through Visual Studio or the CLI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/924/1*k7TwVX_gEGUok1NuFomELw.png" /></figure><pre>dotnet new webapi --framework net9.0 --output AzureCosmosDbNoSql</pre><p>Next, add the necessary NuGet packages.</p><pre>dotnet add package Microsoft.Azure.Cosmos<br>dotnet add package Microsoft.EntityFrameworkCore.Cosmos</pre><p>Next, add the CosmosDB connection string in the appsettings.json or secrets.json. It’s recommended to store it in Azure Key Vault, which is considered the most secure way to manage secrets.</p><p>For more details on configuring and using Azure Key Vault, you can read my Medium article “<a href="https://medium.com/@mohamed.ebrahim.mohsen/mastering-azure-key-vault-integration-for-net-web-apis-405b12edaf4a"><strong>Mastering Azure Key Vault Integration for .NET Web APIs</strong></a>”.</p><p>Then, inject the CosmosDB in the Program.cs</p><pre>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>{<br>    options.UseCosmos(builder.Configuration[&quot;ConnectionStrings-CosmosDB&quot;]!, &quot;store-db&quot;);<br>});</pre><p>Now, let’s establish the CRUD endpoints for our orders table.</p><p>Typically, nowadays CRUD operations are managed through a repository class. Here, I’ve set up a simple repository to mimic real-world scenarios.</p><pre>public class OrdersRepository(AppDbContext context)<br>{<br>    protected readonly AppDbContext _context = context;<br>    protected readonly DbSet&lt;Order&gt; _dbset = context.Set&lt;Order&gt;();<br><br>    public async Task&lt;Order&gt; GetAsync(Guid userId, Guid orderId, CancellationToken cancellationToken)<br>    {<br>        return await _dbset.FirstAsync(e =&gt; e.UserId == userId &amp;&amp; e.OrderId == orderId, cancellationToken);<br>    }<br><br>    public async Task AddAsync(Order entity, CancellationToken cancellationToken) =&gt; await _dbset.AddAsync(entity, cancellationToken);<br>    public void Update(Order entity) =&gt; _dbset.Update(entity);<br>    public async Task DeleteAsync(Guid userId, Guid orderId, CancellationToken cancellationToken)<br>    {<br>        var entity = await GetAsync(userId, orderId, cancellationToken);<br>        _dbset.Remove(entity);<br>    }<br>    public async Task SaveChangesAsync(CancellationToken cancellationToken) =&gt; await _context.SaveChangesAsync(cancellationToken);<br>}</pre><p>Below is the OrdersController</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class OrdersController(OrdersRepository ordersRepository) : ControllerBase<br>{<br>    private readonly OrdersRepository _ordersRepository = ordersRepository;<br><br>    [HttpGet]<br>    public async Task&lt;ActionResult&lt;Order&gt;&gt; Get(Guid userId, Guid orderId, CancellationToken cancellationToken)<br>    {<br>        return Ok(await _ordersRepository.GetAsync(userId, orderId, cancellationToken));<br>    }<br><br>    [HttpPost]<br>    public async Task&lt;ActionResult&gt; Post([FromBody] Order order, CancellationToken cancellationToken)<br>    {<br>        await _ordersRepository.AddAsync(order, cancellationToken);<br>        await _ordersRepository.SaveChangesAsync(cancellationToken);<br>        return Ok();<br>    }<br><br>    [HttpPut]<br>    public async Task&lt;ActionResult&gt; Put([FromBody] Order order, CancellationToken cancellationToken)<br>    {<br>        _ordersRepository.Update(order);<br>        await _ordersRepository.SaveChangesAsync(cancellationToken);<br>        return Ok();<br>    }<br><br>    [HttpDelete]<br>    public async Task&lt;ActionResult&gt; Delete(Guid userId, Guid orderId, CancellationToken cancellationToken)<br>    {<br>        await _ordersRepository.DeleteAsync(userId, orderId, cancellationToken);<br>        await _ordersRepository.SaveChangesAsync(cancellationToken);<br>        return Ok();<br>    }<br>}</pre><p>Ensure to include the OrdersRepository in the dependency injection.</p><pre>builder.Services.AddScoped&lt;OrdersRepository&gt;();</pre><p>Your Program.cs should look something like this:</p><pre>using AzureCosmosDbNoSql;<br>using AzureCosmosDbNoSql.Controllers;<br>using Microsoft.EntityFrameworkCore;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>{<br>    options.UseCosmos(builder.Configuration[&quot;ConnectionStrings-CosmosDB&quot;]!, &quot;store-db&quot;);<br>});<br><br>builder.Services.AddScoped&lt;OrdersRepository&gt;();<br><br>builder.Services.AddControllers();<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>var app = builder.Build();<br><br>if (app.Environment.IsDevelopment())<br>{<br>    app.UseSwagger();<br>    app.UseSwaggerUI();<br>}<br><br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>app.MapControllers();<br>app.Run();</pre><p>Now, let’s run the app and utilize Postman to test all the CRUD operations.</p><p>1- Add a new order</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iAzs0i8M346uLSbYdgYMBA.png" /></figure><p>You can view the created order in Azure Cosmos DB by navigating to the “Data Explorer”, selecting your database, then choosing the table. Finally, click on “Items” to see all the added orders displayed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6FwJBnhi0LbxGxBMkZQbpA.png" /></figure><p>2- Update the added order’s Total to be 700 instead of 500</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*djmQavAQrVjam3Y9LAzU6w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BYBnLKqfKosOHg6XWqq5GQ.png" /></figure><p>3- Get an order with UserIdand OrderId</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E29gHuan0AhHulqoblMRzA.png" /></figure><p>4- Delete an order with UserIdand OrderId</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tzn-IkVupxAzyTZofMKh4g.png" /></figure><p>Now, you’ll notice that the orders table becomes empty after deleting the order from it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2zYz3xd_fFdZhyldVJ1TUg.png" /></figure><h3>GitHub repository</h3><p><a href="https://github.com/dotnet-azure/AzureCosmosDbNoSql">GitHub - dotnet-azure/AzureCosmosDbNoSql</a></p><blockquote><em>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</em></blockquote><p><a href="https://medium.com/@mohamed.ebrahim.mohsen/subscribe"><strong>+ Subscribe to get notified about new articles!</strong></a></p><p><a href="https://medium.com/@mohamed.ebrahim.mohsen"><strong>+ Follow me on Medium for more articles!</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5acbe635f489" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Azure CosmosDB: Types of Accounts Explained]]></title>
            <link>https://medium.com/@mohamed.ebrahim.mohsen/azure-cosmosdb-types-of-accounts-explained-77d6114bb6ec?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/77d6114bb6ec</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[mongodb]]></category>
            <category><![CDATA[nosql]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Sat, 11 May 2024 21:06:30 GMT</pubDate>
            <atom:updated>2024-05-11T21:06:30.032Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEdAeYfih-_7_wpBZkD-IA.png" /></figure><h3>Azure Cosmos DB for NoSQL</h3><p>Azure Cosmos DB’s Core API provides native support for working with documents.</p><p>It facilitates rapid and flexible development using a familiar SQL query language and client libraries for .NET, JavaScript, Python, and Java.</p><p>While it employs a similar structure and syntax to working with traditional SQL, the key distinction lies in storing data within a NoSQL container rather than conventional SQL tables.</p><pre>builder.Services.AddDbContext&lt;TweetsDbContext&gt;(options =&gt;<br>{<br>    options.UseCosmos(client.GetSecret(&quot;ConnectionStrings-Tweets-CosmosDB&quot;).Value.Value, &quot;tweets-db&quot;);<br>});</pre><pre>await _tweetRepository.AddAsync(tweet, cancellationToken);<br>await _tweetRepository.SaveChangesAsync(cancellationToken);</pre><p>As demonstrated above, despite working with a NoSQL database, the syntax remains identical. Therefore, this option is most suitable for developers experienced and familiar with SQL.</p><h3>Azure Cosmos DB for MongoDB</h3><p>If you’re currently using MongoDB and looking to migrate to CosmosDB, or if you’re familiar with MongoDB syntax and drivers, you can choose this option and treat CosmosDB just like MongoDB.</p><p>Similar to the previous example where we utilized SQL syntax to interact with CosmosDB NoSQL in .NET, integrating CosmosDB for MongoDB offers the same querying and development experience, leveraging existing expertise, whether you’re integrating it with NodeJS, Go, or other platforms.</p><h3>Azure Cosmos DB for PostgreSQL</h3><p>Fully-managed relational database service for PostgreSQL with distributed query execution.</p><p>It’s important to understand and distinguish between CosmosDB’s PostgreSQL and Azure’s PostgreSQL.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/759/1*tnuonZZWpAB4X3fVVy4OyA.png" /><figcaption>Reserved for Microsoft blog (<a href="https://devblogs.microsoft.com/cosmosdb/azure-cosmos-db-for-postgresql-vs-azure-database-for-postgresql-when-to-choose-which/">link</a>)</figcaption></figure><p>Remember: Azure Cosmos DB for PostgreSQL is a relational database option.</p><h3>Azure Cosmos DB for Apache Gremlin</h3><p>Azure Cosmos DB for Apache Gremlin is a graph database service designed to store enormous graphs containing billions of vertices and edges.</p><p>Queries on these graphs yield results in milliseconds, and adjusting the graph’s structure is straightforward.</p><p>The Gremlin API is constructed upon Apache TinkerPop, a graph computing framework that employs the Gremlin query language.</p><h3>Azure Cosmos DB for Apache Cassandra</h3><p>If you’re currently using Apache Cassandra and considering a migration to Cosmos DB, you can seamlessly transition while leveraging your familiarity with Apache Cassandra’s syntax and drivers.</p><h3>Azure Cosmos DB for Table</h3><p>Fully managed database service for apps written for Azure Table storage.</p><p>also the already existed applications written for Azure Table Storage using the Azure Tables SDKs can be migrated to the Azure Cosmos DB with no code changes to take advantage of premium capabilities.</p><p>it’s recommended to use the Azure Cosmos DB for Table instead of the azure table storage as it’s more faster and also has low latency by its SLA, which guarantee that your data will be retrieved in less than 10 milli-seconds which make it incredibly fast.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_9uMnypttSQdLAQjKQ5RoA.png" /><figcaption>Reserved for YouTube channel video (<a href="https://www.youtube.com/watch?v=J5fsKMkRqV8">link</a>)</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/857/1*dJBtXvmj_mo9sWRlhm7xYw.png" /><figcaption>Reserved for Microsoft docs (<a href="https://learn.microsoft.com/en-us/azure/cosmos-db/table/introduction#api-for-table-benefits">link</a>)</figcaption></figure><blockquote>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=77d6114bb6ec" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[.NET8 Identity: Register, Login, Email Confirmation, and Two-Factor Authentication (2FA)]]></title>
            <link>https://medium.com/@mohamed.ebrahim.mohsen/net8-identity-register-login-email-confirmation-and-two-factor-authentication-2fa-c8acfbc3e14c?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8acfbc3e14c</guid>
            <category><![CDATA[identity]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[two-factor-authentication]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Sat, 11 May 2024 14:16:15 GMT</pubDate>
            <atom:updated>2024-05-11T14:16:15.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZOdZR1Lrf4meXh-LzML3ng.jpeg" /></figure><p>Starting a new project and tackling authentication and authorization from scratch can be exhausted. It often involves creating login and registration features, which can be time-consuming. Challenges like managing refresh tokens and implementing two-factor authentication add to the complexity.</p><p>Thankfully, with the arrival of .NET 8, these tasks are greatly simplified, requiring minimal configuration.</p><p>In this article, I aim to guide you through various identity configuration scenarios, including:</p><ul><li>Basic registration and login.</li><li>Securing endpoints with Bearer tokens.</li><li>Retrieving user information.</li><li>Email confirmation.</li><li>Resend email confirmation.</li><li>Change default settings and add custom user properties.</li><li>Configure two-factor authentication (MVC).</li></ul><p>Prerequisites: .NET 8 or later.</p><p>Before proceeding, let me outline my current environment setup:</p><ul><li>.NET Web API application.</li><li>Visual Studio 2022.</li><li>Utilizing SQLite to simulate a real database instead of an in-memory database.</li></ul><p>Next, let’s install the necessary NuGet packages.</p><pre>dotnet add package Microsoft.AspNetCore.Identity.EntityFrameworkCore<br>dotnet add package Microsoft.EntityFrameworkCore.Design<br>dotnet add package Microsoft.EntityFrameworkCore.Sqlite<br>dotnet add package Microsoft.EntityFrameworkCore.Tools</pre><h3>Basic registration and login.</h3><p>Firstly, start by creating the DbContext where all the identity-generated tables will be stored.</p><pre>// IdentityUser is the Microsoft base identity class.<br>// creates empty scheme with just all the identity tables.<br>class AppDbContext : IdentityDbContext&lt;IdentityUser&gt;<br>{<br>    public AppDbContext(DbContextOptions options) : base(options)<br>    {<br>    }<br>}</pre><p>Next, we’ll register the authentication and authorization middleware&#39;s, offering the flexibility to choose between bearer tokens or cookies. In this example, we’ll opt for bearer tokens, facilitating the retrieval of a bearer token upon logging in.</p><pre>// Program.cs<br>builder.Services.AddAuthentication()<br>                .AddBearerToken(IdentityConstants.BearerScheme);<br><br>builder.Services.AddAuthorizationBuilder();</pre><p>Following that, we’ll register our DbContext, which in this example is a SQLite database.</p><pre>// Program.cs<br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>{<br>    options.UseSqlite(&quot;DataSource=app.db&quot;);<br>});</pre><p>After that, we need to connect the DbContext as the identity store so that all actions are directed towards the SQLite database.</p><pre>// Program.cs<br>builder.Services.AddIdentityCore&lt;IdentityUser&gt;()<br>    .AddEntityFrameworkStores&lt;AppDbContext&gt;()<br>    .AddApiEndpoints();</pre><p>Lastly, we need to add all the endpoints to be part of our application’s endpoints. This can be achieved by mapping the identity endpoints after building the builder.</p><pre>app.MapIdentityApi&lt;IdentityUser&gt;();</pre><p>Your Program.cs file should now resemble this structure.</p><pre>using Microsoft.AspNetCore.Identity;<br>using Microsoft.EntityFrameworkCore;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddControllers();<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddAuthentication()<br>                .AddBearerToken(IdentityConstants.BearerScheme);<br><br>builder.Services.AddAuthorizationBuilder();<br><br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>{<br>    options.UseSqlite(&quot;DataSource=app.db&quot;);<br>});<br><br>builder.Services.AddIdentityCore&lt;IdentityUser&gt;()<br>    .AddEntityFrameworkStores&lt;AppDbContext&gt;()<br>    .AddApiEndpoints();<br><br>var app = builder.Build();<br><br>app.MapIdentityApi&lt;IdentityUser&gt;();<br><br><br>app.UseSwagger();<br>app.UseSwaggerUI();<br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>app.MapControllers();<br><br>app.Run();</pre><p>Before running your application, don’t forget to add a new migration and update the database by executing the following commands from the Package Manager Console.</p><pre>Add-Migration initial<br>Update-Database</pre><p>Now, run your application and open Swagger. You should see a collection of endpoints automatically generated for you.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VcnyhnsiFc152wACRwj38w.png" /><figcaption>Generated identity endpoints.</figcaption></figure><p>Attempt to register a new user. If you try to create a new user with an invalid email address or a password that doesn’t meet the criteria, the identity will return an error along with the specific details of the occurrence.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*naQBLAFZBdvr12efDEErVQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4fx3eiRjVSeRP29FmoTxg.png" /></figure><p>Now, let’s proceed with the login process. If the email or password provided is not valid, the identity will return a 401 Unauthorized status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*s_kzJG3H37HV9q-1bM-htQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6Hmka8zUAN42vxgRvleiA.png" /></figure><h3>Securing endpoints with Bearer tokens.</h3><p>After configuring the authentication to return a bearer token, we’ll need to utilize this bearer token with any protected endpoint that requires authorization.</p><p>It’s essential to note that the tokens generated are not standard JSON Web Tokens (JWT). This decision was intentional, as the built-in identity is primarily intended for simple scenarios. The token option is not meant to serve as a fully-featured identity service provider or token server but rather an alternative to the cookie option for clients that cannot use cookies.</p><p>Now, let’s attempt to access an authorized endpoint, specifically the /manage/info endpoint. If you try to access it from Swagger, it will show an unauthorized error. Next, use Postman to login, save the accessToken, and include it when calling the /manage/info endpoint. This time, it should return the desired results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JG-uzQvvvrQRSbJagNKaVw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*svCMcXChZuc6O1HsSU9P-w.png" /></figure><h3>Retrieving user information</h3><p>To retrieve the currently logged-in user’s information at any moment, utilize the ClaimsPrincipal class, which stores the information of the current logged-in user.</p><p>To achieve this with the Minimal API approach:</p><pre>app.Map(&quot;/&quot;, (ClaimsPrincipal user) =&gt; $&quot;Hello {user.Identity!.Name}&quot;)<br>    .RequireAuthorization();</pre><p>For the controller approach:</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class TestController: ControllerBase<br>{<br>    [HttpGet]<br>    [Authorize]<br>    public string Get()<br>    {<br>        return User.Identity!.Name;<br>    }<br>}</pre><p>Ensure to note that the above examples utilize the “<strong>!</strong>” operator, implying that the identity is expected to always exist without the possibility of being null. This assumption holds true as both are authorized endpoints requiring prior login. However, it’s advisable to verify the existence of the identity to prevent potential null reference exceptions.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yPWGD0kBEO-mTm151g9drw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j36b63JeWAoSAbBbQk8AsA.png" /></figure><h3>Email confirmation</h3><p>Microsoft is recommending using SendGrid or another email service to send email rather than SMTP. SMTP is difficult to secure and set up correctly.</p><p>In this tutorial, SendGrid is used to send email. A SendGrid account and key is needed to send email. See <a href="https://sendgrid.com/free/">Get Started with SendGrid for Free</a> to register for a free SendGrid account.</p><p>1- Configure the SendGrid required information in the secrets.json file. Avoid adding these settings directly to the appsettings.json file to mitigate security risks.</p><pre>{<br>  &quot;SendGridKey&quot;: &quot;your send-grid key&quot;,<br>  &quot;From&quot;: &quot;your registered email&quot;,<br>  &quot;Name&quot;: &quot;your registered name&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2gdcvU0bRGpO3MIK0ljj8Q.png" /><figcaption>Registered email and name</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yr2tOH3ejbevVYHgxItgcQ.png" /><figcaption>SendGrid API key</figcaption></figure><p>2- Install the necessary NuGet packages.</p><pre>#.NET CLI<br>dotnet add package SendGrid<br>dotnet add package SendGrid.Extensions.DependencyInjection</pre><p>3- Implement IEmailSender</p><p>To Implement IEmailSender, create EmailSender.cs with code similar to the following:</p><pre>using Microsoft.AspNetCore.Identity.UI.Services;<br>using SendGrid;<br>using SendGrid.Helpers.Mail;<br><br>namespace Identity;<br><br>public class EmailSender : IEmailSender<br>{<br>    private readonly ILogger _logger;<br>    private readonly IConfiguration _configuration;<br><br>    public EmailSender(IConfiguration configuration, ILogger&lt;EmailSender&gt; logger)<br>    {<br>        _configuration = configuration;<br>        _logger = logger;<br>    }<br><br>    public async Task SendEmailAsync(string toEmail, string subject, string message)<br>    {<br>        var sendGridKey = _configuration[&quot;SendGridKey&quot;];<br>        ArgumentNullException.ThrowIfNullOrEmpty(sendGridKey, nameof(sendGridKey));<br>        await Execute(sendGridKey, subject, message, toEmail);<br>    }<br><br>    public async Task Execute(string apiKey, string subject, string message, string toEmail)<br>    {<br>        var client = new SendGridClient(apiKey);<br><br>        var msg = new SendGridMessage()<br>        {<br>            From = new EmailAddress(_configuration[&quot;From&quot;], _configuration[&quot;Name&quot;]),<br>            Subject = subject,<br>            PlainTextContent = message,<br>            HtmlContent = message<br>        };<br><br>        msg.AddTo(new EmailAddress(toEmail));<br><br>        // Disable click tracking.<br>        // See https://sendgrid.com/docs/User_Guide/Settings/tracking.html<br>        msg.SetClickTracking(false, false);<br><br>        var response = await client.SendEmailAsync(msg);<br>        _logger.LogInformation(response.IsSuccessStatusCode<br>                               ? $&quot;Email to {toEmail} queued successfully!&quot;<br>                               : $&quot;Failure Email to {toEmail}&quot;);<br>    }<br>}</pre><p>4- Inject EmailService into Program.cs to enable its usage.</p><pre>// Program.cs<br>builder.Services.AddTransient&lt;IEmailSender, EmailSender&gt;();</pre><p>5- Enforce sign-in confirmation and integrate the SendGrid service.</p><p>Now, if you attempt to register again, it will work, but you’ll notice that no email confirmation is sent. Additionally, users can log in without any confirmation being required.</p><p>To address this and ensure the correct flow, we need to first require email confirmation during the signing process. Then, we need to integrate the SendGrid service so that the identity framework can utilize it.</p><pre>// Program.cs<br><br>builder.Services.AddIdentityCore&lt;IdentityUser&gt;(options =&gt;<br>{<br>    options.SignIn.RequireConfirmedEmail = true;<br>})<br><br>builder.Services.AddSendGrid(options =&gt;<br>    options.ApiKey = builder.Configuration[&quot;SendGridKey&quot;]!<br>);</pre><p>Your Program.cs file should now resemble this structure.</p><pre>using Identity;<br>using Microsoft.AspNetCore.Identity;<br>using Microsoft.AspNetCore.Identity.UI.Services;<br>using Microsoft.EntityFrameworkCore;<br>using SendGrid.Extensions.DependencyInjection;<br>using System.Security.Claims;<br><br>var builder = WebApplication.CreateBuilder(args);<br><br>builder.Services.AddControllers();<br>builder.Services.AddEndpointsApiExplorer();<br>builder.Services.AddSwaggerGen();<br><br>builder.Services.AddAuthentication()<br>                .AddBearerToken(IdentityConstants.BearerScheme);<br><br>builder.Services.AddSendGrid(options =&gt;<br>    options.ApiKey = builder.Configuration[&quot;SendGridKey&quot;]!<br>);<br><br>builder.Services.AddTransient&lt;IEmailSender, EmailSender&gt;();<br><br>builder.Services.AddAuthorizationBuilder();<br><br>builder.Services.AddDbContext&lt;AppDbContext&gt;(options =&gt;<br>{<br>    options.UseSqlite(&quot;DataSource=app.db&quot;);<br>});<br><br>builder.Services.AddIdentityCore&lt;IdentityUser&gt;(options =&gt;<br>{<br>    options.SignIn.RequireConfirmedEmail = true;<br>})<br>    .AddEntityFrameworkStores&lt;AppDbContext&gt;()<br>    .AddApiEndpoints();<br><br>var app = builder.Build();<br><br>app.MapIdentityApi&lt;IdentityUser&gt;();<br><br>app.Map(&quot;/&quot;, (ClaimsPrincipal user) =&gt; $&quot;Hello {user.Identity!.Name} from minimal apis.&quot;)<br>    .RequireAuthorization();<br><br>app.UseSwagger();<br>app.UseSwaggerUI();<br>app.UseHttpsRedirection();<br>app.UseAuthorization();<br>app.MapControllers();<br><br>app.Run();</pre><p>Now, it’s time to test our application. Try registering a new user and check your email for a confirmation link. Clicking the link should change the confirmation status in the database to TRUE.</p><p>Remember to check your spam folder, as emails often end up there. Additionally, note that emails are queued before being sent, so expect a slight delay of a few seconds.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jZe3UbwzNRi8hpIbUQN73A.png" /><figcaption>Register new user</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/581/1*MPr7RAoM4PJYTOmhxkaSsw.png" /><figcaption>Visual studio logs</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DbwC5ddzQz3jNrYpcgOwKQ.png" /><figcaption>User created in the databse</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/776/1*v_iyhF9jFIjw2cKFit9Sww.png" /><figcaption>Confirmation link email</figcaption></figure><p>By clicking the link “clicking here,” it should redirect you back to localhost and update the user’s confirmation status in the database to TRUE.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*eJARK9xhLt0nFKnqG7B-PQ.png" /><figcaption>Confirmation message</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6fMbWgT2OLeR8RDK4DpXtg.png" /><figcaption>Confirmation status changed to TRUE</figcaption></figure><p>Lastly, with the SendGrid service injected, we can streamline our EmailService, resulting in fewer lines of code.</p><p>Here is an updated version of the EmailService that should effectively handle all the tested scenarios.</p><pre><br>using Microsoft.AspNetCore.Identity.UI.Services;<br>using SendGrid;<br>using SendGrid.Helpers.Mail;<br><br>public class EmailSender : IEmailSender<br>{<br>    private readonly ILogger _logger;<br>    private readonly IConfiguration _configuration;<br>    private readonly ISendGridClient _sendGridClient;<br><br><br>    public EmailSender(IConfiguration configuration, ILogger&lt;EmailSender&gt; logger, ISendGridClient sendGridClient)<br>    {<br>        _configuration = configuration;<br>        _logger = logger;<br>        _sendGridClient = sendGridClient;<br>    }<br><br>    public async Task SendEmailAsync(string toEmail, string subject, string message)<br>    {<br>        var msg = new SendGridMessage()<br>        {<br>            From = new EmailAddress(_configuration[&quot;From&quot;], _configuration[&quot;Name&quot;]),<br>            Subject = subject,<br>            PlainTextContent = message,<br>            HtmlContent = message<br>        };<br>        msg.AddTo(new EmailAddress(toEmail));<br><br>        var response = await _sendGridClient.SendEmailAsync(msg);<br>        _logger.LogInformation(response.IsSuccessStatusCode<br>                               ? $&quot;Email to {toEmail} queued successfully!&quot;<br>                               : $&quot;Failure Email to {toEmail}&quot;);<br>    }<br>}</pre><h3><strong>Resend email confirmation</strong></h3><p>You’ll certainly need the option to resend confirmation emails, a feature crucial for any application. .NET 8 Identity provides a resend confirmation endpoint: simply call /resendConfirmationEmail and set the body as follows:</p><pre>{<br>  &quot;Email&quot;: &quot;user email&quot;<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5ugswPh9pvWQeocjpr3LwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/745/1*56dkShNcmyTWPaVHZyaMLw.png" /></figure><h3>Change default settings and add custom user properties</h3><p>Microsoft Identity also provides the capability to modify default settings or introduce new custom attributes.</p><p>Adjust default settings.</p><pre>builder.Services.Configure&lt;IdentityOptions&gt;(options =&gt;<br>{<br>    // Password settings.<br>    options.Password.RequireDigit = true;<br>    options.Password.RequireLowercase = true;<br>    options.Password.RequireNonAlphanumeric = true;<br>    options.Password.RequireUppercase = true;<br>    options.Password.RequiredLength = 6;<br>    options.Password.RequiredUniqueChars = 1;<br><br>    // Lockout settings.<br>    options.Lockout.DefaultLockoutTimeSpan = TimeSpan.FromMinutes(5);<br>    options.Lockout.MaxFailedAccessAttempts = 5;<br>    options.Lockout.AllowedForNewUsers = true;<br><br>    // User settings.<br>    options.User.AllowedUserNameCharacters = &quot;abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._@+&quot;;<br>    options.User.RequireUniqueEmail = false;<br>});</pre><p>Adding new custom properties into user attributes. This can be achieved by creating a new user class, AppUser, inheriting from IdentityUser.</p><pre>class AppUser : IdentityUser <br>{<br>    public int MyProperty { get; set; }<br>}</pre><p>Subsequently, a new migration needs to be added, and the new property should be integrated into the AspNetUserstable.</p><p>Remember to update every occurrence of IdentityUserin your application to AppUser</p><h3>Configure two-factor authentication (MVC)</h3><p>Before we go, here is some concepts it’s good to know before we start.</p><p><strong>What is Multi-factor authentication (MFA)?</strong></p><p>Multi-factor authentication (MFA) enhances security by requiring users to provide additional forms of identification during the sign-in process. This could include entering a code from a cellphone, using a FIDO2 key, or providing a fingerprint scan. By requiring a second form of authentication, MFA makes it more difficult for attackers to gain unauthorized access, as the additional factor is not easily obtained or duplicated.</p><p><strong>What is Two-factor authentication (2FA)?</strong></p><p>Two-factor authentication (2FA) is like a subset of MFA, but the difference being that MFA can require two or more factors to prove the identity.</p><p><strong>What is TOTP (Time-based One-time Password Algorithm)?</strong></p><p>MFA using TOTP is supported by default when using ASP.NET Core Identity. This approach can be used together with any compliant authenticator app, including:</p><ul><li>Microsoft Authenticator</li><li>Google Authenticator</li></ul><p><strong>What is MFA SMS?</strong></p><p>MFA with SMS increases security massively compared with password authentication (single factor). However, using SMS as a second factor is no longer recommended. Too many known attack vectors exist for this type of implementation.</p><p><strong>What is Fast Identity Online (FIDO)?</strong><br>FIDO is an open standard for passwordless authentication, allowing users to sign in without passwords. FIDO2 keys, typically USB but also Bluetooth or NFC, enhance security by removing password risks.<br>They are currently considered the most secure MFA methods available.</p><p>Now, let’s begin configuring the 2FA.</p><p>We’ll leverage the integration of 2FA with an MVC project. When you create a new MVC project for the first time, there’s an option to generate the identity system, including Register, Login, and 2FA, from the outset. Our first step is to create a new MVC project.</p><p>In Visual Studio 2022, you can accomplish the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/577/1*MHr_NCJGPMeaYvYlKtsy0Q.png" /></figure><p>Select the individual accounts identity option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1011/1*aGjNt9WIJyJKVKDAR-l3WA.png" /></figure><p>Alternatively, you can use the command line.</p><pre>dotnet new mvc -n &quot;2FA&quot; -au individual</pre><p>The created project should resemble the following.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*SKGw9P3wBigVh9odxuGKQA.png" /></figure><p>Now, run the created project. A welcome page should appear with login and register buttons.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gktZ97b6Le2i38eGkA-GnQ.png" /></figure><p>Click “Register” to create a new user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/555/1*YlCDfWeECPdsHGyMQXJlyg.png" /></figure><p>Confirm your email by clicking “Click here to confirm your account.”</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Be_y0ptwyZATwk6VopQ6g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pe1L5JIbpAs_mv7JQtWLcg.png" /></figure><p>Next, logout and then login again. Click on your email at the top right.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rC1bSZ8dmPRnsPMZ3cf2xw.png" /></figure><p>Navigate to the Two-factor authentication section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SBOyi1FpA7Jf60OR6mIAuA.png" /></figure><p>Click “Add authenticator app” The two-factor authentication setup screen should appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S9u0Rr3720U3NGPVlHmeKw.png" /></figure><p>As you can see, it’s added out of the box for you, but without the option of scanning the QR code; it only works with a code.</p><p>Now, let’s add the QR code feature, allowing users to simply scan the QR code to add the key automatically.</p><p>We need to access the generated cshtml pages that were created for us. By default, these pages are located in Areas/Identity/Pages directory. However, if you haven’t expanded the directory, dotnet won’t show you the files unless they’re generated.</p><p>To do this, run the command.</p><pre>dotnet tool install -g dotnet-aspnet-codegenerator</pre><p>Next, we need to install all the necessary NuGet packages.</p><pre>dotnet add pacakge Microsoft.EntityFrameworkCore.Design<br>dotnet add package Microsoft.VisualStudio.Web.CodeGeneration.Design</pre><p>Then, run the code generator and specify which pages we want to retrieve. By default, if you leave it blank, it will generate numerous pages. However, to avoid cluttering your project with unnecessary pages, we’ll specify the specific page we need.</p><pre>cd &quot;your project directory&quot;<br>dotnet aspnet-codegenerator identity -dc _2FA.Data.ApplicationDbContext --files &quot;Account.Manage.EnableAuthenticator&quot;</pre><p>To view all the files that you can generate, run the command.</p><pre>dotnet aspnet-codegenerator identity -dc _2FA.Data.ApplicationDbContext -lf</pre><p>Here is a full list of all the files that could be generated.</p><pre>File List:<br>Account._StatusMessage<br>Account.AccessDenied<br>Account.ConfirmEmail<br>Account.ConfirmEmailChange<br>Account.ExternalLogin<br>Account.ForgotPassword<br>Account.ForgotPasswordConfirmation<br>Account.Lockout<br>Account.Login<br>Account.LoginWith2fa<br>Account.LoginWithRecoveryCode<br>Account.Logout<br>Account.Manage._Layout<br>Account.Manage._ManageNav<br>Account.Manage._StatusMessage<br>Account.Manage.ChangePassword<br>Account.Manage.DeletePersonalData<br>Account.Manage.Disable2fa<br>Account.Manage.DownloadPersonalData<br>Account.Manage.Email<br>Account.Manage.EnableAuthenticator<br>Account.Manage.ExternalLogins<br>Account.Manage.GenerateRecoveryCodes<br>Account.Manage.Index<br>Account.Manage.PersonalData<br>Account.Manage.ResetAuthenticator<br>Account.Manage.SetPassword<br>Account.Manage.ShowRecoveryCodes<br>Account.Manage.TwoFactorAuthentication<br>Account.Register<br>Account.RegisterConfirmation<br>Account.ResendEmailConfirmation<br>Account.ResetPassword<br>Account.ResetPasswordConfirmation</pre><p>Back in Visual Studio, you should now see the EnableAuthenticator.cshtml file added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/617/1*7NgILa6cFJp8d9-jU1z_Xw.png" /></figure><p>Before editing the EnableAuthenticator.cshtml file, we need to download the <a href="https://davidshimjs.github.io/qrcodejs/">qrcode.js</a> JavaScript library, which will render and generate the QR code for us. Save it in the wwwroot\lib folder.</p><p>Here, I renamed it to just qrcodejs</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/354/1*5lHmVSX-kqsFuJMcCCYNrQ.png" /></figure><p>Next, create a new file call it qr.js in the wwwroot\jswith the following code.</p><pre>window.addEventListener(&quot;load&quot;, () =&gt; {<br>  const uri = document.getElementById(&quot;qrCodeData&quot;).getAttribute(&#39;data-url&#39;);<br>  new QRCode(document.getElementById(&quot;qrCode&quot;),<br>    {<br>      text: uri,<br>      width: 150,<br>      height: 150<br>    });<br>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/209/1*0zCirTpQX9SnaNaYqWJWSA.png" /></figure><p>Lastly, open the EnableAuthenticator.cshtml file then:</p><ul><li>Update the Scripts section to add a reference to the qrcode.js library previously downloaded.</li><li>Add the qr.js file with the call to generate the QR code.</li></ul><pre>@section Scripts {<br>    @await Html.PartialAsync(&quot;_ValidationScriptsPartial&quot;)<br><br>    &lt;script type=&quot;text/javascript&quot; src=&quot;~/lib/qrcodejs/qrcode.js&quot;&gt;&lt;/script&gt;<br>    &lt;script type=&quot;text/javascript&quot; src=&quot;~/js/qr.js&quot;&gt;&lt;/script&gt;<br>}</pre><p>Run the application again, the QR code should now appear.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*L6iJEszlvvZEM3VrWBGSeg.png" /></figure><p>Scan it with your Authenticator app, and it should work perfectly.</p><p>By adding it to your authenticator app, you can verify the code from the generated codes in the app. It should show you the 2FA confirmation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6z7BhUPu7nbpeHTLiFHFSw.png" /></figure><p>Now, try logging out and then logging in again. The 2FA form will appear, prompting you to enter a 2FA code.</p><p>Congratulations, your 2FA has been set up perfectly.</p><blockquote>If you enjoyed this article and are hungry for more .NET and Azure content, consider following me for regular updates and fresh insights into the world of .NET and Azure development</blockquote><h3>GitHub repository</h3><p><a href="https://github.com/dotnet-azure/identity">GitHub - dotnet-azure/identity</a></p><h3>References</h3><ul><li><a href="https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity?view=aspnetcore-8.0&amp;tabs=visual-studio">Introduction to Identity on ASP.NET Core</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/security/authentication/accconfirm?view=aspnetcore-8.0&amp;tabs=visual-studio">Account confirmation and password recovery in ASP.NET Core</a></li><li><a href="https://devblogs.microsoft.com/dotnet/whats-new-with-identity-in-dotnet-8/">What&#39;s new with identity in .NET 8 - .NET Blog</a></li><li><a href="https://www.twilio.com/en-us/blog/how-to-send-asp-net-core-identity-emails-with-twilio-sendgrid">How to send ASP.NET Core Identity emails with Twilio SendGrid</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-api-authorization?view=aspnetcore-8.0">Use Identity to secure a Web API backend for SPAs</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/security/authentication/scaffold-identity?view=aspnetcore-8.0&amp;tabs=netcore-cli">Scaffold Identity in ASP.NET Core projects</a></li><li><a href="https://learn.microsoft.com/en-us/aspnet/core/security/authentication/identity-enable-qrcodes?view=aspnetcore-8.0&amp;viewFallbackFrom=aspnetcore-1.1">Enable QR code generation for TOTP authenticator apps in ASP.NET Core</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8acfbc3e14c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Azure Key Vault Integration for .NET Web APIs]]></title>
            <link>https://medium.com/@mohamed.ebrahim.mohsen/mastering-azure-key-vault-integration-for-net-web-apis-405b12edaf4a?source=rss-abd0cf67189c------2</link>
            <guid isPermaLink="false">https://medium.com/p/405b12edaf4a</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[keyvault]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[azure]]></category>
            <dc:creator><![CDATA[Mohamed Mohsen]]></dc:creator>
            <pubDate>Mon, 06 May 2024 21:38:05 GMT</pubDate>
            <atom:updated>2024-05-06T21:38:05.959Z</atom:updated>
            <content:encoded><![CDATA[<h3>Mastering Azure Key Vault Integration for .NET Web APIs</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jXK5TTvjEHcl1HUxJNpGqA.jpeg" /></figure><p>Embark on a journey to secure your .NET Web API application with Azure Key Vault. In this comprehensive guide, I’ll walk you through the seamless integration of your application with Azure Key Vault, Microsoft’s cutting-edge cloud service for securely storing and managing sensitive information.</p><p>As of the time of writing, the latest version of .NET is .NET 9. If you are using an older version of .NET, the configurations may differ slightly or remain the same.</p><p>Now, let’s dive in and unlock the full potential of Azure Key Vault in your .NET Web API application!</p><h3>What is Azure Key Vault?</h3><p>Azure Key Vault is a cloud service provided by Microsoft Azure for securely storing and managing sensitive information such as <strong>keys</strong>, <strong>secrets</strong>, <strong>certificates</strong>, and <strong>connection strings</strong>. It helps in protecting cryptographic keys and secrets used by cloud applications and services.</p><h3>Why Azure Key Vault?</h3><ol><li><strong>Centralized Management</strong>: Key Vault centralizes sensitive data storage and management.</li><li><strong>Security</strong>: Ensures high-level security for cryptographic keys and secrets.</li><li><strong>Monitoring Access and Usage</strong>: You can monitor activity by enabling logging for your vaults. <br>​ ​ ​​​ ​ ​​​ ​​ ​ ​​​ ​ ​​​ ​. Archive to a storage account.<br>​ ​ ​​​ ​ ​​​ ​​ ​ ​​​ ​ ​​​ ​. Stream to an event hub.<br>​ ​ ​​​ ​ ​​​ ​​ ​ ​​​ ​ ​​​ ​. Send the logs to Azure Monitor logs.</li><li><strong>Compliance</strong>: Helps meet regulatory standards with access controls and auditing.</li><li><strong>Integration</strong>: Seamlessly integrates with Azure services and applications.</li><li><strong>Developer Productivity</strong>: Simplifies data management, allowing focus on application development.</li></ol><h3>Integrate with .NET9 Web API</h3><p>To seamlessly integrate a .NET Web API application with Azure Key Vault, follow these steps:</p><ol><li>Create and configure Azure Key Vault secrets.</li><li>Register your application in Azure App Registrations.</li><li>Incorporate the secret configurations into the appsettings.json</li><li>Utilize dependency injection to inject the secrets, enabling their use throughout the application.</li></ol><h4>Create and configure Azure Key Vault secrets</h4><p>If you’ve already created your Key Vault, feel free to skip the initial steps.</p><p>To create and configure Azure Key Vault secrets:</p><ol><li>Navigate to the Azure portal homepage and search for “Key Vault”.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*SmsNfyYGqaB2C8fSNL3gwg.png" /><figcaption><a href="https://portal.azure.com/#home">Azure portal search bar</a></figcaption></figure><p>2. Create a new Key Vault and select a unique name for it.</p><p>3. Choose the pricing tier based on your requirements.</p><p>Azure Key Vault offers two service tiers: <strong>Standard </strong>and <strong>Premium</strong>.</p><p>The Standard tier encrypts data with a software key, while the Premium tier includes hardware security module (HSM)-protected keys. <br>You can review the details on the <a href="https://azure.microsoft.com/pricing/details/key-vault/">Azure Key Vault pricing page</a>.</p><p>For this demonstration, I’ve selected the Standard tier, but you have the option to choose Premium if needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/846/1*rFvjRQQ2s3vUheOEkTX0ww.png" /></figure><p>4. Set the permission level</p><p>Now, navigate to the “<strong>Access configuration</strong>” tab, where you’ll be able to configure the permission model.</p><p>Authorization may be done via <strong>Azure role-based access control</strong> (Azure RBAC) or <strong>Key Vault access policy</strong>.</p><p>Azure RBAC can be used for both management of the vaults and to access data stored in a vault, while key vault access policy can only be used when attempting to access data stored in a vault.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*sKKJpruIfwHvbqxOFjPJug.png" /></figure><p>5. Keep all settings as default and proceed to create the Key Vault.</p><p>6. After creating the Key Vault, navigate to the created resource, and from the left sidebar, go to “Secrets” to create a new secret.</p><p>7. Select your desired secret name.</p><p>In this example, I’m creating a secret named “MyConnectionString”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qSbIITHlXBRTs9_4gD5lOA.png" /></figure><p>If you encounter a warning or error after creating the secret, following the steps outlined in this <a href="https://stackoverflow.com/questions/69971341/unable-to-create-secrets-in-azure-key-vault-if-using-azure-role-based-access-con#answer-69971679">Stack Overflow solution</a> will resolve the issue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/929/1*QYwBDKghv8i5hLb2F8zt9w.png" /><figcaption>Warning</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*ap8RzrLpfhMIwbqq5NXLbA.png" /><figcaption>Error</figcaption></figure><p>Remember:</p><ul><li>Azure Key Vault is a cloud service for securely storing and accessing secrets.</li><li>A secret is anything that you want to tightly control access to, such as API keys, passwords, certificates, or cryptographic keys.</li></ul><h4>Register our application in Azure App Registrations.</h4><p>Back to the Azure portal homepage and search for “app registrations”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*OLU0teYzCjQq-OZw2uTxTQ.png" /><figcaption><a href="https://portal.azure.com/#home">Azure portal search bar</a></figcaption></figure><p>Create a new registration and specify your application name, then proceed to create it.</p><p><em>By registering our app, we are informing the Key Vault that we have an application that needs to access the Key Vault secrets.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/826/1*8coycUa_7bomSu5EsTDILg.png" /><figcaption>New registration</figcaption></figure><p>After registration, although we have a registered app and a Key Vault, we still need to connect them.</p><p>This is achieved by creating a <strong>client secret</strong> for our registered application and adding an <strong>authorization role policy</strong>.</p><p>This policy informs the Key Vault to grant our application access to the secrets.</p><p><strong>Create a new client secret.</strong></p><p>Navigate to “Certificates &amp; secrets” in App Registrations from the left sidebar, then create a new client secret and specify the secret name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m62NvS8T75Bqp1P21qj2_A.png" /><figcaption>New client secret</figcaption></figure><p>Next, add the necessary policy with role assignment. Navigate to the Key Vault resource, select “Access control (IAM)” from the left sidebar, then choose the “Role assignments” tab, and click “Create role assignment”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G6lIT8neJ3Mwbe8ahEsoXg.png" /></figure><p>Search for the required role. In this example, I used an admin role. Make sure to select the needed role, then click “Next” and proceed to create it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SMf2HLoBRHh_nAAaKPPblg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfIgUziw3o1T4SO6-3yHbQ.png" /></figure><p>Before proceeding to the next section, ensure you have the following information ready:</p><ul><li>Vault URI</li><li>Client Id</li><li>Tenant Id</li><li>Client Secret</li><li>Secret name (for testing purposes)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qQLp9QtWWacPOamJLv0-GA.png" /><figcaption>Vault URI</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*zyz0R-docksXKS1alirsuQ.png" /><figcaption>Client Id and Tenant Id</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrhvE_Ruh_F3UekfwCuvGQ.png" /><figcaption>Client Secret</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xTGGnRusltTvaw11BKGwsQ.png" /><figcaption>Secret name</figcaption></figure><h4>Incorporate the secret configurations into the appsettings.json</h4><p>Next, open the appsettings.json file and add the following section:</p><pre>&quot;AzureKeyVault&quot;: {<br>  &quot;VaultURI&quot;: &quot;Your vault URI&quot;,<br>  &quot;ClientId&quot;: &quot;Your client id&quot;,<br>  &quot;TenantId&quot;: &quot;Your tenant id&quot;,<br>  &quot;ClientSecret&quot;: &quot;Your client secret&quot;<br>}</pre><p>You can enhance security further by utilizing secrets.json instead. However, remember that secrets.json will not be pushed to the Git repository. Each team member will need to create it manually to maintain security standards.</p><h4>Utilize dependency injection to inject the secrets, enabling their use throughout the application</h4><p>Firstly, install the necessary NuGet packages.</p><pre>dotnet add package Azure.Identity<br>dotnet add package Azure.Security.KeyVault.Secrets<br>dotnet add package Azure.Extensions.AspNetCore.Configuration.Secrets</pre><p>Next, we need to inject the Key Vault service into the IConfiguration service, allowing us to retrieve the vault secrets from IConfiguration at runtime.</p><pre>// Program.cs<br><br>using Azure.Identity;<br><br>builder.Configuration.AddAzureKeyVault(<br>    new Uri(builder.Configuration[&quot;AzureKeyVault:VaultURI&quot;]!),<br>    new ClientSecretCredential(<br>        tenantId: builder.Configuration[&quot;AzureKeyVault:TenantId&quot;]!,<br>        clientId: builder.Configuration[&quot;AzureKeyVault:ClientId&quot;]!,<br>        clientSecret: builder.Configuration[&quot;AzureKeyVault:ClientSecret&quot;]!<br>        ));</pre><p>Well done! We have configured our application to retrieve all the required configurations from the vault in addition to appsettings.json file.</p><h4>Retrieval Preceding</h4><p>After integrating the Key Vault secrets, we now have four potential sources from which to retrieve a key’s value: Azure Key Vault, appsettings.json, environment variables, and secrets.json.</p><p>Here is the precedence order from highest to lowest:</p><ol><li>Azure Key Vault</li><li>secrets.json</li><li>appsettings.json</li><li>environment variables</li></ol><h3>Testing</h3><p>Let’s create an endpoint that takes the secret name as a string parameter and returns its value from Azure Key Vault.</p><pre>[ApiController]<br>[Route(&quot;[controller]&quot;)]<br>public class VaultController : ControllerBase<br>{<br>    private readonly IConfiguration _configuration;<br><br>    public VaultController(IConfiguration configuration)<br>    {<br>        _configuration = configuration;<br>    }<br><br>    [HttpGet]<br>    [Route(&quot;secret&quot;)]<br>    public string? GetSecret(string secretName)<br>    {<br>        return _configuration[secretName];<br>    }<br>}</pre><p>Run the application and open the Swagger window. Try sending your secret name in the endpoint. It should return the secret value if it’s in the Azure Key Vault secrets. Otherwise, it will attempt to search based on the precedence order.</p><p>Remember, the secret name is case-insensitive, so you can write it in lowercase, uppercase, or mixed case; it will be normalized at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UAR5x6RnI1yQqwCGSW-G8A.png" /><figcaption>Retrieving key vault secret value</figcaption></figure><h3>Monitoring: Logging</h3><p>After you create one or more key vaults, you’ll likely want to monitor how and when your key vaults are accessed, and by whom.</p><p><strong>What is logged:</strong></p><ol><li>Authenticated REST API requests and failed attempts.</li><li>Key vault operations like creation, deletion, and access policy changes.</li><li>Key and secret operations such as creation, modification, and listing.</li><li>Unauthenticated requests resulting in a 401 response.</li><li>Azure Event Grid notifications for expiration and policy changes.</li></ol><p><strong>Log sample:</strong></p><pre>{<br>    &quot;time&quot;: &quot;2024-05-06T20:47:43.4966268Z&quot;,<br>    &quot;category&quot;: &quot;AuditEvent&quot;,<br>    &quot;operationName&quot;: &quot;VaultGet&quot;,<br>    &quot;resultType&quot;: &quot;Success&quot;,<br>    &quot;correlationId&quot;: &quot;a3007d05-6es4-4d78-a541-XXXXXXXXXXXX&quot;,<br>    &quot;callerIpAddress&quot;: &quot;xx.78.xx.172&quot;,<br>    &quot;identity&quot;: {<br>        &quot;claim&quot;: {<br>            &quot;http://schemas.microsoft.com/identity/claims/objectidentifier&quot;: &quot;2b46553d-rl15-3ec5-bc4d-XXXXXXXXXXXX&quot;,<br>            &quot;appid&quot;: &quot;11c174dc-1526-4a9a-f79b-XXXXXXXXXXXX&quot;<br>        }<br>    },<br>    &quot;properties&quot;: {<br>        &quot;id&quot;: &quot;https://my-keyvault-00001.vault.azure.net/&quot;,<br>        &quot;clientInfo&quot;: &quot;&quot;,<br>        &quot;requestUri&quot;: &quot;https://management.azure.com/subscriptions/361DA5D4-A47A-4C79-AFDD-XXXXXXXXXXXX/resourceGroups/my-resource-group/providers/Microsoft.KeyVault/vaults/my-keyvault-00001?api-version=2019-09-01&quot;,<br>        &quot;httpStatusCode&quot;: 200,<br>        &quot;properties&quot;: {<br>            &quot;sku&quot;: {<br>                &quot;Family&quot;: &quot;A&quot;,<br>                &quot;Name&quot;: &quot;Standard&quot;,<br>                &quot;Capacity&quot;: null<br>            },<br>            &quot;tenantId&quot;: &quot;2bc9q3c3-372a-79e5-aa0b-XXXXXXXXXXXX&quot;,<br>            &quot;networkAcls&quot;: null,<br>            &quot;enabledForDeployment&quot;: false,<br>            &quot;enabledForDiskEncryption&quot;: false,<br>            &quot;enabledForTemplateDeployment&quot;: false,<br>            &quot;enableSoftDelete&quot;: true,<br>            &quot;softDeleteRetentionInDays&quot;: 90,<br>            &quot;enableRbacAuthorization&quot;: true,<br>            &quot;enablePurgeProtection&quot;: null<br>        }<br>    },<br>    &quot;resourceId&quot;: &quot;/SUBSCRIPTIONS/361DA5D4-A47A-4C79-AFDD-XXXXXXXXXXXX/RESOURCEGROUPS/MY-RESOURCE-GROUP/PROVIDERS/MICROSOFT.KEYVAULT/VAULTS/MY-KEYVAULT-00001&quot;,<br>    &quot;operationVersion&quot;: &quot;2019-09-01&quot;,<br>    &quot;resultSignature&quot;: &quot;OK&quot;,<br>    &quot;durationMs&quot;: &quot;16&quot;<br>}</pre><p><strong>Enable logging to Log Analytics and Blob Containers</strong></p><p>The following steps are copied from <a href="https://learn.microsoft.com/en-us/azure/key-vault/general/howto-logging?tabs=azure-portal">Microsoft documentation</a>.</p><ul><li>From the Resource pane menu, select Diagnostic settings, and then Add diagnostic setting</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*juIDU8JsvibMCuYC.png" /><figcaption>Microsoft reserved image (<a href="https://learn.microsoft.com/en-us/azure/key-vault/general/howto-logging?tabs=azure-portal">link</a>)</figcaption></figure><ul><li>Under Category groups, select both audit and allLogs.</li><li>If Azure Log Analytics is the destination, select Send to Log Analytics workspace and choose your subscription and workspace from the drop-down menus. <br>You may also select Archive to a storage account and choose your subscription and storage account from the drop-down menus.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*bfx4_8c8soJipAjE.png" /><figcaption>Microsoft reserved image (<a href="https://learn.microsoft.com/en-us/azure/key-vault/general/howto-logging?tabs=azure-portal">link</a>)</figcaption></figure><ul><li>When you’ve selected your desired options, select Save.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/770/0*gCG_kTbdM146nL4b.png" /><figcaption>Microsoft reserved image (<a href="https://learn.microsoft.com/en-us/azure/key-vault/general/howto-logging?tabs=azure-portal">link</a>)</figcaption></figure><p><strong>Explore Blob Containers logs:</strong></p><p>To generate some logs, run the testing application again.</p><p>Navigate to the configured storage account and locate the blob containers. You should find a new blob container named “insights-logs-auditevent”. Navigate to the deepest folder to find log files in JSON format.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Sa6zvAWiKXqH827tGsR80g.png" /><figcaption>Generated log file in JSON format</figcaption></figure><h3>Protection</h3><p>If your secrets are accessed by anonymous users or compromised in any way, it’s crucial to detect and respond to such incidents promptly.</p><p>Microsoft offers a solution for this called “Azure Sentinel.” By implementing trapped keys, Azure Sentinel notifies you immediately whenever someone accesses them.</p><p>You can find a comprehensive demonstration of this feature in a <a href="https://www.youtube.com/watch?v=LZoj0fqcfQY">YouTube video</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/533/0*g56bmSR0eHjgdzAC.png" /><figcaption><a href="https://learn.microsoft.com/en-us/azure/sentinel/overview">Microsoft Sentinel</a></figcaption></figure><h3>References</h3><ul><li><a href="https://learn.microsoft.com/en-us/azure/key-vault/general/overview">Azure Key Vault Overview - Azure Key Vault</a></li><li><a href="https://learn.microsoft.com/en-us/azure/key-vault/general/tutorial-net-create-vault-azure-web-app">Tutorial - Use Azure Key Vault with an Azure web app in .NET</a></li><li><a href="https://learn.microsoft.com/en-us/azure/azure-app-configuration/use-key-vault-references-dotnet-core">Tutorial for using Azure App Configuration Key Vault references in an ASP.NET Core app</a></li><li><a href="https://learn.microsoft.com/en-us/azure/role-based-access-control/role-assignments-portal?WT.mc_id=Portal-Microsoft_Azure_KeyVault">Assign Azure roles using the Azure portal - Azure RBAC</a></li><li><a href="https://learn.microsoft.com/en-us/azure/sentinel/overview">What is Microsoft Sentinel?</a></li><li><a href="https://learn.microsoft.com/en-us/azure/key-vault/general/howto-logging?tabs=azure-portal">Enable Azure Key Vault logging</a></li></ul><p><a href="https://azure.microsoft.com/en-us/pricing/details/key-vault/">https://azure.microsoft.com/en-us/pricing/details/key-vault/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=405b12edaf4a" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>